hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
d47e9a215d9e523cad0384a023e847aad45c5a31
18,330
cpp
C++
DerivedSources/WebCore/JSSVGTransformList.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
DerivedSources/WebCore/JSSVGTransformList.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
DerivedSources/WebCore/JSSVGTransformList.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #if ENABLE(SVG) #include "JSSVGTransformList.h" #include "ExceptionCode.h" #include "JSDOMBinding.h" #include "JSSVGMatrix.h" #include "JSSVGTransform.h" #include "SVGTransform.h" #include "SVGTransformList.h" #include <runtime/Error.h> #include <runtime/JSNumberCell.h> #include <wtf/GetPtr.h> using namespace JSC; namespace WebCore { ASSERT_CLASS_FITS_IN_CELL(JSSVGTransformList); /* Hash table */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGTransformListTableValues[3] = { { "numberOfItems", DontDelete | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGTransformListNumberOfItems), (intptr_t)0 THUNK_GENERATOR(0) }, { "constructor", DontEnum | ReadOnly, (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsSVGTransformListConstructor), (intptr_t)0 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGTransformListTable = { 4, 3, JSSVGTransformListTableValues, 0 }; /* Hash table for constructor */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGTransformListConstructorTableValues[1] = { { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGTransformListConstructorTable = { 1, 0, JSSVGTransformListConstructorTableValues, 0 }; class JSSVGTransformListConstructor : public DOMConstructorObject { public: JSSVGTransformListConstructor(JSC::ExecState*, JSDOMGlobalObject*); virtual bool getOwnPropertySlot(JSC::ExecState*, const JSC::Identifier&, JSC::PropertySlot&); virtual bool getOwnPropertyDescriptor(JSC::ExecState*, const JSC::Identifier&, JSC::PropertyDescriptor&); static const JSC::ClassInfo s_info; static PassRefPtr<JSC::Structure> createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype) { return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info); } protected: static const unsigned StructureFlags = JSC::OverridesGetOwnPropertySlot | JSC::ImplementsHasInstance | DOMConstructorObject::StructureFlags; }; const ClassInfo JSSVGTransformListConstructor::s_info = { "SVGTransformListConstructor", &DOMConstructorObject::s_info, &JSSVGTransformListConstructorTable, 0 }; JSSVGTransformListConstructor::JSSVGTransformListConstructor(ExecState* exec, JSDOMGlobalObject* globalObject) : DOMConstructorObject(JSSVGTransformListConstructor::createStructure(globalObject->globalData(), globalObject->objectPrototype()), globalObject) { ASSERT(inherits(&s_info)); putDirect(exec->globalData(), exec->propertyNames().prototype, JSSVGTransformListPrototype::self(exec, globalObject), DontDelete | ReadOnly); } bool JSSVGTransformListConstructor::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSSVGTransformListConstructor, DOMObject>(exec, &JSSVGTransformListConstructorTable, this, propertyName, slot); } bool JSSVGTransformListConstructor::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSSVGTransformListConstructor, DOMObject>(exec, &JSSVGTransformListConstructorTable, this, propertyName, descriptor); } /* Hash table for prototype */ #if ENABLE(JIT) #define THUNK_GENERATOR(generator) , generator #else #define THUNK_GENERATOR(generator) #endif static const HashTableValue JSSVGTransformListPrototypeTableValues[10] = { { "clear", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionClear), (intptr_t)0 THUNK_GENERATOR(0) }, { "initialize", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionInitialize), (intptr_t)1 THUNK_GENERATOR(0) }, { "getItem", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionGetItem), (intptr_t)1 THUNK_GENERATOR(0) }, { "insertItemBefore", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionInsertItemBefore), (intptr_t)2 THUNK_GENERATOR(0) }, { "replaceItem", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionReplaceItem), (intptr_t)2 THUNK_GENERATOR(0) }, { "removeItem", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionRemoveItem), (intptr_t)1 THUNK_GENERATOR(0) }, { "appendItem", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionAppendItem), (intptr_t)1 THUNK_GENERATOR(0) }, { "createSVGTransformFromMatrix", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionCreateSVGTransformFromMatrix), (intptr_t)1 THUNK_GENERATOR(0) }, { "consolidate", DontDelete | Function, (intptr_t)static_cast<NativeFunction>(jsSVGTransformListPrototypeFunctionConsolidate), (intptr_t)0 THUNK_GENERATOR(0) }, { 0, 0, 0, 0 THUNK_GENERATOR(0) } }; #undef THUNK_GENERATOR static JSC_CONST_HASHTABLE HashTable JSSVGTransformListPrototypeTable = { 33, 31, JSSVGTransformListPrototypeTableValues, 0 }; const ClassInfo JSSVGTransformListPrototype::s_info = { "SVGTransformListPrototype", &JSC::JSObjectWithGlobalObject::s_info, &JSSVGTransformListPrototypeTable, 0 }; JSObject* JSSVGTransformListPrototype::self(ExecState* exec, JSGlobalObject* globalObject) { return getDOMPrototype<JSSVGTransformList>(exec, globalObject); } bool JSSVGTransformListPrototype::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticFunctionSlot<JSObject>(exec, &JSSVGTransformListPrototypeTable, this, propertyName, slot); } bool JSSVGTransformListPrototype::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticFunctionDescriptor<JSObject>(exec, &JSSVGTransformListPrototypeTable, this, propertyName, descriptor); } const ClassInfo JSSVGTransformList::s_info = { "SVGTransformList", &DOMObjectWithGlobalPointer::s_info, &JSSVGTransformListTable, 0 }; JSSVGTransformList::JSSVGTransformList(NonNullPassRefPtr<Structure> structure, JSDOMGlobalObject* globalObject, PassRefPtr<SVGTransformListPropertyTearOff > impl) : DOMObjectWithGlobalPointer(structure, globalObject) , m_impl(impl) { ASSERT(inherits(&s_info)); } JSObject* JSSVGTransformList::createPrototype(ExecState* exec, JSGlobalObject* globalObject) { return new (exec) JSSVGTransformListPrototype(globalObject, JSSVGTransformListPrototype::createStructure(globalObject->globalData(), globalObject->objectPrototype())); } bool JSSVGTransformList::getOwnPropertySlot(ExecState* exec, const Identifier& propertyName, PropertySlot& slot) { return getStaticValueSlot<JSSVGTransformList, Base>(exec, &JSSVGTransformListTable, this, propertyName, slot); } bool JSSVGTransformList::getOwnPropertyDescriptor(ExecState* exec, const Identifier& propertyName, PropertyDescriptor& descriptor) { return getStaticValueDescriptor<JSSVGTransformList, Base>(exec, &JSSVGTransformListTable, this, propertyName, descriptor); } JSValue jsSVGTransformListNumberOfItems(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(slotBase)); UNUSED_PARAM(exec); JSValue result = jsNumber(castedThis->impl()->numberOfItems()); return result; } JSValue jsSVGTransformListConstructor(ExecState* exec, JSValue slotBase, const Identifier&) { JSSVGTransformList* domObject = static_cast<JSSVGTransformList*>(asObject(slotBase)); return JSSVGTransformList::getConstructor(exec, domObject->globalObject()); } JSValue JSSVGTransformList::getConstructor(ExecState* exec, JSGlobalObject* globalObject) { return getDOMConstructor<JSSVGTransformListConstructor>(exec, static_cast<JSDOMGlobalObject*>(globalObject)); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionClear(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); ExceptionCode ec = 0; imp->clear(ec); setDOMException(exec, ec); return JSValue::encode(jsUndefined()); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionInitialize(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; if (exec->argumentCount() > 0 && !exec->argument(0).isUndefinedOrNull() && !exec->argument(0).inherits(&JSSVGTransform::s_info)) return throwVMTypeError(exec); SVGPropertyTearOff<SVGTransform>* item(toSVGTransform(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->initialize(item, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionGetItem(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; unsigned index(exec->argument(0).toUInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->getItem(index, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionInsertItemBefore(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; if (exec->argumentCount() > 0 && !exec->argument(0).isUndefinedOrNull() && !exec->argument(0).inherits(&JSSVGTransform::s_info)) return throwVMTypeError(exec); SVGPropertyTearOff<SVGTransform>* item(toSVGTransform(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); unsigned index(exec->argument(1).toUInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->insertItemBefore(item, index, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionReplaceItem(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 2) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; if (exec->argumentCount() > 0 && !exec->argument(0).isUndefinedOrNull() && !exec->argument(0).inherits(&JSSVGTransform::s_info)) return throwVMTypeError(exec); SVGPropertyTearOff<SVGTransform>* item(toSVGTransform(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); unsigned index(exec->argument(1).toUInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->replaceItem(item, index, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionRemoveItem(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; unsigned index(exec->argument(0).toUInt32(exec)); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->removeItem(index, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionAppendItem(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; if (exec->argumentCount() > 0 && !exec->argument(0).isUndefinedOrNull() && !exec->argument(0).inherits(&JSSVGTransform::s_info)) return throwVMTypeError(exec); SVGPropertyTearOff<SVGTransform>* item(toSVGTransform(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->appendItem(item, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionCreateSVGTransformFromMatrix(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); if (exec->argumentCount() < 1) return throwVMError(exec, createSyntaxError(exec, "Not enough arguments")); ExceptionCode ec = 0; if (exec->argumentCount() > 0 && !exec->argument(0).isUndefinedOrNull() && !exec->argument(0).inherits(&JSSVGMatrix::s_info)) return throwVMTypeError(exec); SVGPropertyTearOff<SVGMatrix>* matrix(toSVGMatrix(exec->argument(0))); if (exec->hadException()) return JSValue::encode(jsUndefined()); JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->createSVGTransformFromMatrix(matrix, ec))); setDOMException(exec, ec); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL jsSVGTransformListPrototypeFunctionConsolidate(ExecState* exec) { JSValue thisValue = exec->hostThisValue(); if (!thisValue.inherits(&JSSVGTransformList::s_info)) return throwVMTypeError(exec); JSSVGTransformList* castedThis = static_cast<JSSVGTransformList*>(asObject(thisValue)); SVGTransformListPropertyTearOff * imp = static_cast<SVGTransformListPropertyTearOff *>(castedThis->impl()); ExceptionCode ec = 0; JSC::JSValue result = toJS(exec, castedThis->globalObject(), WTF::getPtr(imp->consolidate(ec))); setDOMException(exec, ec); return JSValue::encode(result); } JSC::JSValue toJS(JSC::ExecState* exec, JSDOMGlobalObject* globalObject, SVGTransformListPropertyTearOff * object) { return getDOMObjectWrapper<JSSVGTransformList>(exec, globalObject, object); } SVGTransformListPropertyTearOff * toSVGTransformList(JSC::JSValue value) { return value.inherits(&JSSVGTransformList::s_info) ? static_cast<JSSVGTransformList*>(asObject(value))->impl() : 0; } } #endif // ENABLE(SVG)
47.364341
198
0.765357
[ "object" ]
d4836b5415cca3521f156994048f9b6c5fb0937e
3,447
cc
C++
src/main/cpp/workspace_layout.cc
Tingbopku/tingbo1
ce11cf40008d004260defd110fdbb621d87e1f3d
[ "Apache-2.0" ]
null
null
null
src/main/cpp/workspace_layout.cc
Tingbopku/tingbo1
ce11cf40008d004260defd110fdbb621d87e1f3d
[ "Apache-2.0" ]
null
null
null
src/main/cpp/workspace_layout.cc
Tingbopku/tingbo1
ce11cf40008d004260defd110fdbb621d87e1f3d
[ "Apache-2.0" ]
null
null
null
// Copyright 2016 The Bazel 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 "src/main/cpp/workspace_layout.h" #include <assert.h> #include <unistd.h> // access #include "src/main/cpp/blaze_util_platform.h" #include "src/main/cpp/util/file.h" namespace blaze { using std::string; using std::vector; static const char kWorkspaceMarker[] = "WORKSPACE"; string WorkspaceLayout::GetOutputRoot() { return blaze::GetOutputRoot(); } bool WorkspaceLayout::InWorkspace(const string &workspace) { return access( blaze_util::JoinPath(workspace, kWorkspaceMarker).c_str(), F_OK) == 0; } string WorkspaceLayout::GetWorkspace(const string &cwd) { assert(!cwd.empty()); string workspace = cwd; do { if (InWorkspace(workspace)) { return workspace; } workspace = blaze_util::Dirname(workspace); } while (!workspace.empty() && workspace != "/"); return ""; } string WorkspaceLayout::RcBasename() { return ".bazelrc"; } static string FindDepotBlazerc(const string& workspace) { // Package semantics are ignored here, but that's acceptable because // blaze.blazerc is a configuration file. vector<string> candidates; WorkspaceLayout::WorkspaceRcFileSearchPath(&candidates); for (const auto& candidate : candidates) { string blazerc = blaze_util::JoinPath(workspace, candidate); if (!access(blazerc.c_str(), R_OK)) { return blazerc; } } return ""; } static string FindAlongsideBinaryBlazerc(const string& cwd, const string& arg0) { string path = arg0[0] == '/' ? arg0 : blaze_util::JoinPath(cwd, arg0); string base = blaze_util::Basename(arg0); string binary_blazerc_path = path + "." + base + "rc"; if (!access(binary_blazerc_path.c_str(), R_OK)) { return binary_blazerc_path; } return ""; } static string FindSystemWideBlazerc() { string path = "/etc/bazel.bazelrc"; if (!access(path.c_str(), R_OK)) { return path; } return ""; } void WorkspaceLayout::FindCandidateBlazercPaths( const string& workspace, const string& cwd, const vector<string>& args, std::vector<string>* result) { result->push_back(FindDepotBlazerc(workspace)); result->push_back(FindAlongsideBinaryBlazerc(cwd, args[0])); result->push_back(FindSystemWideBlazerc()); } void WorkspaceLayout::WorkspaceRcFileSearchPath( vector<string>* candidates) { candidates->push_back("tools/bazel.rc"); } bool WorkspaceLayout::WorkspaceRelativizeRcFilePath(const string &workspace, string *path_fragment) { // Strip off the "%workspace%/" prefix and prepend the true workspace path. // In theory this could use alternate search paths for blazerc files. path_fragment->assign( blaze_util::JoinPath(workspace, path_fragment->substr(WorkspacePrefixLength))); return true; } } // namespace blaze
30.776786
77
0.695677
[ "vector" ]
d4848a8666d6a60e5b47129ffd00ecc03487a11f
459
cpp
C++
platform/android/CocoRender/Classes/Render.cpp
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
7
2015-04-17T20:50:13.000Z
2019-09-21T10:45:39.000Z
platform/android/CocoRender/Classes/Render.cpp
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
null
null
null
platform/android/CocoRender/Classes/Render.cpp
chukong/CocoStudioConnector
f0ff090e0e14a7d768bfc17b1d667471bea6d7eb
[ "MIT" ]
8
2015-01-18T09:37:17.000Z
2021-04-21T05:54:38.000Z
#include "Render.h" #include "cocos-ext.h" using namespace cocos2d; using namespace cocos2d::extension; Render::Render(const char* filename) { name = CCString::create(filename); initSceneLayer(name->getCString()); } Render::~Render(void) { } void Render::initSceneLayer(const char* filename) { CCLayer::init(); CCNode* pScene = SceneReader::sharedSceneReader()->createNodeWithSceneFile(filename); this->addChild(pScene); }
19.125
87
0.699346
[ "render" ]
d484cd3ccaa9f9f273c84e5053916fd1734921df
14,371
cpp
C++
src/code2tap.cpp
maziac/zx-code2tap
1e0c1b8fc29eaa0d3256ff8fbc27bd507c573e57
[ "MIT" ]
null
null
null
src/code2tap.cpp
maziac/zx-code2tap
1e0c1b8fc29eaa0d3256ff8fbc27bd507c573e57
[ "MIT" ]
null
null
null
src/code2tap.cpp
maziac/zx-code2tap
1e0c1b8fc29eaa0d3256ff8fbc27bd507c573e57
[ "MIT" ]
null
null
null
/* Inspired by bin2tap from http://metalbrain.speccy.org/. This program takes a binary or obj ZX Spectrum machine code program and creates a tap file from it. It adds a ZX Basic loader as well. I.e. the user just needs to type LOAD "" This will load the ZX Basic loader, which contains a program that consists basically of LOAD "" CODE 16384 LOAD "" CODE RANDOMIZE USR EXEC_ADDR The tap file is configurable: - name of the program; shown after LOAD "" - EXEC_ADDR: The start address of the machine code executable - screen data: Screen$ to load - binary code: the machine code data */ //#include <stdio.h> #include <iostream> #include <string.h> //#include <linux/limits.h> #include <vector> #include <stdarg.h> #include <iterator> #include <fstream> // The version string. #define VERSION "1.1.0" // ZX Basic commands coding. #define CLEAR "\xFD" #define CLS "\xFB" #define LOAD "\xEF" #define CODE "\xAF" #define RANDOMIZE "\xF9" #define REM "\xEA" #define USR "\xC0" #define BORDER "\xE7" #define POKE "\xF4" #define PAPER "\xDA" #define INK "\xD9" #define VAL "\xB0" #define BLACK VAL "\"0\"" #define WHITE VAL "\"7\"" // TAP types #define TAP_HDR_BASIC 0 #define TAP_HDR_CODE 3 // Max number of character for program name. #define MAX_PRG_NAME_LENGTH 10 using namespace std; // Define byte. typedef char byte; // Prototypes. void print_help(); void tap_create_zx_basic_loader( FILE *fp, char* name, int start_address, int exec_address, char* screen_file_name ); void tap_create_code( FILE *fp, char* file_name, int start_address ); vector<byte> create_zx_basic_line(int line_number, const char* line_fmt, ... ); void tap_write_data_block_with_checksum( FILE* fp, byte flags, vector<byte>& data ); void tap_write_prg_header( FILE* fp, char* fname, vector<byte>& data ); void tap_write_code_header( FILE* fp, const char* fname, vector<byte>& data, int start_address ); /////////////////////////////////////////////////////////////////// /// Main. /////////////////////////////////////////////////////////////////// int main( int argc, char* argv[] ) { int i = 1; char* screen_file_name = NULL; char* code_file_name = NULL; char* prg_name = NULL; int start_address = -1; int exec_address = -1; char tap_file_name[PATH_MAX]; tap_file_name[0] = 0; while( i < argc ) { char* s = argv[i]; if( ! strncmp( "-", s, 1 ) ) { // some option if( ! strcmp( "-h", s ) ) { // Help print_help(); exit( EXIT_SUCCESS ); } else if( ! strcmp( "-code", s ) ) { // machine code file i++; code_file_name = argv[i]; } else if( ! strcmp( "-screen", s ) ) { // screen data file i++; screen_file_name = argv[i]; } else if( ! strcmp( "-start", s ) ) { // Start address of machine code i++; start_address = strtol( argv[i], NULL, 0 ); } else if( ! strcmp( "-exec", s ) ) { // Execution address of machine code i++; exec_address = strtol( argv[i], NULL, 0 ); } else if( ! strcmp( "-o", s ) ) { // Output filename i++; strcpy(tap_file_name, argv[i] ); } else { // unknown option cout << "Error: Unknown option '" << s << "'" << endl << endl; print_help(); exit( EXIT_FAILURE ); } } else { // No option, so it is the program name if( prg_name ) { // already a name given cout << "Error: two program names given '" << s << "'" << endl << endl; print_help(); exit( EXIT_FAILURE ); } // Use program name prg_name = s; if(strlen(prg_name) > MAX_PRG_NAME_LENGTH) { cout << "Error: The program name is too long. Only " << MAX_PRG_NAME_LENGTH << " characters are allowed." << endl << endl; exit( EXIT_FAILURE ); } } // Next i++; } // Check for program name if( ! prg_name ) { // No program name cout << "Error: No program name given." << endl << endl; print_help(); exit( EXIT_FAILURE ); } // Check for filename if( ! code_file_name ) { // No filename cout << "Error: Expected a binary filename." << endl << endl; print_help(); exit( EXIT_FAILURE ); } // Check for a start address if( start_address < 0 ) { // No start address cout << "Error: No start address given." << endl << endl; print_help(); exit( EXIT_FAILURE ); } // Check for a execution address if( exec_address < 0 ) { // No execution address cout << "Error: No execution address given." << endl << endl; print_help(); exit( EXIT_FAILURE ); } // Check if filename was given. if(tap_file_name[0] == 0) sprintf( tap_file_name, "%s.tap", prg_name ); // Open file FILE* fp_out = fopen( tap_file_name, "w" ); if (fp_out == NULL) { // Error cout << "Error: Couldn't open file '" << code_file_name << "' for writing." << endl; exit(EXIT_FAILURE); } // Process the data. // ZX Basic loader: tap_create_zx_basic_loader( fp_out, prg_name, start_address, exec_address, screen_file_name ); // Screen data: if( screen_file_name ) { tap_create_code( fp_out, screen_file_name, 16384 ); } // The machine code data: tap_create_code( fp_out, code_file_name, start_address ); // close fclose( fp_out ); // exit return EXIT_SUCCESS; } /// Prints the usage. void print_help() { cout << "code2tap (v" << VERSION << ")" << endl; cout << "Usage:" << endl; cout << " code2tap prg_name -code code_file_name -start addr1 -exec addr2 [-screen screen_file_name] [-o tap_file_name]" << endl; cout << " prg_name: The name of the program." << endl; cout << " I.e. the name presented while loading." << endl; cout << " -code code_file_name: The file containing the machine code binary." << endl; cout << " -start addr1: The load code start address." << endl; cout << " -exec addr2: The machine code execution start address." << endl; cout << " -screen screen_file_name: The file name of the screen data." << endl; cout << " -o tap_file_name: The filename for the tap file." << endl; cout << " If omitted 'prg_name'.tap is used." << endl; } /// Creates a ZX Basic loader tap binary code. /// @param fp The file pointer to write to. /// @param name The name of the program. /// @param start_address The LOAD""CODE start address. /// @param exec_address The USR execution address. /// @param screen_file_name The file name for the screen data. void tap_create_zx_basic_loader( FILE *fp, char* name, int start_address, int exec_address, char* screen_file_name ) { vector<byte> basic_loader; vector<byte> basic_line; int line_number = 10; // CLEAR start_address-1 basic_line = create_zx_basic_line( line_number, CLEAR VAL "\"%d\"", start_address-1 ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; // BORDER black, INK white, PAPER black, CLS basic_line = create_zx_basic_line( line_number, BORDER BLACK ":" PAPER BLACK ":" INK WHITE ":" CLS ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; #if 01 // POKE 23739,111: Redirect output stream address to 0x096f which contains a simple "ret" (111=6F), // so that "CODE: name" or whatever will not be written to the screen. basic_line = create_zx_basic_line( line_number, POKE VAL "\"23739\"," VAL "\"111\"" ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; #endif // LOAD "" CODE 16384 if( screen_file_name ) { basic_line = create_zx_basic_line( line_number, LOAD "\"\"" CODE ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; } // LOAD "" CODE basic_line = create_zx_basic_line( line_number, LOAD "\"\"" CODE ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; // POKE 23739,244: So that text output will be visible again basic_line = create_zx_basic_line( line_number, POKE VAL "\"23739\"," VAL "\"244\"" ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); line_number += 10; // RANDOMIZE USR EXEC_ADDR basic_line = create_zx_basic_line( line_number, RANDOMIZE USR VAL "\"%d\"", exec_address ); basic_loader.insert(basic_loader.end(), basic_line.begin(), basic_line.end()); //line_number += 10; //cout << "basic_size=" << basic_loader.size() << endl; // Write to tap tap_write_prg_header(fp, name, basic_loader); tap_write_data_block_with_checksum( fp, (byte)-1, basic_loader ); } /// Creates a sinlge line of basic in memory. /// @param line_number The Basic listing line number /// @param line_fmt The Basic commands etc. as string. Acts /// as a format string if argumens should follow. /// @param ... arguments vector<byte> create_zx_basic_line(int line_number, const char* line_fmt, ... ) { // ZX Basic line, see http://www.worldofspectrum.org/ZXBasicManual/zxmanchap24.html // 2 bytes: line number (big endian) // 2 bytes: length of text + enter (little endian) // x bytes: text (the basic command(s)) // 1 byte: enter (0x0D = "\r") // Basic commands might be separated by ":" (0x3A like ASCII) // create line string from format. char line_string[1024]; // should be enough va_list argptr; va_start(argptr, line_fmt); vsprintf(line_string, line_fmt, argptr); va_end(argptr); // Encode line vector<byte> line; // Basic line number line.push_back(line_number >> 8); line.push_back(line_number & 0xFF); // add 2 (for now) empty entries line.push_back(0); line.push_back(0); // add the basic commands int slen = strlen(line_string); for( int i=0; i<slen; i++ ) { byte b = line_string[i]; line.push_back(b); } // add 'enter' line.push_back('\r'); // line length int line_length = slen+1; line[2] = line_length & 0xFF; line[3] = line_length >> 8; // return return line; } /// Creates a tap binary code. /// @param fp The file pointer to write to. /// @param fname the filename to put into the header. /// @param start_address of the code area. void tap_create_code( FILE *fp, char* file_name, int start_address ) { if( ! file_name ) return; // open input data ifstream in_file(file_name, ios::binary); if( in_file.fail() ) { // Error cout << "Error: Couldn't open file '" << file_name << "'." << endl; exit(EXIT_FAILURE); } // load data into vector vector<byte> data((istreambuf_iterator<byte>(in_file)), istreambuf_iterator<byte>()); // Write header tap_write_code_header(fp, "code", data, start_address); // tap data tap_write_data_block_with_checksum(fp, (byte)-1, data); } /// Writes a tap program header. /// @param fp The file pointer to write to. /// @param fname the filename to put into the header. /// @param data the data to write. Used only for the size of the data. void tap_write_prg_header( FILE* fp, char* fname, vector<byte>& data ) { vector<byte> hdr; // See http://www.zx-modules.de/fileformats/tapformat.html // 2 bytes: length // 1 byte: always 0 // Here the block starts: // 1 byte: type, 0=basic prgm // 10 char: file name // 2 byte: length of following data (basic+variables) // 2 byte: autostart line number or start address // 2 byte: basic program length // 1 byte: checksum // Type hdr.push_back(TAP_HDR_BASIC); // filename size_t fname_len = strlen(fname); for( size_t i=0; i<MAX_PRG_NAME_LENGTH; i++ ) { if( i < fname_len ) hdr.push_back(fname[i]); else hdr.push_back(' '); } // length of basic+variables int len_basic = data.size(); hdr.push_back(len_basic & 0xFF); hdr.push_back(len_basic >> 8); // autostart line number. Use the first line of the program. #if 01 hdr.push_back(data[1]); // exchange high and low byte hdr.push_back(data[0]); #else // No autostart line hdr.push_back(0); hdr.push_back(0x80); #endif // basic program length hdr.push_back(len_basic & 0xFF); hdr.push_back(len_basic >> 8); // Write data block with check sum tap_write_data_block_with_checksum(fp, 0, hdr); } /// Writes a tap code header. /// @param fp The file pointer to write to. /// @param fname the filename to put into the header. /// @param data the data to write. Used only for the size of the data. /// @param start_address of the code area. void tap_write_code_header( FILE* fp, const char* fname, vector<byte>& data, int start_address ) { vector<byte> hdr; // See http://www.zx-modules.de/fileformats/tapformat.html // 2 bytes: length // 1 byte: always 0 // Here the block starts: // 1 byte: type, 3=code // 10 char: file name // 2 byte: code length // 2 byte: start address // 2 byte: 32768 // 1 byte: checksum // Type hdr.push_back(TAP_HDR_CODE); // filename size_t fname_len = strlen(fname); for( size_t i=0; i<10; i++ ) { if( i < fname_len ) hdr.push_back(fname[i]); else hdr.push_back(' '); } // length of code int len_data = data.size(); hdr.push_back(len_data & 0xFF); hdr.push_back(len_data >> 8); // start address hdr.push_back(start_address & 0xFF); hdr.push_back(start_address >> 8); // 32768 hdr.push_back(0); hdr.push_back(0x80); // Write data block with check sum tap_write_data_block_with_checksum(fp, 0, hdr); } /// Writes a tap data block with checksum. /// @param fp The file pointer to write to. /// @param flags The flags to use for the block. /// @param data the data to write. void tap_write_data_block_with_checksum( FILE* fp, byte flags, vector<byte>& data ) { // Write length of block int16_t len = data.size() + 2; // size of complete block fwrite(&len, sizeof(len), 1, fp ); // Flags = 0 fputc( flags, fp ); byte checksum = flags; // Write data for( auto b : data ) { // Write fputc( b, fp ); // Checksum checksum ^= b; } // Checksum fputc( checksum, fp ); }
29.630928
133
0.628627
[ "vector" ]
d4866bb31b79e48e3bee7030008dcab71fd88483
7,528
cpp
C++
benchmarks/DNN/blocks/LSTM/gpu_lib/reference_generator.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
23
2017-05-03T13:06:34.000Z
2018-06-07T07:12:43.000Z
benchmarks/DNN/blocks/LSTM/gpu_lib/reference_generator.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
2
2017-04-25T08:59:09.000Z
2017-05-11T16:41:55.000Z
benchmarks/DNN/blocks/LSTM/gpu_lib/reference_generator.cpp
akmaru/tiramisu
8ca4173547b6d12cff10575ef0dc48cf93f7f414
[ "MIT" ]
5
2017-02-16T14:26:40.000Z
2018-05-30T16:49:27.000Z
#include <tiramisu/tiramisu.h> #include "configuration.h" using namespace tiramisu; int main(int argc, char **argv) { // Reference LSTM implementation for correctness check tiramisu::init("lstm_ref"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Inner dimensions var i("i", 0, FEATURE_SIZE), j("j", 0, FEATURE_SIZE), k("k", 0, BATCH_SIZE); // Outer dimensions var l("l", 0, NUM_LAYERS), m("m", 0, SEQ_LENGTH); input R_i("R_i", {l, i, j}, p_float32); input R_z("R_z", {l, i, j}, p_float32); input R_o("R_o", {l, i, j}, p_float32); input R_f("R_f", {l, i, j}, p_float32); input W_i("W_i", {l, i, j}, p_float32); input W_z("W_z", {l, i, j}, p_float32); input W_o("W_o", {l, i, j}, p_float32); input W_f("W_f", {l, i, j}, p_float32); input b_i("b_i", {l, i}, p_float32); input b_z("b_z", {l, i}, p_float32); input b_o("b_o", {l, i}, p_float32); input b_f("b_f", {l, i}, p_float32); input x({m, k, i}, p_float32); // h(m, l) is the output of the block (m, l) // which takes h(m - 1, l) and h(m, l - 1) as inputs // initial hidden states are h(-1, l) and c(-1, l) // input x is copied to h(m, -1) computation h({m, l, k, i}, p_float32); computation c({m, l, k, i}, p_float32); computation h_init({l, k, i}, expr(float(0))); computation c_init({l, k, i}, expr(float(0))); computation h_copy_x({m, k, i}, x(m, k, i)); computation sum_i_init({m, l, k, i}, b_i(l, i)); computation sum_z_init({m, l, k, i}, b_z(l, i)); computation sum_o_init({m, l, k, i}, b_o(l, i)); computation sum_f_init({m, l, k, i}, b_f(l, i)); computation sum_i1({m, l, k, i, j}, sum_i_init(m, l, k, i) + R_i(l, i, j) * h(m - 1, l, k, j)); computation sum_i2({m, l, k, i, j}, sum_i_init(m, l, k, i) + W_i(l, i, j) * h(m, l - 1, k, j)); computation sum_z1({m, l, k, i, j}, sum_z_init(m, l, k, i) + R_z(l, i, j) * h(m - 1, l, k, j)); computation sum_z2({m, l, k, i, j}, sum_z_init(m, l, k, i) + W_z(l, i, j) * h(m, l - 1, k, j)); computation sum_o1({m, l, k, i, j}, sum_o_init(m, l, k, i) + R_o(l, i, j) * h(m - 1, l, k, j)); computation sum_o2({m, l, k, i, j}, sum_o_init(m, l, k, i) + W_o(l, i, j) * h(m, l - 1, k, j)); computation sum_f1({m, l, k, i, j}, sum_f_init(m, l, k, i) + R_f(l, i, j) * h(m - 1, l, k, j)); computation sum_f2({m, l, k, i, j}, sum_f_init(m, l, k, i) + W_f(l, i, j) * h(m, l - 1, k, j)); #define sigmoid(x) expr(float(1)) / (1 + expr(o_expo, -(x))) computation sig_i({m, l, k, i}, sigmoid(sum_i2(m, l, k, i, 0))); computation tnh_z({m, l, k, i}, expr(o_tanh, sum_z2(m, l, k, i, 0))); computation sig_o({m, l, k, i}, sigmoid(sum_o2(m, l, k, i, 0))); computation sig_f({m, l, k, i}, sigmoid(sum_f2(m, l, k, i, 0))); computation mul_iz({m, l, k, i}, sig_i(m, l, k, i) * tnh_z(m, l, k, i)); computation mul_fc({m, l, k, i}, sig_f(m, l, k, i) * c(m - 1, l, k, i)); c.set_expression(mul_iz(m, l, k, i) + mul_fc(m, l, k, i)); computation tnh_c({m, l, k, i}, expr(o_tanh, c(m, l, k, i))); h.set_expression(tnh_c(m, l, k, i) * sig_o(m, l, k, i)); // Output is the last layer computation y({m, k, i}, h(m, NUM_LAYERS - 1, k, i)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Scheduling commands h_init.then(c_init, computation::root) .then(h_copy_x, computation::root) .then(sum_i_init, computation::root) .then(sum_z_init, l) .then(sum_o_init, l) .then(sum_f_init, l) .then(sum_i1, l) .then(sum_i2, l) .then(sum_z1, l) .then(sum_z2, l) .then(sum_o1, l) .then(sum_o2, l) .then(sum_f1, l) .then(sum_f2, l) .then(sig_i, l) .then(tnh_z, l) .then(sig_o, l) .then(sig_f, l) .then(mul_iz, l) .then(mul_fc, l) .then(c, l) .then(tnh_c, l) .then(h, l) .then(y, computation::root); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer buf_params("buf_params", {4}, p_int32, a_input); buffer buf_Weights("buf_Weights", {NUM_LAYERS, 2, 4 * FEATURE_SIZE, FEATURE_SIZE}, p_float32, a_input); buffer buf_biases("buf_biases", {NUM_LAYERS, 4 * FEATURE_SIZE}, p_float32, a_input); buffer buf_x("buf_x", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_input); buffer buf_y("buf_y", {SEQ_LENGTH, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_output); buffer buf_tmp_i("buf_tmp_i", {BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); buffer buf_tmp_z("buf_tmp_z", {BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); buffer buf_tmp_o("buf_tmp_o", {BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); buffer buf_tmp_f("buf_tmp_f", {BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); buffer buf_h("buf_h", {SEQ_LENGTH + 1, NUM_LAYERS + 1, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); buffer buf_c("buf_c", {SEQ_LENGTH + 1, NUM_LAYERS, BATCH_SIZE, FEATURE_SIZE}, p_float32, a_temporary); // store_in workaround W_i.store_in(&buf_Weights, {l, 0, i + 0 * FEATURE_SIZE, j}); W_f.store_in(&buf_Weights, {l, 0, i + 1 * FEATURE_SIZE, j}); W_z.store_in(&buf_Weights, {l, 0, i + 2 * FEATURE_SIZE, j}); W_o.store_in(&buf_Weights, {l, 0, i + 3 * FEATURE_SIZE, j}); R_i.store_in(&buf_Weights, {l, 1, i + 0 * FEATURE_SIZE, j}); R_f.store_in(&buf_Weights, {l, 1, i + 1 * FEATURE_SIZE, j}); R_z.store_in(&buf_Weights, {l, 1, i + 2 * FEATURE_SIZE, j}); R_o.store_in(&buf_Weights, {l, 1, i + 3 * FEATURE_SIZE, j}); b_i.store_in(&buf_biases, {l, i + 0 * FEATURE_SIZE}); b_f.store_in(&buf_biases, {l, i + 1 * FEATURE_SIZE}); b_z.store_in(&buf_biases, {l, i + 2 * FEATURE_SIZE}); b_o.store_in(&buf_biases, {l, i + 3 * FEATURE_SIZE}); x.store_in(&buf_x); y.store_in(&buf_y); sum_i_init.store_in(&buf_tmp_i, {k, i}); sum_z_init.store_in(&buf_tmp_z, {k, i}); sum_o_init.store_in(&buf_tmp_o, {k, i}); sum_f_init.store_in(&buf_tmp_f, {k, i}); sum_i1.store_in(&buf_tmp_i, {k, i}); sum_i2.store_in(&buf_tmp_i, {k, i}); sum_z1.store_in(&buf_tmp_z, {k, i}); sum_z2.store_in(&buf_tmp_z, {k, i}); sum_o1.store_in(&buf_tmp_o, {k, i}); sum_o2.store_in(&buf_tmp_o, {k, i}); sum_f1.store_in(&buf_tmp_f, {k, i}); sum_f2.store_in(&buf_tmp_f, {k, i}); sig_i.store_in(&buf_tmp_i, {k, i}); tnh_z.store_in(&buf_tmp_z, {k, i}); sig_o.store_in(&buf_tmp_o, {k, i}); sig_f.store_in(&buf_tmp_f, {k, i}); mul_iz.store_in(&buf_tmp_i, {k, i}); mul_fc.store_in(&buf_tmp_f, {k, i}); tnh_c.store_in(&buf_tmp_i, {k, i}); h.store_in(&buf_h, {m + 1, l + 1, k, i}); c.store_in(&buf_c, {m + 1, l, k, i}); h_init.store_in(&buf_h, {0, l + 1, k, i}); c_init.store_in(&buf_c, {0, l, k, i}); h_copy_x.store_in(&buf_h, {m + 1, 0, k, i}); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Generate object files. tiramisu::codegen({ &buf_Weights, &buf_biases, &buf_x, &buf_y, }, "lstm_ref.o"); return 0; }
44.809524
110
0.532678
[ "object" ]
d491e6bbdf46401d756c72f78405be9d962e7b10
3,405
cpp
C++
aws-cpp-sdk-appflow/source/model/SAPODataConnectorProfileProperties.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-appflow/source/model/SAPODataConnectorProfileProperties.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-appflow/source/model/SAPODataConnectorProfileProperties.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/appflow/model/SAPODataConnectorProfileProperties.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Appflow { namespace Model { SAPODataConnectorProfileProperties::SAPODataConnectorProfileProperties() : m_applicationHostUrlHasBeenSet(false), m_applicationServicePathHasBeenSet(false), m_portNumber(0), m_portNumberHasBeenSet(false), m_clientNumberHasBeenSet(false), m_logonLanguageHasBeenSet(false), m_privateLinkServiceNameHasBeenSet(false), m_oAuthPropertiesHasBeenSet(false) { } SAPODataConnectorProfileProperties::SAPODataConnectorProfileProperties(JsonView jsonValue) : m_applicationHostUrlHasBeenSet(false), m_applicationServicePathHasBeenSet(false), m_portNumber(0), m_portNumberHasBeenSet(false), m_clientNumberHasBeenSet(false), m_logonLanguageHasBeenSet(false), m_privateLinkServiceNameHasBeenSet(false), m_oAuthPropertiesHasBeenSet(false) { *this = jsonValue; } SAPODataConnectorProfileProperties& SAPODataConnectorProfileProperties::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("applicationHostUrl")) { m_applicationHostUrl = jsonValue.GetString("applicationHostUrl"); m_applicationHostUrlHasBeenSet = true; } if(jsonValue.ValueExists("applicationServicePath")) { m_applicationServicePath = jsonValue.GetString("applicationServicePath"); m_applicationServicePathHasBeenSet = true; } if(jsonValue.ValueExists("portNumber")) { m_portNumber = jsonValue.GetInteger("portNumber"); m_portNumberHasBeenSet = true; } if(jsonValue.ValueExists("clientNumber")) { m_clientNumber = jsonValue.GetString("clientNumber"); m_clientNumberHasBeenSet = true; } if(jsonValue.ValueExists("logonLanguage")) { m_logonLanguage = jsonValue.GetString("logonLanguage"); m_logonLanguageHasBeenSet = true; } if(jsonValue.ValueExists("privateLinkServiceName")) { m_privateLinkServiceName = jsonValue.GetString("privateLinkServiceName"); m_privateLinkServiceNameHasBeenSet = true; } if(jsonValue.ValueExists("oAuthProperties")) { m_oAuthProperties = jsonValue.GetObject("oAuthProperties"); m_oAuthPropertiesHasBeenSet = true; } return *this; } JsonValue SAPODataConnectorProfileProperties::Jsonize() const { JsonValue payload; if(m_applicationHostUrlHasBeenSet) { payload.WithString("applicationHostUrl", m_applicationHostUrl); } if(m_applicationServicePathHasBeenSet) { payload.WithString("applicationServicePath", m_applicationServicePath); } if(m_portNumberHasBeenSet) { payload.WithInteger("portNumber", m_portNumber); } if(m_clientNumberHasBeenSet) { payload.WithString("clientNumber", m_clientNumber); } if(m_logonLanguageHasBeenSet) { payload.WithString("logonLanguage", m_logonLanguage); } if(m_privateLinkServiceNameHasBeenSet) { payload.WithString("privateLinkServiceName", m_privateLinkServiceName); } if(m_oAuthPropertiesHasBeenSet) { payload.WithObject("oAuthProperties", m_oAuthProperties.Jsonize()); } return payload; } } // namespace Model } // namespace Appflow } // namespace Aws
22.401316
102
0.761821
[ "model" ]
d49600ef6d6bfab80fa342d0690873d6616d717e
15,468
cc
C++
src/reporter.cc
ronilan/appoptics-bindings-node
3012b8a767b0c94a9532bfc5ca2d97b2832b9cb3
[ "Apache-2.0" ]
null
null
null
src/reporter.cc
ronilan/appoptics-bindings-node
3012b8a767b0c94a9532bfc5ca2d97b2832b9cb3
[ "Apache-2.0" ]
22
2018-08-29T22:19:44.000Z
2022-02-11T02:28:20.000Z
src/reporter.cc
ronilan/appoptics-bindings-node
3012b8a767b0c94a9532bfc5ca2d97b2832b9cb3
[ "Apache-2.0" ]
5
2019-02-27T22:42:03.000Z
2021-12-18T00:18:59.000Z
#include "bindings.h" #include <vector> int64_t get_integer(Napi::Object, const char*, int64_t = 0); std::string* get_string(Napi::Object, const char*, const char* = ""); bool get_boolean(Napi::Object obj, const char*, bool = false); int send_event_x(const Napi::CallbackInfo&, int); Napi::Value send_span(const Napi::CallbackInfo&, send_generic_span_t send_function); // // send a span using oboe_http_span // Napi::Value sendHttpSpan(const Napi::CallbackInfo& info) { return send_span(info, oboe_http_span); } // // send a metrics span using oboe_span // Napi::Value sendNonHttpSpan(const Napi::CallbackInfo& info) { return send_span(info, oboe_span); } // // do all the work to send a span // Napi::Value send_span(const Napi::CallbackInfo& info, send_generic_span_t send_function) { Napi::Env env = info.Env(); if (info.Length() != 1 || !info[0].IsObject()) { Napi::TypeError::New(env, "sendXSpan() - requires Object parameter").ThrowAsJavaScriptException(); return env.Null(); } Napi::Object obj = info[0].ToObject(); oboe_span_params_t args; args.version = 1; // Number.MAX_SAFE_INTEGER is big enough for any reasonable transaction time. // max_safe_seconds = MAX_SAFE_INTEGER / 1000000 microseconds // max_safe_days = max_safe_seconds / 86400 seconds // max_safe_days > 100000. Seems long enough to me. args.duration = get_integer(obj, "duration"); args.has_error = get_boolean(obj, "error", false); args.status = get_integer(obj, "status"); // REMEMBER TO FREE ALL RETURNED STD::STRINGS AFTER PASSING // THEM TO OBOE. std::string* txname = get_string(obj, "txname"); args.transaction = txname->c_str(); std::string* url = get_string(obj, "url"); args.url = url->c_str(); std::string* domain = get_string(obj, "domain"); args.domain = domain->c_str(); std::string* method = get_string(obj, "method"); args.method = method->c_str(); std::string* service = get_string(obj, "service"); args.service = service->c_str(); char final_txname[OBOE_TRANSACTION_NAME_MAX_LENGTH + 1]; int length = send_function(final_txname, sizeof(final_txname), &args); // don't forget to FREE STRINGS CREATED by get_string(). delete txname; delete url; delete domain; delete method; delete service; // if an error return the code. if (length < 0) { return Napi::Number::New(env, length); } // return the transaction name used so it can be used by the agent. return Napi::String::New(env, final_txname); } enum SMFlags { kSMFlagsTesting = 1 << 0, kSMFlagsNoop = 1 << 1 }; // // internal function used by sendMetric() (deprecated) and sendMetrics(). // Napi::Value send_metrics_core (Napi::Env env, Napi::Array metrics, uint64_t flags) { int64_t goodCount = 0; const char* service_name = ""; bool testing = flags & kSMFlagsTesting; bool noop = flags & kSMFlagsNoop; Napi::Array errors = Napi::Array::New(env); Napi::Array echo; Napi::Object echoTags; if (testing) { echo = Napi::Array::New(env); } // // loop through each metric and send if valid else // report back in errors array. // for (size_t i = 0; i < metrics.Length(); i++) { bool is_summary = false; std::string name; int64_t count; double value = 0; bool add_host_tag = false; Napi::Value element = metrics[i]; // little lambda for errors. auto set_error = [&](const char* code) { Napi::Object err = Napi::Object::New(env); err.Set("code", code); err.Set("metric", element); errors[errors.Length()] = err; }; if (!element.IsObject() || element.IsArray()) { set_error("metric must be plain object"); continue; } Napi::Object metric = element.As<Napi::Object>(); // make sure there is a string name. valid characters if // choosing to add in the future: ‘A-Za-z0-9.:-_’. if (!metric.Has("name") || !metric.Get("name").IsString()) { set_error("must have string name"); continue; } name = metric.Get("name").As<Napi::String>(); // and a numeric count if (!metric.Has("count")) { count = 1; } else { Napi::Value c = metric.Get("count"); if (!c.IsNumber()) { set_error("count must be a number"); continue; } count = c.As<Napi::Number>().DoubleValue(); if (count <= 0) { set_error("count must be greater than 0"); continue; } } // if there is a value it's a summary metric if (metric.Has("value")) { Napi::Value v = metric.Get("value"); if (!v.IsNumber()) { set_error("summary value must be numeric"); continue; } is_summary = true; value = v.As<Napi::Number>().DoubleValue(); } if (metric.Has("addHostTag")) { add_host_tag = metric.Get("addHostTag").ToBoolean(); } // // handle tags // size_t tag_count = 0; Napi::Object tags; Napi::Array keys; if (metric.Has("tags")) { Napi::Value v = metric.Get("tags"); if (!v.IsObject() || v.IsArray()) { set_error("tags must be plain object"); continue; } tags = v.As<Napi::Object>(); keys = tags.GetPropertyNames(); tag_count = keys.Length(); if (testing) { echoTags = Napi::Object::New(env); } } // allocate oboe's key-value pair structure oboe_metric_tag_t otags[tag_count]; // save all the tag strings so they won't go out of scope std::vector<std::string> holdKeys(tag_count); std::vector<std::string> holdValues(tag_count); bool had_error = false; size_t n = 0; while (n < tag_count) { Napi::Value key = keys[n]; holdKeys[n] = key.ToString(); Napi::Value value = tags.Get(keys[n]); holdValues[n] = value.ToString(); // i don't know how ToString() can fail but the doc says // it can so let's try to handle it. if (env.IsExceptionPending()) { Napi::Error error = env.GetAndClearPendingException(); had_error = true; break; } otags[n].key = (char*)holdKeys[n].c_str(); otags[n].value = (char*)holdValues[n].c_str(); if (testing) { echoTags.Set(holdKeys[n], holdValues[n]); } n += 1; } if (had_error) { set_error("string conversion of value failed"); continue; } int status; if (noop) { status = 0; } else { if (is_summary) { status = oboe_custom_metric_summary(name.c_str(), value, count, add_host_tag, service_name, otags, tag_count); } else { status = oboe_custom_metric_increment(name.c_str(), count, add_host_tag, service_name, otags, tag_count); } } // oboe returns 0 for success else a status code; if (status != 0) { std::string error_msg = "metric send failed: " + std::to_string(status); set_error(error_msg.c_str()); continue; } // everything is set at this point goodCount += 1; // if testing also return metrics that were sent. if (testing) { Napi::Object m = Napi::Object::New(env); m.Set("name", Napi::String::New(env, name)); m.Set("count", Napi::Number::New(env, count)); if (is_summary) { m.Set("value", Napi::Number::New(env, value)); } m.Set("addHostTag", Napi::Boolean::New(env, add_host_tag)); if (tag_count > 0) { m.Set("tags", echoTags); } echo[echo.Length()] = m; } } Napi::Object result = Napi::Object::New(env); result.Set("errors", errors); if (testing) { result.Set("correct", echo); } return result; } // // javascript // // sendMetrics(globalOptions, metrics) returns {status, errorMetrics[]} // // globalOptions - object // globalOptions.addHostTag - boolean - add {host: hostname} to tags // globalOptions.tags - tags which are sent with each metric, individual tags // override // like: // tags = Object.assign({}, globalTags, individualMetricTags); // // metrics - array of metrics to send // metric - each element of metrics is an object: // metric.name - name of the metric // metric.count - number of observations being reported // metric.value - if present this is a "summary" metric. if not it is an // "increment" metric. contains the value, or sum of the // values if count is greater than 1. // metric.addHostTag - boolean (overrides options.addHostTag if present) // metric.tags - object of {tag: value} pairs. // // // c++ - process an array of metrics each with a fully specified set of tags // // aob.reporter.sendMetrics(increments, summaries) // Napi::Value sendMetrics(const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); // check args if (info.Length() < 1 || !info[0].IsArray()) { Napi::TypeError::New(env, "invalid signature for sendMetrics()") .ThrowAsJavaScriptException(); return env.Undefined(); } // allow some testing uint64_t flags = 0; if (info.Length() == 2 && info[1].IsObject()) { Napi::Object options = info[1].As<Napi::Object>(); if (options.Get("testing").ToBoolean()) flags |= kSMFlagsTesting; if (options.Get("noop").ToBoolean()) flags |= kSMFlagsNoop; } Napi::Array metrics = info[0].As<Napi::Array>(); return send_metrics_core(env, metrics, flags); } // // sendMetric(name, object) // // only the first argument is required for an increment call. // // name - the name of the metric // object - an object containing optional parameters // object.count - the number of observations being reported (default: 1) // object.addHostTag - boolean - {host: hostname} to tags. // object.tags - an object containing {tag: value} pairs. // object.value - if present this call is a valued-based call and this contains // the value, or sum of values if count is greater than 1, being // reported. // // there are two types of metrics: // 1) count-based - the number of times something has occurred (no value associated with this metric) // 2) value-based - a specific value is being reported (or a sum of values) // // simplest forms: // sendMetric('my.little.count') // sendMetric('my.little.value', {value: 234.7}) // // to report two observations: // sendMetric('my.little.count', {count: 2}) // sendMetric('my.little.value', {count: 2, value: 469.4}) // // to supply tags that can be used for filtering: // sendMetric('my.little.count', {tags: {status: error}}) // // to add a host name tag: // sendMetric('my.little.count', {addHostTag: true, tags: {status: error}}) // // returns -1 for success else error code. the only error now is 0. // Napi::Value sendMetric (const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); // check args if (info.Length() == 0) { Napi::TypeError::New(env, "sendMetric() requires 1 or 2 arguments") .ThrowAsJavaScriptException(); return env.Null(); } else if (!info[0].IsString()) { Napi::TypeError::New(env, "sendMetric(name) name argument must be a string") .ThrowAsJavaScriptException(); return env.Null(); } // default the options object if not supplied Napi::Object o; if (info.Length() == 1) { o = Napi::Object::New(env); } else if (info[1].IsObject() && !info[1].IsArray()) { o = info[1].ToObject(); } else { Napi::TypeError::New(env, "sendMetric(name, params) params must be a plain object") .ThrowAsJavaScriptException(); return env.Null(); } Napi::Object metric = Napi::Object::New(env); // name metric.Set("name", info[0]); // count int count = 1; Napi::Value v = o.Get("count"); if (v.IsNumber()) { count = v.As<Napi::Number>().Int64Value(); } metric.Set("count", count); // value double value = 0; if (o.Has("value")) { v = o.Get("value"); if (!v.IsNumber()) { Napi::TypeError::New(env, "sendMetric options.value must be a number") .ThrowAsJavaScriptException(); return env.Null(); } value = v.As<Napi::Number>().DoubleValue(); metric.Set("value", value); } // host_tag if (o.Has("addHostTag")) { metric.Set("addHostTag", o.Get("addHostTag")); } // tags if (o.Has("tags")) { v = o.Get("tags"); if (!v.IsObject() || v.IsArray()) { Napi::TypeError::New(env, "sendMetric() tags must be a plain object") .ThrowAsJavaScriptException(); return env.Null(); } metric.Set("tags", v); } int64_t flags = 0; // noop - don't call oboe if set. if (o.Get("noop").ToBoolean().Value()) flags |= kSMFlagsNoop; Napi::Array metrics_array = Napi::Array::New(env, 1); metrics_array[(uint32_t)0] = metric; Napi::Value result = send_metrics_core(env, metrics_array, flags); // if unexpected results don't know what to do. if (!result.IsObject()) { return Napi::Number::New(env, 0); } Napi::Object robj = result.As<Napi::Object>(); int error = 0; if (robj.Has("errors")) { Napi::Value errors = robj.Get("errors"); if (errors.IsArray()) { Napi::Array error_array = errors.As<Napi::Array>(); if (error_array.Length()) { error = -1; } } } return Napi::Number::New(env, -error); } // // lambda additions // Napi::Value flush (const Napi::CallbackInfo& info) { int status = oboe_reporter_flush(); // {OK: 0, TOO_BIG: 1, BAD_UTF8: 2, NO_REPORTER: 3, NOT_READY: 4} return Napi::Number::New(info.Env(), status); } Napi::Value getType (const Napi::CallbackInfo& info) { Napi::Env env = info.Env(); const char* type = oboe_get_reporter_type(); if (!type) { return env.Undefined(); } return Napi::String::New(env, type); } // // Initialize the module. // namespace Reporter { Napi::Object Init(Napi::Env env, Napi::Object exports) { Napi::HandleScope scope(env); Napi::Object module = Napi::Object::New(env); module.Set("sendHttpSpan", Napi::Function::New(env, sendHttpSpan)); module.Set("sendNonHttpSpan", Napi::Function::New(env, sendNonHttpSpan)); module.Set("sendMetric", Napi::Function::New(env, sendMetric)); module.Set("sendMetrics", Napi::Function::New(env, sendMetrics)); module.Set("flush", Napi::Function::New(env, flush)); module.Set("getType", Napi::Function::New(env, getType)); exports.Set("Reporter", module); return exports; } } // // Helpers // // given an object and a key, if object.key matches the expected type, return the // appropriate value. if object.key doesn't match the expected type return a default // value. // // // return an integer // int64_t get_integer(Napi::Object obj, const char* key, int64_t default_value) { Napi::Value v = obj.Get(key); if (v.IsNumber()) { return v.As<Napi::Number>().Int64Value(); } return default_value; } // // returns a new std::string that MUST BE DELETED. // std::string* get_string(Napi::Object obj, const char* key, const char* default_value) { Napi::Value v = obj.Get(key); if (v.IsString()) { return new std::string(v.As<Napi::String>()); } return new std::string(default_value); } // // return a boolean // bool get_boolean(Napi::Object obj, const char* key, bool default_value) { Napi::Value v = obj.Get(key); if (v.IsBoolean()) { return v.As<Napi::Boolean>().Value(); } return default_value; }
28.226277
104
0.622576
[ "object", "vector" ]
d496eab0096cb508471d7ea2d5a10861854cb9f4
1,281
hpp
C++
BrowserPopupDlg.hpp
thulya/iedrip
37451c307ba9999e35083be769d34d32c8dbd93c
[ "Unlicense" ]
null
null
null
BrowserPopupDlg.hpp
thulya/iedrip
37451c307ba9999e35083be769d34d32c8dbd93c
[ "Unlicense" ]
null
null
null
BrowserPopupDlg.hpp
thulya/iedrip
37451c307ba9999e35083be769d34d32c8dbd93c
[ "Unlicense" ]
null
null
null
#pragma once #include "resource.h" #include "BrowserHostDlg.hpp" // forward declaration class JSHook; // CBrowserPopupDlg dialog class CBrowserPopupDlg : public CBrowserHostDlg { private: CComObject<JSHook>* m_hook; void repositionExplorer(); DECLARE_DYNAMIC(CBrowserPopupDlg) public: CBrowserPopupDlg(CComObject<JSHook>* hook, std::vector<CBrowserPopupDlg*> *popups, CWnd* pParent = NULL); // standard constructor virtual ~CBrowserPopupDlg(); void createPopup(LPDISPATCH* ppDisp); bool isFinished(); void requestClose(); // Dialog Data enum { IDD = IDD_BROWSER_POPUP_DIALOG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support DECLARE_MESSAGE_MAP() afx_msg BOOL OnInitDialog(); afx_msg void OnSize(UINT nType, int cx, int cy); virtual CComObject<JSHook>* getHook(); virtual bool isHookActive(); virtual void onTitleChange(LPCTSTR lpszText); virtual void onWindowSetHeight(long height); virtual void onWindowSetWidth(long width); virtual void onOuterDocumentLoad(MSHTML::IHTMLDocument2Ptr doc); virtual void onNewWindow(CBrowserHostDlg** ppDlg); virtual void onClosing(); std::vector<CBrowserPopupDlg*> *m_popups; bool m_waitingForBlankDoc, m_isFinished; };
25.117647
133
0.742389
[ "vector" ]
d49a2bca02a83738555dcb9f24b46aa3bc597208
2,447
cc
C++
components/service/ucloud/live/src/model/CreateMixStreamRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
components/service/ucloud/live/src/model/CreateMixStreamRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
components/service/ucloud/live/src/model/CreateMixStreamRequest.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/live/model/CreateMixStreamRequest.h> using AlibabaCloud::Live::Model::CreateMixStreamRequest; CreateMixStreamRequest::CreateMixStreamRequest() : RpcServiceRequest("live", "2016-11-01", "CreateMixStream") { setMethod(HttpRequest::Method::Post); } CreateMixStreamRequest::~CreateMixStreamRequest() {} std::string CreateMixStreamRequest::getOutputConfig()const { return outputConfig_; } void CreateMixStreamRequest::setOutputConfig(const std::string& outputConfig) { outputConfig_ = outputConfig; setParameter("OutputConfig", outputConfig); } std::string CreateMixStreamRequest::getLayoutId()const { return layoutId_; } void CreateMixStreamRequest::setLayoutId(const std::string& layoutId) { layoutId_ = layoutId; setParameter("LayoutId", layoutId); } std::string CreateMixStreamRequest::getDomainName()const { return domainName_; } void CreateMixStreamRequest::setDomainName(const std::string& domainName) { domainName_ = domainName; setParameter("DomainName", domainName); } std::string CreateMixStreamRequest::getInputStreamList()const { return inputStreamList_; } void CreateMixStreamRequest::setInputStreamList(const std::string& inputStreamList) { inputStreamList_ = inputStreamList; setParameter("InputStreamList", inputStreamList); } long CreateMixStreamRequest::getOwnerId()const { return ownerId_; } void CreateMixStreamRequest::setOwnerId(long ownerId) { ownerId_ = ownerId; setParameter("OwnerId", std::to_string(ownerId)); } std::string CreateMixStreamRequest::getCallbackConfig()const { return callbackConfig_; } void CreateMixStreamRequest::setCallbackConfig(const std::string& callbackConfig) { callbackConfig_ = callbackConfig; setParameter("CallbackConfig", callbackConfig); }
25.489583
84
0.760114
[ "model" ]
d49df7218c2ee5b32c15acf8f87668b118f9c157
74,446
cpp
C++
Server Lib/Game Server/SESSION/player.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
null
null
null
Server Lib/Game Server/SESSION/player.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
null
null
null
Server Lib/Game Server/SESSION/player.cpp
eantoniobr/SuperSS-Dev
f57c094f164cc90c2694df33ba394304cd0e7846
[ "MIT" ]
1
2021-11-03T00:21:07.000Z
2021-11-03T00:21:07.000Z
// Arquivo player.cpp // Criado em 07/03/2018 as 22:03 por Acrisio // Implementação da classe player Polimofismo #if defined(_WIN32) #pragma pack(1) #endif #if defined(_WIN32) #include <WinSock2.h> #endif #include "player.hpp" #include "../../Projeto IOCP/UTIL/exception.h" #include "../../Projeto IOCP/TYPE/stda_error.h" #include "../../Projeto IOCP/UTIL/message_pool.h" #include "../GAME/mail_box_manager.hpp" #include "../GAME/item_manager.h" #include "../PANGYA_DB/cmd_player_info.hpp" #include "../PANGYA_DB/cmd_update_caddie_info.hpp" #include "../PANGYA_DB/cmd_update_mascot_info.hpp" #include "../../Projeto IOCP/PANGYA_DB/cmd_update_character_equiped.hpp" #include "../PANGYA_DB/cmd_update_item_slot.hpp" #include "../PANGYA_DB/cmd_update_caddie_equiped.hpp" #include "../PANGYA_DB/cmd_update_ball_equiped.hpp" #include "../PANGYA_DB/cmd_update_clubset_equiped.hpp" #include "../PANGYA_DB/cmd_update_mascot_equiped.hpp" #include "../PANGYA_DB/cmd_update_character_cutin_equiped.hpp" #include "../PANGYA_DB/cmd_update_skin_equiped.hpp" #include "../PANGYA_DB/cmd_update_poster_equiped.hpp" #include "../PANGYA_DB/cmd_update_character_all_part_equiped.hpp" #include "../PANGYA_DB/cmd_insert_cp_log.hpp" #include "../PANGYA_DB/cmd_insert_cp_log_item.hpp" #include "../../Projeto IOCP/DATABASE/normal_manager_db.hpp" #include "../GAME/premium_system.hpp" #include "../PACKET/packet_func_sv.h" using namespace stdA; player::player(threadpool_base& _threadpool) : session(_threadpool), m_pi(), m_gi() #if STDA_BLOCK_PACKET_ONE_TIME_DISABLE != 0x1 , m_sbeopt(nullptr) #endif { }; player::~player() { #if STDA_BLOCK_PACKET_ONE_TIME_DISABLE != 0x1 && STDA_BLOCK_PACKET_ONE_TIME_VER == 0x2 if (m_sbeopt != nullptr) delete m_sbeopt; m_sbeopt = nullptr; #endif }; bool player::clear() { bool ret = true; if ((ret = session::clear())) { // Block Packet Exec One Per Time #if STDA_BLOCK_PACKET_ONE_TIME_DISABLE != 0x1 && STDA_BLOCK_PACKET_ONE_TIME_VER == 0x2 if (m_sbeopt != nullptr) delete m_sbeopt; m_sbeopt = nullptr; #elif STDA_BLOCK_PACKET_ONE_TIME_DISABLE != 0x1 sSyncBlockExecOnePerTime::getInstance().removePlayer(m_pi.uid); #endif // Player Info m_pi.clear(); // Game Master Info m_gi.clear(); // Game Guard m_gg.m_auth_reply = false; m_gg.m_auth_time = 0; m_gg.m_csa.Close(); } return ret; }; unsigned char player::getStateLogged() { return m_pi.m_state_logged; }; uint32_t player::getUID() { return m_pi.uid; }; uint32_t player::getCapability() { return m_pi.m_cap.ulCapability; }; char* player::getNickname() { return m_pi.nickname; }; char* player::getID() { return m_pi.id; }; void player::addExp(uint32_t _exp, bool _upt_on_game) { if (_exp == 0) throw exception("[player::addExp][Error] _exp is invalid(zero)", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 1, 0)); try { // UPDATE ON GAME packet p; int ret = -1; if ((ret = m_pi.addExp(_exp)) >= 0) { if (ret > 0) { // Player Upou de level std::vector< stItem > v_item; stItem item{ 0 }; BuyItem bi{ 0 }; auto level_prize = sIff::getInstance().getLevelUpPrizeItem(); for (auto i = (m_pi.mi.level - ret + 1); i <= m_pi.mi.level; ++i) { // Zera o vector de item que vai ser enviado por level UP! para o mail box do player v_item.clear(); auto it = level_prize.end(); if ((it = level_prize.find(i)) == level_prize.end()) throw exception("[player::addExp][ErrorSystem] player[UID=" + std::to_string(m_pi.uid) + "] addExp, mas nao encontrou o level up prize[level=" + std::to_string(i) + "] no IFF_STRUCT do server", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2, 0)); for (auto ii = 0u; ii < (sizeof(it->second.reward._typeid) / sizeof(it->second.reward._typeid[0])); ++ii) { if (it->second.reward._typeid[ii] != 0) { bi.clear(); item.clear(); bi.id = -1; bi._typeid = it->second.reward._typeid[ii]; bi.qntd = it->second.reward.qntd[ii]; bi.time = (unsigned short)it->second.reward.time[ii]; item_manager::initItemFromBuyItem(m_pi, item, bi, false, 0, 0, 1/*não checar o level*/); if (item._typeid == 0) throw exception("[player::addExp][ErrorSystem] player[UID=" + std::to_string(m_pi.uid) + "] addExp, mas nao conseguiu inicializar o item[TYPEID=" + std::to_string(bi._typeid) + "]", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 3, 0)); v_item.push_back(item); } } auto msg = std::string("Level UP! Prize."); // Envia Prêmio de Level UP! para o Mail Box do player MailBoxManager::sendMessageWithItem(0, m_pi.uid, msg, v_item); } // Mostra msg que o player Upou de level p.init_plain((unsigned short)0x10F); p.addUint32(0); // OK p.addUint8((unsigned char)ret); // Qntd de level(s) que ele upou p.addUint8((unsigned char)m_pi.mi.level); // Novo level que o player ficou packet_func::session_send(p, this, 1); } } // Att Level e Exp do player IN GAME if (_upt_on_game) { // Só att se for pegando do mail ou ticket report esses negocio, por que jogando vs/tourney, nao precisa desse pacote p.init_plain((unsigned short)0x1D9); p.addUint32(m_pi.mi.level); p.addUint32(m_pi.ui.exp); packet_func::session_send(p, this, 1); } }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::addExp][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::PLAYER_INFO) throw; } }; void player::addCaddieExp(uint32_t _exp) { if (_exp == 0) throw exception("[player::addCaddieExp][Error] player[UID=" + std::to_string(m_pi.uid) + "] tentou adicionar mais exp[VALUE=" + std::to_string(_exp) + "] ao caddie equipado, mas exp is invalid(zero).", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 300, 0)); if (m_pi.ei.cad_info == nullptr) throw exception("[player::addCaddieExp][Error] player[UID=" + std::to_string(m_pi.uid) + "] tentou adicionar mais exp[VALUE=" + std::to_string(_exp) + "] ao caddie equipado, mas ele nao esta com nenhum caddie equipado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 301, 0)); #define CALC_CADDIE_EXP_LEVEL(_level) 520 + (160 * (_level)) #define LIMIT_LEVEL_CADDIE 3 // Só add Exp se não estiver no ultimo level do Caddie if (m_pi.ei.cad_info->level < LIMIT_LEVEL_CADDIE) { m_pi.ei.cad_info->exp += _exp; uint32_t exp_level = 0u; bool upou = false; while (m_pi.ei.cad_info->level < LIMIT_LEVEL_CADDIE && m_pi.ei.cad_info->exp >= (exp_level = CALC_CADDIE_EXP_LEVEL(m_pi.ei.cad_info->level))) { // Upou 1 Level m_pi.ei.cad_info->level++; m_pi.ei.cad_info->exp -= exp_level; upou = true; } // UPDATE ON DB NormalManagerDB::add(1, new CmdUpdateCaddieInfo(m_pi.uid, *m_pi.ei.cad_info), player::SQLDBResponse, this); // LOG _smp::message_pool::getInstance().push(new message("[player::addCaddieExp][Log] player[UID=" + std::to_string(m_pi.uid) + "] add Exp para o Caddie[TYPEID=" + std::to_string(m_pi.ei.cad_info->_typeid) + ", ID=" + std::to_string(m_pi.ei.cad_info->id) + ", LEVEL=" + std::to_string((unsigned short)m_pi.ei.cad_info->level + 1/*Visual*/) + ", EXP=" + std::to_string(m_pi.ei.cad_info->exp) + "]" + (upou ? " Upou de Level!" : ""), CL_FILE_LOG_AND_CONSOLE)); } }; void player::addMascotExp(uint32_t _exp) { if (_exp == 0) throw exception("[player::addMascotExp][Error] player[UID=" + std::to_string(m_pi.uid) + "] tentou adicionar mais exp[VALUE=" + std::to_string(_exp) + "] ao mascot equipado, mas exp is invalid(zero).", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 400, 0)); if (m_pi.ei.mascot_info == nullptr) throw exception("[player::addMascotExp][Error] player[UID=" + std::to_string(m_pi.uid) + "] tentou adicionar mais exp[VALUE=" + std::to_string(_exp) + "] ao mascot equipado, mas ele nao esta com nenhum mascot equipado.", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 401, 0)); // Progressão aritmética de segunda ordem #define CALC_MASCOT_EXP_LEVEL(_level) 50/*Base*/ + ((20 + (20 + ((_level) - 1) * 10)) * (_level) / 2) #define LIMIT_LEVEL_MASCOT 9 // Só add Exp se não estiver no ultimo level do Mascot if (m_pi.ei.mascot_info->level < LIMIT_LEVEL_MASCOT) { m_pi.ei.mascot_info->exp += _exp; uint32_t exp_level = 0u; bool upou = false; while (m_pi.ei.mascot_info->level < LIMIT_LEVEL_MASCOT && m_pi.ei.mascot_info->exp >= (exp_level = CALC_MASCOT_EXP_LEVEL(m_pi.ei.mascot_info->level))) { // Upou 1 Level m_pi.ei.mascot_info->level++; m_pi.ei.mascot_info->exp -= exp_level; upou = true; } // UPDATE ON DB NormalManagerDB::add(2, new CmdUpdateMascotInfo(m_pi.uid, *m_pi.ei.mascot_info), player::SQLDBResponse, this); // LOG _smp::message_pool::getInstance().push(new message("[player::addMascotExp][Log] player[UID=" + std::to_string(m_pi.uid) + "] add Exp para o Mascot[TYPEID=" + std::to_string(m_pi.ei.mascot_info->_typeid) + ", ID=" + std::to_string(m_pi.ei.mascot_info->id) + ", LEVEL=" + std::to_string((unsigned short)m_pi.ei.mascot_info->level + 1/*visual*/) + ", EXP=" + std::to_string(m_pi.ei.mascot_info->exp) + "]" + (upou ? " Upou de Level!" : ""), CL_FILE_LOG_AND_CONSOLE)); } }; void player::addExp(uint32_t _uid, uint32_t _exp) { if (_exp == 0) throw exception("[player::addExp][Error] _exp is invalid(zero)", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 1, 0)); PlayerInfo *pi = nullptr; packet *p = nullptr; try { int ret = -1; CmdPlayerInfo cmd_pi(_uid, true); // Waiter NormalManagerDB::add(0, &cmd_pi, nullptr, nullptr); cmd_pi.waitEvent(); if (cmd_pi.getException().getCodeError() != 0) throw cmd_pi.getException(); pi = new PlayerInfo(); *(player_info*)pi = cmd_pi.getInfo(); if ((ret = pi->addExp(_exp)) >= 0) { // UPDATE ON GAME p = new packet(); if (ret > 0) { // Player Upou de level std::vector< stItem > v_item; stItem item{ 0 }; BuyItem bi{ 0 }; auto level_prize = sIff::getInstance().getLevelUpPrizeItem(); for (auto i = (pi->mi.level - ret + 1); i <= pi->mi.level; ++i) { // Zera o vector de item que vai ser enviado por level UP! para o mail box do player v_item.clear(); auto it = level_prize.end(); if ((it = level_prize.find(i)) == level_prize.end()) throw exception("[player::addExp][ErrorSystem] player[UID=" + std::to_string(pi->uid) + "] addExp, mas nao encontrou o level up prize[level=" + std::to_string(i) + "] no IFF_STRUCT do server", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2, 0)); for (auto ii = 0u; ii < (sizeof(it->second.reward._typeid) / sizeof(it->second.reward._typeid[0])); ++ii) { if (it->second.reward._typeid[ii] != 0) { bi.clear(); item.clear(); bi.id = -1; bi._typeid = it->second.reward._typeid[ii]; bi.qntd = it->second.reward.qntd[ii]; bi.time = (unsigned short)it->second.reward.time[ii]; item_manager::initItemFromBuyItem(*pi, item, bi, false, 0, 0, 1/*não checar o level*/); if (item._typeid == 0) throw exception("[player::addExp][ErrorSystem] player[UID=" + std::to_string(pi->uid) + "] addExp, mas nao conseguiu inicializar o item[TYPEID=" + std::to_string(bi._typeid) + "]", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 3, 0)); v_item.push_back(item); } } auto msg = std::string("Level UP! Prize."); // Envia Prêmio de Level UP! para o Mail Box do player MailBoxManager::sendMessageWithItem(0, pi->uid, msg, v_item); } } } }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::addExp][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); // Clean if (pi != nullptr) { delete pi; pi = nullptr; } if (p != nullptr) { delete p; p = nullptr; } if (STDA_SOURCE_ERROR_DECODE(e.getCodeError()) != STDA_ERROR_TYPE::PLAYER_INFO) throw; } // Clean if (pi != nullptr) { delete pi; pi = nullptr; } if (p != nullptr) { delete p; p = nullptr; } }; void player::addPang(uint64_t _pang) { m_pi.addPang(_pang); // UPDATE ON GAME packet p((unsigned short)0xC8); p.addUint64(m_pi.ui.pang); p.addUint64(_pang); packet_func::session_send(p, this, 1); }; void player::consomePang(uint64_t _pang) { m_pi.consomePang(_pang); // UPDATE ON GAME packet p((unsigned short)0xC8); p.addUint64(m_pi.ui.pang); p.addUint64(_pang); packet_func::session_send(p, this, 1); }; void player::addCookie(uint64_t _cookie) { m_pi.addCookie(_cookie); // UPDATE ON GAME packet p((unsigned short)0x96); p.addQWord(&m_pi.cookie); packet_func::session_send(p, this, 1); }; void player::consomeCookie(uint64_t _cookie) { m_pi.consomeCookie(_cookie); // UPDATE ON GAME packet p((unsigned short)0x96); p.addQWord(&m_pi.cookie); packet_func::session_send(p, this, 1); }; void player::addMoeda(uint64_t _pang, uint64_t _cookie) { addPang(_pang); addCookie(_cookie); }; void player::consomeMoeda(uint64_t _pang, uint64_t _cookie) { consomePang(_pang); consomeCookie(_cookie); }; void player::saveCPLog(CPLog& _cp_log) { auto cp = _cp_log.getCookie(); try { if (cp > 0ull) { int64_t log_id = -1ll; CmdInsertCPLog cmd_icpl(m_pi.uid, _cp_log, true); // Waiter NormalManagerDB::add(0, &cmd_icpl, nullptr, nullptr); cmd_icpl.waitEvent(); if (cmd_icpl.getException().getCodeError() != 0) throw cmd_icpl.getException(); if ((log_id = cmd_icpl.getId()) <= 0) throw exception("[player::saveCPLog][Error] Player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu salvar o CPLog[" + _cp_log.toString() + "] do player. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 1300, 0)); if ((_cp_log.getType() == CPLog::TYPE::BUY_SHOP || _cp_log.getType() == CPLog::TYPE::GIFT_SHOP) && _cp_log.getItemCount() > 0) { // Tem item(ns), salva o log do(s) item(ns) for (auto& el : _cp_log.getItens()) NormalManagerDB::add(3, new CmdInsertCPLogItem(m_pi.uid/*Para Log, não usa no Proc do DB*/, log_id, el), player::SQLDBResponse, this); } } }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::saveCPLog][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } }; void player::saveCPLog(uint32_t _uid, CPLog& _cp_log) { if (_uid == 0u) throw exception("[player::saveCPLog(static)][Error] _uid is invalid(" + std::to_string(_uid) + ")", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 1301, 0)); auto cp = _cp_log.getCookie(); try { if (cp > 0ull) { int64_t log_id = -1ll; CmdInsertCPLog cmd_icpl(_uid, _cp_log, true); // Waiter NormalManagerDB::add(0, &cmd_icpl, nullptr, nullptr); cmd_icpl.waitEvent(); if (cmd_icpl.getException().getCodeError() != 0) throw cmd_icpl.getException(); if ((log_id = cmd_icpl.getId()) <= 0) throw exception("[player::saveCPLog(static)][Error] Player[UID=" + std::to_string(_uid) + "] nao conseguiu salvar o CPLog[" + _cp_log.toString() + "] do player. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 1300, 0)); if ((_cp_log.getType() == CPLog::TYPE::BUY_SHOP || _cp_log.getType() == CPLog::TYPE::GIFT_SHOP) && _cp_log.getItemCount() > 0) { // Tem item(ns), salva o log do(s) item(ns) for (auto& el : _cp_log.getItens()) NormalManagerDB::add(3, new CmdInsertCPLogItem(_uid/*Para Log, não usa no Proc do DB*/, log_id, el), player::SQLDBResponse, nullptr); } } }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::saveCPLog(static)][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } }; bool player::checkCharacterEquipedPart(CharacterInfo& ci) { uint32_t def_part = 0u; // Angel Part of character 3% quit rate para equipar o Normal angel wings auto angel_wings_typeid = std::find_if(angel_wings, LAST_ELEMENT_IN_ARRAY(angel_wings), [&](auto& el) { return (sIff::getInstance().getItemCharIdentify(el) == (ci._typeid & 0x000000FF)); }); int32_t angel_wings_part_num = (angel_wings_typeid == LAST_ELEMENT_IN_ARRAY(angel_wings) ? -1 : sIff::getInstance().getItemCharPartNumber(*angel_wings_typeid)); bool upt_on_db = false; // Checks Parts Equiped for (auto i = 0u; i < (sizeof(ci.parts_typeid) / sizeof(ci.parts_typeid[0])); ++i) { if (ci.parts_typeid[i] != 0) { if (sIff::getInstance().getItemGroupIdentify(ci.parts_typeid[i]) == iff::PART && (sIff::getInstance().getItemCharPartNumber(ci.parts_typeid[i]) == i || (ci.parts_typeid[i] & 0x08000400/*def part*/) == 0x8000400)) { auto part = sIff::getInstance().findPart(ci.parts_typeid[i]); if (part != nullptr && part->active) { if (ci.parts_id[i] == 0) { def_part = ((sIff::getInstance().getItemCharPartNumber(ci.parts_typeid[i]) | (uint32_t)(ci._typeid << 5)) << 13) | 0x8000400; if ((ci.parts_typeid[i] & def_part) == def_part) { #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + (ci.parts_typeid[i] & 0x00000200/*sub*/ ? std::string(" Sub") : std::string("")) + " Def Part Equiped.", CL_FILE_LOG_AND_CONSOLE)); #endif // _DEBUG }else { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar ci.unequipPart(part); upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "] Not Def Part, Unequip part, Pode ser Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "] Not Def Part, Unequip part, Pode ser Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { auto parts = m_pi.findWarehouseItemById(ci.parts_id[i]); if (parts != nullptr/* != _session.m_pi.v_wi.end()*/) { char slot = part->part_type.getSlot(i); if (slot == -1) { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar ci.unequipPart(part); upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " desconhecido, Unequip Part. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " desconhecido, Unequip Part. Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG }else if (slot) { if (part->level.goodLevel((unsigned char)m_pi.level)) { if (angel_wings_part_num == -1l || parts->_typeid != *angel_wings_typeid || m_pi.ui.getQuitRate() < 3.f) { #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "] Equiped.", CL_FILE_LOG_AND_CONSOLE)); //#else // _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) // + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) // + "] Equiped.", CL_ONLY_FILE_LOG)); #endif // _DEBUG }else { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar ci.unequipPart(part); upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player nao pode equipar a asa [Angel Wings] por que ele nao tem menos que 3% do quit rate[" + std::to_string(m_pi.ui.getQuitRate()) + "]. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player nao pode equipar a asa [Angel Wings] por que ele nao tem menos que 3% do quit rate[" + std::to_string(m_pi.ui.getQuitRate()) + "]. Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar ci.unequipPart(part); upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)part->level.is_max) + ", Lv=" + std::to_string((unsigned short)part->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)part->level.is_max) + ", Lv=" + std::to_string((unsigned short)part->level.level) + "] para equipar esse item. Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } } }else { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar ci.unequipPart(part); upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player nao tem o item, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Player nao tem o item, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } } }else { // Deseequipa o Part do character e coloca os Parts Default do Character no lugar if (part != nullptr) ci.unequipPart(part); else { part = sIff::getInstance().findPart((def_part = ((i | (uint32_t)(ci._typeid << 5)) << 13) | 0x8000400)); ci.parts_typeid[i] = (part != nullptr) ? def_part : 0; ci.parts_id[i] = 0; } upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Not found in IFF_STRUCTURE or Not Actived, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Not found in IFF_STRUCTURE or Not Actived, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { auto part = sIff::getInstance().findPart(ci.parts_typeid[i]); // Deseequipa o Part do character e coloca os Parts Default do Character no lugar if (part != nullptr) ci.unequipPart(part); else { part = sIff::getInstance().findPart((def_part = ((i | (uint32_t)(ci._typeid << 5)) << 13) | 0x8000400)); ci.parts_typeid[i] = (part != nullptr) ? def_part : 0; ci.parts_id[i] = 0; } upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Slot wrong or Group id not match, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "]" + " Slot wrong or Group id not match, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) + "] Not Equiped.", CL_FILE_LOG_AND_CONSOLE)); //#else // _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedPart][Log] Player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) // + ", ID=" + std::to_string(ci.id) + "] Part[TYPEID=" + std::to_string(ci.parts_typeid[i]) + ", Slot=" + std::to_string(i) // + "] Not Equiped.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } } return upt_on_db; } bool player::checkCharacterEquipedAuxPart(CharacterInfo& ci) { bool upt_on_db = false; // Check AuxPart Equiped for (auto i = 0u; i < (sizeof(ci.auxparts) / sizeof(ci.auxparts[0])); ++i) { if (ci.auxparts[i] != 0) { // Esse AuxPartNumber é o 0x0 anel que consome(só mão direita), 0x1 mão direita, 0x21 mão esquerda if (sIff::getInstance().getItemGroupIdentify(ci.auxparts[i]) == iff::AUX_PART) { auto aux = sIff::getInstance().findAuxPart(ci.auxparts[i]); auto pAux = m_pi.findWarehouseItemByTypeid(ci.auxparts[i]); if (aux != nullptr && aux->active && pAux != nullptr) { if (aux->level.goodLevel((unsigned char)m_pi.level)) { if (aux->cc[0]/*qntd*/ == 0 || pAux->c[0] > 0) { #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Equiped.", CL_FILE_LOG_AND_CONSOLE)); //#else // _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) // + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" // + std::to_string(i) + "] Equiped.", CL_ONLY_FILE_LOG)); #endif // _DEBUG }else { // Desequipa ci.auxparts[i] = 0; upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Not have enough count item for equip, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Not have enough count item for equip, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { // Desequipa ci.auxparts[i] = 0; upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)aux->level.is_max) + ", Lv=" + std::to_string((unsigned short)aux->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)aux->level.is_max) + ", Lv=" + std::to_string((unsigned short)aux->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #endif // _DEBUG } }else { // Desequipa ci.auxparts[i] = 0; upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Not found in IFF_STRUCTURE, Not Actived or player nao tem esse item, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Not found in IFF_STRUCTURE, Not Actived or player nao tem esse item, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { // Desequipa ci.auxparts[i] = 0; upt_on_db = true; #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Group id not match, Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Group id not match, Hacker ou bug.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } }else { #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" + std::to_string(i) + "] Not Equiped.", CL_FILE_LOG_AND_CONSOLE)); //#else // _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedAuxPart][Log] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) // + ", ID=" + std::to_string(ci.id) + "] AuxPart[TYPEID=" + std::to_string(ci.auxparts[i]) + ", SLOT=" // + std::to_string(i) + "] Not Equiped.", CL_ONLY_FILE_LOG)); #endif // _DEBUG } } return upt_on_db; } bool player::checkCharacterEquipedCutin(CharacterInfo& ci) { bool upt_on_db = false; for (auto i = 0u; i < (sizeof(ci.cut_in) / sizeof(ci.cut_in[0])); ++i) { if (ci.cut_in[i] != 0) { auto pCutin = m_pi.findWarehouseItemById(ci.cut_in[i]); if (pCutin == nullptr) { // Zera (Desequipa) ci.cut_in[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedCutin][Error] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Not Have Cutin[ID=" + std::to_string(ci.cut_in[i]) + ", SLOT=" + std::to_string(i) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto cutin = sIff::getInstance().findSkin(pCutin->_typeid); if (cutin != nullptr && !cutin->level.goodLevel((unsigned char)m_pi.level)) { // Zera (Desequipa) ci.cut_in[i] = 0; upt_on_db = true; // Não tem o level necessário para equipar esse Cutin _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedCutin][Error] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Cutin[TYPEID=" + std::to_string(pCutin->_typeid) + " ID=" + std::to_string(pCutin->id) + ", SLOT=" + std::to_string(i) + "] Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)cutin->level.is_max) + ", Lv=" + std::to_string((unsigned short)cutin->level.level) + "] para equipar esse item. Hacker ou bug..", CL_FILE_LOG_AND_CONSOLE)); }else if (cutin == nullptr) { // Zera (Desequipa) ci.cut_in[i] = 0; upt_on_db = true; // Não tem esse Cutin no IFF_STRUCT do server desequipa ele _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquipedCutin][Error] player[UID=" + std::to_string(m_pi.uid) + "] Character[TYPEID=" + std::to_string(ci._typeid) + ", ID=" + std::to_string(ci.id) + "] Not Have Cutin[TYPEID=" + std::to_string(pCutin->_typeid) + " ID=" + std::to_string(pCutin->id) + ", SLOT=" + std::to_string(i) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } } } return upt_on_db; } void player::checkCharacterAllItemEquiped(CharacterInfo& ci) { auto ret = checkCharacterEquipedPart(ci); ret |= checkCharacterEquipedAuxPart(ci); ret |= checkCharacterEquipedCutin(ci); // Atualiza os parts equipados do player no banco de dados, que tinha parts errados if (ret) NormalManagerDB::add(5, new CmdUpdateCharacterAllPartEquiped(m_pi.uid, ci), player::SQLDBResponse, this); } bool player::checkSkinEquiped(UserEquip& _ue) { bool upt_on_db = false; unsigned tmp_typeid = 0, tmp_id = 0; for (auto i = 0u; i < (sizeof(_ue.skin_typeid) / sizeof(_ue.skin_typeid[0])); ++i) { if (_ue.skin_typeid[i] != 0) { auto pSkin = m_pi.findWarehouseItemByTypeid(_ue.skin_typeid[i]); if (pSkin == nullptr) { // Guarda para usar no Log tmp_typeid = _ue.skin_typeid[i]; tmp_id = _ue.skin_id[i]; // Zera (Desequipa) _ue.skin_id[i] = 0; _ue.skin_typeid[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkSkinEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Skin[TYPEID=" + std::to_string(tmp_typeid) + ", ID=" + std::to_string(tmp_id) + ", SLOT=" + std::to_string(i) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto skin = sIff::getInstance().findSkin(pSkin->_typeid); // Aqui tem que verificar as condições dos Title, uns só com 3% de quit rate, % de acerto de pangya e etc if (skin != nullptr && !skin->level.goodLevel((unsigned char)m_pi.level)) { // Zera (Desequipa) _ue.skin_id[i] = 0; _ue.skin_typeid[i] = 0; upt_on_db = true; // Não tem o level necessário para equipar esse Skin _smp::message_pool::getInstance().push(new message("[player::checkSkinEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Skin[TYPEID=" + std::to_string(pSkin->_typeid) + " ID=" + std::to_string(pSkin->id) + ", SLOT=" + std::to_string(i) + "] Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)skin->level.is_max) + ", Lv=" + std::to_string((unsigned short)skin->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (skin != nullptr && sIff::getInstance().IsTitle(pSkin->_typeid)) { // Verifica se o title tem condição e atualiza se tiver uint32_t title_num = sIff::getInstance().getItemTitleNum(pSkin->_typeid); auto check_title = m_pi.getTitleCallBack(title_num); // check_title == nullptr, title não tem condição if (check_title != nullptr/*Tem Condição*/ && check_title->exec() == 0/*Não passou na condição*/) { // Zera (Desequipa) _ue.skin_id[i] = 0; _ue.skin_typeid[i] = 0; upt_on_db = true; // Não passa na condição do title, desequipa ele _smp::message_pool::getInstance().push(new message("[player::checkSkinEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Skin[TYPEID=" + std::to_string(pSkin->_typeid) + " ID=" + std::to_string(pSkin->id) + ", SLOT=" + std::to_string(i) + "] nao passou na condition TITLE[NUM=" + std::to_string(title_num) + "], para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); } }else if (skin == nullptr) { // Zera (Desequipa) _ue.skin_id[i] = 0; _ue.skin_typeid[i] = 0; upt_on_db = true; // Não tem o Skin no IFF_STRUCT do server desequipa ele _smp::message_pool::getInstance().push(new message("[player::checkSkinEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Skin[TYPEID=" + std::to_string(pSkin->_typeid) + ", ID=" + std::to_string(pSkin->id) + ", SLOT=" + std::to_string(i) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } } } return upt_on_db; } bool player::checkPosterEquiped(UserEquip& _ue) { bool upt_on_db = false; int32_t tmp_typeid = 0; for (auto i = 0u; i < (sizeof(_ue.poster) / sizeof(_ue.poster[0])); ++i) { if (_ue.poster[i] != 0) { auto pPoster = m_pi.findMyRoomItemByTypeid(_ue.poster[i]); if (pPoster == nullptr) { // Guarda para enviar no log tmp_typeid = _ue.poster[i]; // Zera (Desequipa) _ue.poster[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkPosterEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Poster[TYPEID=" + std::to_string(tmp_typeid) + ", SLOT=" + std::to_string(i) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto poster = sIff::getInstance().findFurniture(pPoster->_typeid); if (poster != nullptr && !poster->level.goodLevel((unsigned char)m_pi.level)) { // Zera (Desequipa) _ue.poster[i] = 0; upt_on_db = true; // Não tem o level necessário para equipar esse Poster _smp::message_pool::getInstance().push(new message("[player::checkPosterEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Poster[TYPEID=" + std::to_string(pPoster->_typeid) + " ID=" + std::to_string(pPoster->id) + ", SLOT=" + std::to_string(i) + "] Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)poster->level.is_max) + ", Lv=" + std::to_string((unsigned short)poster->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (poster == nullptr) { // Zera (Desequipa) _ue.poster[i] = 0; upt_on_db = true; // Não tem esse Poster no IFF_STRUCT do Server desequipa ele _smp::message_pool::getInstance().push(new message("[player::checkPosterEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Poster[TYPEID=" + std::to_string(pPoster->_typeid) + ", ID=" + std::to_string(pPoster->id) + ", SLOT=" + std::to_string(i) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } } } return upt_on_db; } bool player::checkCharacterEquiped(UserEquip& _ue) { bool upt_on_db = false; int32_t tmp_id = 0; if (_ue.character_id != 0) { if (m_pi.findCharacterById(_ue.character_id) == nullptr) { // Guarda para usar no Log tmp_id = _ue.character_id; try { // Equipa Character Padrão equipDefaultCharacter(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Character[ID=" + std::to_string(tmp_id) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }//else Character não tem tempo ou level para equipar, então não precisa verificar o character se o player tiver ele }else { try { // Equipa Character Padrão equipDefaultCharacter(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não tem nenhum character normal ou padrão equipado, equipado o character padrão _smp::message_pool::getInstance().push(new message("[player::checkCharacterEquiped][Error][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao tem um character equipado. Bug", CL_FILE_LOG_AND_CONSOLE)); } return upt_on_db; } bool player::checkCaddieEquiped(UserEquip& _ue) { bool upt_on_db = false; int32_t tmp_id = 0; if (_ue.caddie_id != 0) { auto pCaddie = m_pi.findCaddieById(_ue.caddie_id); if (pCaddie == nullptr) { // Guarda para usar no Log tmp_id = _ue.caddie_id; // Zera (Desequipa) _ue.caddie_id = 0; m_pi.ei.cad_info = nullptr; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkCaddieEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Caddie[ID=" + std::to_string(tmp_id) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto caddie = sIff::getInstance().findCaddie(pCaddie->_typeid); if (caddie != nullptr && !caddie->level.goodLevel((unsigned char)m_pi.level)) { // Zera (Desequipa) _ue.caddie_id = 0; m_pi.ei.cad_info = nullptr; upt_on_db = true; // Não tem o level necessário para equipar esse caddie _smp::message_pool::getInstance().push(new message("[player::checkCaddieEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Caddie[TYPEID=" + std::to_string(pCaddie->_typeid) + " ID=" + std::to_string(pCaddie->id) + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)caddie->level.is_max) + ", Lv=" + std::to_string((unsigned short)caddie->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (caddie != nullptr && pCaddie->rent_flag == 2 && getLocalTimeDiffDESC(pCaddie->end_date) <= 0ll) { // Zera (Desequipa) _ue.caddie_id = 0; m_pi.ei.cad_info = nullptr; upt_on_db = true; // Caddie está de ferias não pode equipar esse caddie _smp::message_pool::getInstance().push(new message("[player::checkCaddieEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Caddie[TYPEID=" + std::to_string(pCaddie->_typeid) + " ID=" + std::to_string(pCaddie->id) + ", END_DATE=" + _formatDate(pCaddie->end_date) + "] esta de ferias, nao pode equipar esse caddie. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (caddie == nullptr) { // Zera (Desequipa) _ue.caddie_id = 0; m_pi.ei.cad_info = nullptr; upt_on_db = true; // Não tem esse caddie no IFF_STRUCT do server, desequipa ele _smp::message_pool::getInstance().push(new message("[player::checkCaddieEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Caddie[TYPEID=" + std::to_string(pCaddie->_typeid) + ", ID=" + std::to_string(pCaddie->id) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } } return upt_on_db; } bool player::checkMascotEquiped(UserEquip& _ue) { bool upt_on_db = false; int32_t tmp_id = 0; if (_ue.mascot_id != 0) { auto pMascot = m_pi.findMascotById(_ue.mascot_id); if (pMascot == nullptr) { // Guarda para usar no Log tmp_id = _ue.mascot_id; // Zera (Desequipa) _ue.mascot_id = 0; m_pi.ei.mascot_info = nullptr; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkMascotEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Mascot[ID=" + std::to_string(tmp_id) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto mascot = sIff::getInstance().findMascot(pMascot->_typeid); if (mascot != nullptr && !mascot->level.goodLevel((unsigned char)m_pi.level)) { // Zera (Desequipa) _ue.mascot_id = 0; m_pi.ei.mascot_info = nullptr; upt_on_db = true; // Não tem o level necessário para equipar esse mascot, desequipa _smp::message_pool::getInstance().push(new message("[player::checkMascotEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Mascot[TYPEID=" + std::to_string(pMascot->_typeid) + " ID=" + std::to_string(pMascot->id) + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)mascot->level.is_max) + ", Lv=" + std::to_string((unsigned short)mascot->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (mascot != nullptr && pMascot->tipo == 1 && getLocalTimeDiffDESC(pMascot->data) <= 0ll) { // Zera (Desequipa) _ue.mascot_id = 0; m_pi.ei.mascot_info = nullptr; upt_on_db = true; // O tempo do mascot acabou, desequipa _smp::message_pool::getInstance().push(new message("[player::checkMascotEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Caddie[TYPEID=" + std::to_string(pMascot->_typeid) + " ID=" + std::to_string(pMascot->id) + ", END_DATE=" + _formatDate(pMascot->data) + "] acabou o tempo do mascot, nao pode equipar esse mascot. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (mascot == nullptr) { // Zera (Desequipa) _ue.mascot_id = 0; m_pi.ei.mascot_info = nullptr; upt_on_db = true; // Não tem esse mascot no IFF_STRUCT do server, desequipa _smp::message_pool::getInstance().push(new message("[player::checkMascotEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Mascot[TYPEID=" + std::to_string(pMascot->_typeid) + ", ID=" + std::to_string(pMascot->id) + "] in IFF_STRCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } } return upt_on_db; } bool player::checkClubSetEquiped(UserEquip& _ue){ bool upt_on_db = false; int32_t tmp_id = 0; if (_ue.clubset_id != 0) { auto pClubSet = m_pi.findWarehouseItemById(_ue.clubset_id); if (pClubSet == nullptr) { // Guarda para usar no Log auto tmp_id = _ue.clubset_id; try { // Equipa ClubSet Padrão equipDefaultClubSet(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have ClubSet[ID=" + std::to_string(tmp_id) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto clubset = sIff::getInstance().findClubSet(pClubSet->_typeid); if (clubset != nullptr && !clubset->level.goodLevel((unsigned char)m_pi.level)) { try { // Equipa ClubSet Padrão equipDefaultClubSet(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não tem o level necessário para equipar esse clubset, equipa o clubset padrão _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] ClubSet[TYPEID=" + std::to_string(pClubSet->_typeid) + " ID=" + std::to_string(pClubSet->id) + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)clubset->level.is_max) + ", Lv=" + std::to_string((unsigned short)clubset->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (clubset == nullptr) { try { // Equipa ClubSet Padrão equipDefaultClubSet(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não tem esse clubset no IFF_STRUCT do server, equipa clubset padrão _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have ClubSet[TYPEID=" + std::to_string(pClubSet->_typeid) + ", ID=" + std::to_string(pClubSet->id) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } }else { try { // Equipa ClubSet Padrão equipDefaultClubSet(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não está com um clubset normal ou padrão equipado, equipa o clubset padrão _smp::message_pool::getInstance().push(new message("[player::checkClubSetEquiped][Error][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao esta com um ClubSet equipado. Bug", CL_FILE_LOG_AND_CONSOLE)); } return upt_on_db; } bool player::checkBallEquiped(UserEquip& _ue) { bool upt_on_db = false; uint32_t tmp_typeid = 0u; if (_ue.ball_typeid != 0) { auto pBall = m_pi.findWarehouseItemByTypeid(_ue.ball_typeid); if (pBall == nullptr) { // Guarda para usar no Log auto tmp_typeid = _ue.ball_typeid; try { // Equipa Ball padrão equipDefaultBall(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Ball[TYPEID=" + std::to_string(tmp_typeid) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { auto ball = sIff::getInstance().findBall(pBall->_typeid); if (ball != nullptr && !ball->level.goodLevel((unsigned char)m_pi.level)) { try { // Equipa Ball padrão equipDefaultBall(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não tem o level necessário para equipar a bola _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Ball[TYPEID=" + std::to_string(pBall->_typeid) + " ID=" + std::to_string(pBall->id) + " Player[Lv=" + std::to_string(m_pi.level) + "] nao tem o level[is_max=" + std::to_string((unsigned short)ball->level.is_max) + ", Lv=" + std::to_string((unsigned short)ball->level.level) + "] para equipar esse item. Hacker ou bug.", CL_FILE_LOG_AND_CONSOLE)); }else if (ball == nullptr) { try { // Equipa Ball padrão equipDefaultBall(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não tem essa bola no IFF_STRUCT do server, equipa a bola padrão _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Ball[TYPEID=" + std::to_string(pBall->_typeid) + ", ID=" + std::to_string(pBall->id) + "] in IFF_STRUCT of server, but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); } } }else { try { // Equipa Ball padrão equipDefaultBall(_ue); }catch (exception& e) { _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } upt_on_db = true; // Não está com nenhuma bola normal ou padrão equipada, equipa a bola padrão _smp::message_pool::getInstance().push(new message("[player::checkBallEquiped][Error][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao esta com uma Ball equipada. Bug", CL_FILE_LOG_AND_CONSOLE)); } return upt_on_db; } bool player::checkItemEquiped(UserEquip& _ue) { bool upt_on_db = false; uint32_t tmp_typeid = 0u; WarehouseItemEx *pWi = nullptr; std::map< uint32_t/*TYPEID*/, uint32_t/*Count*/ > mp_count_same_item; std::map< uint32_t/*TYPEID*/, uint32_t/*Count*/ >::iterator it; for (auto i = 0u; i < (sizeof(_ue.item_slot) / sizeof(_ue.item_slot[0])); ++i) { if (_ue.item_slot[i] != 0) { if (!sIff::getInstance().ItemEquipavel(_ue.item_slot[i])) { // Guarda para usar no Log tmp_typeid = _ue.item_slot[i]; // Zera _ue.item_slot[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkItemEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Equipable Item[TYPEID=" + std::to_string(tmp_typeid) + ", SLOT=" + std::to_string(i) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else if ((pWi = m_pi.findWarehouseItemByTypeid(_ue.item_slot[i])) == nullptr) { _ue.item_slot[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkItemEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Not Have Item[TYPEID=" + std::to_string(_ue.item_slot[i]) + ", SLOT=" + std::to_string(i) + "], but it is equiped. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else { if ((it = mp_count_same_item.find(pWi->_typeid)) != mp_count_same_item.end()) { if (std::find(active_item_cant_have_2_inveroty, LAST_ELEMENT_IN_ARRAY(active_item_cant_have_2_inveroty), pWi->_typeid) != LAST_ELEMENT_IN_ARRAY(active_item_cant_have_2_inveroty)) { // Não pode equipa 2 item Ex:[ Corta com (Toma ou Safety) ] no inventory // Guarda para usar no Log tmp_typeid = _ue.item_slot[i]; // Zera _ue.item_slot[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkItemEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Nao pode equipar 2 Ex:[Corta com (Toma ou Safety)] Item[TYPEID=" + std::to_string(pWi->_typeid) + ", ID=" + std::to_string(pWi->id) + "] no inventory. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else if (pWi->STDA_C_ITEM_QNTD < (int)(it->second + 1)/*Count*/) { // Not Have AMOUNT Suficiente // Guarda para usar no Log tmp_typeid = _ue.item_slot[i]; // Zera _ue.item_slot[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkItemEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Nao tem quantidade do Item[TYPEID=" + std::to_string(pWi->_typeid) + ", ID=" + std::to_string(pWi->id) + "] para equipar ele. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else // Increase Count of Item Necessary to Equip it->second++; }else { // Insert New Item Equiped Count // check Not Have AMOUNT Suficiente if (pWi->STDA_C_ITEM_QNTD < 1/*Count*/) { // Guarda para usar no Log tmp_typeid = _ue.item_slot[i]; // Zera _ue.item_slot[i] = 0; upt_on_db = true; _smp::message_pool::getInstance().push(new message("[player::checkItemEquiped][Error] player[UID=" + std::to_string(m_pi.uid) + "] Nao tem quantidade do Item[TYPEID=" + std::to_string(pWi->_typeid) + ", ID=" + std::to_string(pWi->id) + "] para equipar ele. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); }else // Insert mp_count_same_item.insert(std::make_pair(pWi->_typeid, 1)); } } } } return upt_on_db; } void player::checkAllItemEquiped(UserEquip& _ue) { if (checkSkinEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateSkinEquiped(m_pi.uid, _ue), player::SQLDBResponse, this); if (checkPosterEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdatePosterEquiped(m_pi.uid, _ue), player::SQLDBResponse, this); if (checkCharacterEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateCharacterEquiped(m_pi.uid, _ue.character_id), player::SQLDBResponse, this); if (checkCaddieEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateCaddieEquiped(m_pi.uid, _ue.caddie_id), player::SQLDBResponse, this); if (checkMascotEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateMascotEquiped(m_pi.uid, _ue.mascot_id), player::SQLDBResponse, this); if (checkItemEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateItemSlot(m_pi.uid, (uint32_t*)_ue.item_slot), player::SQLDBResponse, this); if (checkClubSetEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateClubsetEquiped(m_pi.uid, _ue.clubset_id), player::SQLDBResponse, this); if (checkBallEquiped(_ue)) NormalManagerDB::add(0, new CmdUpdateBallEquiped(m_pi.uid, _ue.ball_typeid), player::SQLDBResponse, this); } void player::equipDefaultCharacter(UserEquip& _ue) { // Valor padrão caso o adicionar Character de error auto tmp_id = _ue.character_id; _ue.character_id = 0; m_pi.ei.char_info = nullptr; if (m_pi.mp_ce.size() > 0) { _smp::message_pool::getInstance().push(new message("[player::equipDefaultCharacter][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar o Character[ID=" + std::to_string(tmp_id) + "] para comecar o jogo, colocando o primeiro character do player. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); m_pi.ei.char_info = &m_pi.mp_ce.begin()->second; _ue.character_id = m_pi.ei.char_info->id; }else { _smp::message_pool::getInstance().push(new message("[player::equipDefaultCharacter][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar o Character[ID=" + std::to_string(tmp_id) + "] para comecar o jogo, ele nao tem nenhum character. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); BuyItem bi{ 0 }; stItem item{ 0 }; int32_t item_id = 0; bi.id = -1; bi._typeid = iff::CHARACTER << 26; // Nuri bi.qntd = 1; item_manager::initItemFromBuyItem(m_pi, item, bi, false, 0, 0, 1/*Não verifica o Level*/); if (item._typeid != 0) { // Add Item já atualiza o Character equipado if ((item_id = item_manager::addItem(item, *this, 2/*Padrão Item*/, 0)) == item_manager::RetAddItem::T_ERROR) throw exception("[player::equipDefaultCharacter][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu adicionar o Character[TYPEID=" + std::to_string(item._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2500, 2)); }else throw exception("[player::equipDefaultCharacter][Log][WARNING][Error] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu inicializar o Character[TYPEID=" + std::to_string(bi._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2500, 1)); } } void player::equipDefaultClubSet(UserEquip& _ue) { // Guarda para usar no Log auto tmp_id = _ue.clubset_id; // Valor padrão caso de erro no add ClubSet Padrão _ue.clubset_id = 0; m_pi.ei.clubset = nullptr; m_pi.ei.csi.clear(); _smp::message_pool::getInstance().push(new message("[player::equipDefaultClubSet][Error] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar o Clubset[ID=" + std::to_string(tmp_id) + "] equipado, mas ClubSet Not exists on IFF structure. Equipa o ClubSet padrao. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); // Coloca o ClubSet CV1 no lugar do ClubSet que acabou o tempo auto pWi = m_pi.findWarehouseItemByTypeid(AIR_KNIGHT_SET); if (pWi != nullptr) { _smp::message_pool::getInstance().push(new message("[player::equipDefaultClubSet][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar o ClubSet[ID=" + std::to_string(tmp_id) + "], mas acabou o tempo do ClubSet[ID=" + std::to_string(tmp_id) + "], colocando o ClubSet Padrao\"CV1\" do player. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); // Esse C do WarehouseItem, que pega do DB, não é o ja updado inicial da taqueira é o que fica tabela enchant, // que no original fica no warehouse msm, eu só confundi quando fiz m_pi.ei.csi = { pWi->id, pWi->_typeid, pWi->c }; IFF::ClubSet *cs = sIff::getInstance().findClubSet(pWi->_typeid); if (cs != nullptr) for (auto j = 0u; j < (sizeof(m_pi.ei.csi.enchant_c) / sizeof(short)); ++j) m_pi.ei.csi.enchant_c[j] = cs->slot[j] + pWi->clubset_workshop.c[j]; m_pi.ei.clubset = pWi; _ue.clubset_id = pWi->id; }else { _smp::message_pool::getInstance().push(new message("[player::equipDefaultClubSet][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar o ClubSet[ID=" + std::to_string(tmp_id) + "], mas acabou o tempo do ClubSet[ID=" + std::to_string(tmp_id) + "], ele nao tem o ClubSet Padrao\"CV1\". Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); BuyItem bi{ 0 }; stItem item{ 0 }; int32_t item_id = 0; bi.id = -1; bi._typeid = AIR_KNIGHT_SET; bi.qntd = 1; item_manager::initItemFromBuyItem(m_pi, item, bi, false, 0, 0, 1/*Não verifica o Level*/); if (item._typeid != 0) { if ((item_id = item_manager::addItem(item, *this, 2/*Padrão Item*/, 0)) != item_manager::RetAddItem::T_ERROR) { // Equipa o ClubSet CV1 pWi = m_pi.findWarehouseItemById(item_id); if (pWi != nullptr) { // Esse C do WarehouseItem, que pega do DB, não é o ja updado inicial da taqueira é o que fica tabela enchant, // que no original fica no warehouse msm, eu só confundi quando fiz m_pi.ei.csi = { pWi->id, pWi->_typeid, pWi->c }; IFF::ClubSet *cs = sIff::getInstance().findClubSet(pWi->_typeid); if (cs != nullptr) for (auto j = 0u; j < (sizeof(m_pi.ei.csi.enchant_c) / sizeof(short)); ++j) m_pi.ei.csi.enchant_c[j] = cs->slot[j] + pWi->clubset_workshop.c[j]; m_pi.ei.clubset = pWi; m_pi.ue.clubset_id = pWi->id; // Update ON DB NormalManagerDB::add(0, new CmdUpdateClubsetEquiped(m_pi.uid, item_id), player::SQLDBResponse, this); }else throw exception("[player::equipDefaultClubSet][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu achar o ClubSet\"CV1\"[ID=" + std::to_string(item.id) + "] padrao que acabou de adicionar para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2501, 3)); }else throw exception("[player::equipDefaultClubSet][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu adicionar o ClubSet[TYPEID=" + std::to_string(item._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2501, 2)); }else throw exception("[player::equipDefaultClubSet][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu inicializar o ClubSet[TYPEID=" + std::to_string(bi._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2501, 1)); } } void player::equipDefaultBall(UserEquip& _ue) { // Verifica se o player é um premium user try { if (m_pi.m_cap.stBit.premium_user) { // Equipa a Ball Premium User Padrão equipDefaultBallPremiumUser(_ue); return; // Equipou a bola premium user com sucesso } }catch (exception& e){ _smp::message_pool::getInstance().push(new message("[player::equipDefaultBall][ErrorSystem] " + e.getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); } // Guarda para usar no Log auto tmp_typeid = _ue.ball_typeid; // Valor padrão caso de erro no adicionar a Ball padrão _ue.ball_typeid = DEFAULT_COMET_TYPEID; m_pi.ei.comet = nullptr; auto pWi = m_pi.findWarehouseItemByTypeid(DEFAULT_COMET_TYPEID); if (pWi != nullptr) { _smp::message_pool::getInstance().push(new message("[player::equipDefaultBall][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar a Ball[TYPEID=" + std::to_string(tmp_typeid) + "] para comecar o jogo, colocando a Ball Padrao do player. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); m_pi.ei.comet = pWi; _ue.ball_typeid = pWi->_typeid; }else { _smp::message_pool::getInstance().push(new message("[player::equipDefaultBall][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou trocar a Ball[TYPEID=" + std::to_string(tmp_typeid) + "] para comecar o jogo, ele nao tem a Ball Padrao. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); BuyItem bi{ 0 }; stItem item{ 0 }; int32_t item_id = 0; bi.id = -1; bi._typeid = DEFAULT_COMET_TYPEID; bi.qntd = 1; item_manager::initItemFromBuyItem(m_pi, item, bi, false, 0); if (item._typeid != 0) { if ((item_id = item_manager::addItem(item, *this, 2/*Padrão Item*/, 0)) != item_manager::RetAddItem::T_ERROR) { // Equipa a Ball padrao pWi = m_pi.findWarehouseItemById(item_id); if (pWi != nullptr) { m_pi.ei.comet = pWi; m_pi.ue.ball_typeid = pWi->_typeid; // Update ON DB NormalManagerDB::add(0, new CmdUpdateBallEquiped(m_pi.uid, item_id), player::SQLDBResponse, this); }else throw exception("[player::equipDefaultBall][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu achar a Ball[ID=" + std::to_string(item.id) + "] padrao que acabou de adicionar para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2502, 3)); }else throw exception("[player::equipDefaultBall][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu adicionar a Ball[TYPEID=" + std::to_string(item._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2502, 2)); }else throw exception("[player::equipDefaultBall][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] nao conseguiu inicializar a Ball[TYPEID=" + std::to_string(bi._typeid) + "] padrao para ele. Bug", STDA_MAKE_ERROR(STDA_ERROR_TYPE::PLAYER, 2502, 1)); } } void player::equipDefaultBallPremiumUser(UserEquip& _ue) { // Guarda para usar no Log auto tmp_typeid = _ue.ball_typeid; // Valor padrão caso de erro no adicionar a Ball Premium User padrão _ue.ball_typeid = sPremiumSystem::getInstance().getPremiumBallByTicket(m_pi.pt._typeid); m_pi.ei.comet = nullptr; auto pWi = m_pi.findWarehouseItemByTypeid(_ue.ball_typeid); if (pWi != nullptr) { _smp::message_pool::getInstance().push(new message("[player::equipDefaultBallPremiumUser][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou verificar a Ball[TYPEID=" + std::to_string(tmp_typeid) + "] para comecar o jogo, colocando a Ball Premium User Padrao do player. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); m_pi.ei.comet = pWi; _ue.ball_typeid = pWi->_typeid; }else { _smp::message_pool::getInstance().push(new message("[player::equipDefaultBallPremiumUser][Log][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou trocar a Ball[TYPEID=" + std::to_string(tmp_typeid) + "] para comecar o jogo, ele nao tem a Ball Premium User Padrao. Hacker ou Bug", CL_FILE_LOG_AND_CONSOLE)); // Add Premium Ball stItem item = sPremiumSystem::getInstance().addPremiumBall(*this); if (item._typeid != 0u) // Update ON DB NormalManagerDB::add(0, new CmdUpdateBallEquiped(m_pi.uid, item._typeid), player::SQLDBResponse, this); else _smp::message_pool::getInstance().push(new message("[player::equipDefaultBallPremiumUser][ERROR][WARNING] player[UID=" + std::to_string(m_pi.uid) + "] tentou trocar a Ball[TYPEID=" + std::to_string(tmp_typeid) + "] para comecar o jogo, mas nao conseguiu adicionar a ball premium. Hacker ou Bug.", CL_FILE_LOG_AND_CONSOLE)); } } std::vector< CharacterInfo* > player::isAuxPartEquiped(uint32_t _typeid) { std::vector< CharacterInfo* > v_ci; std::for_each(m_pi.mp_ce.begin(), m_pi.mp_ce.end(), [&](auto& _el) { // O AuxPart está equipado nesse character if (_el.second.isAuxPartEquiped(_typeid)) v_ci.push_back(&_el.second); }); return v_ci; } CharacterInfo* player::isPartEquiped(uint32_t _typeid) { auto it = std::find_if(m_pi.mp_ce.begin(), m_pi.mp_ce.end(), [&](auto& _el) { return _el.second.isPartEquiped(_typeid); }); return (it != m_pi.mp_ce.end() ? &it->second : nullptr); } void player::SQLDBResponse(uint32_t _msg_id, pangya_db& _pangya_db, void* _arg) { if (_arg == nullptr) { _smp::message_pool::getInstance().push(new message("[player::SQLDBResponse][WARNING] _arg is nullptr na msg_id = " + std::to_string(_msg_id), CL_FILE_LOG_AND_CONSOLE)); return; } // Por Hora só sai, depois faço outro tipo de tratamento se precisar if (_pangya_db.getException().getCodeError() != 0) { _smp::message_pool::getInstance().push(new message("[player:SQLDBResponse][Error] " + _pangya_db.getException().getFullMessageError(), CL_FILE_LOG_AND_CONSOLE)); return; } // isso aqui depois pode mudar para o Item_manager, que vou tirar de ser uma classe static e usar ela como objeto(instancia) auto _session = reinterpret_cast< player* >(_arg); switch (_msg_id) { case 1: // Update Caddie Info { break; } case 2: // Update Mascot Info { break; } case 3: // Insert CPLog Item { auto cmd_icpli = reinterpret_cast< CmdInsertCPLogItem* >(&_pangya_db); #ifdef _DEBUG _smp::message_pool::getInstance().push(new message("[player::SQLDBResponse][Log] Inseriu CPLogItem[LOD_ID=" + std::to_string(cmd_icpli->getLogId()) + ", ITEM_TYPEID=" + std::to_string(cmd_icpli->getItem()._typeid) + ", ITEM_QNTD=" + std::to_string(cmd_icpli->getItem().qntd) + ", ITEM_PRICE=" + std::to_string(cmd_icpli->getItem().price) + "] do Player[UID=" + std::to_string(cmd_icpli->getUID()) + "] com sucesso.", CL_FILE_LOG_AND_CONSOLE)); #else _smp::message_pool::getInstance().push(new message("[player::SQLDBResponse][Log] Inseriu CPLogItem[LOD_ID=" + std::to_string(cmd_icpli->getLogId()) + ", ITEM_TYPEID=" + std::to_string(cmd_icpli->getItem()._typeid) + ", ITEM_QNTD=" + std::to_string(cmd_icpli->getItem().qntd) + ", ITEM_PRICE=" + std::to_string(cmd_icpli->getItem().price) + "] do Player[UID=" + std::to_string(cmd_icpli->getUID()) + "] com sucesso.", CL_ONLY_FILE_LOG)); #endif // _DEBUG break; } case 0: default: break; } };
37.924605
217
0.661567
[ "vector" ]
d49f7159c152dce278c2cae9a5f9c75fac9e5c5c
5,722
cpp
C++
ml/skylark_ml.cpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
86
2015-01-20T03:12:46.000Z
2022-01-10T04:05:21.000Z
ml/skylark_ml.cpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
48
2015-05-12T09:31:23.000Z
2018-12-05T14:45:46.000Z
ml/skylark_ml.cpp
xdata-skylark/libskylark
89c3736136a24d519c14fc0738c21f37f1e10360
[ "Apache-2.0" ]
25
2015-01-18T23:02:11.000Z
2021-06-12T07:30:35.000Z
#include <El.hpp> #include <skylark.hpp> #include <fstream> #include <iostream> #include <sstream> #include <cstdlib> #include <string> #include <boost/program_options.hpp> #include "hilbert.hpp" #if SKYLARK_HAVE_OPENMP #include <omp.h> #endif int main(int argc, char* argv[]) { El::Initialize (argc, argv); boost::mpi::environment env (argc, argv); boost::mpi::communicator comm; hilbert_options_t options (argc, argv, comm.size()); skylark::base::context_t context (options.seed); if (options.exit_on_return) { return -1; } bool sparse = (options.fileformat == LIBSVM_SPARSE) || (options.fileformat == HDF5_SPARSE); SKYLARK_BEGIN_TRY() if (!options.trainfile.empty()) { // Training if (comm.rank() == 0) { std::cout << options.print(); std::cout << "Mode: Training. Loading data..." << std::endl; } if (sparse) { skylark::base::sparse_matrix_t<double> X; El::Matrix<double> Y; read(comm, options.fileformat, options.trainfile, X, Y); skylark::ml::LargeScaleKernelLearning(comm, X, Y, context, options); } else { El::Matrix<double> X, Y; read(comm, options.fileformat, options.trainfile, X, Y); skylark::ml::LargeScaleKernelLearning(comm, X, Y, context, options); } } else if (!options.testfile.empty()) { // Testing from file if (comm.rank() == 0) { std::cout << "Mode: Predicting (from file). Loading data..." << std::endl; std::cout << options.print(); } El::Matrix<double> Y; El::DistMatrix<double, El::VC, El::STAR> DecisionValues; El::DistMatrix<El::Int, El::VC, El::STAR> PredictedLabels; El::Int n; skylark::ml::hilbert_model_t model(options.modelfile); if (sparse) { skylark::base::sparse_matrix_t<double> X; read(comm, options.fileformat, options.testfile, X, Y, model.get_input_size()); boost::mpi::all_reduce(comm, Y.Height(), n, std::plus<El::Int>()); PredictedLabels.Resize(n, 1); DecisionValues.Resize(n, model.get_output_size()); model.predict(X, PredictedLabels.Matrix(), DecisionValues.Matrix(), options.numthreads); } else { El::Matrix<double> X; read(comm, options.fileformat, options.testfile, X, Y, model.get_input_size()); boost::mpi::all_reduce(comm, Y.Height(), n, std::plus<El::Int>()); PredictedLabels.Resize(n, 1); DecisionValues.Resize(n, model.get_output_size()); model.predict(X, PredictedLabels.Matrix(), DecisionValues.Matrix(), options.numthreads); } if (model.is_regression()) { // TODO can be done better if Y and VC,STAR as well... El::Matrix<double> Ye = DecisionValues.Matrix(); El::Axpy(-1.0, Y, Ye); double localerr = std::pow(El::Nrm2(Ye), 2); double localnrm = std::pow(El::Nrm2(Y), 2); double err, nrm; boost::mpi::reduce(comm, localerr, err, std::plus<double>(), 0); boost::mpi::reduce(comm, localnrm, nrm, std::plus<double>(), 0); if (!options.outputfile.empty()) El::Write(DecisionValues, options.outputfile, El::ASCII); if (comm.rank() == 0) std::cout << "Error rate: " << boost::format("%.4e") % std::sqrt(err / nrm) << std::endl; } else { El::Int correct = skylark::ml::classification_accuracy(Y, DecisionValues.Matrix()); El::Int totalcorrect, total; boost::mpi::reduce(comm, correct, totalcorrect, std::plus<El::Int>(), 0); if (!options.outputfile.empty()) { if (options.decisionvals) El::Write(DecisionValues, options.outputfile, El::ASCII); else El::Write(PredictedLabels, options.outputfile, El::ASCII); } if(comm.rank() == 0) std::cout << "Error rate: " << boost::format("%.2f") % ((n - totalcorrect) * 100.0 / n) << "%" << std::endl; } // TODO list? // fix logistic case // option for probabilities in predicition // clean up evaluate } else { // Preidicting from stdin mode skylark::ml::hilbert_model_t model(options.modelfile); El::Matrix<double> X, DecisionValues(1, model.get_output_size()); El::Matrix<El::Int> PredictedLabel(1, 1); while(true) { std::string line, token; std::getline(std::cin, line); if (line.empty()) break; El::Zeros(X, model.get_input_size(), 1); std::istringstream tokenstream(line); while (tokenstream >> token) { int delim = token.find(':'); std::string ind = token.substr(0, delim); std::string val = token.substr(delim+1); X.Set(atoi(ind.c_str()) - 1, 0, atof(val.c_str())); } model.predict(X, PredictedLabel, DecisionValues, options.numthreads); std::cout << (model.is_regression() ? DecisionValues.Get(0,0) : PredictedLabel.Get(0, 0)) << std::endl; } } comm.barrier(); SKYLARK_END_TRY() SKYLARK_CATCH_AND_PRINT((comm.rank() == 0)) El::Finalize(); return 0; }
32.697143
80
0.53338
[ "model" ]
d4a3ed4036b15a084957bf83c42da4b6f21d7563
3,757
cpp
C++
android-28/android/icu/text/StringPrepParseException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-28/android/icu/text/StringPrepParseException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-30/android/icu/text/StringPrepParseException.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "../../../JObject.hpp" #include "../../../JString.hpp" #include "./StringPrepParseException.hpp" namespace android::icu::text { // Fields jint StringPrepParseException::ACE_PREFIX_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "ACE_PREFIX_ERROR" ); } jint StringPrepParseException::BUFFER_OVERFLOW_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "BUFFER_OVERFLOW_ERROR" ); } jint StringPrepParseException::CHECK_BIDI_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "CHECK_BIDI_ERROR" ); } jint StringPrepParseException::DOMAIN_NAME_TOO_LONG_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "DOMAIN_NAME_TOO_LONG_ERROR" ); } jint StringPrepParseException::ILLEGAL_CHAR_FOUND() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "ILLEGAL_CHAR_FOUND" ); } jint StringPrepParseException::INVALID_CHAR_FOUND() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "INVALID_CHAR_FOUND" ); } jint StringPrepParseException::LABEL_TOO_LONG_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "LABEL_TOO_LONG_ERROR" ); } jint StringPrepParseException::PROHIBITED_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "PROHIBITED_ERROR" ); } jint StringPrepParseException::STD3_ASCII_RULES_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "STD3_ASCII_RULES_ERROR" ); } jint StringPrepParseException::UNASSIGNED_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "UNASSIGNED_ERROR" ); } jint StringPrepParseException::VERIFICATION_ERROR() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "VERIFICATION_ERROR" ); } jint StringPrepParseException::ZERO_LENGTH_LABEL() { return getStaticField<jint>( "android.icu.text.StringPrepParseException", "ZERO_LENGTH_LABEL" ); } // QJniObject forward StringPrepParseException::StringPrepParseException(QJniObject obj) : java::text::ParseException(obj) {} // Constructors StringPrepParseException::StringPrepParseException(JString arg0, jint arg1) : java::text::ParseException( "android.icu.text.StringPrepParseException", "(Ljava/lang/String;I)V", arg0.object<jstring>(), arg1 ) {} StringPrepParseException::StringPrepParseException(JString arg0, jint arg1, JString arg2, jint arg3) : java::text::ParseException( "android.icu.text.StringPrepParseException", "(Ljava/lang/String;ILjava/lang/String;I)V", arg0.object<jstring>(), arg1, arg2.object<jstring>(), arg3 ) {} StringPrepParseException::StringPrepParseException(JString arg0, jint arg1, JString arg2, jint arg3, jint arg4) : java::text::ParseException( "android.icu.text.StringPrepParseException", "(Ljava/lang/String;ILjava/lang/String;II)V", arg0.object<jstring>(), arg1, arg2.object<jstring>(), arg3, arg4 ) {} // Methods jboolean StringPrepParseException::equals(JObject arg0) const { return callMethod<jboolean>( "equals", "(Ljava/lang/Object;)Z", arg0.object<jobject>() ); } jint StringPrepParseException::getError() const { return callMethod<jint>( "getError", "()I" ); } jint StringPrepParseException::hashCode() const { return callMethod<jint>( "hashCode", "()I" ); } JString StringPrepParseException::toString() const { return callObjectMethod( "toString", "()Ljava/lang/String;" ); } } // namespace android::icu::text
24.083333
112
0.728241
[ "object" ]
d4a5c4db975a5e5e760700fd62ec3af74c9580d7
3,015
cpp
C++
layer0/PostProcess.cpp
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
636
2018-06-21T20:46:36.000Z
2022-03-30T13:07:47.000Z
layer0/PostProcess.cpp
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
218
2018-06-25T00:10:59.000Z
2022-03-23T14:15:48.000Z
layer0/PostProcess.cpp
dualword/pymol-open-source
abc307745d7d231af4f77f984ebd64f1b428cef8
[ "CNRI-Python" ]
192
2018-06-21T17:33:10.000Z
2022-03-31T17:53:03.000Z
#include "PostProcess.h" #include "gl_def.h" #include "GenericBuffer.h" #include "os_gl.h" #include "pymol/memory.h" #ifndef _PYMOL_NO_AA_SHADERS #endif void PostProcess::activateRTAsTexture(std::size_t idx, GLuint textureUnit) { glActiveTexture(GL_TEXTURE0 + textureUnit); auto& rt = m_renderTargets[idx]; if (rt && rt->textures().front()) { rt->textures().front()->bind(); } } void PostProcess::activateTexture(std::size_t idx, GLuint textureUnit) { glActiveTexture(GL_TEXTURE0 + textureUnit); auto& tex = m_textures[idx]; if (tex) { tex->bind(); } } void PostProcess::bindRT(std::size_t idx, bool clear) { if (idx < m_renderTargets.size()) { auto& t = m_renderTargets[idx]; if (t) { t->bind(clear); } } } void PostProcess::bindFBORBO(std::size_t idx) { if (idx < m_renderTargets.size()) { auto& t = m_renderTargets[idx]; if (t) { t->bindFBORBO(); } } } const renderTarget_t::shape_type PostProcess::size(std::size_t idx) const noexcept { return m_renderTargets[idx]->size(); } #ifndef _PYMOL_NO_AA_SHADERS #endif OIT_PostProcess::OIT_PostProcess(int width, int height, renderBuffer_t* rbo) { if (TM3_IS_ONEBUF) { auto rt0 = pymol::make_unique<renderTarget_t>(width, height); rt0->layout({{4, rt_layout_t::FLOAT}}, rbo); m_renderTargets.push_back(std::move(rt0)); auto rt1 = pymol::make_unique<renderTarget_t>(width, height); rt1->layout({{1, rt_layout_t::FLOAT}}, rt0->rbo()); m_renderTargets.push_back(std::move(rt1)); } else { std::vector<rt_layout_t> layouts; layouts.emplace_back(4, rt_layout_t::FLOAT); if (GLEW_VERSION_3_0) { layouts.emplace_back(1, rt_layout_t::FLOAT); } else { layouts.emplace_back(2, rt_layout_t::FLOAT); } auto rt0 = pymol::make_unique<renderTarget_t>(width, height); rt0->layout(std::move(layouts), rbo); m_renderTargets.push_back(std::move(rt0)); } } void OIT_PostProcess::bindRT(std::size_t idx, bool clear) { #if !defined(PURE_OPENGL_ES_2) || defined(_WEBGL) if (TM3_IS_ONEBUF) { auto& rt = m_renderTargets[idx - 1]; if (rt) rt->fbo()->bind(); } else { const GLenum bufs[] = {GL_COLOR_ATTACHMENT0_EXT, GL_COLOR_ATTACHMENT1_EXT}; if (!m_renderTargets.empty()) { auto& rt = m_renderTargets.front(); if (rt) { rt->fbo()->bind(); } } glDrawBuffers(2, bufs); } glClearColor(0.f, 0.f, 0.f, 0.f); glClear(GL_COLOR_BUFFER_BIT); glDepthMask(GL_FALSE); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); #endif } void OIT_PostProcess::activateRTAsTexture(std::size_t idx, GLuint textureUnit) { glActiveTexture(GL_TEXTURE0 + textureUnit); if (TM3_IS_ONEBUF) { auto& rt = m_renderTargets[idx]; auto& tex = rt->textures().front(); if (tex) { tex->bind(); } } else { auto& rt = m_renderTargets.front(); if (rt) { rt->textures()[idx]->bind(); } } }
23.928571
79
0.658375
[ "vector" ]
d4a6fce56bc3c20aef59a83cdb303c9c833b2b33
2,148
hpp
C++
include/seqan3/core/detail/debug_stream_tuple.hpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
include/seqan3/core/detail/debug_stream_tuple.hpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
include/seqan3/core/detail/debug_stream_tuple.hpp
SGSSGene/seqan3
ab9ccb94d02c2f27b9b73b134ee2713de91bf722
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
// ----------------------------------------------------------------------------------------------------- // Copyright (c) 2006-2019, Knut Reinert & Freie Universität Berlin // Copyright (c) 2016-2019, Knut Reinert & MPI für molekulare Genetik // This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License // shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md // ----------------------------------------------------------------------------------------------------- /*!\file * \author Hannes Hauswedell <hannes.hauswedell AT fu-berlin.de> * \brief Provides seqan3::debug_stream and related types. */ #pragma once #include <seqan3/alphabet/concept.hpp> #include <seqan3/core/concept/tuple.hpp> #include <seqan3/core/detail/debug_stream_type.hpp> #include <seqan3/std/ranges> namespace seqan3 { /*!\name Formatted output overloads * \{ */ } // namespace seqan3 namespace seqan3::detail { //!\brief Helper function to print elements of a tuple separately. template <typename char_t, typename tuple_t, std::size_t ...I> void print_tuple(debug_stream_type<char_t> & s, tuple_t && t, std::index_sequence<I...> const &) { using std::get; s << '('; ((s << (I == 0 ? "" : ",") << get<I>(t)), ...); s << ')'; } } // namespace seqan3::detail namespace seqan3 { /*!\brief All tuples can be printed by printing their elements separately. * \tparam tuple_t Type of the tuple to be printed; must model seqan3::tuple_like. * \param s The seqan3::debug_stream. * \param t The tuple. * \relates seqan3::debug_stream_type */ template <typename tuple_t, typename char_t> //!\cond requires !std::ranges::input_range<tuple_t> && !alphabet<tuple_t> && // exclude alphabet_tuple_base tuple_like<remove_cvref_t<tuple_t>> //!\endcond inline debug_stream_type<char_t> & operator<<(debug_stream_type<char_t> & s, tuple_t && t) { detail::print_tuple(s, std::forward<tuple_t>(t), std::make_index_sequence<std::tuple_size_v<remove_cvref_t<tuple_t>>>{}); return s; } //!\} } // namespace seqan3
32.059701
104
0.622905
[ "model" ]
d4b11a8eb7c70ce2b6a5daffcaf4516f2b7b551c
3,059
cc
C++
tests/test_materials.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
null
null
null
tests/test_materials.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
null
null
null
tests/test_materials.cc
pbedenbaugh/MeshFEM
742d609d4851582ffb9c5616774fc2ef489e2f88
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// #include <MeshFEM/Materials.hh> #include <catch2/catch.hpp> //////////////////////////////////////////////////////////////////////////////// using json = nlohmann::json; //////////////////////////////////////////////////////////////////////////////// template<int N> void test_material(const std::string &config) { // Test reading Materials::Constant<N> mat; mat.setFromJson(json::parse(config)); std::cout << mat.getJson().dump(4) << std::endl; // Test writing and reading again json output1 = mat.getJson(); Materials::Constant<N> mat2; mat2.setFromJson(output1); json output2 = mat2.getJson(); REQUIRE(output1 == output2); } //////////////////////////////////////////////////////////////////////////////// TEST_CASE("reading material json files", "[materials]" ) { std::string config2d; std::string config3d; SECTION("Isotropic mateiral") { config2d = config3d = R"({ "type": "isotropic", "young": 200, "poisson": 0.3 })"; } SECTION("Othrotropic mateiral") { // 2D: "young": [young_x, young_y], // "poisson": [poisson_xy, poisson_yx], // "shear": [shear_xy], config2d = R"({ "type": "orthotropic", "young": [2.933545, 2.933545], "poisson": [0.27186, 0.27186], "shear": [0.87212] })"; // 3D: "young": [young_x, young_y, young_z], // "poisson": [poisson_yz, poisson_zy, // poisson_zx, poisson_xz, // poisson_xy, poisson_yx], // "shear": [shear_yz, shear_zx, shear_xy], config3d = R"({ "type": "orthotropic", "young": [1.0, 2.0, 3.0], "poisson": [0.6, 0.9, 0.9, 0.3, 0.3, 0.6], "shear": [0.1, 0.2, 0.3] })"; } SECTION("Anisotropic mateiral") { // "material_matrix": [[C_00, C_01, C02, C03, C04, C05], // [C_10, C_11, C12, C13, C14, C15], // [C_20, C_21, C22, C23, C24, C25], // [C_30, C_31, C32, C33, C34, C35], // [C_40, C_41, C42, C43, C44, C45], // [C_50, C_51, C52, C53, C54, C55]], config2d = R"({ "type": "anisotropic", "material_matrix": [ [9.0, 0.1, 0.2], [0.1, 9.0, 0.3], [0.2, 0.3, 1.0] ] })"; config3d = R"({ "type": "anisotropic", "material_matrix": [ [9.0, 0.1, 0.2, 0.5, 0.5, 0.5], [0.1, 9.0, 0.3, 0.5, 0.5, 0.5], [0.2, 0.3, 9.0, 0.5, 0.5, 0.5], [0.5, 0.5, 0.5, 1.5, 0.1, 0.2], [0.5, 0.5, 0.5, 0.1, 1.6, 0.3], [0.5, 0.5, 0.5, 0.2, 0.3, 1.7] ] })"; } test_material<2>(config2d); test_material<3>(config3d); } TEST_CASE("setting material bounds", "[materials]" ) { const std::string config = R"({ "lower": [ [0, 25], [1, 0.1] ], "upper": [ [0, 292], [1, 0.6] ] })"; Materials::Isotropic<2>::setBoundsFromJson(json::parse(config)); Materials::Orthotropic<2>::setBoundsFromJson(json::parse(config)); Materials::Isotropic<3>::setBoundsFromJson(json::parse(config)); Materials::Orthotropic<3>::setBoundsFromJson(json::parse(config)); }
28.06422
80
0.490356
[ "3d" ]
d4ca5518668e5ed02c2f292e4bbdaf091f26ee20
262,339
cpp
C++
fallen/DDEngine/Source/figure.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
188
2017-05-20T03:26:33.000Z
2022-03-10T16:58:39.000Z
fallen/DDEngine/Source/figure.cpp
dizzy2003/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
7
2017-05-28T14:28:13.000Z
2022-01-09T01:47:38.000Z
fallen/DDEngine/Source/figure.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
43
2017-05-20T07:31:32.000Z
2022-03-09T18:39:35.000Z
// // Draw a person. // #include "game.h" #include "aeng.h" #include "poly.h" #include "figure.h" #include "sprite.h" #include "c:\fallen\headers\fmatrix.h" #include "c:\fallen\headers\mav.h" #include "c:\fallen\headers\interact.h" #include "night.h" #include "shadow.h" #include "matrix.h" #include "animate.h" #include "mesh.h" #include "dirt.h" #include "texture.h" #include "math.h" #include "interfac.h" #include "Hierarchy.h" // JCL is gay // MA wears girly shorts // JCL #include "Quaternion.h" #include "memory.h" #include "c:\fallen\headers\person.h" #include "c:\fallen\headers\pcom.h" #include "c:\fallen\headers\eway.h" #include "c:\fallen\headers\dirt.h" #include "ddlib.h" #include "panel.h" #include "renderstate.h" #include "poly.h" #include "polypage.h" #include "psystem.h" #ifndef TARGET_DC #define LOG_ENTER(x) {} #define LOG_EXIT(x) {} #define LOG_EVENT(x) {} #endif #ifdef TARGET_DC // intrinsic maths #include <shsgintr.h> #endif extern BOOL allow_debug_keys; SLONG FIGURE_alpha = 255; SLONG steam_seed; extern UWORD alt_texture[]; UBYTE body_part_upper[]= { 0,0,0,0,1,1,1,1,1,1,1,1,0,0,0 }; void DeadAndBuried ( DWORD dwColour ) { // draw a colour on the screen to try to diagnose things if they do crash. DDSURFACEDESC2 mine; HRESULT res; InitStruct(mine); mine.dwFlags = DDSD_PITCH; res = the_display.lp_DD_FrontSurface->Lock ( NULL, &mine, DDLOCK_WAIT, NULL ); if (FAILED(res)) return; char *pdwDest = (char *)mine.lpSurface; for ( int i = 0; i < 50; i++ ) { DWORD *pdwDest1 = (DWORD*)pdwDest; pdwDest += mine.lPitch; for ( int j = 0; j < 50; j++ ) { *pdwDest1++ = dwColour; } } res = the_display.lp_DD_FrontSurface->Unlock ( NULL ); } // Returns TRUE if this chunk is not near-Z clipped, FALSE if it is. bool FIGURE_draw_prim_tween_person_only_just_set_matrix ( int iMatrixNum, SLONG prim, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, SLONG recurse_level, Thing *p_thing ); void FIGURE_draw_prim_tween_person_only( SLONG prim, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, SLONG recurse_level, Thing *p_thing ); // Now enabled only on a cheat! //#define HIGH_REZ_PEOPLE_PLEASE_BOB #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB bool m_bPleaseInflatePeople = FALSE; #endif #if USE_TOMS_ENGINE_PLEASE_BOB #if USE_TOMS_ENGINE_PLEASE_BOB // Useful. #define ALIGNED_STATIC_ARRAY(def,name,number,mytype,align) \ static char c##name##mytype##align##StaticArray [ align + number * sizeof ( mytype ) ]; \ def##name = (mytype *)( ( (DWORD)c##name##mytype##align##StaticArray + (align-1) ) & ~(align-1) ) ALIGNED_STATIC_ARRAY ( static D3DCOLOR *, MM_pcFadeTable, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( static D3DCOLOR *, MM_pcFadeTableTint, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( static D3DMATRIX *, MM_pMatrix, 1, D3DMATRIX, 32 ); ALIGNED_STATIC_ARRAY ( static D3DVERTEX *, MM_Vertex, 4, D3DVERTEX, 32 ); ALIGNED_STATIC_ARRAY ( static float *, MM_pNormal, 4, float, 8 ); #if 0 // The MM lighting table. D3DCOLOR *MM_pcFadeTable = NULL; D3DCOLOR *MM_pcFadeTableTint = NULL; D3DMATRIX *MM_pMatrix = NULL; D3DVERTEX *MM_Vertex = NULL; float *MM_pNormal = NULL; #endif D3DVECTOR MM_vLightDir; bool MM_bLightTableAlreadySetUp = FALSE; // Something to build lighting tables. void BuildMMLightingTable ( Pyro *p, DWORD colour_and=0xffffffff ) { LOG_ENTER ( Figure_Build_Table ) // REMEMBER THAT ALL THE LIGHT DIRECTIONS ARE NEGATIVE, // EXCEPT FOR THE AMBIENT ONE, WHICH IS CORRECT. // Daft bloody system. ASSERT ( MM_pcFadeTable != NULL ); ASSERT ( MM_pcFadeTableTint != NULL ); ASSERT ( MM_pMatrix != NULL ); ASSERT ( MM_Vertex != NULL ); ASSERT ( MM_pNormal != NULL ); // Find the brightest-lit vector. float fBright = NIGHT_amb_red * 0.35f + NIGHT_amb_green * 0.45f + NIGHT_amb_blue * 0.2f; D3DVECTOR vTotal; vTotal.x = fBright * NIGHT_amb_norm_x; vTotal.y = fBright * NIGHT_amb_norm_y; vTotal.z = fBright * NIGHT_amb_norm_z; NIGHT_Found *nf; for (int j = 0; j < NIGHT_found_upto; j++) { nf = &NIGHT_found[j]; // Find a rough approximation to brightness. float fBright = nf->r * 0.35f + nf->g * 0.45f + nf->b * 0.2f; // If it is a negative light - make it "illuminate" from the opposite direction. // This solves the problem of a red light above, an anti-red below, and a soft green to the right. // If the reds both pulled in opposite direction, the green would actually be the main one, // which is silly as the object is obviously mainly red and black. //if ( fBright > 0.0f ) { // These are negative! vTotal.x -= fBright * nf->dx; vTotal.y -= fBright * nf->dy; vTotal.z -= fBright * nf->dz; } #if 0 else { // Negative light - make it "illuminate" from the correct direction. // Directions are also negative! vTotal.x += fBright * nf->dx; vTotal.y += fBright * nf->dy; vTotal.z += fBright * nf->dz; } #endif } // Unitise the vector. #ifdef TARGET_DC float fLength = _InvSqrtA ( vTotal.x * vTotal.x + vTotal.y * vTotal.y + vTotal.z * vTotal.z ); #else float fLength = 1.0f / sqrtf ( vTotal.x * vTotal.x + vTotal.y * vTotal.y + vTotal.z * vTotal.z ); #endif vTotal.x *= fLength; vTotal.y *= fLength; vTotal.z *= fLength; // Now light this vector and its negative, just as the software engine does. D3DCOLORVALUE cvAmb, cvLight; //#define AMBIENT_FACTOR (1.0f * 256.0f) #define AMBIENT_FACTOR (0.5f * 256.0f) // Real ambient factor. cvAmb.r = NIGHT_amb_red * AMBIENT_FACTOR; cvAmb.g = NIGHT_amb_green * AMBIENT_FACTOR; cvAmb.b = NIGHT_amb_blue * AMBIENT_FACTOR; // Terrible fudge - on nighttime missions, the ambient is too dark, or on daytime ones, it's too bright. // So if the given ambient (the sun) is below a certain value, ramp up the ambient to compensate. if ( ( NIGHT_amb_red + NIGHT_amb_green + NIGHT_amb_blue ) < 100 ) { // FUDGE IT! cvAmb.r *= 2.0f; cvAmb.g *= 2.0f; cvAmb.b *= 2.0f; } cvLight = cvAmb; float fDotProd = vTotal.x * NIGHT_amb_norm_x + vTotal.y * NIGHT_amb_norm_y + vTotal.z * NIGHT_amb_norm_z; if ( fDotProd < 0.0f ) { cvAmb.r -= fDotProd * NIGHT_amb_red; cvAmb.g -= fDotProd * NIGHT_amb_green; cvAmb.b -= fDotProd * NIGHT_amb_blue; } else { cvLight.r += fDotProd * NIGHT_amb_red; cvLight.g += fDotProd * NIGHT_amb_green; cvLight.b += fDotProd * NIGHT_amb_blue; } for (j = 0; j < NIGHT_found_upto; j++) { nf = &NIGHT_found[j]; // These are negative! fDotProd = - vTotal.x * nf->dx - vTotal.y * nf->dy - vTotal.z * nf->dz; if ( fDotProd < 0.0f ) { cvAmb.r -= fDotProd * nf->r; cvAmb.g -= fDotProd * nf->g; cvAmb.b -= fDotProd * nf->b; } else { cvLight.r += fDotProd * nf->r; cvLight.g += fDotProd * nf->g; cvLight.b += fDotProd * nf->b; } } MM_vLightDir = vTotal; // Is this thing on fire? if ( p != NULL ) { // On fire. Blacken with soot or something. cvLight.r = (cvLight.r > p->counter) ? (cvLight.r - p->counter) : 10; cvLight.g = (cvLight.g > p->counter) ? (cvLight.g - p->counter) : 4; cvLight.b = (cvLight.b > p->counter) ? (cvLight.b - p->counter) : 3; cvAmb.r = (cvAmb.r > p->counter) ? (cvAmb.r - p->counter) : 10; cvAmb.g = (cvAmb.g > p->counter) ? (cvAmb.g - p->counter) : 4; cvAmb.b = (cvAmb.b > p->counter) ? (cvAmb.b - p->counter) : 3; } #if 1 // On the PC, people are lit x2, so we need to double these. cvLight.r *= 2.0f; cvLight.g *= 2.0f; cvLight.b *= 2.0f; cvAmb.r *= 2.0f; cvAmb.g *= 2.0f; cvAmb.b *= 2.0f; #endif // OK, now make up the fade table for this light. const float fColourScale = ( 1.0f / ( 256.0f * 128.0f ) ) * 255.0f * NIGHT_LIGHT_MULTIPLIER; D3DCOLORVALUE cvCur = cvAmb; cvLight.r -= cvAmb.r; cvLight.g -= cvAmb.g; cvLight.b -= cvAmb.b; cvCur.r *= fColourScale; cvCur.g *= fColourScale; cvCur.b *= fColourScale; cvLight.r *= ( fColourScale / 64.0f ); cvLight.g *= ( fColourScale / 64.0f ); cvLight.b *= ( fColourScale / 64.0f ); // Ambient colour. unsigned char cR, cG, cB; if ( cvCur.r > 255.0f ) { cR = 255; } else if ( cvCur.r < 0.0f ) { cR = 0; } else { cR = (unsigned char)( cvCur.r ); } if ( cvCur.g > 255.0f ) { cG = 255; } else if ( cvCur.g < 0.0f ) { cG = 0; } else { cG = (unsigned char)( cvCur.g ); } if ( cvCur.b > 255.0f ) { cB = 255; } else if ( cvCur.b < 0.0f ) { cB = 0; } else { cB = (unsigned char)( cvCur.b ); } DWORD dwColour = ( (DWORD)cR << 16 ) | ( (DWORD)cG << 8 ) | ( (DWORD)cB ); for ( int i = 64; i < 128; i++ ) { MM_pcFadeTable[i] = dwColour; MM_pcFadeTableTint[i] = dwColour & colour_and; } // Ramp up to full brightness. for ( i = 0; i < 64; i++ ) { if ( cvCur.r > 255.0f ) { cR = 255; } else if ( cvCur.r < 0.0f ) { cR = 0; } else { cR = (unsigned char)( cvCur.r ); } if ( cvCur.g > 255.0f ) { cG = 255; } else if ( cvCur.g < 0.0f ) { cG = 0; } else { cG = (unsigned char)( cvCur.g ); } if ( cvCur.b > 255.0f ) { cB = 255; } else if ( cvCur.b < 0.0f ) { cB = 0; } else { cB = (unsigned char)( cvCur.b ); } dwColour = ( (DWORD)cR << 16 ) | ( (DWORD)cG << 8 ) | ( (DWORD)cB ); MM_pcFadeTable[i] = dwColour; MM_pcFadeTableTint[i] = dwColour & colour_and; cvCur.r += cvLight.r; cvCur.g += cvLight.g; cvCur.b += cvLight.b; } LOG_EXIT ( Figure_Build_Table ) } #endif struct EdgeList { WORD wPt1, wPt2; WORD wMidPt; }; // The MS list optimiser. They gave it to me, so I'll use it! Might as well. /*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 1998-1999 Microsoft Corporation Module Name: optlist.cpp Abstract: Source code for Index List Optimizer -------------------------------------------------------------------*/ typedef struct tagIndexTri { int v1,v2,v3; int done; } INDEXTRISTRUCT; typedef struct tagIndexVert { WORD wIndex; // Index of this vertex int nShareCount; // Number of triangles sharing this vertex int rgSharedTris[30]; // Array of triangles that share this vertex } INDEXVERTSTRUCT; class MSMesh { private: INDEXTRISTRUCT *m_aTri; int m_nNumTri; int m_nMaxTri; INDEXVERTSTRUCT *m_aVert; int m_nNumVert; int m_nMaxVert; int NextTri( int v1, int v2, int *v3 ); void ClearTempDone( int nValue ); int StripLen( int startTri, int dir, int setit, WORD *pwOut, int nMaxLen ); public: MSMesh(); ~MSMesh(); void Clear() { m_nNumTri = 0; m_nNumVert = 0; } int AddTri( WORD wV1, WORD wV2, WORD wV3 ); int GetStrip( WORD *pwV, int maxlen ); int NumVertices() { return m_nNumVert; } int FindOrAddVertex( WORD wVert ); int SetSize( int nTriangles ); }; MSMesh::MSMesh() { memset( this, 0, sizeof(*this) ); } int MSMesh::SetSize ( int nTriangles ) { if ( nTriangles <= 0 ) { // printf("SetSize: freeing allocations\n"); if ( m_aTri ) { MemFree( m_aTri ); m_aTri = (INDEXTRISTRUCT *)NULL; } if ( m_aVert ) { MemFree( m_aVert ); m_aVert = (INDEXVERTSTRUCT *)NULL; } m_nMaxTri = 0; m_nMaxVert = 0; } else { if( nTriangles > m_nMaxTri ) { // MemFree any previous allocation SetSize(0); m_nMaxTri = nTriangles + 10; // allow room for growth m_nMaxVert = m_nMaxTri * 3; if( m_nMaxVert > 65536 ) m_nMaxVert = 65536; // Allocate new space // printf("SetSize allocating space for %d indices and %d vertices\n", // m_nMaxTri, m_nMaxVert ); m_aTri = (INDEXTRISTRUCT *)MemAlloc( m_nMaxTri * sizeof(INDEXTRISTRUCT) ); if ( m_aTri == NULL ) { DeadAndBuried ( 0x07e007e0 ); } m_aVert = (INDEXVERTSTRUCT *)MemAlloc( m_nMaxVert * sizeof(INDEXVERTSTRUCT) ); if ( m_aVert == NULL ) { DeadAndBuried ( 0x07e007e0 ); } if( !m_aTri || !m_aVert ) SetSize(0); // MemFree half-allocations } } return m_nMaxTri; } MSMesh::~MSMesh() { SetSize(0); } int MSMesh::FindOrAddVertex( WORD wVert ) { int vertno; for( vertno =0; vertno < m_nNumVert; vertno++ ) if( m_aVert[vertno].wIndex == wVert ) return vertno; vertno = m_nNumVert++; m_aVert[vertno].wIndex = wVert; m_aVert[vertno].nShareCount = 0; return vertno; } int MSMesh::AddTri( WORD wV1, WORD wV2, WORD wV3 ) { int trino = m_nNumTri++; int v1 = FindOrAddVertex( wV1 ); int v2 = FindOrAddVertex( wV2 ); int v3 = FindOrAddVertex( wV3 ); m_aVert[v1].rgSharedTris[m_aVert[v1].nShareCount++] = trino; m_aVert[v2].rgSharedTris[m_aVert[v2].nShareCount++] = trino; m_aVert[v3].rgSharedTris[m_aVert[v3].nShareCount++] = trino; m_aTri[trino].v1 = v1; m_aTri[trino].v2 = v2; m_aTri[trino].v3 = v3; /* printf(" tri %d(%d,%d,%d)\n", trino, m_aTri[trino].v1, m_aTri[trino].v2, m_aTri[trino].v3 ); */ m_aTri[trino].done = 0; return trino; } void MSMesh::ClearTempDone( int nValue ) { int trino; for( trino = 0; trino < m_nNumTri; trino++ ) if( m_aTri[trino].done == 2 ) { m_aTri[trino].done = nValue; } } int MSMesh::StripLen( int startTri, int dir, int setit, WORD *pwOut, int nMaxLen ) { int v1, v2, v3; int trino = startTri; int len = 0; if( (dir>>1) == 0 ) { v1 = m_aTri[startTri].v1; v2 = m_aTri[startTri].v2; v3 = m_aTri[startTri].v3; } else if( (dir>>1) == 1 ) { v1 = m_aTri[startTri].v2; v2 = m_aTri[startTri].v3; v3 = m_aTri[startTri].v1; } else { v1 = m_aTri[startTri].v3; v2 = m_aTri[startTri].v1; v3 = m_aTri[startTri].v2; } while( trino != -1 ) { if( pwOut ) { *pwOut++ = m_aVert[v1].wIndex; *pwOut++ = m_aVert[v2].wIndex; *pwOut++ = m_aVert[v3].wIndex; // printf("len = %d, adding triangle %d: %d,%d,%d\n", len, trino, v1, v2, v3 ); } len++; m_aTri[trino].done = 2; // mark as temporarily done if( len >= nMaxLen ) break; // Sequence: // // 0 1 2 // 1 3 2 // 2 3 4 // 3 5 4 if( len & 1 ) // generate 1 3 2 from 0 1 2 { v1 = v2; trino = NextTri( v3, v1, &v2 ); } else // generate 2 3 4 from 1 3 2 { v1 = v3; trino = NextTri( v1, v2, &v3 ); } } ClearTempDone(setit); // printf( "\nStrip starting at triangle %d, dir %d len=%d\n", startTri, dir, len); return len; } int MSMesh::GetStrip ( WORD *pwVT, int maxLen ) { int trino; int len; int dir; int bestStart; int bestDir; int bestLen=0; // printf("MSMesh: %d triangles, %d vertices\n", m_nNumTri, m_nNumVert ); for( trino = 0; trino < m_nNumTri; trino++ ) { if( m_aTri[trino].done ) continue; for( dir = 0; dir<3; dir++ ) { if( ( len = StripLen( trino, dir, 0, NULL, maxLen ) ) > bestLen ) { bestLen = len; bestStart = trino; bestDir = dir; if( bestLen >= maxLen ) { // force it to exit trino = m_nNumTri; break; } } } } if( bestLen > 0 ) StripLen( bestStart, bestDir, 1, pwVT, maxLen ); return bestLen; } int MSMesh::NextTri( int v1, int v2, int *v3 ) { int subtri; int trino; for( subtri = 0; subtri < m_aVert[v1].nShareCount; subtri++ ) { trino = m_aVert[v1].rgSharedTris[subtri]; if( m_aTri[trino].done ) continue; if( m_aTri[trino].v1 == v1 ) { if( m_aTri[trino].v2 == v2 ) { *v3 = m_aTri[trino].v3; // printf("found tri %d: %d,%d,%d\n", trino, v1, v2, *v3 ); return trino; } } else if( m_aTri[trino].v2 == v1 ) { if( m_aTri[trino].v3 == v2 ) { *v3 = m_aTri[trino].v1; // printf("found tri %d: %d,%d,%d\n", trino, v1, v2, *v3 ); return trino; } } else if( m_aTri[trino].v3 == v1 ) { if( m_aTri[trino].v1 == v2 ) { *v3 = m_aTri[trino].v2; // printf("found tri %d: %d,%d,%d\n", trino, v1, v2, *v3 ); return trino; } } } return -1; // no more in this direction } static MSMesh mesh; BOOL MSOptimizeIndexedList( WORD *pwIndices, int nTriangles ) { if( !mesh.SetSize( nTriangles ) ) return FALSE; mesh.Clear(); WORD *pwInd = pwIndices; for ( int i = 0; i < nTriangles; i++ ) { mesh.AddTri( pwInd[0], pwInd[1], pwInd[2] ); pwInd += 3; } if( mesh.NumVertices() == 0 ) return FALSE; int nLength = nTriangles; int nTotal = 0; while ( nTotal < nTriangles ) { nLength = mesh.GetStrip( pwIndices, nLength ); pwIndices += ( nLength * 3 ); nTotal += nLength; } return TRUE; } #endif //#if USE_TOMS_ENGINE_PLEASE_BOB /* // D3D lighting fucntions. #define MAX_NUM_OF_LIGHTS 10 LPDIRECT3DLIGHT m_pLight[MAX_NUM_OF_LIGHTS]; bool m_bLightInScene[MAX_NUM_OF_LIGHTS]; int m_iNumLights = 0; int FindMeAFreeLightAndPutItInTheScene ( void ) { int i = 0; while ( TRUE ) { ASSERT ( i < MAX_NUM_OF_LIGHTS ); if ( !m_bLightInScene[i] ) { // Found one. break; } i++; } if ( m_pLight[i] == NULL ) { // Haven't created this one yet. HRESULT hres = (the_display.lp_D3D)->CreateLight ( &(m_pLight[i]), NULL ); ASSERT ( SUCCEEDED ( hres ) ); } // Add the light in. HRESULT hres = (the_display.lp_D3D_Viewport)->AddLight ( m_pLight[i] ); ASSERT ( SUCCEEDED ( hres ) ); m_bLightInScene[i] = TRUE; return ( i ); } void MakeThisLightLikeThis ( int iLightNum, D3DLIGHT *pd3dLight ) { ASSERT ( m_bLightInScene[iLightNum] ); ASSERT ( m_pLight[iLightNum] != NULL ); HRESULT hres = (m_pLight[iLightNum])->SetLight ( (D3DLIGHT *)pd3dLight ); ASSERT ( SUCCEEDED ( hres ) ); } void MakeThisLightLikeThis ( int iLightNum, D3DLIGHT2 *pd3dLight ) { MakeThisLightLikeThis ( iLightNum, (D3DLIGHT *)pd3dLight ); } void RemoveThisLightFromScene ( int iLightNum ) { ASSERT ( m_bLightInScene[iLightNum] ); ASSERT ( m_pLight[iLightNum] != NULL ); HRESULT hres = (the_display.lp_D3D_Viewport)->DeleteLight ( m_pLight[iLightNum] ); ASSERT ( SUCCEEDED ( hres ) ); m_bLightInScene[iLightNum] = FALSE; } #if 0 int AddThisSortOfLightToTheScene ( D3DLIGHT *pd3dLight ) { int iLightNum = FindMeAFreeLightAndPutItInTheScene(); MakeThisLightLikeThis ( iLightNum, pd3dLight ); return ( iLightNum ); } int AddThisSortOfLightToTheScene ( D3DLIGHT2 *pd3dLight ) { return ( AddThisSortOfLightToTheScene ( (D3DLIGHT *)pd3dLight ) ); } void RemoveAllLightsFromScene ( void ) { for ( int i = 0; i < MAX_NUM_OF_LIGHTS; i++ ) { if ( m_bLightInScene[i] ) { RemoveThisLightFromScene ( i ); } } } #else // HACKED! int AddThisSortOfLightToTheScene ( D3DLIGHT2 *pd3dLight ) { if ( m_pLight[0] == NULL ) { FindMeAFreeLightAndPutItInTheScene(); MakeThisLightLikeThis ( 0, pd3dLight ); } return ( 0 ); } void RemoveAllLightsFromScene ( void ) { } #endif */ SLONG get_steam_rand(void) { steam_seed*=31415965; steam_seed+=123456789; return(steam_seed>>8); } extern int AENG_detail_crinkles; #define MAX_STEAM 100 void draw_steam(SLONG x,SLONG y,SLONG z,SLONG lod) { SLONG c0; float u,v; SLONG trans; // // waft gently up from x,y,z // // Internal gubbins. POLY_set_local_rotation_none(); steam_seed=54321678; if(lod>40) lod=40; for(c0=0;c0<lod;c0++) { SLONG dx,dy,dz; if(c0&1) u=0.0; else u=0.5; if(c0&2) v=0.0; else v=0.5; dy=get_steam_rand()&0x1ff; dy+=(GAME_TURN*((c0&3)+2)); dy%=500; dx=(((get_steam_rand()&0xff)-128)*((dy>>2)+80))>>9; dz=(((get_steam_rand()&0xff)-128)*((dy>>2)+80))>>9; if(dy>16) { // dx+=COS(GAME_TURN*10)%(dy>>4); // dz+=SIN(GAME_TURN*10)%(dy>>4); } if(c0&4) { dx+=COS(dy*4); dz+=SIN(dy*4); } /* trans=(c0*128)/MAX_STEAM; if(dy>300) trans=(trans*5)/(dy-295);*/ /* if (dy<40) trans=dy*3; else // trans=(256-dy)*0.5; trans=(256-dy) / 2; // JCL - changed to fix an annoying warning (don't think it worked anyway...) */ /* trans=128-(dy>>2); if(trans<1) trans=1; */ if(dy>500-(13*16)) { trans=(500-dy)>>4; } if(dy<13*4) { trans=dy>>2; } else { trans=13; } dx+=x; dy+=y; dz+=z; if(trans>=1) { // trans*=0x010101; trans |= trans << 8; trans |= trans << 8; SPRITE_draw_tex( float(dx), float(dy), float(dz), float(((dy-y)>>2)+150), trans, 0, POLY_PAGE_STEAM, u,v,0.5,0.5, SPRITE_SORT_NORMAL); } } } UBYTE fire_pal[768]; void init_flames() { MFFileHandle handle = FILE_OPEN_ERROR; handle=FileOpen("data\\flames1.pal"); if(handle!=FILE_OPEN_ERROR) { FileRead(handle,(UBYTE*)&fire_pal,768); FileClose(handle); } else TRACE("Missing flame palette file.\n"); } extern int AENG_detail_skyline; void draw_flames(SLONG x,SLONG y,SLONG z,SLONG lod,SLONG offset) { SLONG c0; SLONG trans; SLONG page; float scale; float u,v,w,h; UBYTE* palptr; SLONG palndx; float wx1,wy1,wx2,wy2,wx3,wy3,wx4,wy4; UBYTE type; // // waft gently up from x,y,z // steam_seed=54321678+offset; #if 0 // Now moved to the actual callers instead. SLONG lod_mul; #ifndef TARGET_DC extern UBYTE sw_hack; if (sw_hack || !AENG_detail_skyline)//||ShiftFlag) #else if (!AENG_detail_skyline)//||ShiftFlag) #endif { lod_mul = 2; } else { lod_mul = 5; } #endif //for(c0=0;c0<lod*lod_mul;c0++) for(c0=0;c0<lod;c0++) { SLONG dx,dy,dz; w=h=1.0; u=v=0.0; type=c0&3; /* if (!type) { page=POLY_PAGE_SMOKECLOUD2; } else */ { // page=POLY_PAGE_FLAMES2; if ((type==1)||(type==2)) page=POLY_PAGE_FLAMES2; else page=POLY_PAGE_PCFLAMER; dy=(GAME_TURN+c0)/2; u=0.25f*(dy&3); v=0.25f*((dy&!3)/3); v+=0.002f; w=h=0.25f; dy=0; } dy=get_steam_rand()&0x1ff; dy+=(GAME_TURN*5); dy%=500; dx=(((get_steam_rand()&0xff)-128)*((dy>>2)+150))>>9; dz=(((get_steam_rand()&0xff)-128)*((dy>>2)+150))>>9; if (type==2) { dx>>=2; dz>>=2; } if (type==1) { dx>>=1; dz>>=1; } wy1=wy2=wy3=wy4=0; wx1=(float)COS(((dy+c0)*11)&1023)*0.0001f; wx2=(float)COS(((dy+c0)*10)&1023)*0.0001f; wx3=(float)COS(((dy+c0)*8)&1023)*0.0001f; wx4=(float)COS(((dy+c0)*9)&1023)*0.0001f; trans=255-dy; dx+=x; dy+=y; dz+=z; if(trans>=1) { switch (type) { /* case 0: // smoke trans+=(trans<<8)|(trans<<16)|(trans<<24); scale=float(((dy-y)>>1)+80); dy+=50; palptr=(trans*3)+fire_pal; palndx=(256-trans)*3; trans<<=24; trans+=(fire_pal[palndx]<<16)+(fire_pal[palndx+1]<<8)+fire_pal[palndx+2];*/ // break; case 1: // outer dy>>=1; case 2: // innter palptr=(trans*3)+fire_pal; palndx=(256-trans)*3; // trans=0xff; trans<<=24; // trans+=0xffffff; // trans+=((*palptr++)<<8)|((*palptr++)<<16)|((*palptr++)<<24); trans+=(fire_pal[palndx]<<16)+(fire_pal[palndx+1]<<8)+fire_pal[palndx+2]; //scale=(dy>>2)+50; scale=50; break; case 0: case 3: // flame trans=abs(dy-y)*20; trans=SIN(trans); trans|=0x00FFFFFF; scale=100; dy=y; break; } // SPRITE_draw_tex( #ifdef TARGET_DC SPRITE_draw_tex_distorted_params Params; #define SET_IN_PARAMS(argname) Params.argname = argname SET_IN_PARAMS(u); SET_IN_PARAMS(v); SET_IN_PARAMS(w); SET_IN_PARAMS(h); SET_IN_PARAMS(wx1); SET_IN_PARAMS(wy1); SET_IN_PARAMS(wx2); SET_IN_PARAMS(wy2); SET_IN_PARAMS(wx3); SET_IN_PARAMS(wy3); SET_IN_PARAMS(wx4); SET_IN_PARAMS(wy4); #undef SET_IN_PARAMS SPRITE_draw_tex_distorted( float(dx), float(dy), float(dz), float(scale), trans, 0xff000000, page, SPRITE_SORT_NORMAL, &Params); #else //#ifdef TARGET_DC SPRITE_draw_tex_distorted( float(dx), float(dy), float(dz), float(scale), trans, 0xff000000, page, u, v, w, h, wx1,wy1,wx2,wy2,wx3,wy3,wx4,wy4, SPRITE_SORT_NORMAL); #endif //#else //#ifdef TARGET_DC } } } #ifndef PSX void draw_flame_element(SLONG x,SLONG y,SLONG z,SLONG c0,UBYTE base,UBYTE rand) { // SLONG c0; SLONG trans; SLONG page; float scale; float u,v,w,h; UBYTE* palptr; SLONG palndx; float wx1,wy1,wx2,wy2,wx3,wy3,wx4,wy4; SLONG dx,dy,dz; // // waft gently up from x,y,z // if (rand) steam_seed=54321678+(c0*get_steam_rand()); else steam_seed=54321678+c0; w=h=1.0; u=v=0.0; if(!(c0&3)) page=POLY_PAGE_FLAMES; else if (c0&4) page=POLY_PAGE_SMOKE; else { if (!base) { page=POLY_PAGE_FLAMES; } else { page=POLY_PAGE_FLAMES2; dy=(GAME_TURN+c0)/2; u=0.25f*(dy&3); // v=0.25f*((dy&~3)/4); v=0.25f*((dy>>2)&3); w=h=0.25f; } } dy=get_steam_rand()&0x1ff; dy+=(GAME_TURN*5); dy%=500; dx=(((get_steam_rand()&0xff)-128)*((dy>>2)+150))>>9; dz=(((get_steam_rand()&0xff)-128)*((dy>>2)+150))>>9; if (page==POLY_PAGE_FLAMES) { dx>>=2; dz>>=2; } wx1=wx2=wx3=wx4=0; wy1=wy2=wy3=wy4=0; /* wx1=COS(((dy+c0)*11)%1024)*0.0001; wx2=COS(((dy+c0)*10)%1024)*0.0001; wx3=COS(((dy+c0)*8)%1024)*0.0001; wx4=COS(((dy+c0)*9)%1024)*0.0001; */ wx1=(float)COS(((dy+c0)*11)&1023)*0.0001f; wx2=(float)COS(((dy+c0)*10)&1023)*0.0001f; wx3=(float)COS(((dy+c0)*8)&1023)*0.0001f; wx4=(float)COS(((dy+c0)*9)&1023)*0.0001f; trans=255-dy; dx+=x; dy+=y; dz+=z; if(trans>=1) { switch (page) { case POLY_PAGE_FLAMES: palptr=(trans*3)+fire_pal; palndx=(256-trans)*3; trans<<=24; trans+=(fire_pal[palndx]<<16)+(fire_pal[palndx+1]<<8)+fire_pal[palndx+2]; scale=50; break; case POLY_PAGE_FLAMES2: // trans=0xFFFFFFFF; palptr=(trans*3)+fire_pal; palndx=(256-trans)*3; trans<<=24; trans+=(fire_pal[palndx]<<16)+(fire_pal[palndx+1]<<8)+fire_pal[palndx+2]; scale=100; dy=50; break; case POLY_PAGE_SMOKE: trans+=(trans<<8)|(trans<<16)|(trans<<24); scale=float(((dy-y)>>1)+50); dy+=50; break; } #ifdef TARGET_DC SPRITE_draw_tex_distorted_params Params; #define SET_IN_PARAMS(argname) Params.argname = argname SET_IN_PARAMS(u); SET_IN_PARAMS(v); SET_IN_PARAMS(w); SET_IN_PARAMS(h); SET_IN_PARAMS(wx1); SET_IN_PARAMS(wy1); SET_IN_PARAMS(wx2); SET_IN_PARAMS(wy2); SET_IN_PARAMS(wx3); SET_IN_PARAMS(wy3); SET_IN_PARAMS(wx4); SET_IN_PARAMS(wy4); #undef SET_IN_PARAMS SPRITE_draw_tex_distorted( float(dx), float(dy), float(dz), float(scale), trans, 0xff000000, page, SPRITE_SORT_NORMAL, &Params); #else //#ifdef TARGET_DC SPRITE_draw_tex_distorted( float(dx), float(dy), float(dz), float(scale), trans, 0xff000000, page, u, v, w, h, wx1,wy1,wx2,wy2,wx3,wy3,wx4,wy4, SPRITE_SORT_NORMAL); #endif //#else //#ifdef TARGET_DC } } #endif //void FIGURE_rotate_obj2(SLONG matrix[9], SLONG yaw, SLONG pitch, SLONG roll) void FIGURE_rotate_obj2(SLONG pitch,SLONG yaw,SLONG roll, Matrix33 *r3) { SLONG cy, cp, cr; SLONG sy, sp, sr; cy = COS(yaw & 2047); cp = COS(pitch & 2047); cr = COS(roll & 2047); sy = SIN(yaw & 2047); sp = SIN(pitch & 2047); sr = SIN(roll & 2047); // // Jan I trust you... but only becuase I've already seen it working! // r3->M[0][0]= (MUL64( cy, cr) + MUL64(MUL64(sy, sp), sr))>>1; r3->M[0][1]= (MUL64( cy, sr) - MUL64(MUL64(sy, sp), cr))>>1; r3->M[0][2]= (MUL64( sy, cp))>>1; r3->M[1][0]= (MUL64(-cp, sr))>>1; r3->M[1][1]= (MUL64( cp, cr))>>1; r3->M[1][2]= (sp)>>1; r3->M[2][0]= (MUL64(-sy, cr) + MUL64(MUL64(cy, sp), sr))>>1; r3->M[2][1]= (MUL64(-sy, sr) - MUL64(MUL64(cy, sp), cr))>>1; r3->M[2][2]= (MUL64( cy, cp))>>1; } void FIGURE_rotate_obj(SLONG xangle,SLONG yangle,SLONG zangle, Matrix33 *r3) { SLONG sinx, cosx, siny, cosy, sinz, cosz; SLONG cxcz,sysz,sxsycz,sxsysz,sysx,cxczsy,sxsz,cxsysz,czsx,cxsy,sycz,cxsz; FIGURE_rotate_obj2(xangle,yangle,zangle,r3); return; sinx = SIN(xangle & (2048-1)) >>1; // 15's cosx = COS(xangle & (2048-1)) >>1; siny = SIN(yangle & (2048-1)) >>1; cosy = COS(yangle & (2048-1)) >>1; sinz = SIN(zangle & (2048-1)) >>1; cosz = COS(zangle & (2048-1)) >>1; cxsy = (cosx*cosy); // 30's sycz = (cosy*cosz); cxcz = (cosx*cosz); cxsz = (cosx*sinz); czsx = (cosz*sinx); sysx = (cosy*sinx); sysz = (cosy*sinz); sxsz = (sinx*sinz); sxsysz = (sxsz>>15)*siny; cxczsy = (cxcz>>15)*siny; cxsysz = ((cosx*siny)>>15)*sinz; sxsycz = (czsx>>15)*siny; // Define rotation matrix r3. r3->M[0][0] = (sycz)>>15; // 14's r3->M[0][1] = (-sysz)>>15; r3->M[0][2] = siny; r3->M[1][0] = (sxsycz+cxsz)>>15; r3->M[1][1] = (cxcz-sxsysz)>>15; r3->M[1][2] = (-sysx)>>15; r3->M[2][0] = (sxsz-cxczsy)>>15; r3->M[2][1] = (cxsysz+czsx)>>15; r3->M[2][2] = (cxsy)>>15; } //UBYTE store_dprod[500]; extern UBYTE TEXTURE_dontexist[]; // 0->3 // 4->7 // 8->11 // 12->15 UWORD jacket_lookup[4][8]= { {64+21,10*64+2,10*64+2,10*64+32}, {64+22,10*64+3,10*64+3,10*64+33}, {64+24,10*64+4,10*64+4,10*64+36}, {64+25,10*64+5,10*64+5,10*64+37} }; #if USE_TOMS_ENGINE_PLEASE_BOB // A huge number!!!! #define MAX_NUMBER_D3D_PRIMS MAX_PRIM_OBJECTS TomsPrimObject D3DObj[MAX_NUMBER_D3D_PRIMS]; float m_fObjectBoundingSphereRadius[MAX_NUMBER_D3D_PRIMS]; // 16 people types, 32 types of civ, and 6 different Roper ones (five weapons + no weapon). // Oh - number eight is his magic hip-flask! #define NUM_ROPERS_THINGIES 8 #define MAX_NUMBER_D3D_PEOPLE (32 + 16 + NUM_ROPERS_THINGIES) TomsPrimObject D3DPeopleObj[MAX_NUMBER_D3D_PEOPLE]; // iFaceNum: the face number // bTri: TRUE if it's a tri, FALSE if it's a quad. UWORD FIGURE_find_face_D3D_texture_page ( int iFaceNum, bool bTri ) { // Find the texture page/shading info. UWORD wTexturePage; DWORD dwDrawFlags, dwFaceFlags; if ( bTri ) { PrimFace3 *p_f3 = &prim_faces3[iFaceNum]; dwDrawFlags = p_f3->DrawFlags; dwFaceFlags = p_f3->FaceFlags; wTexturePage = p_f3->UV[0][0] & 0xc0; wTexturePage <<= 2; wTexturePage |= p_f3->TexturePage; } else { PrimFace4 *p_f4 = &prim_faces4[iFaceNum]; dwDrawFlags = p_f4->DrawFlags; dwFaceFlags = p_f4->FaceFlags; wTexturePage = p_f4->UV[0][0] & 0xc0; wTexturePage <<= 2; wTexturePage |= p_f4->TexturePage; } if ( ( dwDrawFlags & POLY_FLAG_TEXTURED ) == 0 ) { // Untextured. wTexturePage = TEXTURE_PAGE_FLAG_NOT_TEXTURED | POLY_PAGE_COLOUR; } else { // Textured. if(dwFaceFlags&FACE_FLAG_THUG_JACKET) { switch(wTexturePage) { case 64+21: case 10*64+2: case 10*64+32: wTexturePage = 0 | TEXTURE_PAGE_FLAG_JACKET; //page=jacket_lookup[0][GET_SKILL(p_thing)>>2]; break; case 64+22: case 10*64+3: case 10*64+33: wTexturePage = 1 | TEXTURE_PAGE_FLAG_JACKET; //page=jacket_lookup[1][GET_SKILL(p_thing)>>2]; break; case 64+24: case 10*64+4: case 10*64+36: wTexturePage = 2 | TEXTURE_PAGE_FLAG_JACKET; //page=jacket_lookup[2][GET_SKILL(p_thing)>>2]; break; case 64+25: case 10*64+5: case 10*64+37: wTexturePage = 3 | TEXTURE_PAGE_FLAG_JACKET; //page=jacket_lookup[3][GET_SKILL(p_thing)>>2]; break; default: ASSERT(FALSE); break; } //page+=FACE_PAGE_OFFSET; } else if ( ( wTexturePage > 10*64 ) && ( alt_texture[wTexturePage-10*64] != 0 ) ) { // An "offset" texture. This will be offset by a certain amount to // allow each prim to have different coloured clothes on. // Store the original value in the page number, because if tex_offset is zero // at runtime, we just add on FACE_PAGE_OFFSET. ASSERT ( ( wTexturePage & ~TEXTURE_PAGE_MASK ) == 0 ); wTexturePage |= TEXTURE_PAGE_FLAG_OFFSET; } else { wTexturePage += FACE_PAGE_OFFSET; // Make sure it actually fits in the available bit space. ASSERT ( ( wTexturePage & ~TEXTURE_PAGE_MASK ) == 0 ); } } if (dwFaceFlags & FACE_FLAG_TINT) { wTexturePage |= TEXTURE_PAGE_FLAG_TINT; } return ( wTexturePage ); } // The LRU queue for the prims. // Psycho Park is the most hungry. // Actually, Day of Reckoning is pretty bad too. // Max length of actual queue in TomsPrimObjects // MUST BE LESS THAN 256! #define PRIM_LRU_QUEUE_LENGTH 250 // Max size in number of vertices in queue. #define PRIM_LRU_QUEUE_SIZE 6000 int m_iLRUQueueSize = 0; TomsPrimObject *ptpoLRUQueue[PRIM_LRU_QUEUE_LENGTH]; DWORD dwGameTurnLastUsed[PRIM_LRU_QUEUE_LENGTH]; // Size of the queue in vertices. DWORD m_dwSizeOfQueue = 0; // "Cleans" a slot. void FIGURE_clean_LRU_slot ( int iSlot ) { TomsPrimObject *ptpo = ptpoLRUQueue[iSlot]; ASSERT ( ptpo != NULL ); if ( ptpo == NULL ) { // Toast aversion. This will cause it to leak memory, // but at least it won't die immediately. return; } m_dwSizeOfQueue -= (DWORD)ptpo->wTotalSizeOfObj; // Make sure it doesn't go negative! ASSERT ( ( m_dwSizeOfQueue & 0x80000000 ) == 0 ); ASSERT ( ptpo != NULL ); ASSERT ( ptpo->bLRUQueueNumber == iSlot ); ASSERT ( ptpo->wNumMaterials > 0 ); ASSERT ( ptpo->pMaterials != NULL ); ASSERT ( ptpo->pwListIndices != NULL ); MemFree ( ptpo->pMaterials ); // This block include pwStripIndices and pD3DVertices. MemFree ( ptpo->pwListIndices ); ptpo->pMaterials = NULL; ptpo->pwListIndices = NULL; ptpo->pD3DVertices = NULL; ptpo->pwStripIndices = NULL; ptpo->bLRUQueueNumber = 0xff; ptpo->wNumMaterials = 0; ptpo->wTotalSizeOfObj = 0; ptpoLRUQueue[iSlot] = NULL; } // This is suitable for calling at end of level. void FIGURE_clean_all_LRU_slots ( void ) { for ( int i = 0; i < m_iLRUQueueSize; i++ ) { if ( ptpoLRUQueue[i] != NULL ) { FIGURE_clean_LRU_slot ( i ); } } // And zero-length the queue. m_iLRUQueueSize = 0; // Make sure the queue is actually zero length, // or some accounting has screwed up somewhere. ASSERT ( m_dwSizeOfQueue == 0 ); } #ifdef DEBUG int g_iCacheReplacements = 0; bool g_bCacheReplacementThrash = FALSE; #endif // Adds the primobj to the LRU queue somewhere, evicting something else if need be. void FIGURE_find_and_clean_prim_queue_item ( TomsPrimObject *pPrimObj, int iThrashIndex = 0 ) { int iQueuePos; // Make sure nothing even gets close to filling all the space - that would be a disaster. // If this happens, the queue is far too small. // Roper is the biggest so far, at 529 vertices. ASSERT ( (DWORD)pPrimObj->wTotalSizeOfObj * 5< PRIM_LRU_QUEUE_SIZE ); // Silly man! ASSERT ( (DWORD)pPrimObj->wTotalSizeOfObj > 0 ); if ( ( m_iLRUQueueSize < PRIM_LRU_QUEUE_LENGTH ) && ( ( (DWORD)pPrimObj->wTotalSizeOfObj + m_dwSizeOfQueue ) < PRIM_LRU_QUEUE_SIZE ) ) { // That's easy then. iQueuePos = m_iLRUQueueSize; m_iLRUQueueSize++; } else { // No more free slots, or not enough free "memory" (vertices). Find the oldest one then. // First find enough memory. while ( ( (DWORD)pPrimObj->wTotalSizeOfObj + m_dwSizeOfQueue ) >= PRIM_LRU_QUEUE_SIZE ) { #ifdef DEBUG g_iCacheReplacements++; #endif DWORD dwMostTurns = 0; int iOldestSlot = -1; for ( int i = 0; i < m_iLRUQueueSize; i++ ) { if ( ptpoLRUQueue[i] != NULL ) { // Careful of wrap-arounds! DWORD dwTurnsAgo = ( GAME_TURN - dwGameTurnLastUsed[i] ); if ( dwMostTurns <= dwTurnsAgo ) { // This is older. dwMostTurns = dwTurnsAgo; iOldestSlot = i; } } } ASSERT ( ( iOldestSlot > -1 ) && ( iOldestSlot < m_iLRUQueueSize ) ); if ( dwMostTurns < 3 ) { // Shit - this is probably about to thrash. // There is nothing we can do to prevent it in this case really. // Could try binning the _newest_ instead, but that's a real pain. // Just try not to. // iOldestSlot = iThrashIndex; #ifdef DEBUG // And warn us. g_bCacheReplacementThrash = TRUE; #endif } // Clean out this prim & slot. FIGURE_clean_LRU_slot ( iOldestSlot ); iQueuePos = iOldestSlot; } // Now check there is a queue space free. if ( m_iLRUQueueSize >= PRIM_LRU_QUEUE_LENGTH ) { // Nope - bin oldest. #ifdef DEBUG g_iCacheReplacements++; #endif DWORD dwMostTurns = 0; int iOldestSlot = -1; for ( int i = 0; i < m_iLRUQueueSize; i++ ) { if ( ptpoLRUQueue[i] != NULL ) { // Careful of wrap-arounds! DWORD dwTurnsAgo = ( GAME_TURN - dwGameTurnLastUsed[i] ); if ( dwMostTurns <= dwTurnsAgo ) { // This is older. dwMostTurns = dwTurnsAgo; iOldestSlot = i; } } } ASSERT ( ( iOldestSlot > -1 ) && ( iOldestSlot < m_iLRUQueueSize ) ); if ( dwMostTurns < 3 ) { // Shit - this is probably about to thrash. Prevent too much thrashing by always using the same slot. // FIRST CHECK THAT THIS SLOW IS ACTUALLY USED. if ( ptpoLRUQueue[iThrashIndex] == NULL ) { // No, it isn't actually used. // Allow the thrash then. } else { // Yes, it's used - bin it. iOldestSlot = iThrashIndex; } #ifdef DEBUG // And warn us. g_bCacheReplacementThrash = TRUE; #endif } // In some cases, we may have decided to clean a cache position that // isn't ocupied, which will die nicely. // In this case, just find the first that is occupied and clean it instead. if ( ptpoLRUQueue[iOldestSlot] == NULL ) { // Warn me. ASSERT ( FALSE ); // And recover gracefully... // Nads. Find the first used one. iOldestSlot = -1; for ( int i = 0; i < m_iLRUQueueSize; i++ ) { if ( ptpoLRUQueue[i] != NULL ) { // Found one. iOldestSlot = i; break; } } } // Clean out this prim & slot. FIGURE_clean_LRU_slot ( iOldestSlot ); iQueuePos = iOldestSlot; } } ptpoLRUQueue[iQueuePos] = pPrimObj; pPrimObj->bLRUQueueNumber = iQueuePos; dwGameTurnLastUsed[iQueuePos] = GAME_TURN; m_dwSizeOfQueue += (DWORD)pPrimObj->wTotalSizeOfObj; ASSERT ( m_dwSizeOfQueue < PRIM_LRU_QUEUE_SIZE ); } void FIGURE_touch_LRU_of_object ( TomsPrimObject *pPrimObj ) { ASSERT ( ( pPrimObj->bLRUQueueNumber >= 0 ) && ( pPrimObj->bLRUQueueNumber < m_iLRUQueueSize ) ); ASSERT ( ptpoLRUQueue[pPrimObj->bLRUQueueNumber] == pPrimObj ); dwGameTurnLastUsed[pPrimObj->bLRUQueueNumber] = GAME_TURN; } #ifdef DEBUG int m_iMaxNumVertsUsed = 0; int m_iMaxNumIndicesUsed = 0; #endif // Used by the FIGURE_TPO lot. static D3DVERTEX *TPO_pVert = NULL; static UWORD *TPO_pStripIndices = NULL; static UWORD *TPO_pListIndices = NULL; static int *TPO_piVertexRemap = NULL; static int *TPO_piVertexLinks = NULL; static D3DVERTEX *TPO_pCurVertex = NULL; static UWORD *TPO_pCurStripIndex = NULL; static UWORD *TPO_pCurListIndex = NULL; static TomsPrimObject *TPO_pPrimObj = NULL; static int TPO_iNumListIndices = 0; static int TPO_iNumStripIndices = 0; static int TPO_iNumVertices = 0; #define TPO_MAX_NUMBER_PRIMS 16 static int TPO_iNumPrims = 0; //static PrimObject *TPO_PrimObjects[TPO_MAX_NUMBER_PRIMS]; static SLONG TPO_PrimObjects[TPO_MAX_NUMBER_PRIMS]; static UBYTE TPO_ubPrimObjMMIndex[TPO_MAX_NUMBER_PRIMS]; static int TPO_iPrimObjIndexOffset[TPO_MAX_NUMBER_PRIMS+1]; // Starts off a 3D object. // iThrashIndex - can be ignored normally. void FIGURE_TPO_init_3d_object ( TomsPrimObject *pPrimObj /*, int iThrashIndex = 0 */ ) { //PrimObject *p_obj = &prim_objects[prim]; //ASSERT ( prim < MAX_NUMBER_D3D_PRIMS ); TRACE("Started conversion 0x%x...", pPrimObj); // Make sure we're not in the middle of compiling and object already. ASSERT ( TPO_pVert == NULL ); ASSERT ( TPO_pStripIndices == NULL ); ASSERT ( TPO_pListIndices == NULL ); ASSERT ( TPO_piVertexRemap == NULL ); ASSERT ( TPO_piVertexLinks == NULL ); ASSERT ( TPO_pCurVertex == NULL ); ASSERT ( TPO_pCurStripIndex == NULL ); ASSERT ( TPO_pCurListIndex == NULL ); ASSERT ( TPO_pPrimObj == NULL ); ASSERT ( TPO_iNumListIndices == 0 ); ASSERT ( TPO_iNumStripIndices == 0 ); ASSERT ( TPO_iNumVertices == 0 ); ASSERT ( TPO_iNumPrims == 0 ); // Temporary space that gets freed at the end. #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB #define MAX_VERTS 4096 #define MAX_INDICES (MAX_VERTS * 4) #else #define MAX_VERTS 1024 #define MAX_INDICES (MAX_VERTS * 4) #endif TPO_pVert = (D3DVERTEX *)MemAlloc ( MAX_VERTS * sizeof ( D3DVERTEX ) ); ASSERT ( TPO_pVert != NULL ); if ( TPO_pVert == NULL ) { DeadAndBuried ( 0xf800f800 ); } TPO_pStripIndices = (UWORD *)MemAlloc ( MAX_INDICES * sizeof ( UWORD ) ); ASSERT ( TPO_pStripIndices != NULL ); if ( TPO_pStripIndices == NULL ) { DeadAndBuried ( 0xf800f800 ); } TPO_pListIndices = (UWORD *)MemAlloc ( MAX_INDICES * sizeof ( UWORD ) ); ASSERT ( TPO_pListIndices != NULL ); if ( TPO_pListIndices == NULL ) { DeadAndBuried ( 0xf800f800 ); } TPO_piVertexRemap = (int *)MemAlloc ( MAX_VERTS * sizeof ( int ) ); ASSERT ( TPO_piVertexRemap != NULL ); if ( TPO_piVertexRemap == NULL ) { DeadAndBuried ( 0xf800f800 ); } TPO_piVertexLinks = (int *)MemAlloc ( MAX_VERTS * sizeof ( int ) ); ASSERT ( TPO_piVertexLinks != NULL ); if ( TPO_piVertexLinks == NULL ) { DeadAndBuried ( 0xf800f800 ); } TPO_pCurVertex = TPO_pVert; TPO_pCurStripIndex = TPO_pStripIndices; TPO_pCurListIndex = TPO_pListIndices; //TomsPrimObject *pPrimObj = &(D3DObj[prim]); // Make sure it's not been initialised. ASSERT ( pPrimObj->pD3DVertices == NULL ); ASSERT ( pPrimObj->pMaterials == NULL ); ASSERT ( pPrimObj->pwListIndices == NULL ); ASSERT ( pPrimObj->pwStripIndices == NULL ); ASSERT ( pPrimObj->wNumMaterials == 0 ); TPO_pPrimObj = pPrimObj; #if 0 // Do this after the object has been compiled, so we know how big it is. // Add this to a good place in the LRU queue. FIGURE_find_and_clean_prim_queue_item ( pPrimObj, iThrashIndex ); #endif // No index offset for the first object TPO_iPrimObjIndexOffset[0] = 0; pPrimObj->wFlags = 0; pPrimObj->fBoundingSphereRadius = 0.0f; TPO_iNumListIndices = 0; TPO_iNumStripIndices = 0; TPO_iNumVertices = 0; TPO_iNumPrims = 0; // Ready for action. } // Add a prim to this 3D object. // prim = the prim number to add. // iSubObjectNumber = sub-object number, used for multimatrix stuff. // Start at 0 and go up by one for each object. //void FIGURE_TPO_add_prim_to_current_object ( PrimObject *p_obj, UBYTE ubSubObjectNumber ) void FIGURE_TPO_add_prim_to_current_object ( SLONG prim, UBYTE ubSubObjectNumber ) { // Make sure it's been properly prepped. ASSERT ( TPO_pVert != NULL ); ASSERT ( TPO_pStripIndices != NULL ); ASSERT ( TPO_pListIndices != NULL ); ASSERT ( TPO_piVertexRemap != NULL ); ASSERT ( TPO_piVertexLinks != NULL ); ASSERT ( TPO_pCurVertex != NULL ); ASSERT ( TPO_pCurStripIndex != NULL ); ASSERT ( TPO_pCurListIndex != NULL ); ASSERT ( TPO_pPrimObj != NULL ); ASSERT ( prim < MAX_NUMBER_D3D_PRIMS ); PrimObject *p_obj = &prim_objects[prim]; ASSERT ( p_obj != NULL ); TRACE("added prim 0x%x...", p_obj); TPO_PrimObjects[TPO_iNumPrims] = prim; TPO_ubPrimObjMMIndex[TPO_iNumPrims] = ubSubObjectNumber; // Work out what index offset to add to the _next_ object. // It's this object's offset plus the number of points // in this object. TPO_iPrimObjIndexOffset[TPO_iNumPrims+1] = TPO_iPrimObjIndexOffset[TPO_iNumPrims] + ( p_obj->EndPoint - p_obj->StartPoint ); TPO_iNumPrims++; ASSERT ( TPO_iNumPrims <= TPO_MAX_NUMBER_PRIMS ); } // Compile the object - this actually does all the work. // pPrimObj the prim obj that was passed to FIGURE_TPO_init_3d_object // iThrashIndex - can be ignored normally. void FIGURE_TPO_finish_3d_object ( TomsPrimObject *pPrimObj, int iThrashIndex = 0 ) { // Make sure one has actually been started. ASSERT ( TPO_pVert != NULL ); ASSERT ( TPO_pStripIndices != NULL ); ASSERT ( TPO_pListIndices != NULL ); ASSERT ( TPO_piVertexRemap != NULL ); ASSERT ( TPO_piVertexLinks != NULL ); ASSERT ( TPO_pCurVertex != NULL ); ASSERT ( TPO_pCurStripIndex != NULL ); ASSERT ( TPO_pCurListIndex != NULL ); ASSERT ( TPO_pPrimObj != NULL ); ASSERT ( pPrimObj == TPO_pPrimObj ); TRACE ( "compiling %i prims...", TPO_iNumPrims ); // OK, now scan through the faces. Check to see if the face uses a new material. // If so, create this new material and add in this face and all subsequent faces // that use it. // If not, then this face should already have been added, so ignore it. // // This sequence is, of course, complicated by there being both quads and tris. :-( for ( int iOuterPrimNumber = 0; iOuterPrimNumber < TPO_iNumPrims; iOuterPrimNumber++ ) { PrimObject *pOuterObj = &prim_objects[TPO_PrimObjects[iOuterPrimNumber]]; ASSERT ( pOuterObj != NULL ); bool bOuterTris = FALSE; do { int iOuterFaceNum; int iOuterFaceEnd; if ( bOuterTris ) { iOuterFaceNum = pOuterObj->StartFace3; iOuterFaceEnd = pOuterObj->EndFace3; } else { iOuterFaceNum = pOuterObj->StartFace4; iOuterFaceEnd = pOuterObj->EndFace4; } for ( ; iOuterFaceNum < iOuterFaceEnd; iOuterFaceNum++ ) { UWORD wTexturePage = FIGURE_find_face_D3D_texture_page ( iOuterFaceNum, bOuterTris ); // Find the _rendered_ page, to allow texture paging to do its stuff. UWORD wRealPage = wTexturePage & TEXTURE_PAGE_MASK; PolyPage *pRenderedPage = NULL; #ifdef TEX_EMBED if ( ( wTexturePage & ~TEXTURE_PAGE_MASK ) != 0 ) { // Something special about this page, e.g. jacket, special shading, etc. // Don't try to combine them. pRenderedPage = NULL; } else { pRenderedPage = POLY_Page[wTexturePage & TEXTURE_PAGE_MASK].pTheRealPolyPage; } #endif // OK, now we have a material description in wTexturePage. // Look for an existing material with this. PrimObjectMaterial *pMaterial = pPrimObj->pMaterials; int iMatNum; for ( iMatNum = pPrimObj->wNumMaterials; iMatNum > 0; iMatNum-- ) { #if 1 #ifdef TEX_EMBED if ( pRenderedPage != NULL ) { if ( ( pMaterial->wTexturePage & ~TEXTURE_PAGE_MASK ) == 0 ) { // Nothing special about this page. if ( pRenderedPage == ( POLY_Page[pMaterial->wTexturePage & TEXTURE_PAGE_MASK].pTheRealPolyPage ) ) { // The textures match! break; } } } #endif #endif if ( pMaterial->wTexturePage == wTexturePage ) { // Exactly the same page. break; } pMaterial++; } if ( iMatNum != 0 ) { // Found one. So this face should be in it somewhere already. Ignore. } else { // Didn't find this material, so add it. pPrimObj->wNumMaterials++; // Yes, this is a horrible way to do things - memory fragmented all over the place. Tough. Deal with it. // And yes, I could use realloc(), but it doesn't seem to be very happy on the DC, so I won't. void *pOldMats = (void *)pPrimObj->pMaterials; pPrimObj->pMaterials = (PrimObjectMaterial *)MemAlloc ( pPrimObj->wNumMaterials * sizeof ( *pMaterial ) ); ASSERT ( pPrimObj->pMaterials != NULL ); if ( pPrimObj->pMaterials == NULL ) { DeadAndBuried ( 0x001f001f ); } if ( pOldMats != NULL ) { memcpy ( pPrimObj->pMaterials, pOldMats, ( pPrimObj->wNumMaterials - 1 ) * sizeof ( *pMaterial ) ); MemFree ( pOldMats ); } pMaterial = pPrimObj->pMaterials + pPrimObj->wNumMaterials - 1; pMaterial->wNumListIndices = 0; pMaterial->wNumStripIndices = 0; pMaterial->wNumVertices = 0; pMaterial->wTexturePage = wTexturePage; D3DVERTEX *pFirstVertex = TPO_pCurVertex; WORD *pFirstListIndex = TPO_pCurListIndex; WORD *pFirstStripIndex = TPO_pCurStripIndex; // Renit the vertex remapping. for ( int i = 0; i < MAX_VERTS; i++ ) { // The first D3Dvertex that has the right posnorm. TPO_piVertexRemap[i] = -1; // A possible next vertex that uses this posnorm. TPO_piVertexLinks[i] = -1; } // Now scan all the rest of the faces and add any that have this page. // Just scan from this face onwards. for ( int iInnerPrimNumber = iOuterPrimNumber; iInnerPrimNumber < TPO_iNumPrims; iInnerPrimNumber++ ) { PrimObject *pInnerObj = &prim_objects[TPO_PrimObjects[iInnerPrimNumber]]; float *pfBoundingSphereRadius = &(m_fObjectBoundingSphereRadius[TPO_PrimObjects[iInnerPrimNumber]]); *pfBoundingSphereRadius = 0.0f; ASSERT ( pInnerObj != NULL ); bool bInnerTris; if ( iInnerPrimNumber == iOuterPrimNumber ) { // Just scan this object from where the outer one is. bInnerTris = bOuterTris; } else { bInnerTris = FALSE; } do { int iInnerFaceEnd; int iInnerFaceNum; if ( iInnerPrimNumber == iOuterPrimNumber ) { // Just scan from where we are onwards if ( bInnerTris ) { if ( bOuterTris ) { iInnerFaceNum = iOuterFaceNum; } else { iInnerFaceNum = pInnerObj->StartFace3; } iInnerFaceEnd = pInnerObj->EndFace3; } else { if ( bOuterTris ) { // If the outer loop was scanning tris, // it did so after scanning all quads, // so why are we scanning quads in the inner loop? ASSERT ( FALSE ); iInnerFaceNum = pInnerObj->StartFace4; } else { iInnerFaceNum = iOuterFaceNum; } iInnerFaceEnd = pInnerObj->EndFace4; } } else { if ( bInnerTris ) { iInnerFaceNum = pInnerObj->StartFace3; iInnerFaceEnd = pInnerObj->EndFace3; } else { iInnerFaceNum = pInnerObj->StartFace4; iInnerFaceEnd = pInnerObj->EndFace4; } } ASSERT ( iInnerFaceNum <= iInnerFaceEnd ); for ( ; iInnerFaceNum < iInnerFaceEnd; iInnerFaceNum++ ) { UWORD wTexturePage = FIGURE_find_face_D3D_texture_page ( iInnerFaceNum, bInnerTris ); bool bSamePage = FALSE; if ( pMaterial->wTexturePage == wTexturePage ) { // Exactly the same page. bSamePage = TRUE; } #if 1 #ifdef TEX_EMBED else if ( pRenderedPage != NULL ) { //if ( ( ( pMaterial->wTexturePage & ~TEXTURE_PAGE_MASK ) == 0 ) && // ( ( wTexturePage & ~TEXTURE_PAGE_MASK ) == 0 ) if ( ( ( pMaterial->wTexturePage | wTexturePage ) & ~TEXTURE_PAGE_MASK ) == 0 ) { // Nothing special about either page. if ( pRenderedPage == ( POLY_Page[wTexturePage & TEXTURE_PAGE_MASK].pTheRealPolyPage ) ) { // The textures match! bSamePage = TRUE; } } } #endif #endif if ( bSamePage ) { // This uses this material, so add it. // Find the actual polypage, because that will give us UV offsets. // NOTE! This means that all thug jackets must have the same offsets * scales. // Shouldn't be too hard to arrange. // Ditto for offset tetxures. UWORD wRealPage = wTexturePage & TEXTURE_PAGE_MASK; if ( wTexturePage & TEXTURE_PAGE_FLAG_JACKET ) { // Find the real jacket page. // Assume skill of 0 wRealPage = jacket_lookup [ wRealPage ][0]; wRealPage += FACE_PAGE_OFFSET; } else if ( wTexturePage & TEXTURE_PAGE_FLAG_OFFSET ) { // An "offset" texture. This will be offset by a certain amount to // allow each prim to have different coloured clothes on. // For now, assume no offset. wRealPage += FACE_PAGE_OFFSET; } #ifdef DEBUG if ( wTexturePage & TEXTURE_PAGE_FLAG_NOT_TEXTURED ) { ASSERT ( wRealPage == POLY_PAGE_COLOUR ); } #endif PolyPage *pa = &(POLY_Page[wRealPage]); // Add the vertices. int iIndices[4]; PrimFace3 *p_f3; PrimFace4 *p_f4; int iVerts; if ( bInnerTris ) { p_f3 = &prim_faces3[iInnerFaceNum]; iVerts = 3; } else { p_f4 = &prim_faces4[iInnerFaceNum]; iVerts = 4; } for ( int i = 0; i < iVerts; i++ ) { const float fNormScale = 1.0f / 256.0f; D3DVERTEX d3dvert; int pt; if ( bInnerTris ) { pt = p_f3->Points[i]; d3dvert.dvTU = float(p_f3->UV[i][0] & 0x3f) * (1.0F / 32.0F); d3dvert.dvTV = float(p_f3->UV[i][1] ) * (1.0F / 32.0F); } else { pt = p_f4->Points[i]; d3dvert.dvTU = float(p_f4->UV[i][0] & 0x3f) * (1.0F / 32.0F); d3dvert.dvTV = float(p_f4->UV[i][1] ) * (1.0F / 32.0F); } #ifdef TEX_EMBED // Clamp if they go out of range. // This can produce a little bit of distortion, but it's better than nothing. if ( d3dvert.dvTU < 0.0f ) { TRACE("Clamped a U coord to 0"); d3dvert.dvTU = 0.0f; } else if ( d3dvert.dvTU > 1.0f ) { TRACE("Clamped a U coord to 1"); d3dvert.dvTU = 1.0f; } if ( d3dvert.dvTV < 0.0f ) { TRACE("Clamped a V coord to 0"); d3dvert.dvTV = 0.0f; } else if ( d3dvert.dvTV > 1.0f ) { TRACE("Clamped a V coord to 1"); d3dvert.dvTV = 1.0f; } d3dvert.dvTU = d3dvert.dvTU * pa->m_UScale + pa->m_UOffset; d3dvert.dvTV = d3dvert.dvTV * pa->m_VScale + pa->m_VOffset; // Now scale by the page offset and scale #endif d3dvert.dvX = AENG_dx_prim_points[pt].X; d3dvert.dvY = AENG_dx_prim_points[pt].Y; d3dvert.dvZ = AENG_dx_prim_points[pt].Z; d3dvert.dvNX = prim_normal[pt].X * fNormScale; d3dvert.dvNY = prim_normal[pt].Y * fNormScale; d3dvert.dvNZ = prim_normal[pt].Z * fNormScale; // This must be done after setting the rest up, since it blats the 12th byte of the vertex. SET_MM_INDEX ( d3dvert, TPO_ubPrimObjMMIndex[iInnerPrimNumber] ); // Look for this vertex. ASSERT ( pt >= pInnerObj->StartPoint ); ASSERT ( pt < pInnerObj->EndPoint ); ASSERT ( ( pt - pInnerObj->StartPoint ) < MAX_VERTS ); if ( ( pt - pInnerObj->StartPoint ) >= MAX_VERTS ) { DeadAndBuried ( 0xffffffff ); } int iPtIndex = TPO_iPrimObjIndexOffset[iInnerPrimNumber] + ( pt - pInnerObj->StartPoint ); int iVertIndex = TPO_piVertexRemap[iPtIndex]; if ( iVertIndex == -1 ) { // Never-referenced vertex. Add it. TPO_piVertexRemap[iPtIndex] = pMaterial->wNumVertices; TPO_piVertexLinks[pMaterial->wNumVertices] = -1; iIndices[i] = pMaterial->wNumVertices; *TPO_pCurVertex = d3dvert; TPO_pCurVertex++; pMaterial->wNumVertices++; TPO_iNumVertices++; ASSERT ( TPO_iNumVertices < MAX_VERTS ); if ( TPO_iNumVertices >= MAX_VERTS ) { DeadAndBuried ( 0xffffffff ); } #ifdef DEBUG if ( m_iMaxNumVertsUsed < TPO_iNumVertices ) { //ASSERT ( TPO_iNumVertices < 256 ); m_iMaxNumVertsUsed = TPO_iNumVertices; } #endif // Grow the bounding sphere if need be. #if 0 // THIS IS NOT BEING DONE RIGHT! float fDistSqu = ( d3dvert.dvX * d3dvert.dvX ) + ( d3dvert.dvY * d3dvert.dvY ) + ( d3dvert.dvZ * d3dvert.dvZ ); if ( pPrimObj->fBoundingSphereRadius < fDistSqu ) { pPrimObj->fBoundingSphereRadius = fDistSqu; } #else float fDistSqu = ( d3dvert.dvX * d3dvert.dvX ) + ( d3dvert.dvY * d3dvert.dvY ) + ( d3dvert.dvZ * d3dvert.dvZ ); if ( ( *pfBoundingSphereRadius * *pfBoundingSphereRadius ) < fDistSqu ) { *pfBoundingSphereRadius = sqrtf(fDistSqu); } #endif } else { // OK, try the links. int iLastIndex = iVertIndex; while ( iVertIndex != -1 ) { ASSERT ( pFirstVertex[iVertIndex].dvX == d3dvert.dvX ); ASSERT ( pFirstVertex[iVertIndex].dvY == d3dvert.dvY ); ASSERT ( pFirstVertex[iVertIndex].dvZ == d3dvert.dvZ ); ASSERT ( pFirstVertex[iVertIndex].dvNX == d3dvert.dvNX ); ASSERT ( pFirstVertex[iVertIndex].dvNY == d3dvert.dvNY ); ASSERT ( pFirstVertex[iVertIndex].dvNZ == d3dvert.dvNZ ); #define CLOSE_ENOUGH(a,b) ( fabsf ( (a) - (b) ) < 0.00001f ) if ( CLOSE_ENOUGH ( pFirstVertex[iVertIndex].dvTU, d3dvert.dvTU ) && CLOSE_ENOUGH ( pFirstVertex[iVertIndex].dvTV, d3dvert.dvTV ) ) { // Yes, this is a match. iIndices[i] = iVertIndex; break; } else { // Nope - try the next one. iLastIndex = iVertIndex; iVertIndex = TPO_piVertexLinks[iVertIndex]; } } if ( iVertIndex == -1 ) { // Didn't find one, so add new one. TPO_piVertexLinks[iLastIndex] = pMaterial->wNumVertices; TPO_piVertexLinks[pMaterial->wNumVertices] = -1; iIndices[i] = pMaterial->wNumVertices; *TPO_pCurVertex = d3dvert; TPO_pCurVertex++; pMaterial->wNumVertices++; TPO_iNumVertices++; ASSERT ( TPO_iNumVertices < MAX_VERTS ); if ( TPO_iNumVertices >= MAX_VERTS ) { DeadAndBuried ( 0xffffffff ); } #ifdef DEBUG if ( m_iMaxNumVertsUsed < TPO_iNumVertices ) { //ASSERT ( TPO_iNumVertices < 256 ); m_iMaxNumVertsUsed = TPO_iNumVertices; } #endif } } } // Now add the indices. // This is a braindead method - we will optimise it afterwards. if ( bInnerTris ) { ASSERT ( ( iIndices[0] >= 0 ) && ( iIndices[0] < pMaterial->wNumVertices ) ); ASSERT ( ( iIndices[1] >= 0 ) && ( iIndices[1] < pMaterial->wNumVertices ) ); ASSERT ( ( iIndices[2] >= 0 ) && ( iIndices[2] < pMaterial->wNumVertices ) ); #if 0 // Strip indices. *TPO_pCurStripIndex++ = iIndices[0]; *TPO_pCurStripIndex++ = iIndices[1]; *TPO_pCurStripIndex++ = iIndices[2]; *TPO_pCurStripIndex++ = -1; TPO_iNumStripIndices += 4; pMaterial->wNumStripIndices += 4; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #endif // List indices. *TPO_pCurListIndex++ = iIndices[0]; *TPO_pCurListIndex++ = iIndices[1]; *TPO_pCurListIndex++ = iIndices[2]; TPO_iNumListIndices += 3; pMaterial->wNumListIndices += 3; ASSERT ( TPO_iNumListIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumListIndices ) { m_iMaxNumIndicesUsed = TPO_iNumListIndices; } #endif } else { ASSERT ( ( iIndices[0] >= 0 ) && ( iIndices[0] < pMaterial->wNumVertices ) ); ASSERT ( ( iIndices[1] >= 0 ) && ( iIndices[1] < pMaterial->wNumVertices ) ); ASSERT ( ( iIndices[2] >= 0 ) && ( iIndices[2] < pMaterial->wNumVertices ) ); ASSERT ( ( iIndices[3] >= 0 ) && ( iIndices[3] < pMaterial->wNumVertices ) ); #if 0 // Strip indices. *TPO_pCurStripIndex++ = iIndices[0]; *TPO_pCurStripIndex++ = iIndices[1]; *TPO_pCurStripIndex++ = iIndices[2]; *TPO_pCurStripIndex++ = iIndices[3]; *TPO_pCurStripIndex++ = -1; TPO_iNumStripIndices += 5; pMaterial->wNumStripIndices += 5; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #endif // List indices. *TPO_pCurListIndex++ = iIndices[0]; *TPO_pCurListIndex++ = iIndices[1]; *TPO_pCurListIndex++ = iIndices[2]; *TPO_pCurListIndex++ = iIndices[2]; *TPO_pCurListIndex++ = iIndices[1]; *TPO_pCurListIndex++ = iIndices[3]; TPO_iNumListIndices += 6; pMaterial->wNumListIndices += 6; ASSERT ( TPO_iNumListIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumListIndices ) { m_iMaxNumIndicesUsed = TPO_iNumListIndices; } #endif } } } bInnerTris = !bInnerTris; } while ( bInnerTris ); } // And that's that material fully done. #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB // Do they need inflating? if ( m_bPleaseInflatePeople ) { TRACE("Inflate"); // Make a list of all edges. // At most 3 edges per tri. EdgeList *pEdgeList = (EdgeList *)MemAlloc ( sizeof ( EdgeList ) * pMaterial->wNumListIndices ); ASSERT ( pEdgeList != NULL ); if ( pEdgeList == NULL ) { DeadAndBuried ( 0x0000001f ); } // Add the edges. int iNumEdges = 0; WORD *pSrcIndex = pFirstListIndex; WORD wI1, wI2, wI3, wI4; for ( i = pMaterial->wNumListIndices / 3; i > 0; i-- ) { wI1 = pSrcIndex[0]; wI2 = pSrcIndex[1]; wI3 = pSrcIndex[2]; wI4 = pSrcIndex[0]; for ( int j = 0; j < 3; j++ ) { // Look for edge wI1, wI2. bool bFound = FALSE; for ( int k = 0; k < iNumEdges; k++ ) { if ( ( ( pEdgeList[k].wPt1 == wI1 ) && ( pEdgeList[k].wPt2 == wI2 ) ) || ( ( pEdgeList[k].wPt1 == wI2 ) && ( pEdgeList[k].wPt2 == wI1 ) ) ) { // Found the edge. bFound = TRUE; break; } } if ( !bFound ) { // Make the edge. EdgeList *pEdgeCur = &(pEdgeList[iNumEdges]); pEdgeCur->wPt1 = wI1; pEdgeCur->wPt2 = wI2; iNumEdges++; } // Next edge. wI1 = wI2; wI2 = wI3; wI3 = wI4; } pSrcIndex += 3; } // Now scan the edges, creating the midpoints. EdgeList *pEdgeCur = pEdgeList; for ( i = 0; i < iNumEdges; i++ ) { D3DVERTEX *pvertMid, *pvert1, *pvert2; pvert1 = &pFirstVertex[pEdgeCur->wPt1]; pvert2 = &pFirstVertex[pEdgeCur->wPt2]; pEdgeCur->wMidPt = pMaterial->wNumVertices; pvertMid = TPO_pCurVertex; // Make the midpoint. D3DVECTOR vPos1, vPos2; vPos1.x = pvert1->x; vPos1.y = pvert1->y; vPos1.z = pvert1->z; vPos2.x = pvert2->x; vPos2.y = pvert2->y; vPos2.z = pvert2->z; D3DVECTOR vNorm1, vNorm2; vNorm1.x = pvert1->nx; vNorm1.y = pvert1->ny; vNorm1.z = pvert1->nz; vNorm2.x = pvert2->nx; vNorm2.y = pvert2->ny; vNorm2.z = pvert2->nz; // The edge's vector. D3DVECTOR vEdge = vPos1 - vPos2; D3DVECTOR vAvNorm = vNorm1 + vNorm2; float fLenAvNorm = Magnitude ( vAvNorm ); if ( fLenAvNorm < 0.00001f ) { // Panic. vAvNorm = vNorm1; } else { vAvNorm *= ( 1.0f / fLenAvNorm ); } // Find the normal to the edge. D3DVECTOR vNormToEdge = CrossProduct ( vEdge, vAvNorm ); vNormToEdge = CrossProduct ( vNormToEdge, vEdge ); float fLenNormToEdge = Magnitude ( vNormToEdge ); if ( fLenNormToEdge < 0.00001f ) { // Panic. vNormToEdge = vNorm1; } else { vNormToEdge *= ( 1.0f / fLenNormToEdge ); } // Find the new midpoint. // Adjust lambda until it's a "nice" value. D3DVECTOR vPos3; if ( fLenAvNorm < 0.75f * 2.0f ) { // No curve - just make it flat. vPos3 = ( vPos1 + vPos2 ) * 0.5; } else { // Curve. const float fLambda = 0.15f; vPos3 = ( vPos1 + vPos2 ) * 0.5 + ( ( fLambda * DotProduct ( ( vNorm1 - vNorm2 ), vEdge ) ) * vAvNorm ); } #if 0 // And find the new mid normal. // This is theoretically more "correct", but tends to give unstable behaviour. D3DVECTOR vNorm3 = ( 2 * vNormToEdge ) - vAvNorm; #elif 0 // Much more stable, but produces nasty edges. D3DVECTOR vNorm3 = vAvNorm; #elif 0 // A compromise between the two. D3DVECTOR vNorm3 = vNormToEdge; #else // A blend of above, but hopefully more stable. D3DVECTOR vNorm3 = ( 4 * vNormToEdge ) - vAvNorm; #endif float fLenNorm3 = Magnitude ( vNorm3 ); if ( fLenNorm3 < 0.00001f ) { // Panic. vNorm3 = vNorm1; } else { vNorm3 *= ( 1.0f / fLenNorm3 ); } pvertMid->x = vPos3.x; pvertMid->y = vPos3.y; pvertMid->z = vPos3.z; pvertMid->nx = vNorm3.x; pvertMid->ny = vNorm3.y; pvertMid->nz = vNorm3.z; pvertMid->tu = ( pvert1->tu + pvert2->tu ) * 0.5f; pvertMid->tv = ( pvert1->tv + pvert2->tv ) * 0.5f; //pvertMid->dif = ( ( ( pvert1->dif & 0xfefefefe ) >> 1 ) + ( ( pvert2->dif & 0xfefefefe ) >> 1 ) ); //pvertMid->spec = ( ( ( pvert1->spec & 0xfefefefe ) >> 1 ) + ( ( pvert2->spec & 0xfefefefe ) >> 1 ) ); // This must be done after setting the rest up, since it blats the 12th byte of the vertex. // Just pick either of the vertices - in theory they should all be the same. SET_MM_INDEX ( (*pvertMid), GET_MM_INDEX(*pvert1) ); // Add it officially. TPO_pCurVertex++; pMaterial->wNumVertices++; TPO_iNumVertices++; ASSERT ( TPO_iNumVertices < MAX_VERTS ); if ( TPO_iNumVertices >= MAX_VERTS ) { DeadAndBuried ( 0xffffffff ); } #ifdef DEBUG if ( m_iMaxNumVertsUsed < TPO_iNumVertices ) { //ASSERT ( TPO_iNumVertices < 256 ); m_iMaxNumVertsUsed = TPO_iNumVertices; } #endif pEdgeCur++; } // Now scan all the tris, find their edges, and carve them up into 4 tris. // If we scan the list backwards, we can use the same list. // Add the new indices first, then work out what they are. int iNewNumListIndices = TPO_iNumListIndices + 3 * pMaterial->wNumListIndices; int iNewMatNumListIndices = 4 * pMaterial->wNumListIndices; TPO_pCurListIndex += 3 * pMaterial->wNumListIndices; ASSERT ( iNewNumListIndices < MAX_INDICES ); if ( iNewNumListIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < iNewNumListIndices ) { m_iMaxNumIndicesUsed = iNewNumListIndices; } #endif pSrcIndex = pFirstListIndex + pMaterial->wNumListIndices; WORD *pDstIndex = pFirstListIndex + iNewMatNumListIndices; WORD wMid[3]; for ( i = pMaterial->wNumListIndices / 3; i > 0; i-- ) { pSrcIndex -= 3; pDstIndex -= 3 * 4; wI1 = pSrcIndex[0]; wI2 = pSrcIndex[1]; wI3 = pSrcIndex[2]; wI4 = pSrcIndex[0]; for ( int j = 0; j < 3; j++ ) { // Look for edge wI1, wI2. for ( int k = 0; k < iNumEdges; k++ ) { if ( ( ( pEdgeList[k].wPt1 == wI1 ) && ( pEdgeList[k].wPt2 == wI2 ) ) || ( ( pEdgeList[k].wPt1 == wI2 ) && ( pEdgeList[k].wPt2 == wI1 ) ) ) { // Found the edge - store the midpoint. wMid[j] = pEdgeList[k].wMidPt; break; } } ASSERT ( k != iNumEdges ); // Next edge. wI1 = wI2; wI2 = wI3; wI3 = wI4; } ASSERT ( wI1 < pMaterial->wNumVertices ); ASSERT ( wI2 < pMaterial->wNumVertices ); ASSERT ( wI3 < pMaterial->wNumVertices ); ASSERT ( wMid[0] < pMaterial->wNumVertices ); ASSERT ( wMid[1] < pMaterial->wNumVertices ); ASSERT ( wMid[2] < pMaterial->wNumVertices ); // OK, so we now create 4 tris from wI1-3 and wMid[0-2]. // wMid[0] will be between wI1 and wI2 // wMid[1] will be between wI2 and wI3 // wMid[2] will be between wI3 and wI1 // Copy these, coz the very last 4 tris overwrites them. WORD wSrcIndex0 = pSrcIndex[0]; WORD wSrcIndex1 = pSrcIndex[1]; WORD wSrcIndex2 = pSrcIndex[2]; pDstIndex[0*3+0] = wSrcIndex0; pDstIndex[0*3+1] = wMid[0]; pDstIndex[0*3+2] = wMid[2]; pDstIndex[1*3+0] = wSrcIndex1; pDstIndex[1*3+1] = wMid[1]; pDstIndex[1*3+2] = wMid[0]; pDstIndex[2*3+0] = wSrcIndex2; pDstIndex[2*3+1] = wMid[2]; pDstIndex[2*3+2] = wMid[1]; pDstIndex[3*3+0] = wMid[0]; pDstIndex[3*3+1] = wMid[1]; pDstIndex[3*3+2] = wMid[2]; } ASSERT ( pSrcIndex == pDstIndex ); TPO_iNumListIndices = iNewNumListIndices; pMaterial->wNumListIndices = iNewMatNumListIndices; // Inflation done! MemFree ( pEdgeList ); } #endif //#ifdef HIGH_REZ_PEOPLE_PLEASE_BOB WORD *pSrcIndex; TRACE("Optimise"); // Optimise the lists using MS's optimiser. Ta, MS. Saves me the hassle. int iRes = MSOptimizeIndexedList ( pFirstListIndex, pMaterial->wNumListIndices / 3 ); ASSERT ( iRes != 0 ); TRACE("Stripify"); // And convert back to the strip format. ASSERT ( TPO_pCurStripIndex == pFirstStripIndex ); pSrcIndex = pFirstListIndex; // Previous edge. WORD wIndex0 = -1; WORD wIndex1 = -1; bool bOdd = FALSE; bool bFirst = TRUE; for ( i = pMaterial->wNumListIndices / 3; i > 0; i-- ) { // Can we continue the list? WORD wNextIndex = -1; if ( ( wIndex0 == pSrcIndex[2] ) && ( wIndex1 == pSrcIndex[0] ) ) { wNextIndex = pSrcIndex[1]; } else if ( ( wIndex0 == pSrcIndex[0] ) && ( wIndex1 == pSrcIndex[1] ) ) { wNextIndex = pSrcIndex[2]; } else if ( ( wIndex0 == pSrcIndex[1] ) && ( wIndex1 == pSrcIndex[2] ) ) { wNextIndex = pSrcIndex[0]; } if ( wNextIndex != (WORD)-1 ) { // We can continue the strip. *TPO_pCurStripIndex++ = wNextIndex; TPO_iNumStripIndices += 1; pMaterial->wNumStripIndices += 1; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumStripIndices ) { m_iMaxNumIndicesUsed = TPO_iNumStripIndices; } #endif if ( bOdd ) { wIndex0 = wNextIndex; } else { wIndex1 = wNextIndex; } bOdd = !bOdd; } else { // No. Start a new one. if ( !bFirst ) { *TPO_pCurStripIndex++ = -1; TPO_iNumStripIndices += 1; pMaterial->wNumStripIndices += 1; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumStripIndices ) { m_iMaxNumIndicesUsed = TPO_iNumStripIndices; } #endif } else { bFirst = FALSE; } *TPO_pCurStripIndex++ = pSrcIndex[0]; *TPO_pCurStripIndex++ = pSrcIndex[1]; *TPO_pCurStripIndex++ = pSrcIndex[2]; TPO_iNumStripIndices += 3; pMaterial->wNumStripIndices += 3; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumStripIndices ) { m_iMaxNumIndicesUsed = TPO_iNumStripIndices; } #endif wIndex0 = pSrcIndex[2]; wIndex1 = pSrcIndex[1]; bOdd = FALSE; } pSrcIndex += 3; } // Finish with a final -1 *TPO_pCurStripIndex++ = -1; TPO_iNumStripIndices += 1; pMaterial->wNumStripIndices += 1; ASSERT ( TPO_iNumStripIndices < MAX_INDICES ); if ( TPO_iNumStripIndices >= MAX_INDICES ) { DeadAndBuried ( 0x07ff07ff ); } #ifdef DEBUG if ( m_iMaxNumIndicesUsed < TPO_iNumStripIndices ) { m_iMaxNumIndicesUsed = TPO_iNumStripIndices; } #endif ASSERT ( pMaterial->wNumStripIndices == ( TPO_pCurStripIndex - pFirstStripIndex ) ); TRACE("Done "); } } bOuterTris = !bOuterTris; } while ( bOuterTris ); } // Set up the total number of vertices used. pPrimObj->wTotalSizeOfObj = TPO_iNumVertices; // Copy the vertices and indices. // These vertices much be aligned properly for the MM stuff, remember! // Do the alloc in one block to be nice to the TLB. DWORD dwTotalSize = 0; dwTotalSize += TPO_iNumListIndices * sizeof ( UWORD ); dwTotalSize += 32 + TPO_iNumVertices * sizeof ( D3DVERTEX ); dwTotalSize += TPO_iNumStripIndices * sizeof ( UWORD ); // NOTE! I allocate an extra bit of space on the end because the MM code // actually reads the index just after the end, so that must be valid memory, // or you get a page fault. Now _that_ was a tricky bug to find, and had // been happening on and off for ages, and I could never track it down // (coz it would crash in the D3D driver, and the stack gets scrogged // in there, so I can't back-trace to find out what happened). dwTotalSize += 4 * sizeof (WORD); // Now that it's a unified block, TPO_pListIndices is the thing that needs to // be freed. Obviously, don't free the others - they don't own memory. char *pcBlock = (char *)MemAlloc ( dwTotalSize ); ASSERT ( pcBlock != NULL ); if ( pcBlock == NULL ) { DeadAndBuried ( 0xffe0ffe0 ); } pPrimObj->pwListIndices = (UWORD *)pcBlock; memcpy ( pPrimObj->pwListIndices, TPO_pListIndices, TPO_iNumListIndices * sizeof ( UWORD ) ); pcBlock += TPO_iNumListIndices * sizeof ( UWORD ); // Now the verts, aligned to 32 bytes lines. pPrimObj->pD3DVertices = (void *)( ( (DWORD)pcBlock + 31 ) & ~31 ); memcpy ( pPrimObj->pD3DVertices , TPO_pVert, TPO_iNumVertices * sizeof ( D3DVERTEX ) ); pcBlock = (char *)pPrimObj->pD3DVertices + TPO_iNumVertices * sizeof ( D3DVERTEX ); pPrimObj->pwStripIndices = (UWORD *)pcBlock; memcpy ( pPrimObj->pwStripIndices, TPO_pStripIndices, TPO_iNumStripIndices * sizeof ( UWORD ) ); pcBlock += TPO_iNumStripIndices * sizeof ( UWORD ); ASSERT ( (DWORD)pcBlock < (DWORD)pPrimObj->pwListIndices + dwTotalSize ); #if 0 //void *pPermanentVerts = MemAlloc ( 32 + TPO_iNumVertices * sizeof ( D3DVERTEX ) ); pPermanentVerts = (void *)( ( (DWORD)pPermanentVerts + 31 ) & ~31 ); ASSERT ( pPermanentVerts != NULL ); memcpy ( pPermanentVerts, TPO_pVert, TPO_iNumVertices * sizeof ( D3DVERTEX ) ); pPrimObj->pD3DVertices = pPermanentVerts; //UWORD *pPermanentIndices = (UWORD *)MemAlloc ( TPO_iNumListIndices * sizeof ( UWORD ) ); ASSERT ( pPermanentIndices != NULL ); memcpy ( pPermanentIndices, TPO_pListIndices, TPO_iNumListIndices * sizeof ( UWORD ) ); pPrimObj->pwListIndices = pPermanentIndices; //pPermanentIndices = (UWORD *)MemAlloc ( TPO_iNumStripIndices * sizeof ( UWORD ) ); ASSERT ( pPermanentIndices != NULL ); memcpy ( pPermanentIndices, TPO_pStripIndices, TPO_iNumStripIndices * sizeof ( UWORD ) ); pPrimObj->pwStripIndices = pPermanentIndices; #endif // Free the temporary spaces. MemFree ( TPO_piVertexLinks ); MemFree ( TPO_piVertexRemap ); MemFree ( TPO_pListIndices ); MemFree ( TPO_pStripIndices ); MemFree ( TPO_pVert ); // And remember to take the square-root of this to make it an actual radius. pPrimObj->fBoundingSphereRadius = sqrtf ( pPrimObj->fBoundingSphereRadius ); // Add this to a good place in the LRU queue. FIGURE_find_and_clean_prim_queue_item ( pPrimObj, iThrashIndex ); // Clean up. TPO_pVert = NULL; TPO_pStripIndices = NULL; TPO_pListIndices = NULL; TPO_piVertexRemap = NULL; TPO_piVertexLinks = NULL; TPO_pCurVertex = NULL; TPO_pCurStripIndex = NULL; TPO_pCurListIndex = NULL; TPO_pPrimObj = NULL; TPO_iNumListIndices = 0; TPO_iNumStripIndices = 0; TPO_iNumVertices = 0; TPO_iNumPrims = 0; TRACE("done all.\n"); #ifdef DEBUG TRACE ( "Max so far: verts %i, indices %i\n", m_iMaxNumVertsUsed, m_iMaxNumIndicesUsed ); #endif } // Takes a "prim" description and generates D3D-style data for a single prim. void FIGURE_generate_D3D_object ( SLONG prim ) { PrimObject *p_obj = &prim_objects[prim]; TomsPrimObject *pPrimObj = &(D3DObj[prim]); // Set it up. FIGURE_TPO_init_3d_object ( pPrimObj ); // Add this prim to it as object 0. //FIGURE_TPO_add_prim_to_current_object ( p_obj, 0 ); FIGURE_TPO_add_prim_to_current_object ( prim, 0 ); // And clean it all up. FIGURE_TPO_finish_3d_object ( pPrimObj ); } #endif //#if USE_TOMS_ENGINE_PLEASE_BOB void FIGURE_draw_prim_tween( SLONG prim, SLONG x, SLONG y, SLONG z, SLONG tween, struct GameKeyFrameElement *anim_info, struct GameKeyFrameElement *anim_info_next, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, ULONG colour, ULONG specular, CMatrix33 *parent_base_mat, Matrix31 *parent_base_pos, Matrix33 *parent_curr_mat, Matrix31 *parent_curr_pos, Matrix33 *end_mat, Matrix31 *end_pos, Thing *p_thing, SLONG part_number = 0xffffffff, ULONG colour_and = 0xffffffff) { SLONG i; SLONG j; SLONG sp; SLONG ep; SLONG p0; SLONG p1; SLONG p2; SLONG p3; SLONG nx; SLONG ny; SLONG nz; SLONG red; SLONG green; SLONG blue; SLONG dprod; SLONG r; SLONG g; SLONG b; SLONG dr; SLONG dg; SLONG db; SLONG face_colour; SLONG page; Matrix31 offset; Matrix33 mat2; Matrix33 mat_final; ULONG qc0; ULONG qc1; ULONG qc2; ULONG qc3; SVector temp; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; NIGHT_Found *nf; POLY_Point *pp; POLY_Point *ps; POLY_Point *tri [3]; POLY_Point *quad[4]; SLONG tex_page_offset; LOG_ENTER ( Figure_Draw_Prim_Tween ) tex_page_offset=p_thing->Genus.Person->pcom_colour&0x3; // // Matrix functions we use. // void matrix_transform (Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_mult33 (Matrix33* result, Matrix33* mat1, Matrix33* mat2); if (parent_base_mat) { // we've got hierarchy info! Matrix31 p; p.M[0] = anim_info->OffsetX; p.M[1] = anim_info->OffsetY; p.M[2] = anim_info->OffsetZ; HIERARCHY_Get_Body_Part_Offset(&offset, &p, parent_base_mat, parent_base_pos, parent_curr_mat, parent_curr_pos); // pass data up the hierarchy if (end_pos) *end_pos = offset; } else { // process at highter resolution offset.M[0] = (anim_info->OffsetX << 8) + ((anim_info_next->OffsetX + off_dx - anim_info->OffsetX) * tween); offset.M[1] = (anim_info->OffsetY << 8) + ((anim_info_next->OffsetY + off_dy - anim_info->OffsetY) * tween); offset.M[2] = (anim_info->OffsetZ << 8) + ((anim_info_next->OffsetZ + off_dz - anim_info->OffsetZ) * tween); /* We don't have bikes. if (p_thing->Class == CLASS_BIKE && part_number == 3) { //offset.M[0] = 0x0; //offset.M[1] = 0x900; offset.M[2] = 0x3500; } */ if (end_pos) { *end_pos = offset; } } // matrix_transformZMY((struct Matrix31*)&temp,rot_mat, &offset); // convert pos to floating point here to preserve accuracy and prevent overflow. float off_x = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[0][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[0][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[0][2]) / 32768.f); float off_y = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[1][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[1][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[1][2]) / 32768.f); float off_z = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[2][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[2][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[2][2]) / 32768.f); SLONG character_scale = person_get_scale(p_thing); float character_scalef = float(character_scale) / 256.f; off_x *= character_scalef; off_y *= character_scalef; off_z *= character_scalef; /* if (p_thing->Class == CLASS_BIKE) { off_x = 0; off_y = 0; off_z = 0; } */ off_x += float(x); off_y += float(y); off_z += float(z); // // Do everything in floats. // float fmatrix[9]; SLONG imatrix[9]; { // // Create a temporary "tween" matrix between current and next // CMatrix33 m1, m2; GetCMatrix(anim_info, &m1); GetCMatrix(anim_info_next, &m2); CQuaternion::BuildTween(&mat2, &m1, &m2, tween); // pass data up the hierarchy if (end_mat) *end_mat = mat2; // // Apply local rotation matrix to get mat_final that rotates // the point into world space. // matrix_mult33(&mat_final, rot_mat, &mat2); //! yeehaw! mat_final.M[0][0] = (mat_final.M[0][0] * character_scale) / 256; mat_final.M[0][1] = (mat_final.M[0][1] * character_scale) / 256; mat_final.M[0][2] = (mat_final.M[0][2] * character_scale) / 256; mat_final.M[1][0] = (mat_final.M[1][0] * character_scale) / 256; mat_final.M[1][1] = (mat_final.M[1][1] * character_scale) / 256; mat_final.M[1][2] = (mat_final.M[1][2] * character_scale) / 256; mat_final.M[2][0] = (mat_final.M[2][0] * character_scale) / 256; mat_final.M[2][1] = (mat_final.M[2][1] * character_scale) / 256; mat_final.M[2][2] = (mat_final.M[2][2] * character_scale) / 256; fmatrix[0] = float(mat_final.M[0][0]) * (1.0F / 32768.0F); fmatrix[1] = float(mat_final.M[0][1]) * (1.0F / 32768.0F); fmatrix[2] = float(mat_final.M[0][2]) * (1.0F / 32768.0F); fmatrix[3] = float(mat_final.M[1][0]) * (1.0F / 32768.0F); fmatrix[4] = float(mat_final.M[1][1]) * (1.0F / 32768.0F); fmatrix[5] = float(mat_final.M[1][2]) * (1.0F / 32768.0F); fmatrix[6] = float(mat_final.M[2][0]) * (1.0F / 32768.0F); fmatrix[7] = float(mat_final.M[2][1]) * (1.0F / 32768.0F); fmatrix[8] = float(mat_final.M[2][2]) * (1.0F / 32768.0F); imatrix[0] = mat_final.M[0][0] * 2; imatrix[1] = mat_final.M[0][1] * 2; imatrix[2] = mat_final.M[0][2] * 2; imatrix[3] = mat_final.M[1][0] * 2; imatrix[4] = mat_final.M[1][1] * 2; imatrix[5] = mat_final.M[1][2] * 2; imatrix[6] = mat_final.M[2][0] * 2; imatrix[7] = mat_final.M[2][1] * 2; imatrix[8] = mat_final.M[2][2] * 2; } /* if (part_number == SUB_OBJECT_HEAD) { fmatrix[0]= +0.131534; fmatrix[1]= -0.000000; fmatrix[2]= +0.991312; fmatrix[3]= +0.00133604; fmatrix[4]= +0.999999; fmatrix[5]= -0.000177275; fmatrix[6]= -0.991311; fmatrix[7]= 0.00134775; fmatrix[8]= 0.131534;; } */ if (prim == 267) { static count = 0; count += 1; #ifndef FINAL #ifndef TARGET_DC if (ControlFlag&&allow_debug_keys) { LOG_EXIT ( Figure_Draw_Prim_Tween ) return; } #endif #endif } LOG_ENTER ( Figure_Set_Rotation ) POLY_set_local_rotation( off_x, off_y, off_z, fmatrix); LOG_ENTER ( Figure_Set_Rotation ) // // Rotate all the points into the POLY_buffer. // p_obj = &prim_objects[prim]; sp = p_obj->StartPoint; ep = p_obj->EndPoint; POLY_buffer_upto = 0; // Check for being a gun #ifndef BUILD_PSX if (prim==256) { i=sp; } else // Or a shotgun if (prim==258) { i=sp+15; } // or an AK else if (prim==260) { i=sp+32; } else goto no_muzzle_calcs; // which skips... // // this bit, which only executes if one of the above tests is true. // pp = &POLY_buffer[POLY_buffer_upto]; // no ++, so reused pp->x=AENG_dx_prim_points[i].X; pp->y=AENG_dx_prim_points[i].Y; pp->z=AENG_dx_prim_points[i].Z; MATRIX_MUL( fmatrix, pp->x, pp->y, pp->z); pp->x+=off_x; pp->y+=off_y; pp->z+=off_z; p_thing->Genus.Person->GunMuzzle.X=pp->x*256; p_thing->Genus.Person->GunMuzzle.Y=pp->y*256; p_thing->Genus.Person->GunMuzzle.Z=pp->z*256; // x=pp->x*256; y=pp->y*256; z=pp->z*256; #endif no_muzzle_calcs: #if USE_TOMS_ENGINE_PLEASE_BOB if ( !MM_bLightTableAlreadySetUp ) { #if 0 // Set it up then. ASSERT ( MM_pcFadeTable == NULL ); ASSERT ( MM_pcFadeTableTint == NULL ); ASSERT ( MM_pMatrix == NULL ); ASSERT ( MM_Vertex == NULL ); ASSERT ( MM_pNormal == NULL ); // Set up some data for the MM rendering thing if it's not already been done. // #define ALIGNED_STATIC_ARRAY(name,number,mytype,align) \ // static char c##name##mytype##align##StaticArray [ align + number * sizeof ( mytype ) ]; \ // name = (mytype *)( ( (DWORD)c##name##mytype##align##StaticArray + (align-1) ) & ~(align-1) ) ALIGNED_STATIC_ARRAY ( MM_pcFadeTable, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pcFadeTableTint, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pMatrix, 1, D3DMATRIX, 32 ); ALIGNED_STATIC_ARRAY ( MM_Vertex, 4, D3DVERTEX, 32 ); ALIGNED_STATIC_ARRAY ( MM_pNormal, 4, float, 8 ); #endif } #endif if (WITHIN(prim, 261, 263)) { // // This is a muzzle flash! They don't have any lighting! // for (i = sp; i < ep; i++) { ASSERT(WITHIN(POLY_buffer_upto, 0, POLY_BUFFER_SIZE - 1)); pp = &POLY_buffer[POLY_buffer_upto++]; POLY_transform_using_local_rotation( AENG_dx_prim_points[i].X, AENG_dx_prim_points[i].Y, AENG_dx_prim_points[i].Z, pp); pp->colour = 0xff808080; pp->specular = 0xff000000; } for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p3, 0, POLY_buffer_upto - 1)); quad[0] = &POLY_buffer[p0]; quad[1] = &POLY_buffer[p1]; quad[2] = &POLY_buffer[p2]; quad[3] = &POLY_buffer[p3]; if (POLY_valid_quad(quad)) { quad[0]->u = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); quad[0]->v = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); quad[1]->u = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); quad[1]->v = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); quad[2]->u = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); quad[2]->v = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); quad[3]->u = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); quad[3]->v = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; POLY_add_quad(quad, page, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); tri[0] = &POLY_buffer[p0]; tri[1] = &POLY_buffer[p1]; tri[2] = &POLY_buffer[p2]; if (POLY_valid_triangle(tri)) { tri[0]->u = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); tri[0]->v = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); tri[1]->u = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); tri[1]->v = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); tri[2]->u = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); tri[2]->v = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; POLY_add_triangle(tri, page, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } LOG_EXIT ( Figure_Draw_Prim_Tween ) return; } else { #if USE_TOMS_ENGINE_PLEASE_BOB if ( !MM_bLightTableAlreadySetUp ) { Pyro *p = NULL; if (p_thing->Class == CLASS_PERSON && p_thing->Genus.Person->BurnIndex) { p = TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType != PYRO_IMMOLATE) { p = NULL; } } BuildMMLightingTable ( p, colour_and ); } LOG_ENTER ( Figure_Build_Matrices ) extern float POLY_cam_matrix_comb[9]; extern float POLY_cam_off_x; extern float POLY_cam_off_y; extern float POLY_cam_off_z; extern D3DMATRIX g_matProjection; extern D3DMATRIX g_matWorld; extern D3DVIEWPORT2 g_viewData; D3DMATRIX matTemp; { //_Multiply4dM((float *)pResultMatrix, (float *)g_matWorld, (float *)g_matProjection); matTemp._11 = g_matWorld._11*g_matProjection._11 + g_matWorld._12*g_matProjection._21 + g_matWorld._13*g_matProjection._31 + g_matWorld._14*g_matProjection._41; matTemp._12 = g_matWorld._11*g_matProjection._12 + g_matWorld._12*g_matProjection._22 + g_matWorld._13*g_matProjection._32 + g_matWorld._14*g_matProjection._42; matTemp._13 = g_matWorld._11*g_matProjection._13 + g_matWorld._12*g_matProjection._23 + g_matWorld._13*g_matProjection._33 + g_matWorld._14*g_matProjection._43; matTemp._14 = g_matWorld._11*g_matProjection._14 + g_matWorld._12*g_matProjection._24 + g_matWorld._13*g_matProjection._34 + g_matWorld._14*g_matProjection._44; matTemp._21 = g_matWorld._21*g_matProjection._11 + g_matWorld._22*g_matProjection._21 + g_matWorld._23*g_matProjection._31 + g_matWorld._24*g_matProjection._41; matTemp._22 = g_matWorld._21*g_matProjection._12 + g_matWorld._22*g_matProjection._22 + g_matWorld._23*g_matProjection._32 + g_matWorld._24*g_matProjection._42; matTemp._23 = g_matWorld._21*g_matProjection._13 + g_matWorld._22*g_matProjection._23 + g_matWorld._23*g_matProjection._33 + g_matWorld._24*g_matProjection._43; matTemp._24 = g_matWorld._21*g_matProjection._14 + g_matWorld._22*g_matProjection._24 + g_matWorld._23*g_matProjection._34 + g_matWorld._24*g_matProjection._44; matTemp._31 = g_matWorld._31*g_matProjection._11 + g_matWorld._32*g_matProjection._21 + g_matWorld._33*g_matProjection._31 + g_matWorld._34*g_matProjection._41; matTemp._32 = g_matWorld._31*g_matProjection._12 + g_matWorld._32*g_matProjection._22 + g_matWorld._33*g_matProjection._32 + g_matWorld._34*g_matProjection._42; matTemp._33 = g_matWorld._31*g_matProjection._13 + g_matWorld._32*g_matProjection._23 + g_matWorld._33*g_matProjection._33 + g_matWorld._34*g_matProjection._43; matTemp._34 = g_matWorld._31*g_matProjection._14 + g_matWorld._32*g_matProjection._24 + g_matWorld._33*g_matProjection._34 + g_matWorld._34*g_matProjection._44; matTemp._41 = g_matWorld._41*g_matProjection._11 + g_matWorld._42*g_matProjection._21 + g_matWorld._43*g_matProjection._31 + g_matWorld._44*g_matProjection._41; matTemp._42 = g_matWorld._41*g_matProjection._12 + g_matWorld._42*g_matProjection._22 + g_matWorld._43*g_matProjection._32 + g_matWorld._44*g_matProjection._42; matTemp._43 = g_matWorld._41*g_matProjection._13 + g_matWorld._42*g_matProjection._23 + g_matWorld._43*g_matProjection._33 + g_matWorld._44*g_matProjection._43; matTemp._44 = g_matWorld._41*g_matProjection._14 + g_matWorld._42*g_matProjection._24 + g_matWorld._43*g_matProjection._34 + g_matWorld._44*g_matProjection._44; } // Now make up the matrices. #if 0 // Officially correct version. DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_viewData.dwHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_viewData.dwY; #else // Version that knows about the letterbox mode hack. extern DWORD g_dw3DStuffHeight; extern DWORD g_dw3DStuffY; DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_dw3DStuffHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_dw3DStuffY; #endif MM_pMatrix[0]._11 = 0.0f; MM_pMatrix[0]._12 = matTemp._11 * (float)dwWidth + matTemp._14 * (float)( dwX + dwWidth ); MM_pMatrix[0]._13 = matTemp._12 * - (float)dwHeight + matTemp._14 * (float)( dwY + dwHeight ); MM_pMatrix[0]._14 = matTemp._14; MM_pMatrix[0]._21 = 0.0f; MM_pMatrix[0]._22 = matTemp._21 * (float)dwWidth + matTemp._24 * (float)( dwX + dwWidth ); MM_pMatrix[0]._23 = matTemp._22 * - (float)dwHeight + matTemp._24 * (float)( dwY + dwHeight ); MM_pMatrix[0]._24 = matTemp._24; MM_pMatrix[0]._31 = 0.0f; MM_pMatrix[0]._32 = matTemp._31 * (float)dwWidth + matTemp._34 * (float)( dwX + dwWidth ); MM_pMatrix[0]._33 = matTemp._32 * - (float)dwHeight + matTemp._34 * (float)( dwY + dwHeight ); MM_pMatrix[0]._34 = matTemp._34; // Validation magic number. unsigned long EVal = 0xe0001000; MM_pMatrix[0]._41 = *(float *)&EVal; MM_pMatrix[0]._42 = matTemp._41 * (float)dwWidth + matTemp._44 * (float)( dwX + dwWidth ); MM_pMatrix[0]._43 = matTemp._42 * - (float)dwHeight + matTemp._44 * (float)( dwY + dwHeight ); MM_pMatrix[0]._44 = matTemp._44; // 251 is a magic number for the DIP call! const float fNormScale = 251.0f; // Transform the lighting direction(s) by the inverse object matrix to get it into object space. // Assume inverse=transpose. D3DVECTOR vTemp; vTemp.x = MM_vLightDir.x * fmatrix[0] + MM_vLightDir.y * fmatrix[3] + MM_vLightDir.z * fmatrix[6]; vTemp.y = MM_vLightDir.x * fmatrix[1] + MM_vLightDir.y * fmatrix[4] + MM_vLightDir.z * fmatrix[7]; vTemp.z = MM_vLightDir.x * fmatrix[2] + MM_vLightDir.y * fmatrix[5] + MM_vLightDir.z * fmatrix[8]; MM_pNormal[0] = 0.0f; MM_pNormal[1] = vTemp.x * fNormScale; MM_pNormal[2] = vTemp.y * fNormScale; MM_pNormal[3] = vTemp.z * fNormScale; LOG_EXIT ( Figure_Build_Matrices ) #else //#if USE_TOMS_ENGINE_PLEASE_BOB Pyro *p = NULL; if (p_thing->Class == CLASS_PERSON && p_thing->Genus.Person->BurnIndex) { p = TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType != PYRO_IMMOLATE) { p = NULL; } } for (i = sp; i < ep; i++) { ASSERT(WITHIN(POLY_buffer_upto, 0, POLY_BUFFER_SIZE - 1)); pp = &POLY_buffer[POLY_buffer_upto++]; POLY_transform_using_local_rotation( AENG_dx_prim_points[i].X, AENG_dx_prim_points[i].Y, AENG_dx_prim_points[i].Z, pp); // // Do the lighting... // { nx = prim_normal[i].X; ny = prim_normal[i].Y; nz = prim_normal[i].Z; FMATRIX_MUL( imatrix, nx, ny, nz); dprod = nx * NIGHT_amb_norm_x + ny * NIGHT_amb_norm_y + nz * NIGHT_amb_norm_z; r = NIGHT_amb_red << 0; g = NIGHT_amb_green << 0; b = NIGHT_amb_blue << 0; #ifndef TARGET_DC extern UBYTE sw_hack; #endif if (dprod > 0) { dr = NIGHT_amb_red * dprod >> 15; dg = NIGHT_amb_green * dprod >> 15; db = NIGHT_amb_blue * dprod >> 15; r += dr;// + (dr >> 1); g += dg;// + (dg >> 1); b += db;// + (db >> 1); } // // Now for the lights... // for (j = 0; j < NIGHT_found_upto; j++) { nf = &NIGHT_found[j]; dprod = nx * nf->dx + ny * nf->dy + nz * nf->dz; if (dprod < 0) { dr = nf->r * dprod >> 15; dg = nf->g * dprod >> 15; db = nf->b * dprod >> 15; r -= dr;// + (dr >> 1); g -= dg;// + (dg >> 1); b -= db;// + (db >> 1); } } if (p) { r = (r > p->counter) ? (r - p->counter) : 10; g = (g > p->counter) ? (g - p->counter) : 4; b = (b > p->counter) ? (b - p->counter) : 3; } #ifndef TARGET_DC if (sw_hack) { r <<= 1; g <<= 1; b <<= 1; } #endif SATURATE(r, 0, 255); SATURATE(g, 0, 255); SATURATE(b, 0, 255); pp->colour = (r << 16) | (g << 8) | (b << 0); pp->colour |= FIGURE_alpha << 24; pp->specular = 0xff000000; } } #endif //#else //#if USE_TOMS_ENGINE_PLEASE_BOB } #if USE_TOMS_ENGINE_PLEASE_BOB #if 1 #if 1 // The wonderful NEW system! LOG_ENTER ( Figure_Draw_Polys ) #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, FALSE ); #endif // For now, just calculate as-and-when. TomsPrimObject *pPrimObj = &(D3DObj[prim]); if ( pPrimObj->wNumMaterials == 0 ) { // Not initialised. Do so. // It's not fair to count this as part of the drawing! :-) LOG_EXIT ( Figure_Draw_Polys ) FIGURE_generate_D3D_object ( prim ); LOG_ENTER ( Figure_Draw_Polys ) } // Tell the LRU cache we used this one. FIGURE_touch_LRU_of_object ( pPrimObj ); ASSERT ( pPrimObj->pD3DVertices != NULL ); ASSERT ( pPrimObj->pMaterials != NULL ); ASSERT ( pPrimObj->pwListIndices != NULL ); ASSERT ( pPrimObj->pwStripIndices != NULL ); ASSERT ( pPrimObj->wNumMaterials != 0 ); PrimObjectMaterial *pMat = pPrimObj->pMaterials; D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; D3DVERTEX *pVertex = (D3DVERTEX *)pPrimObj->pD3DVertices; UWORD *pwListIndices = pPrimObj->pwListIndices; UWORD *pwStripIndices = pPrimObj->pwStripIndices; for ( int iMatNum = pPrimObj->wNumMaterials; iMatNum > 0; iMatNum-- ) { // Set up the right texture for this material. UWORD wPage = pMat->wTexturePage; UWORD wRealPage = wPage & TEXTURE_PAGE_MASK; if ( wPage & TEXTURE_PAGE_FLAG_JACKET ) { // Find the real jacket page. wRealPage = jacket_lookup [ wRealPage ][GET_SKILL(p_thing)>>2]; wRealPage += FACE_PAGE_OFFSET; } else if ( wPage & TEXTURE_PAGE_FLAG_OFFSET ) { // An "offset" texture. This will be offset by a certain amount to // allow each prim to have different coloured clothes on. if ( tex_page_offset == 0 ) { // No lookup offset. // This has not been offset yet. wRealPage += FACE_PAGE_OFFSET; } else { // Look this up. wRealPage = alt_texture[wRealPage-(10*64)]+tex_page_offset-1; } } #ifdef DEBUG if ( wPage & TEXTURE_PAGE_FLAG_NOT_TEXTURED ) { ASSERT ( wRealPage == POLY_PAGE_COLOUR ); } #endif extern D3DMATRIX g_matWorld; PolyPage *pa = &(POLY_Page[wRealPage]); // Not sure if I'm using character_scalef correctly... ASSERT ( ( character_scalef < 1.2f ) && ( character_scalef > 0.8f ) ); if ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) && ( ( ( g_matWorld._43 * 32768.0f ) - ( pPrimObj->fBoundingSphereRadius * character_scalef ) ) > ( POLY_ZCLIP_PLANE * 32768.0f ) ) ) { // Non-alpha path. if ( wPage & TEXTURE_PAGE_FLAG_TINT ) { // Tinted colours. d3dmm.lpLightTable = MM_pcFadeTableTint; } else { // Normal. d3dmm.lpLightTable = MM_pcFadeTable; } d3dmm.lpvVertices = pVertex; #if 1 #ifdef DEBUG static int iCounter = 0; if ( iCounter != 0 ) { iCounter--; ASSERT ( iCounter != 0 ); } #endif // Fast as lightning. LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) #if 0 HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); //TRACE("Drew %i vertices, %i indices\n", (int)( pMat->wNumVertices ), (int)( pMat->wNumStripIndices ) ); #else // Use platform-independent version. HRESULT hres; #define SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB defined #ifdef SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB #ifdef DEBUG #ifdef TARGET_DC #define BUTTON_IS_PRESSED(value) ((value&0x80)!=0) extern DIJOYSTATE the_state; bool bShowDebug = FALSE; if ( BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_LTRIGGER] ) && BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_RTRIGGER] ) ) { DWORD dwColour = (DWORD)pwStripIndices; dwColour = ( dwColour >> 2 ) ^ ( dwColour >> 6 ) ^ ( dwColour ) ^ ( dwColour << 3 ); dwColour = ( dwColour << 9 ) ^ ( dwColour << 19 ) ^ ( dwColour ) ^ ( dwColour << 29 ) ^ ( dwColour >> 3 ); dwColour &= 0x7f7f7f7f; for ( int i = 0; i < 128; i++ ) { d3dmm.lpLightTable[i] = dwColour; } // And NULL texture (i.e. white). the_display.lp_D3D_Device->SetTexture ( 0, NULL ); } #endif #endif #endif //if (pMat->wNumVertices && // pMat->wNumStripIndices) { //TRACE ( "S4" ); hres = DrawIndPrimMM ( (the_display.lp_D3D_Device), D3DFVF_VERTEX, &d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices ); //TRACE ( "F4" ); } #endif #else // Do some performance tracing. #ifndef DTRACE #error Don't use this codepath unless DTRACING, fool! #endif LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); WORD wTempVerts[4]; wTempVerts[0] = 0; wTempVerts[1] = 1; wTempVerts[2] = 2; wTempVerts[3] = -1; (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 3, wTempVerts, 4, D3DDP_MULTIMATRIX ); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); //TRACE("Drew %i vertices, %i indices\n", (int)( pMat->wNumVertices ), (int)( pMat->wNumStripIndices ) ); #endif // ASSERT ( SUCCEEDED ( hres ) ); //triggers all the time when inside on start of RTA #if 0 // Can we have 4x polys for free? Oh go on.... hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); #endif LOG_EXIT ( Figure_DrawIndPrimMM ) } else { // Alpha/clipped path - do with standard non-MM calls. // FIXME. Needs to be done. // Actually, the fast-accept works very well, and it's only when the camera somehow gets REALLY close // that this happens. And actually a pop-reject seems a bit better than a clip. Certainly // there is no visually "right" thing to do. So leave it for now until someone complains. ATF. //TRACE ( "Tried to draw an alpha/clipped prim!" ); } // Next material pVertex += pMat->wNumVertices; pwListIndices += pMat->wNumListIndices; pwStripIndices += pMat->wNumStripIndices; pMat++; } #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, TRUE ); #endif LOG_EXIT ( Figure_Draw_Polys ) #endif #else // // The quads. // float fMyU[4], fMyV[4]; for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; fMyU[0] = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); fMyV[0] = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); fMyU[1] = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); fMyV[1] = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); fMyU[2] = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); fMyV[2] = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); fMyU[3] = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); fMyV[3] = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; if(p_f4->FaceFlags&FACE_FLAG_THUG_JACKET) { switch(page) { case 64+21: case 10*64+2: case 10*64+32: page=jacket_lookup[0][GET_SKILL(p_thing)>>2]; break; case 64+22: case 10*64+3: case 10*64+33: page=jacket_lookup[1][GET_SKILL(p_thing)>>2]; break; case 64+24: case 10*64+4: case 10*64+36: page=jacket_lookup[2][GET_SKILL(p_thing)>>2]; break; case 64+25: case 10*64+5: case 10*64+37: page=jacket_lookup[3][GET_SKILL(p_thing)>>2]; break; default: // ASSERT(0); break; } page+=FACE_PAGE_OFFSET; } else if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) // if(alt_texture[page-512]&&page<1024) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; #ifndef TARGET_DC extern UBYTE sw_hack; #endif PolyPage *pa = &(POLY_Page[page]); if ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ) { // Unlit untransformed vertices! WORD wIndices[5] = {0,1,2,3,-1}; for ( int i = 0; i < 4; i++ ) { const float fNormScale = 1.0f / 256.0f; int pt = p_f4->Points[i]; ASSERT(WITHIN(pt, sp, ep)); MM_Vertex[i].dvX = AENG_dx_prim_points[pt].X; MM_Vertex[i].dvY = AENG_dx_prim_points[pt].Y; MM_Vertex[i].dvZ = AENG_dx_prim_points[pt].Z; MM_Vertex[i].dvNX = prim_normal[pt].X * fNormScale; MM_Vertex[i].dvNY = prim_normal[pt].Y * fNormScale; MM_Vertex[i].dvNZ = prim_normal[pt].Z * fNormScale; MM_Vertex[i].dvTU = fMyU[i]; MM_Vertex[i].dvTV = fMyV[i]; // This must be done after setting the rest up, since it blats the 12th byte of the vertex. SET_MM_INDEX ( (MM_Vertex[i]), 0 ); } D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; if (p_f4->FaceFlags & FACE_FLAG_TINT) { // Tinted colours. d3dmm.lpLightTable = MM_pcFadeTableTint; } else { // Normal. d3dmm.lpLightTable = MM_pcFadeTable; } d3dmm.lpvVertices = MM_Vertex; // Although in theory this might happen, I've never actually seen it. ASSERT ( ( p_f4->DrawFlags & POLY_FLAG_TEXTURED ) != 0 ); //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 4, wIndices, 5, D3DDP_MULTIMATRIX ); ASSERT ( SUCCEEDED ( hres ) ); } else { // Alpha-blended, clipped, or otherwise special-cased. Ignore for now, but need to be handled. } } // // The tris. // for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; fMyU[0] = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); fMyV[0] = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); fMyU[1] = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); fMyV[1] = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); fMyU[2] = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); fMyV[2] = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; if(p_f3->FaceFlags&FACE_FLAG_THUG_JACKET) { switch(page) { case 64+21: case 10*64+2: case 10*64+32: page=jacket_lookup[0][GET_SKILL(p_thing)>>2]; break; case 64+22: case 10*64+3: case 10*64+33: page=jacket_lookup[1][GET_SKILL(p_thing)>>2]; break; case 64+24: case 10*64+4: case 10*64+36: page=jacket_lookup[2][GET_SKILL(p_thing)>>2]; break; case 64+25: case 10*64+5: case 10*64+37: page=jacket_lookup[3][GET_SKILL(p_thing)>>2]; break; default: // ASSERT(0); break; } page+=FACE_PAGE_OFFSET; } else if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) // if(alt_texture[page-512]&&page<1024) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; #ifndef TARGET_DC extern UBYTE sw_hack; #endif PolyPage *pa = &(POLY_Page[page]); if ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ) { // Unlit untransformed vertices! WORD wIndices[4] = {0,1,2,-1}; for ( int i = 0; i < 3; i++ ) { const float fNormScale = 1.0f / 256.0f; int pt = p_f3->Points[i]; ASSERT(WITHIN(pt, sp, ep)); MM_Vertex[i].dvX = AENG_dx_prim_points[pt].X; MM_Vertex[i].dvY = AENG_dx_prim_points[pt].Y; MM_Vertex[i].dvZ = AENG_dx_prim_points[pt].Z; MM_Vertex[i].dvNX = prim_normal[pt].X * fNormScale; MM_Vertex[i].dvNY = prim_normal[pt].Y * fNormScale; MM_Vertex[i].dvNZ = prim_normal[pt].Z * fNormScale; MM_Vertex[i].dvTU = fMyU[i]; MM_Vertex[i].dvTV = fMyV[i]; // This must be done after setting the rest up, since it blats the 12th byte of the vertex. SET_MM_INDEX ( (MM_Vertex[i]), 0 ); } D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; if (p_f3->FaceFlags & FACE_FLAG_TINT) { // Tinted colours. d3dmm.lpLightTable = MM_pcFadeTableTint; } else { // Normal. d3dmm.lpLightTable = MM_pcFadeTable; } d3dmm.lpvVertices = MM_Vertex; // Although in theory this might happen, I've never actually seen it. ASSERT ( ( p_f3->DrawFlags & POLY_FLAG_TEXTURED ) != 0 ); //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 3, wIndices, 4, D3DDP_MULTIMATRIX ); ASSERT ( SUCCEEDED ( hres ) ); } else { // Alpha-blended, clipped, or otherwise special-cased. Ignore for now, but need to be handled. } } #endif #else //#if USE_TOMS_ENGINE_PLEASE_BOB // // The quads. // for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p3, 0, POLY_buffer_upto - 1)); /* p_f4->Bright[0]=store_dprod[p0]; p_f4->Bright[1]=store_dprod[p1]; p_f4->Bright[2]=store_dprod[p2]; p_f4->Bright[4]=store_dprod[p3]; */ quad[0] = &POLY_buffer[p0]; quad[1] = &POLY_buffer[p1]; quad[2] = &POLY_buffer[p2]; quad[3] = &POLY_buffer[p3]; if (POLY_valid_quad(quad)) { if (p_f4->DrawFlags & POLY_FLAG_TEXTURED) { quad[0]->u = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); quad[0]->v = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); quad[1]->u = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); quad[1]->v = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); quad[2]->u = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); quad[2]->v = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); quad[3]->u = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); quad[3]->v = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); if (p_f4->FaceFlags & FACE_FLAG_TINT) { qc0 = quad[0]->colour; qc1 = quad[1]->colour; qc2 = quad[2]->colour; qc3 = quad[3]->colour; quad[0]->colour &= colour_and; quad[1]->colour &= colour_and; quad[2]->colour &= colour_and; quad[3]->colour &= colour_and; } page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; if(p_f4->FaceFlags&FACE_FLAG_THUG_JACKET) { switch(page) { case 64+21: case 10*64+2: case 10*64+32: page=jacket_lookup[0][GET_SKILL(p_thing)>>2]; break; case 64+22: case 10*64+3: case 10*64+33: page=jacket_lookup[1][GET_SKILL(p_thing)>>2]; break; case 64+24: case 10*64+4: case 10*64+36: page=jacket_lookup[2][GET_SKILL(p_thing)>>2]; break; case 64+25: case 10*64+5: case 10*64+37: page=jacket_lookup[3][GET_SKILL(p_thing)>>2]; break; default: // ASSERT(0); break; } page+=FACE_PAGE_OFFSET; } else if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) // if(alt_texture[page-512]&&page<1024) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; #ifndef TARGET_DC extern UBYTE sw_hack; #endif PolyPage *pa = &(POLY_Page[page]); #if USE_TOMS_ENGINE_PLEASE_BOB if ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ) { // Do an immediate render, not a deferred one. // // and render the polygons // #if 0 WORD wIndices[6] = {0,1,2,2,1,3}; D3DTLVERTEX tlVertex[4]; for ( int i = 0; i < 4; i++ ) { tlVertex[i].dvSX = quad[i]->X * PolyPage::s_XScale; tlVertex[i].dvSY = quad[i]->Y * PolyPage::s_YScale; tlVertex[i].dvSZ = 1.0f - quad[i]->Z; tlVertex[i].dvTU = quad[i]->u; tlVertex[i].dvTV = quad[i]->v; tlVertex[i].dcColor = quad[i]->colour; tlVertex[i].dcSpecular = quad[i]->specular; tlVertex[i].dvRHW = quad[i]->Z; } HRESULT hres; if (FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported()) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); //tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX, tlVertex, 4, wIndices, 6, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetChanged(); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX, tlVertex, 4, wIndices, 6, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); #else static iCount = 0; if ( FALSE ) { // LVertex. WORD wIndices[6] = {0,1,2,2,1,3}; D3DLVERTEX lVertex[4]; for ( int i = 0; i < 4; i++ ) { int pt = p_f4->Points[i]; ASSERT(WITHIN(pt, sp, ep)); lVertex[i].dvX = AENG_dx_prim_points[pt].X; lVertex[i].dvY = AENG_dx_prim_points[pt].Y; lVertex[i].dvZ = AENG_dx_prim_points[pt].Z; lVertex[i].dvTU = quad[i]->u; lVertex[i].dvTV = quad[i]->v; lVertex[i].dcColor = quad[i]->colour; lVertex[i].dcSpecular = quad[i]->specular; } HRESULT hres; if (FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported()) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX, lVertex, 4, wIndices, 6, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX, lVertex, 4, wIndices, 6, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } #ifdef TARGET_DC else { // Use the MM stuff. // Unlit untransformed vertices! WORD wIndices[5] = {0,1,2,3,-1}; for ( int i = 0; i < 4; i++ ) { const float fNormScale = 1.0f / 256.0f; int pt = p_f4->Points[i]; ASSERT(WITHIN(pt, sp, ep)); MM_Vertex[i].dvX = AENG_dx_prim_points[pt].X; MM_Vertex[i].dvY = AENG_dx_prim_points[pt].Y; MM_Vertex[i].dvZ = AENG_dx_prim_points[pt].Z; MM_Vertex[i].dvNX = prim_normal[pt].X * fNormScale; MM_Vertex[i].dvNY = prim_normal[pt].Y * fNormScale; MM_Vertex[i].dvNZ = prim_normal[pt].Z * fNormScale; MM_Vertex[i].dvTU = quad[i]->u; MM_Vertex[i].dvTV = quad[i]->v; // This must be done after setting the rest up, since it blats the 12th byte of the vertex. SET_MM_INDEX ( (MM_Vertex[i]), 0 ); } #if 0 if ( FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported() ) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); //tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, MM_Vertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } #endif D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; d3dmm.lpLightTable = MM_pcFadeTable; d3dmm.lpvVertices = MM_Vertex; //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetChanged(); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 4, wIndices, 5, D3DDP_MULTIMATRIX ); ASSERT ( SUCCEEDED ( hres ) ); } #endif #endif } else #endif //#if USE_TOMS_ENGINE_PLEASE_BOB { if (FIGURE_alpha != 255) { POLY_Page[page].RS.SetTempTransparent(); } #ifndef TARGET_DC else if (the_display.GetDeviceInfo()->AdamiLightingSupported() && !sw_hack) #else else if (the_display.GetDeviceInfo()->AdamiLightingSupported()) #endif { // draw lighting quad POLY_add_quad(quad, POLY_PAGE_COLOUR, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } // draw texture quad POLY_add_quad(quad, page, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } if (p_f4->FaceFlags & FACE_FLAG_TINT) { quad[0]->colour = qc0; quad[1]->colour = qc1; quad[2]->colour = qc2; quad[3]->colour = qc3; } } else { #if 0 // // The colour of the face. // r = ENGINE_palette[p_f4->Col2].red; g = ENGINE_palette[p_f4->Col2].green; b = ENGINE_palette[p_f4->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); #ifdef TARGET_DC face_colour |= 0xff000000; #endif quad[0]->colour = face_colour; quad[1]->colour = face_colour; quad[2]->colour = face_colour; quad[3]->colour = face_colour; if (FIGURE_alpha != 255) { ASSERT(0); } POLY_add_quad(quad, POLY_PAGE_COLOUR, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); #ifdef TARGET_DC colour |= 0xff000000; #endif quad[0]->colour = colour; quad[1]->colour = colour; quad[2]->colour = colour; quad[3]->colour = colour; #endif } } } // // The triangles. // for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; /* p_f3->Bright[0]=store_dprod[p0]; p_f3->Bright[1]=store_dprod[p1]; p_f3->Bright[2]=store_dprod[p2]; */ ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); tri[0] = &POLY_buffer[p0]; tri[1] = &POLY_buffer[p1]; tri[2] = &POLY_buffer[p2]; if (POLY_valid_triangle(tri)) { if (p_f3->DrawFlags & POLY_FLAG_TEXTURED) { tri[0]->u = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); tri[0]->v = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); tri[1]->u = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); tri[1]->v = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); tri[2]->u = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); tri[2]->v = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); if (p_f3->FaceFlags & FACE_FLAG_TINT) { qc0 = tri[0]->colour; qc1 = tri[1]->colour; qc2 = tri[2]->colour; tri[0]->colour &= colour_and; tri[1]->colour &= colour_and; tri[2]->colour &= colour_and; } page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; if(p_f3->FaceFlags&FACE_FLAG_THUG_JACKET) { switch(page) { case 64+21: case 10*64+2: case 10*64+32: page=jacket_lookup[0][GET_SKILL(p_thing)>>2]; break; case 64+22: case 10*64+3: case 10*64+33: page=jacket_lookup[1][GET_SKILL(p_thing)>>2]; break; case 64+24: case 10*64+4: case 10*64+36: page=jacket_lookup[2][GET_SKILL(p_thing)>>2]; break; case 64+25: case 10*64+5: case 10*64+37: page=jacket_lookup[3][GET_SKILL(p_thing)>>2]; break; default: // ASSERT(0); break; } page+=FACE_PAGE_OFFSET; } else if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; //ASSERT(TEXTURE_dontexist[page]==0); #ifndef TARGET_DC extern UBYTE sw_hack; #endif PolyPage *pa = &(POLY_Page[page]); #if USE_TOMS_ENGINE_PLEASE_BOB if ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ) { // Do an immediate render, not a deferred one. // // and render the polygons // #if 0 // TLVERTEX stuff. WORD wIndices[3] = {0,1,2}; D3DTLVERTEX tlVertex[3]; bool bBinned = FALSE; for ( int i = 0; i < 3; i++ ) { tlVertex[i].dvSX = tri[i]->X * PolyPage::s_XScale; tlVertex[i].dvSY = tri[i]->Y * PolyPage::s_YScale; tlVertex[i].dvSZ = 1.0f - tri[i]->Z; tlVertex[i].dvTU = tri[i]->u; tlVertex[i].dvTV = tri[i]->v; tlVertex[i].dcColor = tri[i]->colour; tlVertex[i].dcSpecular = tri[i]->specular; tlVertex[i].dvRHW = tri[i]->Z; if ( ( tri[i]->Z <= 0.0f ) || ( tri[i]->Z >= 1.0f ) ) { bBinned = TRUE; } } if ( !bBinned ) { HRESULT hres; if ( FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported()) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); //tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX, tlVertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_TLVERTEX, tlVertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } #else static int iCount = 0; if ( FALSE ) { // LVertex. WORD wIndices[3] = {0,1,2}; D3DLVERTEX lVertex[3]; for ( int i = 0; i < 3; i++ ) { int pt = p_f3->Points[i]; ASSERT(WITHIN(pt, sp, ep)); lVertex[i].dvX = AENG_dx_prim_points[pt].X; lVertex[i].dvY = AENG_dx_prim_points[pt].Y; lVertex[i].dvZ = AENG_dx_prim_points[pt].Z; lVertex[i].dvTU = tri[i]->u; lVertex[i].dvTV = tri[i]->v; lVertex[i].dcColor = tri[i]->colour; lVertex[i].dcSpecular = tri[i]->specular; } //lVertex[2].dcColor = ( ( lVertex[2].dcColor + 0x00400000 ) & 0x00ff0000 ) | ( lVertex[2].dcColor & ~0x00ff0000 ); HRESULT hres; if ( FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported()) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); //tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX, lVertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX, lVertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } #ifdef TARGET_DC else { // Use the MM stuff. // Unlit untransformed vertices! WORD wIndices[4] = {0,1,2,-1}; for ( int i = 0; i < 3; i++ ) { const float fNormScale = 1.0f / 256.0f; int pt = p_f3->Points[i]; ASSERT(WITHIN(pt, sp, ep)); MM_Vertex[i].dvX = AENG_dx_prim_points[pt].X; MM_Vertex[i].dvY = AENG_dx_prim_points[pt].Y; MM_Vertex[i].dvZ = AENG_dx_prim_points[pt].Z; MM_Vertex[i].dvNX = prim_normal[pt].X * fNormScale; MM_Vertex[i].dvNY = prim_normal[pt].Y * fNormScale; MM_Vertex[i].dvNZ = prim_normal[pt].Z * fNormScale; MM_Vertex[i].dvTU = tri[i]->u; MM_Vertex[i].dvTV = tri[i]->v; // This must be done after setting the rest up, since it blats the 12th byte of the vertex. SET_MM_INDEX ( (MM_Vertex[i]), 0 ); } #if 0 if ( FALSE && the_display.GetDeviceInfo()->AdamiLightingSupported() ) { // Draw lighting triangle PolyPage *tpa = &(POLY_Page[POLY_PAGE_COLOUR]); //tpa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); tpa->RS.SetChanged(); hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, MM_Vertex, 3, wIndices, 3, D3DDP_DONOTUPDATEEXTENTS | D3DDP_DONOTLIGHT ); } #endif D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; d3dmm.lpLightTable = MM_pcFadeTable; d3dmm.lpvVertices = MM_Vertex; //pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetChanged(); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 3, wIndices, 4, D3DDP_MULTIMATRIX ); ASSERT ( SUCCEEDED ( hres ) ); } #endif #endif } else #endif //#if USE_TOMS_ENGINE_PLEASE_BOB { if (FIGURE_alpha != 255) { POLY_Page[page].RS.SetTempTransparent(); } #ifndef TARGET_DC else if (the_display.GetDeviceInfo()->AdamiLightingSupported() && !sw_hack) #else else if (the_display.GetDeviceInfo()->AdamiLightingSupported()) #endif { // add lighting triangle POLY_add_triangle(tri, POLY_PAGE_COLOUR, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } POLY_add_triangle(tri, page, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } if (p_f3->FaceFlags & FACE_FLAG_TINT) { tri[0]->colour = qc0; tri[1]->colour = qc1; tri[2]->colour = qc2; } } else { #if 0 // // The colour of the face. // r = ENGINE_palette[p_f3->Col2].red; g = ENGINE_palette[p_f3->Col2].green; b = ENGINE_palette[p_f3->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); tri[0]->colour = face_colour; tri[1]->colour = face_colour; tri[2]->colour = face_colour; if (FIGURE_alpha != 255) { ASSERT(0); } POLY_add_triangle(tri, POLY_PAGE_COLOUR, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); tri[0]->colour = colour; tri[1]->colour = colour; tri[2]->colour = colour; #endif } } } #endif //#else //#if USE_TOMS_ENGINE_PLEASE_BOB #if USE_TOMS_ENGINE_PLEASE_BOB // Not done yet. #else //#if USE_TOMS_ENGINE_PLEASE_BOB // // Environment mapping! // if (p_thing && p_thing->Class == CLASS_VEHICLE) { float nx; float ny; float nz; float dx; float dy; float dz; float comb[9]; float cam_matrix[9]; SLONG num_points = ep - sp; extern float AENG_cam_yaw; extern float AENG_cam_pitch; extern float AENG_cam_roll; MATRIX_calc(cam_matrix, AENG_cam_yaw, AENG_cam_pitch, AENG_cam_roll); MATRIX_3x3mul(comb, cam_matrix, fmatrix); // // Environment map the van. Work out the uv coords at all the points. // for (i = 0; i < num_points; i++) { nx = prim_normal[sp + i].X * (2.0F / 256.0F); ny = prim_normal[sp + i].Y * (2.0F / 256.0F); nz = prim_normal[sp + i].Z * (2.0F / 256.0F); MATRIX_MUL( comb, nx, ny, nz); dx = POLY_buffer[i].x; dy = POLY_buffer[i].y; dz = POLY_buffer[i].z; POLY_buffer[i].u = (nx * 0.5F) + 0.5F; POLY_buffer[i].v = (ny * 0.5F) + 0.5F; POLY_buffer[i].colour = 0xff888888; } // // Add the triangles and quads. // // // The quads. // for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; if (p_f4->FaceFlags & (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) { p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p3, 0, POLY_buffer_upto - 1)); quad[0] = &POLY_buffer[p0]; quad[1] = &POLY_buffer[p1]; quad[2] = &POLY_buffer[p2]; quad[3] = &POLY_buffer[p3]; if (POLY_valid_quad(quad)) { if ((p_f4->FaceFlags & (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) == (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) { page = POLY_PAGE_WINMAP; } else { page = POLY_PAGE_ENVMAP; } POLY_add_quad(quad, page, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } } // // The triangles. // for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; if (p_f3->FaceFlags & (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) { p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); tri[0] = &POLY_buffer[p0]; tri[1] = &POLY_buffer[p1]; tri[2] = &POLY_buffer[p2]; if (POLY_valid_triangle(tri)) { if ((p_f3->FaceFlags & (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) == (FACE_FLAG_ENVMAP|FACE_FLAG_TINT)) { page = POLY_PAGE_WINMAP; } else { page = POLY_PAGE_ENVMAP; } POLY_add_triangle(tri, page, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } } } #endif //#else //#if USE_TOMS_ENGINE_PLEASE_BOB #if USE_TOMS_ENGINE_PLEASE_BOB if ( !MM_bLightTableAlreadySetUp ) { #if 0 // Clean up after ourselves. MM_pcFadeTable = NULL; MM_pcFadeTableTint = NULL; MM_pMatrix = NULL; MM_Vertex = NULL; MM_pNormal = NULL; #endif } #endif //#if USE_TOMS_ENGINE_PLEASE_BOB LOG_EXIT ( Figure_Draw_Prim_Tween ) } void FIGURE_draw_prim_tween_warped( SLONG prim, SLONG x, SLONG y, SLONG z, SLONG tween, struct GameKeyFrameElement *anim_info, struct GameKeyFrameElement *anim_info_next, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, ULONG colour, ULONG specular, Thing *p_thing) { SLONG i; SLONG j; SLONG sp; SLONG ep; SLONG p0; SLONG p1; SLONG p2; SLONG p3; ULONG red; ULONG green; ULONG blue; ULONG r; ULONG g; ULONG b; ULONG face_colour; SLONG page; Matrix31 offset; Matrix33 mat2; float local_mat[9]; float angle,sint,cost,tmpx,tmpz; SVector temp; SVector_F temp2; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; POLY_Point *pp; POLY_Point *ps; POLY_Point *tri [3]; POLY_Point *quad[4]; red = (colour >> 16) & 0xff; green = (colour >> 8) & 0xff; blue = (colour >> 0) & 0xff; // // Matrix functions we use. // void matrix_transform (Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_mult33 (Matrix33* result, Matrix33* mat1, Matrix33* mat2); offset.M[0] = anim_info->OffsetX + ((anim_info_next->OffsetX + off_dx - anim_info->OffsetX) * tween >> 8); offset.M[1] = anim_info->OffsetY + ((anim_info_next->OffsetY + off_dy - anim_info->OffsetY) * tween >> 8); offset.M[2] = anim_info->OffsetZ + ((anim_info_next->OffsetZ + off_dz - anim_info->OffsetZ) * tween >> 8); matrix_transformZMY((struct Matrix31*)&temp,rot_mat, &offset); SLONG character_scale = person_get_scale(p_thing); temp.X = (temp.X * character_scale) / 256; temp.Y = (temp.Y * character_scale) / 256; temp.Z = (temp.Z * character_scale) / 256; x += temp.X; y += temp.Y; z += temp.Z; // // Create a temporary "tween" matrix between current and next // CMatrix33 m1, m2; GetCMatrix(anim_info, &m1); GetCMatrix(anim_info_next, &m2); build_tween_matrix(&mat2, &m1, &m2, tween); normalise_matrix(&mat2); mat2.M[0][0] = (mat2.M[0][0] * character_scale) / 256; mat2.M[0][1] = (mat2.M[0][1] * character_scale) / 256; mat2.M[0][2] = (mat2.M[0][2] * character_scale) / 256; mat2.M[1][0] = (mat2.M[1][0] * character_scale) / 256; mat2.M[1][1] = (mat2.M[1][1] * character_scale) / 256; mat2.M[1][2] = (mat2.M[1][2] * character_scale) / 256; mat2.M[2][0] = (mat2.M[2][0] * character_scale) / 256; mat2.M[2][1] = (mat2.M[2][1] * character_scale) / 256; mat2.M[2][2] = (mat2.M[2][2] * character_scale) / 256; // // Apply local rotation matrix to get mat_final that rotates // the point into world space. // // matrix_mult33(&mat_final, rot_mat, &mat2); // ^- we don't do this. // instead we need to apply mat2 seperately, then apply the xform, then pass onwards // // Do everything in floats. // float off_x; float off_y; float off_z; float fmatrix[9]; off_x = float(x); off_y = float(y); off_z = float(z); // scale! fmatrix[0] = float(rot_mat->M[0][0]) * (1.0F / 32768.0F); fmatrix[1] = float(rot_mat->M[0][1]) * (1.0F / 32768.0F); fmatrix[2] = float(rot_mat->M[0][2]) * (1.0F / 32768.0F); fmatrix[3] = float(rot_mat->M[1][0]) * (1.0F / 32768.0F); fmatrix[4] = float(rot_mat->M[1][1]) * (1.0F / 32768.0F); fmatrix[5] = float(rot_mat->M[1][2]) * (1.0F / 32768.0F); fmatrix[6] = float(rot_mat->M[2][0]) * (1.0F / 32768.0F); fmatrix[7] = float(rot_mat->M[2][1]) * (1.0F / 32768.0F); fmatrix[8] = float(rot_mat->M[2][2]) * (1.0F / 32768.0F); local_mat[0] = float(mat2.M[0][0]) * (1.0F / 32768.0F); local_mat[1] = float(mat2.M[0][1]) * (1.0F / 32768.0F); local_mat[2] = float(mat2.M[0][2]) * (1.0F / 32768.0F); local_mat[3] = float(mat2.M[1][0]) * (1.0F / 32768.0F); local_mat[4] = float(mat2.M[1][1]) * (1.0F / 32768.0F); local_mat[5] = float(mat2.M[1][2]) * (1.0F / 32768.0F); local_mat[6] = float(mat2.M[2][0]) * (1.0F / 32768.0F); local_mat[7] = float(mat2.M[2][1]) * (1.0F / 32768.0F); local_mat[8] = float(mat2.M[2][2]) * (1.0F / 32768.0F); POLY_set_local_rotation( off_x, off_y, off_z, fmatrix); // // Rotate all the points into the POLY_buffer. // p_obj = &prim_objects[prim]; sp = p_obj->StartPoint; ep = p_obj->EndPoint; POLY_buffer_upto = 0; for (i = sp; i < ep; i++) { ASSERT(WITHIN(POLY_buffer_upto, 0, POLY_BUFFER_SIZE - 1)); temp2=AENG_dx_prim_points[i]; // temp2.X-=offset.M[0]; // temp2.Y-=offset.M[1]; // temp2.Z-=offset.M[2]; angle=(temp2.Z+offset.M[2])*2; angle=angle*PI/180; sint=sin(angle); cost=cos(angle); tmpx = (temp2.X*cost)+(temp2.Z*sint); tmpz =-(temp2.X*sint)+(temp2.Z*cost); temp2.X=tmpx; temp2.Z=tmpz; // temp2.X+=offset.M[0]; // temp2.Y+=offset.M[1]; // temp2.Z+=offset.M[2]; // apply the local (tweening) matrix MATRIX_MUL(local_mat,temp2.X,temp2.Y,temp2.Z); // do some testy gnasty warp effect //... /* angle=(temp2.Z+offset.M[2])*2; angle=angle*PI/180; sint=sin(angle); cost=cos(angle); tmpx = (temp2.X*cost)+(temp2.Z*sint); tmpz =-(temp2.X*sint)+(temp2.Z*cost); temp2.X=tmpx; temp2.Z=tmpz; */ //temp2.X+=(temp2.Z-off_z)/4.0; // do the global matrix (ofs_x/y/z, rot_mat and camera) pp = &POLY_buffer[POLY_buffer_upto++]; POLY_transform_using_local_rotation(temp2.X, temp2.Y, temp2.Z, pp); #ifdef TARGET_DC colour |= 0xff000000; #endif pp->colour = colour; // use_global_cloud(&pp->colour); pp->specular = specular; } // // The quads. // for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p3, 0, POLY_buffer_upto - 1)); quad[0] = &POLY_buffer[p0]; quad[1] = &POLY_buffer[p1]; quad[2] = &POLY_buffer[p2]; quad[3] = &POLY_buffer[p3]; if (POLY_valid_quad(quad)) { if (p_f4->DrawFlags & POLY_FLAG_TEXTURED) { quad[0]->u = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); quad[0]->v = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); quad[1]->u = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); quad[1]->v = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); quad[2]->u = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); quad[2]->v = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); quad[3]->u = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); quad[3]->v = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; page+=FACE_PAGE_OFFSET; POLY_add_quad(quad, page, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } else { // // The colour of the face. // r = ENGINE_palette[p_f4->Col2].red; g = ENGINE_palette[p_f4->Col2].green; b = ENGINE_palette[p_f4->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); #ifdef TARGET_DC face_colour |= 0xff000000; colour |= 0xff000000; #endif quad[0]->colour = face_colour; quad[1]->colour = face_colour; quad[2]->colour = face_colour; quad[3]->colour = face_colour; POLY_add_quad(quad, POLY_PAGE_COLOUR, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); quad[0]->colour = colour; quad[1]->colour = colour; quad[2]->colour = colour; quad[3]->colour = colour; } } } // // The triangles. // for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); tri[0] = &POLY_buffer[p0]; tri[1] = &POLY_buffer[p1]; tri[2] = &POLY_buffer[p2]; if (POLY_valid_triangle(tri)) { if (p_f3->DrawFlags & POLY_FLAG_TEXTURED) { tri[0]->u = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); tri[0]->v = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); tri[1]->u = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); tri[1]->v = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); tri[2]->u = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); tri[2]->v = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; page+=FACE_PAGE_OFFSET; POLY_add_triangle(tri, page, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } else { // // The colour of the face. // r = ENGINE_palette[p_f3->Col2].red; g = ENGINE_palette[p_f3->Col2].green; b = ENGINE_palette[p_f3->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); #ifdef TARGET_DC face_colour |= 0xff000000; colour |= 0xff000000; #endif tri[0]->colour = face_colour; tri[1]->colour = face_colour; tri[2]->colour = face_colour; POLY_add_triangle(tri, POLY_PAGE_COLOUR, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); tri[0]->colour = colour; tri[1]->colour = colour; tri[2]->colour = colour; } } } } //************************************************************************************************* //JCL - heirarchical bones drawing... // global structure to prevent actual recursion... #define MAX_RECURSION 5 struct structFIGURE_dhpr_data { SLONG start_object; BodyDef *body_def; Matrix31 *world_pos; SLONG tween; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; Matrix33 *world_mat; Matrix33 *world_mat2; SLONG dx; SLONG dy; SLONG dz; ULONG colour; ULONG specular; BYTE bPersonType; BYTE bPersonID; } FIGURE_dhpr_data; #if 1 // Got to split this up - the compiler is getting very confused. struct structFIGURE_dhpr_rdata1 { SLONG part_number; SLONG current_child_number; CMatrix33 *parent_base_mat; Matrix31 *parent_base_pos; Matrix33 *parent_current_mat; Matrix31 *parent_current_pos; Matrix31 pos; //Matrix31 end_pos; //Matrix33 end_mat; } FIGURE_dhpr_rdata1[MAX_RECURSION]; struct structFIGURE_dhpr_rdata2 { //SLONG part_number; //SLONG current_child_number; //CMatrix33 *parent_base_mat; //Matrix31 *parent_base_pos; //Matrix33 *parent_current_mat; //Matrix31 *parent_current_pos; //Matrix31 pos; Matrix31 end_pos; Matrix33 end_mat; } FIGURE_dhpr_rdata2[MAX_RECURSION]; #else struct { SLONG part_number; CMatrix33 *parent_base_mat; Matrix31 *parent_base_pos; Matrix33 *parent_current_mat; Matrix31 *parent_current_pos; Matrix33 end_mat; Matrix31 end_pos; Matrix31 pos; SLONG current_child_number; } FIGURE_dhpr_rdata[MAX_RECURSION]; #endif #define PART_FACE 1 #define PART_TROUSERS 2 #define PART_JACKET 3 #define PART_SHOES 4 #define PART_PELVIS 5 #define PART_HANDS 6 UBYTE part_type[]= { 2,//5,//"pelvis", 2,//"lfemur", 2,//"ltibia", 4,//"lfoot", 3,//"torso", 3,//"rhumorus", 3,//"rradius", 6,//"rhand", 3,//"lhumorus", 3,//"lradius", 6,//"lhand", 1,//"skull", 2,//"rfemur", 2,//"rtibia", 4//"rfoot", }; ULONG local_seed; SLONG mandom(void) { local_seed=local_seed*123456789+314159265; return(local_seed); } void local_set_seed(SLONG seed) { seed=local_seed; } ULONG jacket_col; ULONG leg_col; #if 1 // Optimised version //volatile int m_iRecurseLevelDebugging; // Set to 1 for the all-in-one method of drawing things. #define DRAW_WHOLE_PERSON_AT_ONCE 1 #define MAX_NUM_BODY_PARTS_AT_ONCE 20 #if DRAW_WHOLE_PERSON_AT_ONCE // Static arrays of the things we need for each part of the body. ALIGNED_STATIC_ARRAY ( static D3DMATRIX *, MMBodyParts_pMatrix, MAX_NUM_BODY_PARTS_AT_ONCE, D3DMATRIX, 32 ); ALIGNED_STATIC_ARRAY ( static float *, MMBodyParts_pNormal, MAX_NUM_BODY_PARTS_AT_ONCE*4, float, 8 ); void FIGURE_draw_hierarchical_prim_recurse_individual_cull ( Thing *p_person ); #endif #if DRAW_WHOLE_PERSON_AT_ONCE void FIGURE_draw_hierarchical_prim_recurse(Thing *p_person) { SLONG recurse_level = 0; SLONG dx,dy,dz; UWORD f1,f2; SLONG civ_flag=0,legs,body,shoes,face,hands,pelvis; //SLONG limb; struct Matrix33 *rot_mat; LOG_ENTER ( Figure_Draw_Hierarchical ) #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB // Do I need to toggle inflation? extern int g_iCheatNumber; // Well, 0x10f1a7e sort of spells "inflate" :-) if ( g_iCheatNumber == 0x10f1a7e ) { if ( m_bPleaseInflatePeople ) { CONSOLE_text("Looks like the inflation is wearing off now D'arci."); m_bPleaseInflatePeople = FALSE; } else { CONSOLE_text("The Illinois Enema Bandit has inflated everyone D'arci!"); m_bPleaseInflatePeople = TRUE; } // And rebuild all prims. FIGURE_clean_all_LRU_slots(); g_iCheatNumber = 0; } #endif f1=p_person->Draw.Tweened->CurrentFrame->Flags; f2=p_person->Draw.Tweened->NextFrame->Flags; dx=((f1&0xe)<<(28))>>21; dx-=((f2&0xe)<<(28))>>21; dy=((f1&0xff00)<<(16))>>16; dy-=((f2&0xff00)<<(16))>>16; dz=((f1&0x70)<<(25))>>21; dz-=((f1&0x70)<<(25))>>21; ASSERT(p_person->Class == CLASS_PERSON); // Find the first "base" prim number and see if it's been created yet. // Eek - just thought - I hope none of these people share body parts, or it'll get very messy. // I should put some sort of ASSERT in to check that. // Ah - Mike thinks they probably do share stuff. Nads. Well, I only have a small cache, so I can just // do a brute-force search through it by body_def I guess. Or maybe just an array again. ASSERT ( recurse_level == 0 ); ASSERT ( FIGURE_dhpr_rdata1[0].current_child_number == 0 ); // Make the index of the thing. int iIndex = (int)( FIGURE_dhpr_data.bPersonType ); ASSERT ( FIGURE_dhpr_data.bPersonType >= 0 ); ASSERT ( FIGURE_dhpr_data.bPersonType < PERSON_NUM_TYPES ); if ( FIGURE_dhpr_data.bPersonType == PERSON_CIV ) { // Some variation of civs is done by using bPersonID. iIndex = (int)( FIGURE_dhpr_data.bPersonID & 0x1f ) + PERSON_NUM_TYPES; } else if ( FIGURE_dhpr_data.bPersonType == PERSON_ROPER ) { // Treat each version of Roper (with each type of weapon) as a separate mesh, since // his weapons are not done the same as Darci or Mako. Hope this works. // Should be only 6 weapons: none, knife, bat, M16, pistols, shotty. Grenades are done a different way. // But "weapon" eight is his hip-flask, which he drinks from occasionally. ASSERT ( ( FIGURE_dhpr_data.bPersonID >> 5 ) < NUM_ROPERS_THINGIES ); iIndex = (int)( FIGURE_dhpr_data.bPersonID >> 5 ) + PERSON_NUM_TYPES + 32; } // Save this for possible restoration later. structFIGURE_dhpr_rdata1 FIGURE_dhpr_rdata1_0_copy = FIGURE_dhpr_rdata1[0]; structFIGURE_dhpr_data FIGURE_dhpr_data_copy = FIGURE_dhpr_data_copy; ASSERT ( iIndex < MAX_NUMBER_D3D_PEOPLE ); ASSERT ( ( PERSON_NUM_TYPES + 32 + NUM_ROPERS_THINGIES ) <= MAX_NUMBER_D3D_PEOPLE ); TomsPrimObject *pPrimObj = &(D3DPeopleObj[iIndex]); if ( pPrimObj->wNumMaterials == 0 ) { // Meshes have not been created yet - do so. // Set up the object. #if 0 // Use thrash slot 1 because the gun may bump it out later if it's // in slot 0! FIGURE_TPO_init_3d_object ( pPrimObj, 1 ); #else FIGURE_TPO_init_3d_object ( pPrimObj ); #endif int iTPOPartNumber = 0; recurse_level = 0; while (recurse_level >= 0) { //m_iRecurseLevelDebugging = recurse_level; structFIGURE_dhpr_rdata1 *pDHPR1 = FIGURE_dhpr_rdata1 + recurse_level; int iPartNumber = pDHPR1->part_number; if (pDHPR1->current_child_number == 0) { SLONG body_part; // draw this level. ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); body_part=FIGURE_dhpr_data.body_def->BodyPart[iPartNumber]; // Draw thing with: SLONG prim = FIGURE_dhpr_data.start_object + body_part; // Add this prim to it. PrimObject *p_obj = &prim_objects[prim]; //FIGURE_TPO_add_prim_to_current_object ( p_obj, iTPOPartNumber ); FIGURE_TPO_add_prim_to_current_object ( prim, iTPOPartNumber ); iTPOPartNumber++; // Then draw the weapon & muzzle flash if present. However, these are // not part of the compiled person - they will be drawn individually // after drawing the person. } // and do children if (body_part_children[iPartNumber][pDHPR1->current_child_number] != -1) { // Broken up, or the compiler gets very confused. structFIGURE_dhpr_rdata1 *pDHPR1Inc = FIGURE_dhpr_rdata1 + recurse_level + 1; pDHPR1Inc->current_child_number = 0; ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); pDHPR1Inc->part_number = body_part_children[iPartNumber][pDHPR1->current_child_number]; pDHPR1Inc->current_child_number = 0; pDHPR1->current_child_number ++; recurse_level ++; } else { recurse_level --; } } #if 0 // Compile the whole object now. FIGURE_TPO_finish_3d_object ( pPrimObj ); #else // Compile the whole object now. // Use thrash slot 1 because the gun may bump it out later if it's // in slot 0! FIGURE_TPO_finish_3d_object ( pPrimObj, 1 ); #endif // Restore the saved data. FIGURE_dhpr_rdata1[0] = FIGURE_dhpr_rdata1_0_copy; FIGURE_dhpr_data_copy = FIGURE_dhpr_data_copy; } // Gets pre-incremented to 0 before use. int iTPOPartNumber = -1; bool bWholePersonVisible = TRUE; bool bBitsOfPersonVisible = FALSE; recurse_level = 0; while (recurse_level >= 0) { //m_iRecurseLevelDebugging = recurse_level; structFIGURE_dhpr_rdata1 *pDHPR1 = FIGURE_dhpr_rdata1 + recurse_level; int iPartNumber = pDHPR1->part_number; if (pDHPR1->current_child_number == 0) { { SLONG body_part; SLONG id; // draw this level. ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); //limb=part_type[iPartNumber]; body_part=FIGURE_dhpr_data.body_def->BodyPart[iPartNumber]; rot_mat=FIGURE_dhpr_data.world_mat; iTPOPartNumber++; ASSERT ( iTPOPartNumber < MAX_NUM_BODY_PARTS_AT_ONCE ); bool bVisible = FIGURE_draw_prim_tween_person_only_just_set_matrix ( iTPOPartNumber, FIGURE_dhpr_data.start_object + body_part, rot_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, recurse_level, p_person ); bWholePersonVisible &= bVisible; bBitsOfPersonVisible |= bVisible; // // draw a weapon in hand // if(p_person->Genus.Person->PersonType!=PERSON_ROPER) if((id=(p_person->Draw.Tweened->PersonID>>5))) { SLONG hand; if(id==2) hand=SUB_OBJECT_RIGHT_HAND; else hand=SUB_OBJECT_LEFT_HAND; if(iPartNumber==hand) { if(p_person->Draw.Tweened->Flags&DT_FLAG_GUNFLASH) { SLONG prim; bool bDrawMuzzleFlash = FALSE; p_person->Draw.Tweened->Flags&=~DT_FLAG_GUNFLASH; switch(p_person->Draw.Tweened->PersonID>>5) { case 1: // Pistol prim = 261; bDrawMuzzleFlash = TRUE; break; case 3: // Shotgun prim = 262; bDrawMuzzleFlash = TRUE; break; case 5: // AK prim = 263; bDrawMuzzleFlash = TRUE; break; default: break; } // Why does the DC hate GOTOs so much. if ( bDrawMuzzleFlash ) { #if 0 FIGURE_draw_prim_tween( prim, FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); #else // Muzzle flashes are always drawn "normally" FIGURE_draw_prim_tween_person_only( prim, FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, recurse_level, p_person ); #endif } } #if 0 FIGURE_draw_prim_tween( 255+(p_person->Draw.Tweened->PersonID>>5), FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); #else // Weapons are always drawn "normally" FIGURE_draw_prim_tween_person_only( 255+(p_person->Draw.Tweened->PersonID>>5), FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, recurse_level, p_person ); #endif } } } } // and do children if (body_part_children[iPartNumber][pDHPR1->current_child_number] != -1) { // Broken up, or the compiler gets very confused. //structFIGURE_dhpr_rdata1 *pDHPR1 = FIGURE_dhpr_rdata1 + recurse_level; structFIGURE_dhpr_rdata1 *pDHPR1Inc = FIGURE_dhpr_rdata1 + recurse_level + 1; pDHPR1Inc->current_child_number = 0; // really only need to do these next 3 lines once... pDHPR1->pos.M[0] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetX; pDHPR1->pos.M[1] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetY; pDHPR1->pos.M[2] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetZ; ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); pDHPR1Inc->part_number = body_part_children[iPartNumber][pDHPR1->current_child_number]; CMatrix33 tmat; GetCMatrix(&FIGURE_dhpr_data.ae1[iPartNumber], &tmat); pDHPR1Inc->parent_base_mat = &tmat; pDHPR1Inc->parent_base_pos = &(pDHPR1->pos); pDHPR1Inc->parent_current_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; pDHPR1Inc->parent_current_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; pDHPR1Inc->current_child_number = 0; pDHPR1->current_child_number ++; recurse_level ++; } else { recurse_level --; } }; // And now draw the whole person using the matrices and light vectors set up above. if ( !bWholePersonVisible ) { if ( bBitsOfPersonVisible ) { // Draw the person the slow way. TRACE ( "Partial person drawn\n" ); // Restore the saved data. FIGURE_dhpr_rdata1[0] = FIGURE_dhpr_rdata1_0_copy; FIGURE_dhpr_data_copy = FIGURE_dhpr_data_copy; FIGURE_draw_hierarchical_prim_recurse_individual_cull ( p_person ); } else { // None of the person is visible. Don't draw anything. //TRACE ( "Person not drawn\n" ); } return; } //TRACE ( "Full person drawn\n" ); // This many parts. iTPOPartNumber++; ASSERT ( iTPOPartNumber <= MAX_NUM_BODY_PARTS_AT_ONCE ); SLONG face_colour; SLONG page; Matrix31 offset; Matrix33 mat2; Matrix33 mat_final; ULONG qc0; ULONG qc1; ULONG qc2; ULONG qc3; SVector temp; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; NIGHT_Found *nf; POLY_Point *pp; POLY_Point *ps; POLY_Point *tri [3]; POLY_Point *quad[4]; SLONG tex_page_offset; LOG_ENTER ( Figure_Draw_Prim_Tween ) tex_page_offset=p_person->Genus.Person->pcom_colour&0x3; #if !USE_TOMS_ENGINE_PLEASE_BOB #error Dont use this rout if USE_TOMS_ENGINE_PLEASE_BOB is not 1 #endif ASSERT ( MM_bLightTableAlreadySetUp ); // The wonderful NEW system! LOG_ENTER ( Figure_Draw_Polys ) #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, FALSE ); #endif // Tell the LRU cache we used this one. FIGURE_touch_LRU_of_object ( pPrimObj ); ASSERT ( pPrimObj->pD3DVertices != NULL ); ASSERT ( pPrimObj->pMaterials != NULL ); ASSERT ( pPrimObj->pwListIndices != NULL ); ASSERT ( pPrimObj->pwStripIndices != NULL ); ASSERT ( pPrimObj->wNumMaterials != 0 ); PrimObjectMaterial *pMat = pPrimObj->pMaterials; D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MMBodyParts_pMatrix; d3dmm.lpvLightDirs = MMBodyParts_pNormal; D3DVERTEX *pVertex = (D3DVERTEX *)pPrimObj->pD3DVertices; UWORD *pwListIndices = pPrimObj->pwListIndices; UWORD *pwStripIndices = pPrimObj->pwStripIndices; for ( int iMatNum = pPrimObj->wNumMaterials; iMatNum > 0; iMatNum-- ) { // Set up the right texture for this material. UWORD wPage = pMat->wTexturePage; UWORD wRealPage = wPage & TEXTURE_PAGE_MASK; if ( wPage & TEXTURE_PAGE_FLAG_JACKET ) { // Find the real jacket page. wRealPage = jacket_lookup [ wRealPage ][GET_SKILL(p_person)>>2]; wRealPage += FACE_PAGE_OFFSET; } else if ( wPage & TEXTURE_PAGE_FLAG_OFFSET ) { // An "offset" texture. This will be offset by a certain amount to // allow each prim to have different coloured clothes on. if ( tex_page_offset == 0 ) { // No lookup offset. // This has not been offset yet. wRealPage += FACE_PAGE_OFFSET; } else { // Look this up. wRealPage = alt_texture[wRealPage-(10*64)]+tex_page_offset-1; } } #ifdef DEBUG if ( wPage & TEXTURE_PAGE_FLAG_NOT_TEXTURED ) { ASSERT ( wRealPage == POLY_PAGE_COLOUR ); } #endif extern D3DMATRIX g_matWorld; PolyPage *pa = &(POLY_Page[wRealPage]); #if 0 // Near-plane culling! Must implement! // Not sure if I'm using character_scalef correctly... ASSERT ( ( character_scalef < 1.2f ) && ( character_scalef > 0.8f ) ); ASSERT ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ); if ( ( ( ( g_matWorld._43 * 32768.0f ) - ( pPrimObj->fBoundingSphereRadius * character_scalef ) ) > ( POLY_ZCLIP_PLANE * 32768.0f ) ) ) #endif { // Non-alpha path. if ( wPage & TEXTURE_PAGE_FLAG_TINT ) { // Tinted colours. d3dmm.lpLightTable = MM_pcFadeTableTint; } else { // Normal. d3dmm.lpLightTable = MM_pcFadeTable; } d3dmm.lpvVertices = pVertex; #if 1 #ifdef DEBUG static int iCounter = 0; if ( iCounter != 0 ) { iCounter--; ASSERT ( iCounter != 0 ); } #endif // Fast as lightning. LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) HRESULT hres; #define SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB defined #ifdef SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB #ifdef DEBUG #ifdef TARGET_DC #define BUTTON_IS_PRESSED(value) ((value&0x80)!=0) extern DIJOYSTATE the_state; bool bShowDebug = FALSE; if ( BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_LTRIGGER] ) && BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_RTRIGGER] ) ) { DWORD dwColour = (DWORD)pwStripIndices; dwColour = ( dwColour >> 2 ) ^ ( dwColour >> 6 ) ^ ( dwColour ) ^ ( dwColour << 3 ); dwColour = ( dwColour << 9 ) ^ ( dwColour << 19 ) ^ ( dwColour ) ^ ( dwColour << 29 ) ^ ( dwColour >> 3 ); dwColour &= 0x7f7f7f7f; for ( int i = 0; i < 128; i++ ) { d3dmm.lpLightTable[i] = dwColour; } // And NULL texture (i.e. white). the_display.lp_D3D_Device->SetTexture ( 0, NULL ); } #endif #endif #endif //if (pMat->wNumVertices && // pMat->wNumStripIndices) { //TRACE ( "S4" ); hres = DrawIndPrimMM ( (the_display.lp_D3D_Device), D3DFVF_VERTEX, &d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices ); //TRACE ( "F4" ); } #else // Do some performance tracing. #ifndef DTRACE #error Don't use this codepath unless DTRACING, fool! #endif LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); WORD wTempVerts[4]; wTempVerts[0] = 0; wTempVerts[1] = 1; wTempVerts[2] = 2; wTempVerts[3] = -1; (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 3, wTempVerts, 4, D3DDP_MULTIMATRIX ); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); //TRACE("Drew %i vertices, %i indices\n", (int)( pMat->wNumVertices ), (int)( pMat->wNumStripIndices ) ); #endif // ASSERT ( SUCCEEDED ( hres ) ); //triggers all the time when inside on start of RTA LOG_EXIT ( Figure_DrawIndPrimMM ) } #if 0 else { // Alpha/clipped path - do with standard non-MM calls. // FIXME. Needs to be done. // Actually, the fast-accept works very well, and it's only when the camera somehow gets REALLY close // that this happens. And actually a pop-reject seems a bit better than a clip. Certainly // there is no visually "right" thing to do. So leave it for now until someone complains. ATF. //TRACE ( "Tried to draw an alpha/clipped prim!" ); } #endif // Next material pVertex += pMat->wNumVertices; pwListIndices += pMat->wNumListIndices; pwStripIndices += pMat->wNumStripIndices; pMat++; } #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, TRUE ); #endif LOG_EXIT ( Figure_Draw_Polys ) // No environment mapping. ASSERT ( p_person && ( p_person->Class != CLASS_VEHICLE ) ); ASSERT ( MM_bLightTableAlreadySetUp ); LOG_EXIT ( Figure_Draw_Prim_Tween ) #endif // Person drawn! LOG_EXIT ( Figure_Draw_Hierarchical ) } // The slower version that can cull individual chunks. #if DRAW_WHOLE_PERSON_AT_ONCE void FIGURE_draw_hierarchical_prim_recurse_individual_cull ( Thing *p_person ) #else // There can be only one... void FIGURE_draw_hierarchical_prim_recurse ( Thing *p_person ) #endif { SLONG recurse_level = 0; SLONG dx,dy,dz; UWORD f1,f2; SLONG civ_flag=0,legs,body,shoes,face,hands,pelvis; //SLONG limb; struct Matrix33 *rot_mat; LOG_ENTER ( Figure_Draw_Hierarchical ) #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB // Do I need to toggle inflation? extern int g_iCheatNumber; // Well, 0x10f1a7e sort of spells "inflate" :-) if ( g_iCheatNumber == 0x10f1a7e ) { if ( m_bPleaseInflatePeople ) { CONSOLE_text("Looks like the inflation is wearing off now D'arci."); m_bPleaseInflatePeople = FALSE; } else { CONSOLE_text("The Illinois Enema Bandit has inflated everyone D'arci!"); m_bPleaseInflatePeople = TRUE; } // And rebuild all prims. FIGURE_clean_all_LRU_slots(); g_iCheatNumber = 0; } #endif f1=p_person->Draw.Tweened->CurrentFrame->Flags; f2=p_person->Draw.Tweened->NextFrame->Flags; dx=((f1&0xe)<<(28))>>21; dx-=((f2&0xe)<<(28))>>21; dy=((f1&0xff00)<<(16))>>16; dy-=((f2&0xff00)<<(16))>>16; dz=((f1&0x70)<<(25))>>21; dz-=((f1&0x70)<<(25))>>21; ASSERT(p_person->Class == CLASS_PERSON); recurse_level = 0; while (recurse_level >= 0) { //m_iRecurseLevelDebugging = recurse_level; structFIGURE_dhpr_rdata1 *pDHPR1 = FIGURE_dhpr_rdata1 + recurse_level; int iPartNumber = pDHPR1->part_number; if (pDHPR1->current_child_number == 0) { { SLONG body_part; SLONG id; // draw this level. ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); //limb=part_type[iPartNumber]; body_part=FIGURE_dhpr_data.body_def->BodyPart[iPartNumber]; rot_mat=FIGURE_dhpr_data.world_mat; #if 0 FIGURE_draw_prim_tween( FIGURE_dhpr_data.start_object + body_part, //FIGURE_dhpr_data.body_def->BodyPart[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[pDHPR1->part_number], &FIGURE_dhpr_data.ae2[pDHPR1->part_number], rot_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, //limb==PART_JACKET?jacket_col:(limb==PART_TROUSERS?leg_col:FIGURE_dhpr_data.colour), FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); #else FIGURE_draw_prim_tween_person_only ( FIGURE_dhpr_data.start_object + body_part, //FIGURE_dhpr_data.body_def->BodyPart[FIGURE_dhpr_rdata1[recurse_level].part_number], //FIGURE_dhpr_data.world_pos->M[0], //FIGURE_dhpr_data.world_pos->M[1], //FIGURE_dhpr_data.world_pos->M[2], //FIGURE_dhpr_data.tween, //&FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], //&FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], rot_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, //FIGURE_dhpr_data.colour, //limb==PART_JACKET?jacket_col:(limb==PART_TROUSERS?leg_col:FIGURE_dhpr_data.colour), //FIGURE_dhpr_data.specular, recurse_level, //FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, //FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, //&FIGURE_dhpr_rdata2[recurse_level].end_mat, //&FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person //FIGURE_dhpr_rdata1[recurse_level].part_number ); #endif // // draw a weapon in hand // if(p_person->Genus.Person->PersonType!=PERSON_ROPER) if((id=(p_person->Draw.Tweened->PersonID>>5))) { SLONG hand; if(id==2) hand=SUB_OBJECT_RIGHT_HAND; else hand=SUB_OBJECT_LEFT_HAND; if(iPartNumber==hand) { if(p_person->Draw.Tweened->Flags&DT_FLAG_GUNFLASH) { SLONG prim; bool bDrawMuzzleFlash = FALSE; p_person->Draw.Tweened->Flags&=~DT_FLAG_GUNFLASH; switch(p_person->Draw.Tweened->PersonID>>5) { case 1: // Pistol prim = 261; bDrawMuzzleFlash = TRUE; break; case 3: // Shotgun prim = 262; bDrawMuzzleFlash = TRUE; break; case 5: // AK prim = 263; bDrawMuzzleFlash = TRUE; break; default: break; } // Why does the DC hate GOTOs so much. if ( bDrawMuzzleFlash ) { #if 0 FIGURE_draw_prim_tween( prim, FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); #else // Muzzle flashes are always drawn "normally" FIGURE_draw_prim_tween_person_only( prim, //FIGURE_dhpr_data.world_pos->M[0], //FIGURE_dhpr_data.world_pos->M[1], //FIGURE_dhpr_data.world_pos->M[2], //FIGURE_dhpr_data.tween, //&FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], //&FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, //FIGURE_dhpr_data.colour, //FIGURE_dhpr_data.specular, recurse_level, //FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, //FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, //&FIGURE_dhpr_rdata2[recurse_level].end_mat, //&FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person //FIGURE_dhpr_rdata1[recurse_level].part_number ); #endif } } #if 0 FIGURE_draw_prim_tween( 255+(p_person->Draw.Tweened->PersonID>>5), FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); #else // Weapons are always drawn "normally" FIGURE_draw_prim_tween_person_only( 255+(p_person->Draw.Tweened->PersonID>>5), //FIGURE_dhpr_data.world_pos->M[0], //FIGURE_dhpr_data.world_pos->M[1], //FIGURE_dhpr_data.world_pos->M[2], //FIGURE_dhpr_data.tween, //&FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], //&FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, //FIGURE_dhpr_data.colour, //FIGURE_dhpr_data.specular, recurse_level, //FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, //FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, //FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, //&FIGURE_dhpr_rdata2[recurse_level].end_mat, //&FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person //FIGURE_dhpr_rdata1[recurse_level].part_number ); #endif } } } } // and do children if (body_part_children[iPartNumber][pDHPR1->current_child_number] != -1) { #if 0 FIGURE_dhpr_rdata1[recurse_level + 1].current_child_number = 0; // really only need to do these next 3 lines once... FIGURE_dhpr_rdata1[recurse_level].pos.M[0] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetX; FIGURE_dhpr_rdata1[recurse_level].pos.M[1] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetY; FIGURE_dhpr_rdata1[recurse_level].pos.M[2] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetZ; ASSERT ( FIGURE_dhpr_rdata1[recurse_level].part_number >= 0 ); ASSERT ( FIGURE_dhpr_rdata1[recurse_level].part_number <= 14 ); FIGURE_dhpr_rdata1[recurse_level + 1].part_number = body_part_children[FIGURE_dhpr_rdata1[recurse_level].part_number][FIGURE_dhpr_rdata1[recurse_level].current_child_number]; CMatrix33 tmat; GetCMatrix(&FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &tmat); FIGURE_dhpr_rdata1[recurse_level + 1].parent_base_mat = &tmat; FIGURE_dhpr_rdata1[recurse_level + 1].parent_base_pos = &FIGURE_dhpr_rdata1[recurse_level].pos; FIGURE_dhpr_rdata1[recurse_level + 1].parent_current_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; FIGURE_dhpr_rdata1[recurse_level + 1].parent_current_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; FIGURE_dhpr_rdata1[recurse_level + 1].current_child_number = 0; FIGURE_dhpr_rdata1[recurse_level].current_child_number ++ ; #else // Broken up, or the compiler gets very confused. //structFIGURE_dhpr_rdata1 *pDHPR1 = FIGURE_dhpr_rdata1 + recurse_level; structFIGURE_dhpr_rdata1 *pDHPR1Inc = FIGURE_dhpr_rdata1 + recurse_level + 1; pDHPR1Inc->current_child_number = 0; // really only need to do these next 3 lines once... pDHPR1->pos.M[0] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetX; pDHPR1->pos.M[1] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetY; pDHPR1->pos.M[2] = FIGURE_dhpr_data.ae1[iPartNumber].OffsetZ; ASSERT ( iPartNumber >= 0 ); ASSERT ( iPartNumber <= 14 ); pDHPR1Inc->part_number = body_part_children[iPartNumber][pDHPR1->current_child_number]; CMatrix33 tmat; GetCMatrix(&FIGURE_dhpr_data.ae1[iPartNumber], &tmat); pDHPR1Inc->parent_base_mat = &tmat; pDHPR1Inc->parent_base_pos = &(pDHPR1->pos); pDHPR1Inc->parent_current_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; pDHPR1Inc->parent_current_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; pDHPR1Inc->current_child_number = 0; pDHPR1->current_child_number ++; #endif recurse_level ++; } else { recurse_level --; } }; // Person drawn! LOG_EXIT ( Figure_Draw_Hierarchical ) } #else // Old version void FIGURE_draw_hierarchical_prim_recurse(Thing *p_person) { SLONG recurse_level = 0; SLONG dx,dy,dz; UWORD f1,f2; SLONG civ_flag=0,legs,body,shoes,face,hands,pelvis; //SLONG limb; struct Matrix33 *rot_mat; #ifdef HIGH_REZ_PEOPLE_PLEASE_BOB // Do I need to toggle inflation? extern int g_iCheatNumber; // Well, 0x10f1a7e sort of spells "inflate" :-) if ( g_iCheatNumber == 0x10f1a7e ) { if ( m_bPleaseInflatePeople ) { CONSOLE_text("Looks like the inflation is wearing off now D'arci."); m_bPleaseInflatePeople = FALSE; } else { CONSOLE_text("The Illinois Enema Bandit has inflated everyone D'arci!"); m_bPleaseInflatePeople = TRUE; } // And rebuild all prims. FIGURE_clean_all_LRU_slots(); g_iCheatNumber = 0; } #endif LOG_ENTER ( Figure_Draw_Hierarchical ) f1=p_person->Draw.Tweened->CurrentFrame->Flags; f2=p_person->Draw.Tweened->NextFrame->Flags; dx=((f1&0xe)<<(28))>>21; dx-=((f2&0xe)<<(28))>>21; dy=((f1&0xff00)<<(16))>>16; dy-=((f2&0xff00)<<(16))>>16; dz=((f1&0x70)<<(25))>>21; dz-=((f1&0x70)<<(25))>>21; /* if(p_person->Genus.Person->PersonType==PERSON_CIV ||p_person->Genus.Person->PersonType==PERSON_CIV2) { local_set_seed(THING_NUMBER(p_person)); legs=mandom()&3; body=mandom()&3; shoes=mandom()&3; face=mandom()&3; hands=mandom()&1; pelvis=legs; //Random()&3; if (GAME_FLAGS & GF_RAINING) { pelvis=(mandom()%3)+4; body=pelvis; } civ_flag=1; } */ ASSERT(p_person->Class == CLASS_PERSON); while (recurse_level >= 0) { if (FIGURE_dhpr_rdata1[recurse_level].current_child_number == 0) { { SLONG body_part; SLONG id; // draw this level. /* if(civ_flag) { switch(part_type[FIGURE_dhpr_rdata1[recurse_level].part_number]) { case PART_FACE: body_part=face; break; case PART_HANDS: body_part=hands; break; case PART_TROUSERS: body_part=legs; break; case PART_JACKET: body_part=body; break; case PART_SHOES: body_part=shoes; break; case PART_PELVIS: body_part=pelvis; break; default: ASSERT(0); break; } body_part=0; } else { body_part=FIGURE_dhpr_data.body_def->BodyPart[FIGURE_dhpr_rdata1[recurse_level].part_number]; } */ //limb=part_type[FIGURE_dhpr_rdata1[recurse_level].part_number]; body_part=FIGURE_dhpr_data.body_def->BodyPart[FIGURE_dhpr_rdata1[recurse_level].part_number]; /* if( (p_person->Flags&FLAGS_PERSON_AIM_AND_RUN) && body_part_upper[FIGURE_dhpr_rdata1[recurse_level].part_number]) { rot_mat=FIGURE_dhpr_data.world_mat2; } else */ { rot_mat=FIGURE_dhpr_data.world_mat; } FIGURE_draw_prim_tween( FIGURE_dhpr_data.start_object + body_part, //FIGURE_dhpr_data.body_def->BodyPart[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], rot_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, //limb==PART_JACKET?jacket_col:(limb==PART_TROUSERS?leg_col:FIGURE_dhpr_data.colour), FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); // // draw a weapon in hand // if(p_person->Genus.Person->PersonType!=PERSON_ROPER) if((id=(p_person->Draw.Tweened->PersonID>>5))) { SLONG hand; if(id==2) hand=SUB_OBJECT_RIGHT_HAND; else hand=SUB_OBJECT_LEFT_HAND; if(FIGURE_dhpr_rdata1[recurse_level].part_number==hand) { if(p_person->Draw.Tweened->Flags&DT_FLAG_GUNFLASH) { SLONG prim; p_person->Draw.Tweened->Flags&=~DT_FLAG_GUNFLASH; switch(p_person->Draw.Tweened->PersonID>>5) { case 1: // Pistol prim = 261; break; case 3: // Shotgun prim = 262; break; case 5: // AK prim = 263; break; default: goto dont_draw_the_muzzle_flash; break; } FIGURE_draw_prim_tween( prim, FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); dont_draw_the_muzzle_flash:; } FIGURE_draw_prim_tween( 255+(p_person->Draw.Tweened->PersonID>>5), FIGURE_dhpr_data.world_pos->M[0], FIGURE_dhpr_data.world_pos->M[1], FIGURE_dhpr_data.world_pos->M[2], FIGURE_dhpr_data.tween, &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number], FIGURE_dhpr_data.world_mat, FIGURE_dhpr_data.dx+dx, FIGURE_dhpr_data.dy+dy, FIGURE_dhpr_data.dz+dz, FIGURE_dhpr_data.colour, FIGURE_dhpr_data.specular, FIGURE_dhpr_rdata1[recurse_level].parent_base_mat, FIGURE_dhpr_rdata1[recurse_level].parent_base_pos, FIGURE_dhpr_rdata1[recurse_level].parent_current_mat, FIGURE_dhpr_rdata1[recurse_level].parent_current_pos, &FIGURE_dhpr_rdata2[recurse_level].end_mat, &FIGURE_dhpr_rdata2[recurse_level].end_pos, p_person, FIGURE_dhpr_rdata1[recurse_level].part_number); } } } } // and do children if (body_part_children[FIGURE_dhpr_rdata1[recurse_level].part_number][FIGURE_dhpr_rdata1[recurse_level].current_child_number] != -1) { FIGURE_dhpr_rdata1[recurse_level + 1].current_child_number = 0; // really only need to do these next 3 lines once... FIGURE_dhpr_rdata1[recurse_level].pos.M[0] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetX; FIGURE_dhpr_rdata1[recurse_level].pos.M[1] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetY; FIGURE_dhpr_rdata1[recurse_level].pos.M[2] = FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number].OffsetZ; FIGURE_dhpr_rdata1[recurse_level + 1].part_number = body_part_children[FIGURE_dhpr_rdata1[recurse_level].part_number][FIGURE_dhpr_rdata1[recurse_level].current_child_number]; CMatrix33 tmat; GetCMatrix(&FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number], &tmat); FIGURE_dhpr_rdata1[recurse_level + 1].parent_base_mat = &tmat; FIGURE_dhpr_rdata1[recurse_level + 1].parent_base_pos = &FIGURE_dhpr_rdata1[recurse_level].pos; FIGURE_dhpr_rdata1[recurse_level + 1].parent_current_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; FIGURE_dhpr_rdata1[recurse_level + 1].parent_current_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; FIGURE_dhpr_rdata1[recurse_level + 1].current_child_number = 0; FIGURE_dhpr_rdata1[recurse_level].current_child_number ++ ; recurse_level ++; } else recurse_level --; }; LOG_EXIT ( Figure_Draw_Hierarchical ) } #endif //************************************************************************************************* SLONG get_sort_z_bodge(SLONG px,SLONG pz) { SLONG dx,dz; UBYTE cap; dx=px-POLY_cam_x; dz=pz-POLY_cam_z; if(abs(dz)<abs(dx)) { if(dx<0) { if((px&0xff)>128) { cap=MAV_get_caps(px>>8,pz>>8,MAV_DIR_XL); if(!(cap&MAV_CAPS_GOTO)) { return(100); } } } else { if((px&0xff)<128) { cap=MAV_get_caps(px>>8,pz>>8,MAV_DIR_XS); if(!(cap&MAV_CAPS_GOTO)) { return(100); } } } } else { if(dz<0) { if((pz&0xff)>128) { cap=MAV_get_caps(px>>8,pz>>8,MAV_DIR_ZL); if(!(cap&MAV_CAPS_GOTO)) { return(100); } } } else { if((pz&0xff)<128) { cap=MAV_get_caps(px>>8,pz>>8,MAV_DIR_ZS); if(!(cap&MAV_CAPS_GOTO)) { return(100); } } } } return(0); } struct { SWORD r,g,b; }peep_recol[]= { {12,64,64}, {64,28,64}, {64,4,55}, {54,32,22}, {42,14,12}, {32,42,64}, {22,64,54}, {64,14,32}, {34,32,64}, {0,32,64}, {32,64,0}, {64,0,32}, {56,30,0}, {0,40,56}, {33,26,70}, {56,36,0}, }; UBYTE kludge_shrink; #ifndef PSX // New faster version void FIGURE_draw(Thing *p_thing) { SLONG dx; SLONG dy; SLONG dz; SLONG wx,wy,wz; ULONG colour; ULONG specular; Matrix33 r_matrix; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; DrawTween *dt = p_thing->Draw.Tweened; LOG_ENTER ( Figure_FIGURE_Draw ) // calc_global_cloud(p_thing->WorldPos.X>>8,p_thing->WorldPos.Y>>8,p_thing->WorldPos.Z>>8); if (dt->CurrentFrame == 0 || dt->NextFrame == 0) { // // No frames to tween between. // MSG_add("!!!!!!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure"); LOG_EXIT ( Figure_FIGURE_Draw ) return; } // // The offset to keep the locked limb in the same place. // dx = 0; dy = 0; dz = 0; // // The rotation matrix of the whole object. // LOG_ENTER ( Figure_Rotate ) FIGURE_rotate_obj( dt->Tilt, dt->Angle, (dt->Roll+2048)&2047, &r_matrix); LOG_EXIT ( Figure_Rotate ) wx=0; wy=0; wz=0; // // The animation elements for the two frames. // ae1 = dt->CurrentFrame->FirstElement; ae2 = dt->NextFrame ->FirstElement; #ifdef DEBUG if (!ae1 || !ae2) { MSG_add("!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure has no animation elements"); LOG_EXIT ( Figure_FIGURE_Draw ) return; } #endif // // What colour do we draw the figure? // // // All this is done in FIGURE_draw_prim_tween nowadays using the array // filled in by this call to NIGHT_find.... // colour = 0; specular = 0; SLONG lx; SLONG ly; SLONG lz; NIGHT_Colour col; LOG_ENTER ( Figure_Calc_Sub_Objs ) calc_sub_objects_position( p_thing, dt->AnimTween, 0, // 0 is Pelvis &lx, &ly, &lz); lx += p_thing->WorldPos.X >> 8; ly += p_thing->WorldPos.Y >> 8; lz += p_thing->WorldPos.Z >> 8; LOG_EXIT ( Figure_Calc_Sub_Objs ) LOG_ENTER ( Figure_NIGHT_Find ) NIGHT_find(lx, ly, lz); LOG_EXIT ( Figure_NIGHT_Find ) #if USE_TOMS_ENGINE_PLEASE_BOB ASSERT ( !MM_bLightTableAlreadySetUp ); // Set up some data for the MM rendering thing. #if 0 //#define ALIGNED_STATIC_ARRAY(name,number,mytype,align) \ // static char c##name##mytype##align##StaticArray [ align + number * sizeof ( mytype ) ]; \ // name = (mytype *)( ( (DWORD)c##name##mytype##align##StaticArray + (align-1) ) & ~(align-1) ) ALIGNED_STATIC_ARRAY ( MM_pcFadeTable, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pcFadeTableTint, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pMatrix, 1, D3DMATRIX, 32 ); ALIGNED_STATIC_ARRAY ( MM_Vertex, 4, D3DVERTEX, 32 ); ALIGNED_STATIC_ARRAY ( MM_pNormal, 4, float, 8 ); #endif //#undef ALIGNED_STATIC_ARRAY Pyro *p = NULL; if (p_thing->Class == CLASS_PERSON && p_thing->Genus.Person->BurnIndex) { p = TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType != PYRO_IMMOLATE) { p = NULL; } } BuildMMLightingTable ( p, 0 ); MM_bLightTableAlreadySetUp = TRUE; #endif // // Draw each body part. // //SLONG i; SLONG ele_count; SLONG start_object; SLONG object_offset; ele_count = dt->TheChunk->ElementCount; start_object = prim_multi_objects[dt->TheChunk->MultiObject[dt->MeshID]].StartObject; if (ele_count == 15 ) { Matrix31 pos; pos.M[0] = (p_thing->WorldPos.X >> 8)+wx; pos.M[1] = (p_thing->WorldPos.Y >> 8) + wy; pos.M[2] = (p_thing->WorldPos.Z >> 8)+wz; // assume we've got a person, and draw the object hierarchically // fill out data. FIGURE_dhpr_rdata1[0].part_number = 0; FIGURE_dhpr_rdata1[0].current_child_number = 0; FIGURE_dhpr_rdata1[0].parent_base_mat = NULL; FIGURE_dhpr_rdata1[0].parent_base_pos = NULL; FIGURE_dhpr_rdata1[0].parent_current_mat = NULL; FIGURE_dhpr_rdata1[0].parent_current_pos = NULL; FIGURE_dhpr_data.start_object = start_object; if(p_thing->Genus.Person->PersonType==PERSON_ROPER) FIGURE_dhpr_data.body_def = &dt->TheChunk->PeopleTypes[(dt->PersonID>>5)]; else FIGURE_dhpr_data.body_def = &dt->TheChunk->PeopleTypes[(dt->PersonID&0x1f)]; FIGURE_dhpr_data.world_pos = &pos; FIGURE_dhpr_data.tween = dt->AnimTween; FIGURE_dhpr_data.ae1 = ae1; FIGURE_dhpr_data.ae2 = ae2; FIGURE_dhpr_data.world_mat = &r_matrix; // FIGURE_dhpr_data.world_mat2 = &r_matrix2; FIGURE_dhpr_data.dx = dx; FIGURE_dhpr_data.dy = dy; FIGURE_dhpr_data.dz = dz; FIGURE_dhpr_data.colour = colour; FIGURE_dhpr_data.specular = specular; // These two are used to find which unique mesh we are drawing. FIGURE_dhpr_data.bPersonType = p_thing->Genus.Person->PersonType; FIGURE_dhpr_data.bPersonID = dt->PersonID; FIGURE_draw_hierarchical_prim_recurse(p_thing); } else { for (int i = 0; i < ele_count; i++) { object_offset = dt->TheChunk->PeopleTypes[(dt->PersonID & 0x1f)].BodyPart[i]; FIGURE_draw_prim_tween( start_object + object_offset, p_thing->WorldPos.X >> 8, (p_thing->WorldPos.Y >> 8), p_thing->WorldPos.Z >> 8, dt->AnimTween, &ae1[i], &ae2[i], &r_matrix, dx,dy,dz, colour, specular, NULL, NULL, NULL, NULL, NULL, NULL, p_thing); } } #if USE_TOMS_ENGINE_PLEASE_BOB // Clean up after ourselves. ASSERT ( MM_bLightTableAlreadySetUp ); MM_bLightTableAlreadySetUp = FALSE; #if 0 MM_pcFadeTable = NULL; MM_pcFadeTableTint = NULL; MM_pMatrix = NULL; MM_Vertex = NULL; MM_pNormal = NULL; #endif #endif //#if USE_TOMS_ENGINE_PLEASE_BOB // // In case this thing ain't a person... // if (p_thing->Class == CLASS_PERSON) { // // Is this person carrying a grenade? // Thing *p_person = p_thing; if (p_person->Genus.Person->SpecialUse && TO_THING(p_person->Genus.Person->SpecialUse)->Genus.Special->SpecialType == SPECIAL_GRENADE) { SLONG px; SLONG py; SLONG pz; SLONG prim; calc_sub_objects_position( p_person, p_person->Draw.Tweened->AnimTween, SUB_OBJECT_LEFT_HAND, &px, &py, &pz); px += p_person->WorldPos.X >> 8; py += p_person->WorldPos.Y >> 8; pz += p_person->WorldPos.Z >> 8; kludge_shrink = TRUE; MESH_draw_poly( PRIM_OBJ_ITEM_GRENADE, px, py, pz, 0, 0, 0, NULL,0xff); kludge_shrink = FALSE; } } p_thing->Flags&=~FLAGS_PERSON_AIM_AND_RUN; LOG_EXIT ( Figure_FIGURE_Draw ) } #else // Old version void FIGURE_draw(Thing *p_thing) { SLONG dx; SLONG dy; SLONG dz; SLONG wx,wy,wz; ULONG colour; ULONG specular; Matrix33 r_matrix; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; DrawTween *dt = p_thing->Draw.Tweened; /* { static SLONG turn = 0; if(turn!=GAME_TURN) { if(Keys[KB_T]) { peep_recol[0].r+=ShiftFlag?4:-4; SATURATE(peep_recol[0].r,0,256); PANEL_new_text(p_thing,200," peep r %d g %d b %d ",peep_recol[0].r,peep_recol[0].g,peep_recol[0].b); } if(Keys[KB_Y]) { peep_recol[0].g+=ShiftFlag?4:-4; SATURATE(peep_recol[0].g,0,256); PANEL_new_text(p_thing,200," peep r %d g %d b %d ",peep_recol[0].r,peep_recol[0].g,peep_recol[0].b); } if(Keys[KB_U]) { peep_recol[0].b+=ShiftFlag?4:-4; SATURATE(peep_recol[0].b,0,256); PANEL_new_text(p_thing,200," peep r %d g %d b %d ",peep_recol[0].r,peep_recol[0].g,peep_recol[0].b); } } turn=GAME_TURN; } */ LOG_ENTER ( Figure_FIGURE_Draw ) // calc_global_cloud(p_thing->WorldPos.X>>8,p_thing->WorldPos.Y>>8,p_thing->WorldPos.Z>>8); #ifdef PSX // // test some code out for PSX // if(get_sort_z_bodge(p_thing->WorldPos.X>>8,p_thing->WorldPos.Z>>8)) { AENG_world_line( p_thing->WorldPos.X >> 8, p_thing->WorldPos.Y >> 8, p_thing->WorldPos.Z >> 8, 32, 0xffffff, p_thing->WorldPos.X >> 8, p_thing->WorldPos.Y + 0xc000 >> 8, p_thing->WorldPos.Z >> 8, 0, 0xffffff, TRUE); } #endif if (dt->CurrentFrame == 0 || dt->NextFrame == 0) { // // No frames to tween between. // MSG_add("!!!!!!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure"); LOG_EXIT ( Figure_FIGURE_Draw ) return; } // // The offset to keep the locked limb in the same place. // // if (dt->Locked) if(0) { SLONG x1, y1, z1; SLONG x2, y2, z2; // // Taken from temp.cpp // calc_sub_objects_position_global(dt->CurrentFrame, dt->NextFrame, 0, dt->Locked, &x1, &y1, &z1); calc_sub_objects_position_global(dt->CurrentFrame, dt->NextFrame, 256, dt->Locked, &x2, &y2, &z2); dx = x1 - x2; dy = y1 - y2; dz = z1 - z2; } else { dx = 0; dy = 0; dz = 0; } // // The rotation matrix of the whole object. // LOG_ENTER ( Figure_Rotate ) FIGURE_rotate_obj( dt->Tilt, dt->Angle, (dt->Roll+2048)&2047, &r_matrix); /* FIGURE_rotate_obj( dt->Tilt, dt->AngleTo, (dt->Roll+2048)&2047, &r_matrix2); */ LOG_EXIT ( Figure_Rotate ) #ifdef PSX_SIMULATION { SLONG index1,index2; // // stuff added for more compression of anims // extern struct PrimPoint *anim_mids; //[256]; index1=dt->CurrentFrame->XYZIndex; index2=dt->NextFrame->XYZIndex; if(index1!=index2) { /* // // draw some debug lines // SVector temp; Matrix31 offset; wx=anim_mids[index1].X; wy=anim_mids[index1].Y; wz=anim_mids[index1].Z; offset.M[0]=wx; offset.M[1]=wy; offset.M[2]=wz; matrix_transformZMY((struct Matrix31*)&temp,&r_matrix, &offset); wx=temp.X; wy=temp.Y; wz=temp.Z; AENG_world_line((p_thing->WorldPos.X>>8),(p_thing->WorldPos.Y>>8),(p_thing->WorldPos.Z>>8),6,0xff0000, (p_thing->WorldPos.X>>8)+wx,(p_thing->WorldPos.Y>>8)+wy,(p_thing->WorldPos.Z>>8)+wz,1,0xffffff,1); wx=anim_mids[index2].X; wy=anim_mids[index2].Y; wz=anim_mids[index2].Z; offset.M[0]=wx; offset.M[1]=wy; offset.M[2]=wz; matrix_transformZMY((struct Matrix31*)&temp,&r_matrix, &offset); wx=temp.X; wy=temp.Y; wz=temp.Z; AENG_world_line((p_thing->WorldPos.X>>8),(p_thing->WorldPos.Y>>8),(p_thing->WorldPos.Z>>8),6,0xff00, (p_thing->WorldPos.X>>8)+wx,(p_thing->WorldPos.Y>>8)+wy,(p_thing->WorldPos.Z>>8)+wz,1,0xffffff,1); */ wx=anim_mids[index1].X+(((anim_mids[index2].X-anim_mids[index1].X)*dt->AnimTween)>>8); wy=anim_mids[index1].Y+(((anim_mids[index2].Y-anim_mids[index1].Y)*dt->AnimTween)>>8); wz=anim_mids[index1].Z+(((anim_mids[index2].Z-anim_mids[index1].Z)*dt->AnimTween)>>8); } else { wx=anim_mids[index1].X; wy=anim_mids[index1].Y; wz=anim_mids[index1].Z; } // // put offset into object space // { SVector temp; Matrix31 offset; offset.M[0]=wx; offset.M[1]=wy; offset.M[2]=wz; matrix_transformZMY((struct Matrix31*)&temp,&r_matrix, &offset); wx=temp.X; wy=temp.Y; wz=temp.Z; /* AENG_world_line((p_thing->WorldPos.X>>8),(p_thing->WorldPos.Y>>8),(p_thing->WorldPos.Z>>8),6,0x808080, (p_thing->WorldPos.X>>8)+wx,(p_thing->WorldPos.Y>>8)+wy,(p_thing->WorldPos.Z>>8)+wz,1,0xffffff,1); */ } } #else wx=0; wy=0; wz=0; #endif // // The animation elements for the two frames. // ae1 = dt->CurrentFrame->FirstElement; ae2 = dt->NextFrame ->FirstElement; if (!ae1 || !ae2) { MSG_add("!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure has no animation elements"); LOG_EXIT ( Figure_FIGURE_Draw ) return; } // // What colour do we draw the figure? // // // All this is done in FIGURE_draw_prim_tween nowadays using the array // filled in by this call to NIGHT_find.... // colour = 0; specular = 0; SLONG lx; SLONG ly; SLONG lz; NIGHT_Colour col; LOG_ENTER ( Figure_Calc_Sub_Objs ) calc_sub_objects_position( p_thing, dt->AnimTween, 0, // 0 is Pelvis &lx, &ly, &lz); lx += p_thing->WorldPos.X >> 8; ly += p_thing->WorldPos.Y >> 8; lz += p_thing->WorldPos.Z >> 8; LOG_EXIT ( Figure_Calc_Sub_Objs ) LOG_ENTER ( Figure_NIGHT_Find ) NIGHT_find(lx, ly, lz); LOG_EXIT ( Figure_NIGHT_Find ) /* SLONG lx; SLONG ly; SLONG lz; NIGHT_Colour col; calc_sub_objects_position( p_thing, dt->AnimTween, 0, // 0 is Pelvis &lx, &ly, &lz); lx += p_thing->WorldPos.X >> 8; ly += p_thing->WorldPos.Y >> 8; lz += p_thing->WorldPos.Z >> 8; col = NIGHT_get_light_at(lx, ly, lz); if (p_thing->Genus.Person->BurnIndex) { Pyro *p=TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType==PYRO_IMMOLATE) { col.red= (col.red>p->counter) ?col.red-p->counter:0; col.green=(col.green>p->counter)?col.green-p->counter:0; col.blue= (col.blue>p->counter) ?col.blue-p->counter:0; } } if (ControlFlag) { // // Brighten up the person if he is going to be drawn too dark. // if (col.red < 32) {col.red += 32 - col.red >> 1;} if (col.green < 32) {col.green += 32 - col.green >> 1;} if (col.blue < 32) {col.blue += 32 - col.blue >> 1;} } */ /* if(p_thing->Genus.Person->PersonType==PERSON_THUG_RED) { NIGHT_Colour temp; SLONG index; index=THING_NUMBER(p_thing)&15; // index=0; temp.red=(col.red*peep_recol[index].r)>>8; temp.green=(col.green*peep_recol[index].g)>>8; temp.blue=(col.blue*peep_recol[index].b)>>8; NIGHT_get_d3d_colour( temp, &jacket_col,&specular); jacket_col &= ~POLY_colour_restrict; index=(PERSON_NUMBER(p_thing->Genus.Person)>>2)%9; temp.red=(col.red*peep_recol[index].r)>>8; temp.green=(col.green*peep_recol[index].g)>>8; temp.blue=(col.blue*peep_recol[index].b)>>8; NIGHT_get_d3d_colour( temp, &leg_col,&specular); leg_col &= ~POLY_colour_restrict; } */ /* NIGHT_get_d3d_colour( col, &colour, &specular); */ /* if(p_thing->Genus.Person->PersonType!=PERSON_THUG_RED) { jacket_col=colour; leg_col=colour; } */ /* if (p_thing->Genus.Person->BurnIndex) { Pyro *p=TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType==PYRO_IMMOLATE) { colour=0; } }*/ /* colour &= ~POLY_colour_restrict; specular &= ~POLY_colour_restrict; */ #if WE_WANT_TO_DARKEN_PEOPLE_IN_SHADOW_ABRUPTLY if (SHADOW_in( (p_thing->WorldPos.X >> 8), (p_thing->WorldPos.Y >> 8), (p_thing->WorldPos.Z >> 8))) { colour >>= 1; colour &= 0x7f7f7f7f; specular = 0xff000000; } #endif #if USE_TOMS_ENGINE_PLEASE_BOB ASSERT ( !MM_bLightTableAlreadySetUp ); // Set up some data for the MM rendering thing. #if 0 //#define ALIGNED_STATIC_ARRAY(name,number,mytype,align) \ // static char c##name##mytype##align##StaticArray [ align + number * sizeof ( mytype ) ]; \ // name = (mytype *)( ( (DWORD)c##name##mytype##align##StaticArray + (align-1) ) & ~(align-1) ) ALIGNED_STATIC_ARRAY ( MM_pcFadeTable, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pcFadeTableTint, 128, D3DCOLOR, 4 ); ALIGNED_STATIC_ARRAY ( MM_pMatrix, 1, D3DMATRIX, 32 ); ALIGNED_STATIC_ARRAY ( MM_Vertex, 4, D3DVERTEX, 32 ); ALIGNED_STATIC_ARRAY ( MM_pNormal, 4, float, 8 ); #endif //#undef ALIGNED_STATIC_ARRAY Pyro *p = NULL; if (p_thing->Class == CLASS_PERSON && p_thing->Genus.Person->BurnIndex) { p = TO_PYRO(p_thing->Genus.Person->BurnIndex-1); if (p->PyroType != PYRO_IMMOLATE) { p = NULL; } } BuildMMLightingTable ( p, 0 ); MM_bLightTableAlreadySetUp = TRUE; #endif // // Draw each body part. // //SLONG i; SLONG ele_count; SLONG start_object; SLONG object_offset; ele_count = dt->TheChunk->ElementCount; start_object = prim_multi_objects[dt->TheChunk->MultiObject[dt->MeshID]].StartObject; if (ele_count == 15 ) { Matrix31 pos; pos.M[0] = (p_thing->WorldPos.X >> 8)+wx; pos.M[1] = (p_thing->WorldPos.Y >> 8) + wy; pos.M[2] = (p_thing->WorldPos.Z >> 8)+wz; // assume we've got a person, and draw the object hierarchically // fill out data. FIGURE_dhpr_rdata1[0].part_number = 0; FIGURE_dhpr_rdata1[0].current_child_number = 0; FIGURE_dhpr_rdata1[0].parent_base_mat = NULL; FIGURE_dhpr_rdata1[0].parent_base_pos = NULL; FIGURE_dhpr_rdata1[0].parent_current_mat = NULL; FIGURE_dhpr_rdata1[0].parent_current_pos = NULL; FIGURE_dhpr_data.start_object = start_object; if(p_thing->Genus.Person->PersonType==PERSON_ROPER) FIGURE_dhpr_data.body_def = &dt->TheChunk->PeopleTypes[(dt->PersonID>>5)]; else FIGURE_dhpr_data.body_def = &dt->TheChunk->PeopleTypes[(dt->PersonID&0x1f)]; FIGURE_dhpr_data.world_pos = &pos; FIGURE_dhpr_data.tween = dt->AnimTween; FIGURE_dhpr_data.ae1 = ae1; FIGURE_dhpr_data.ae2 = ae2; FIGURE_dhpr_data.world_mat = &r_matrix; // FIGURE_dhpr_data.world_mat2 = &r_matrix2; FIGURE_dhpr_data.dx = dx; FIGURE_dhpr_data.dy = dy; FIGURE_dhpr_data.dz = dz; FIGURE_dhpr_data.colour = colour; FIGURE_dhpr_data.specular = specular; // These two are used to find which unique mesh we are drawing. FIGURE_dhpr_data.bPersonType = p_thing->Genus.Person->PersonType; FIGURE_dhpr_data.bPersonID = dt->PersonID; FIGURE_draw_hierarchical_prim_recurse(p_thing); } else { for (int i = 0; i < ele_count; i++) { object_offset = dt->TheChunk->PeopleTypes[(dt->PersonID & 0x1f)].BodyPart[i]; FIGURE_draw_prim_tween( start_object + object_offset, p_thing->WorldPos.X >> 8, (p_thing->WorldPos.Y >> 8), p_thing->WorldPos.Z >> 8, dt->AnimTween, &ae1[i], &ae2[i], &r_matrix, dx,dy,dz, colour, specular, NULL, NULL, NULL, NULL, NULL, NULL, p_thing); } } #if USE_TOMS_ENGINE_PLEASE_BOB // Clean up after ourselves. ASSERT ( MM_bLightTableAlreadySetUp ); MM_bLightTableAlreadySetUp = FALSE; #if 0 MM_pcFadeTable = NULL; MM_pcFadeTableTint = NULL; MM_pMatrix = NULL; MM_Vertex = NULL; MM_pNormal = NULL; #endif #endif //#if USE_TOMS_ENGINE_PLEASE_BOB // // In case this thing ain't a person... // if (p_thing->Class == CLASS_PERSON) { /* Thing *p_person = p_thing; // // If this person is holding a coke-can... // if (p_person->Genus.Person->Flags & FLAG_PERSON_CANNING) { SLONG px; SLONG py; SLONG pz; SLONG prim; calc_sub_objects_position( p_person, p_person->Draw.Tweened->AnimTween, SUB_OBJECT_LEFT_HAND, &px, &py, &pz); px += p_person->WorldPos.X >> 8; py += p_person->WorldPos.Y >> 8; pz += p_person->WorldPos.Z >> 8; if (p_person->Genus.Person->Flags & FLAG_PERSON_HEADING) { DIRT_Info ans; DIRT_get_info(p_person->Genus.Person->Hold, &ans); prim = ans.prim; } else { prim = PRIM_OBJ_CAN; } MESH_draw_poly( prim, px, py, pz, 0, 0, 0, NULL,0); } */ // // Is this person carrying a grenade? // Thing *p_person = p_thing; if (p_person->Genus.Person->SpecialUse && TO_THING(p_person->Genus.Person->SpecialUse)->Genus.Special->SpecialType == SPECIAL_GRENADE) { SLONG px; SLONG py; SLONG pz; SLONG prim; calc_sub_objects_position( p_person, p_person->Draw.Tweened->AnimTween, SUB_OBJECT_LEFT_HAND, &px, &py, &pz); px += p_person->WorldPos.X >> 8; py += p_person->WorldPos.Y >> 8; pz += p_person->WorldPos.Z >> 8; kludge_shrink = TRUE; MESH_draw_poly( PRIM_OBJ_ITEM_GRENADE, px, py, pz, 0, 0, 0, NULL,0xff); kludge_shrink = FALSE; } } p_thing->Flags&=~FLAGS_PERSON_AIM_AND_RUN; LOG_EXIT ( Figure_FIGURE_Draw ) } #endif void ANIM_obj_draw(Thing *p_thing,DrawTween *dt) { SLONG dx; SLONG dy; SLONG dz; ULONG colour; ULONG specular; Matrix33 r_matrix; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; // calc_global_cloud(p_thing->WorldPos.X>>8,p_thing->WorldPos.Y>>8,p_thing->WorldPos.Z>>8); if (dt->CurrentFrame == 0 || dt->NextFrame == 0) { // // No frames to tween between. // MSG_add("!!!!!!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure"); return; } /* { // // Draw the bounding box. // AnimPrimBbox *apb = &anim_prim_bbox[p_thing->Index]; AENG_world_line( apb->minx + (p_thing->WorldPos.X >> 8), apb->miny + (p_thing->WorldPos.Y >> 8), apb->minz + (p_thing->WorldPos.Z >> 8), 0x16, 0x00ffffff, apb->maxx + (p_thing->WorldPos.X >> 8), apb->maxy + (p_thing->WorldPos.Y >> 8), apb->maxz + (p_thing->WorldPos.Z >> 8), 0x16, 0x000ccccff, TRUE); } */ // // The offset to keep the locked limb in the same place. // dx = 0; dy = 0; dz = 0; // // The animation elements for the two frames. // ae1 = dt->CurrentFrame->FirstElement; ae2 = dt->NextFrame ->FirstElement; if (!ae1 || !ae2) { MSG_add("!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure has no animation elements"); return; } // // The rotation matrix of the whole object. // FIGURE_rotate_obj( dt->Tilt, dt->Angle, (dt->Roll+2048)&2047, &r_matrix); // // What colour do we draw the figure? // colour = 0; specular = 0; SLONG lx; SLONG ly; SLONG lz; NIGHT_Colour col; lx = (p_thing->WorldPos.X >> 8); ly = (p_thing->WorldPos.Y >> 8) + 0x60; lz = (p_thing->WorldPos.Z >> 8); NIGHT_find(lx, ly, lz); /* NIGHT_get_d3d_colour( NIGHT_get_light_at( (p_thing->WorldPos.X >> 8), (p_thing->WorldPos.Y >> 8), (p_thing->WorldPos.Z >> 8)), &colour, &specular); colour &= ~POLY_colour_restrict; specular &= ~POLY_colour_restrict; */ // // Draw each body part. // SLONG i; SLONG ele_count; SLONG start_object; SLONG object_offset; ele_count = dt->TheChunk->ElementCount; start_object = prim_multi_objects[dt->TheChunk->MultiObject[0]].StartObject; for (i = 0; i < ele_count; i++) { object_offset = i; //dt->TheChunk->PeopleTypes[dt->PersonID].BodyPart[i]; FIGURE_draw_prim_tween( start_object + object_offset, p_thing->WorldPos.X >> 8, (p_thing->WorldPos.Y >> 8), p_thing->WorldPos.Z >> 8, dt->AnimTween, &ae1[i], &ae2[i], &r_matrix, dx,dy,dz, colour, specular, // p_thing); NULL, NULL, NULL, NULL, NULL, NULL, p_thing, i, 0xffff00ff); } } void ANIM_obj_draw_warped(Thing *p_thing,DrawTween *dt) { SLONG dx; SLONG dy; SLONG dz; ULONG colour; ULONG specular; Matrix33 r_matrix; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; if (dt->CurrentFrame == 0 || dt->NextFrame == 0) { // // No frames to tween between. // MSG_add("!!!!!!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure"); return; } // // The offset to keep the locked limb in the same place. // dx = 0; dy = 0; dz = 0; // // The animation elements for the two frames. // ae1 = dt->CurrentFrame->FirstElement; ae2 = dt->NextFrame ->FirstElement; if (!ae1 || !ae2) { MSG_add("!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure has no animation elements"); return; } // // The rotation matrix of the whole object. // FIGURE_rotate_obj( dt->Tilt, dt->Angle, (dt->Roll+2048)&2047, &r_matrix); // // What colour do we draw the figure? // NIGHT_get_d3d_colour( NIGHT_get_light_at( (p_thing->WorldPos.X >> 8), (p_thing->WorldPos.Y >> 8), (p_thing->WorldPos.Z >> 8)), &colour, &specular); colour &= ~POLY_colour_restrict; specular &= ~POLY_colour_restrict; // // Draw each body part. // SLONG i; SLONG ele_count; SLONG start_object; SLONG object_offset; ele_count = dt->TheChunk->ElementCount; start_object = prim_multi_objects[dt->TheChunk->MultiObject[0]].StartObject; for (i = 0; i < ele_count; i++) { object_offset = i; //dt->TheChunk->PeopleTypes[dt->PersonID].BodyPart[i]; FIGURE_draw_prim_tween_warped( start_object + object_offset, p_thing->WorldPos.X >> 8, (p_thing->WorldPos.Y >> 8), p_thing->WorldPos.Z >> 8, dt->AnimTween, &ae1[i], &ae2[i], &r_matrix, dx,dy,dz, colour, specular, p_thing); } } #ifndef TARGET_DC // ======================================================== // // DRAWING THE REFLECTION // // ======================================================== // // The bounding box of the reflected points on screen. // SLONG FIGURE_reflect_x1; SLONG FIGURE_reflect_y1; SLONG FIGURE_reflect_x2; SLONG FIGURE_reflect_y2; float FIGURE_reflect_height; // // The points used to create the reflection. // typedef struct { union { float distance; ULONG clip; }; POLY_Point pp; } FIGURE_Rpoint; #define FIGURE_MAX_RPOINTS 256 FIGURE_Rpoint FIGURE_rpoint[FIGURE_MAX_RPOINTS]; SLONG FIGURE_rpoint_upto; void FIGURE_draw_prim_tween_reflection( SLONG prim, SLONG x, SLONG y, SLONG z, SLONG tween, struct GameKeyFrameElement *anim_info, struct GameKeyFrameElement *anim_info_next, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, ULONG colour, ULONG specular, Thing *p_thing) { SLONG i; SLONG j; SLONG sp; SLONG ep; SLONG p0; SLONG p1; SLONG p2; SLONG p3; SLONG px; SLONG py; ULONG red; ULONG green; ULONG blue; ULONG r; ULONG g; ULONG b; ULONG face_colour; SLONG fog; float world_x; float world_y; float world_z; SLONG page; Matrix31 offset; Matrix33 mat2; Matrix33 mat_final; SVector temp; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; POLY_Point *tri [3]; POLY_Point *quad[4]; FIGURE_Rpoint *frp; colour >>= 1; specular >>= 1; colour &= 0x7f7f7f7f; specular &= 0x7f7f7f7f; colour |= 0xff000000; specular |= 0xff000000; red = (colour >> 16) & 0xff; green = (colour >> 8) & 0xff; blue = (colour >> 0) & 0xff; // // Matrix functions we use. // void matrix_transform (Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_mult33 (Matrix33* result, Matrix33* mat1, Matrix33* mat2); offset.M[0] = anim_info->OffsetX + ((anim_info_next->OffsetX + off_dx - anim_info->OffsetX) * tween >> 8); offset.M[1] = anim_info->OffsetY + ((anim_info_next->OffsetY + off_dy - anim_info->OffsetY) * tween >> 8); offset.M[2] = anim_info->OffsetZ + ((anim_info_next->OffsetZ + off_dz - anim_info->OffsetZ) * tween >> 8); matrix_transformZMY((struct Matrix31*)&temp,rot_mat, &offset); SLONG character_scale = person_get_scale(p_thing); temp.X = (temp.X * character_scale) / 256; temp.Y = (temp.Y * character_scale) / 256; temp.Z = (temp.Z * character_scale) / 256; x += temp.X; y += temp.Y; z += temp.Z; // // Create a temporary "tween" matrix between current and next // CMatrix33 m1, m2; GetCMatrix(anim_info, &m1); GetCMatrix(anim_info_next, &m2); build_tween_matrix(&mat2, &m1, &m2 ,tween); normalise_matrix(&mat2); // // Apply local rotation matrix to get mat_final that rotates // the point into world space. // matrix_mult33(&mat_final, rot_mat, &mat2); mat_final.M[0][0] = (mat_final.M[0][0] * character_scale) / 256; mat_final.M[0][1] = (mat_final.M[0][1] * character_scale) / 256; mat_final.M[0][2] = (mat_final.M[0][2] * character_scale) / 256; mat_final.M[1][0] = (mat_final.M[1][0] * character_scale) / 256; mat_final.M[1][1] = (mat_final.M[1][1] * character_scale) / 256; mat_final.M[1][2] = (mat_final.M[1][2] * character_scale) / 256; mat_final.M[2][0] = (mat_final.M[2][0] * character_scale) / 256; mat_final.M[2][1] = (mat_final.M[2][1] * character_scale) / 256; mat_final.M[2][2] = (mat_final.M[2][2] * character_scale) / 256; // // Do everything in floats. // float off_x; float off_y; float off_z; float fmatrix[9]; off_x = float(x); off_y = float(y); off_z = float(z); fmatrix[0] = float(mat_final.M[0][0]) * (1.0F / 32768.0F); fmatrix[1] = float(mat_final.M[0][1]) * (1.0F / 32768.0F); fmatrix[2] = float(mat_final.M[0][2]) * (1.0F / 32768.0F); fmatrix[3] = float(mat_final.M[1][0]) * (1.0F / 32768.0F); fmatrix[4] = float(mat_final.M[1][1]) * (1.0F / 32768.0F); fmatrix[5] = float(mat_final.M[1][2]) * (1.0F / 32768.0F); fmatrix[6] = float(mat_final.M[2][0]) * (1.0F / 32768.0F); fmatrix[7] = float(mat_final.M[2][1]) * (1.0F / 32768.0F); fmatrix[8] = float(mat_final.M[2][2]) * (1.0F / 32768.0F); POLY_set_local_rotation( off_x, off_y, off_z, fmatrix); // // How deep the reflection can be // #define FIGURE_MAX_DY (128.0F) #define FIGURE_255_DIVIDED_BY_MAX_DY (255.0F / FIGURE_MAX_DY) // // Rotate all the points into the POLY_buffer. // p_obj = &prim_objects[prim]; sp = p_obj->StartPoint; ep = p_obj->EndPoint; FIGURE_rpoint_upto = 0; for (i = sp; i < ep; i++) { ASSERT(WITHIN(FIGURE_rpoint_upto, 0, FIGURE_MAX_RPOINTS - 1)); frp = &FIGURE_rpoint[FIGURE_rpoint_upto++]; POLY_transform_using_local_rotation( AENG_dx_prim_points[i].X, AENG_dx_prim_points[i].Y, AENG_dx_prim_points[i].Z, &frp->pp); if (frp->pp.MaybeValid()) { frp->pp.colour = colour; frp->pp.specular = specular; // // Work out the signed distance of this point from the reflection plane. // world_x = AENG_dx_prim_points[i].X; world_y = AENG_dx_prim_points[i].Y; world_z = AENG_dx_prim_points[i].Z; MATRIX_MUL( fmatrix, world_x, world_y, world_z); world_x += off_x; world_y += off_y; world_z += off_z; frp->distance = FIGURE_reflect_height - world_y; if (frp->distance >= 0.0F) { // // Update the bounding box. // px = SLONG(frp->pp.X); py = SLONG(frp->pp.Y); if (px < FIGURE_reflect_x1) {FIGURE_reflect_x1 = px;} if (px > FIGURE_reflect_x2) {FIGURE_reflect_x2 = px;} if (py < FIGURE_reflect_y1) {FIGURE_reflect_y1 = py;} if (py > FIGURE_reflect_y2) {FIGURE_reflect_y2 = py;} // // Fade out the point depending on distance from the reflection plane. // fog = frp->pp.specular >> 24; fog += SLONG(frp->distance * FIGURE_255_DIVIDED_BY_MAX_DY); if (fog > 255) {fog = 255;} frp->pp.specular &= 0x00ffffff; frp->pp.specular |= fog << 24; } else { frp->pp.clip = 0; } } } // // The quads. // for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, FIGURE_rpoint_upto - 1)); ASSERT(WITHIN(p1, 0, FIGURE_rpoint_upto - 1)); ASSERT(WITHIN(p2, 0, FIGURE_rpoint_upto - 1)); ASSERT(WITHIN(p3, 0, FIGURE_rpoint_upto - 1)); // // Add the quads backwards... // quad[0] = &FIGURE_rpoint[p0].pp; quad[2] = &FIGURE_rpoint[p1].pp; quad[1] = &FIGURE_rpoint[p2].pp; quad[3] = &FIGURE_rpoint[p3].pp; if (POLY_valid_quad(quad)) { if (p_f4->DrawFlags & POLY_FLAG_TEXTURED) { quad[0]->u = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); quad[0]->v = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); quad[1]->u = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); quad[1]->v = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); quad[2]->u = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); quad[2]->v = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); quad[3]->u = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); quad[3]->v = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; page+=FACE_PAGE_OFFSET; if (the_display.GetDeviceInfo()->AdamiLightingSupported()) { POLY_add_quad(quad, POLY_PAGE_COLOUR, TRUE); } POLY_add_quad(quad, page, TRUE); } else { /* // // The colour of the face. // r = ENGINE_palette[p_f4->Col2].red; g = ENGINE_palette[p_f4->Col2].green; b = ENGINE_palette[p_f4->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); quad[0]->colour = face_colour; quad[1]->colour = face_colour; quad[2]->colour = face_colour; quad[3]->colour = face_colour; POLY_add_quad(quad, POLY_PAGE_COLOUR, TRUE); quad[0]->colour = colour; quad[1]->colour = colour; quad[2]->colour = colour; quad[3]->colour = colour; */ } } } // // The triangles. // for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; ASSERT(WITHIN(p0, 0, FIGURE_rpoint_upto - 1)); ASSERT(WITHIN(p1, 0, FIGURE_rpoint_upto - 1)); ASSERT(WITHIN(p2, 0, FIGURE_rpoint_upto - 1)); // // Add the triangle backwards! // tri[0] = &FIGURE_rpoint[p0].pp; tri[2] = &FIGURE_rpoint[p1].pp; tri[1] = &FIGURE_rpoint[p2].pp; if (POLY_valid_triangle(tri)) { if (p_f3->DrawFlags & POLY_FLAG_TEXTURED) { tri[0]->u = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); tri[0]->v = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); tri[1]->u = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); tri[1]->v = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); tri[2]->u = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); tri[2]->v = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; page+=FACE_PAGE_OFFSET; if (the_display.GetDeviceInfo()->AdamiLightingSupported()) { POLY_add_triangle(tri, POLY_PAGE_COLOUR, TRUE); } POLY_add_triangle(tri, page, TRUE); } else { /* // // The colour of the face. // r = ENGINE_palette[p_f3->Col2].red; g = ENGINE_palette[p_f3->Col2].green; b = ENGINE_palette[p_f3->Col2].blue; r = r * red >> 8; g = g * green >> 8; b = b * blue >> 8; face_colour = (r << 16) | (g << 8) | (b << 0); tri[0]->colour = face_colour; tri[1]->colour = face_colour; tri[2]->colour = face_colour; POLY_add_triangle(tri, POLY_PAGE_COLOUR, TRUE); tri[0]->colour = colour; tri[1]->colour = colour; tri[2]->colour = colour; */ } } } } void FIGURE_draw_reflection(Thing *p_thing, SLONG height) { SLONG dx; SLONG dy; SLONG dz; ULONG colour; ULONG specular; POLY_Point *pp; Matrix33 r_matrix; GameKeyFrameElement *ae1; GameKeyFrameElement *ae2; DrawTween *dt = p_thing->Draw.Tweened; if (dt->CurrentFrame == 0 || dt->NextFrame == 0) { // // No frames to tween between. // MSG_add("!!!!!!!!!!!!!!!!!!!!!!!!ERROR FIGURE_draw_reflection"); return; } // // The offset to keep the locked limb in the same place. // //if (dt->Locked) if (0) { SLONG x1, y1, z1; SLONG x2, y2, z2; // // Taken from temp.cpp // calc_sub_objects_position_global(dt->CurrentFrame, dt->NextFrame, 0, dt->Locked, &x1, &y1, &z1); calc_sub_objects_position_global(dt->CurrentFrame, dt->NextFrame, 256, dt->Locked, &x2, &y2, &z2); dx = x1 - x2; dy = y1 - y2; dz = z1 - z2; } else { dx = 0; dy = 0; dz = 0; } // // The animation elements for the two frames. // ae1 = dt->CurrentFrame->FirstElement; ae2 = dt->NextFrame ->FirstElement; if (!ae1 || !ae2) { MSG_add("!!!!!!!!!!!!!!!!!!!ERROR AENG_draw_figure has no animation elements"); return; } // // The rotation matrix of the whole object. // FIGURE_rotate_obj( dt->Tilt, dt->Angle, - dt->Roll, // - = JCL &r_matrix); SLONG posx = p_thing->WorldPos.X >> 8; SLONG posy = p_thing->WorldPos.Y >> 8; SLONG posz = p_thing->WorldPos.Z >> 8; // // Reflect about y = height. // posy = height - (posy - height); dy = -dy; r_matrix.M[0][1] = -r_matrix.M[0][1]; r_matrix.M[1][1] = -r_matrix.M[1][1]; r_matrix.M[2][1] = -r_matrix.M[2][1]; // // Initialise the bounding box. // FIGURE_reflect_x1 = +INFINITY; FIGURE_reflect_y1 = +INFINITY; FIGURE_reflect_x2 = -INFINITY; FIGURE_reflect_y2 = -INFINITY; // // The height of the plane the body-parts are clipped against. // FIGURE_reflect_height = float(height); // // What colour do we draw the figure? // SLONG lx; SLONG ly; SLONG lz; NIGHT_Colour col; calc_sub_objects_position( p_thing, dt->AnimTween, 0, // 0 is Pelvis &lx, &ly, &lz); lx += p_thing->WorldPos.X >> 8; ly += p_thing->WorldPos.Y >> 8; lz += p_thing->WorldPos.Z >> 8; col = NIGHT_get_light_at(lx, ly, lz); if (!ControlFlag) { // // Brighten up the person if he is going to be drawn too dark. // if (col.red < 32) {col.red += 32 - col.red >> 1;} if (col.green < 32) {col.green += 32 - col.green >> 1;} if (col.blue < 32) {col.blue += 32 - col.blue >> 1;} } NIGHT_get_d3d_colour( col, &colour, &specular); colour &= ~POLY_colour_restrict; specular &= ~POLY_colour_restrict; // // Draw each body part. // SLONG i; SLONG j; SLONG ele_count; SLONG start_object; SLONG object_offset; SLONG px; SLONG py; ele_count = dt->TheChunk->ElementCount; start_object = prim_multi_objects[dt->TheChunk->MultiObject[dt->MeshID]].StartObject; for (i = 0; i < ele_count; i++) { object_offset = dt->TheChunk->PeopleTypes[dt->PersonID&0x1f].BodyPart[i]; // object_offset = dt->TheChunk->PeopleTypes[0].BodyPart[i]; FIGURE_draw_prim_tween_reflection( start_object + object_offset, posx, posy, posz, dt->AnimTween, &ae1[i], &ae2[i], &r_matrix, dx,dy,dz, colour, specular, p_thing); } } #endif //#ifndef TARGET_DC // Like FIGURE_draw_prim_tween, but optimised for the person-only case. // Also assumes the lighting has been set up, etc. // This just sets up the matrix and light vector it's asked to - it doesn't // do anything else. // Return value is TRUE if this body part is not clipped by the near-Z. bool FIGURE_draw_prim_tween_person_only_just_set_matrix ( int iMatrixNum, SLONG prim, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, SLONG recurse_level, Thing *p_thing ) { SLONG x = FIGURE_dhpr_data.world_pos->M[0]; SLONG y = FIGURE_dhpr_data.world_pos->M[1]; SLONG z = FIGURE_dhpr_data.world_pos->M[2]; SLONG tween = FIGURE_dhpr_data.tween; struct GameKeyFrameElement *anim_info = &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number]; struct GameKeyFrameElement *anim_info_next = &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number]; ULONG colour = FIGURE_dhpr_data.colour; ULONG specular = FIGURE_dhpr_data.specular; CMatrix33 *parent_base_mat = FIGURE_dhpr_rdata1[recurse_level].parent_base_mat; Matrix31 *parent_base_pos = FIGURE_dhpr_rdata1[recurse_level].parent_base_pos; Matrix33 *parent_curr_mat = FIGURE_dhpr_rdata1[recurse_level].parent_current_mat; Matrix31 *parent_curr_pos = FIGURE_dhpr_rdata1[recurse_level].parent_current_pos; Matrix33 *end_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; Matrix31 *end_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; SLONG i; SLONG j; SLONG sp; SLONG ep; SLONG p0; SLONG p1; SLONG p2; SLONG p3; SLONG nx; SLONG ny; SLONG nz; SLONG red; SLONG green; SLONG blue; SLONG dprod; SLONG r; SLONG g; SLONG b; SLONG dr; SLONG dg; SLONG db; SLONG face_colour; SLONG page; Matrix31 offset; Matrix33 mat2; Matrix33 mat_final; ULONG qc0; ULONG qc1; ULONG qc2; ULONG qc3; SVector temp; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; NIGHT_Found *nf; POLY_Point *pp; POLY_Point *ps; POLY_Point *tri [3]; POLY_Point *quad[4]; SLONG tex_page_offset; LOG_ENTER ( Figure_Draw_Prim_Tween ) tex_page_offset=p_thing->Genus.Person->pcom_colour&0x3; // // Matrix functions we use. // void matrix_transform (Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_mult33 (Matrix33* result, Matrix33* mat1, Matrix33* mat2); if (parent_base_mat) { // we've got hierarchy info! Matrix31 p; p.M[0] = anim_info->OffsetX; p.M[1] = anim_info->OffsetY; p.M[2] = anim_info->OffsetZ; HIERARCHY_Get_Body_Part_Offset(&offset, &p, parent_base_mat, parent_base_pos, parent_curr_mat, parent_curr_pos); // pass data up the hierarchy if (end_pos) *end_pos = offset; } else { // process at highter resolution offset.M[0] = (anim_info->OffsetX << 8) + ((anim_info_next->OffsetX + off_dx - anim_info->OffsetX) * tween); offset.M[1] = (anim_info->OffsetY << 8) + ((anim_info_next->OffsetY + off_dy - anim_info->OffsetY) * tween); offset.M[2] = (anim_info->OffsetZ << 8) + ((anim_info_next->OffsetZ + off_dz - anim_info->OffsetZ) * tween); if (end_pos) { *end_pos = offset; } } // convert pos to floating point here to preserve accuracy and prevent overflow. // It's also a shitload faster on P2 and SH4. float off_x = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[0][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[0][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[0][2]) / 32768.f); float off_y = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[1][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[1][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[1][2]) / 32768.f); float off_z = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[2][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[2][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[2][2]) / 32768.f); SLONG character_scale = person_get_scale(p_thing); float character_scalef = float(character_scale) / 256.f; off_x *= character_scalef; off_y *= character_scalef; off_z *= character_scalef; off_x += float(x); off_y += float(y); off_z += float(z); // // Do everything in floats. // float fmatrix[9]; //SLONG imatrix[9]; // // Create a temporary "tween" matrix between current and next // CMatrix33 m1, m2; GetCMatrix(anim_info, &m1); GetCMatrix(anim_info_next, &m2); CQuaternion::BuildTween(&mat2, &m1, &m2, tween); // pass data up the hierarchy if (end_mat) *end_mat = mat2; // // Apply local rotation matrix to get mat_final that rotates // the point into world space. // matrix_mult33(&mat_final, rot_mat, &mat2); //! yeehaw! mat_final.M[0][0] = (mat_final.M[0][0] * character_scale) / 256; mat_final.M[0][1] = (mat_final.M[0][1] * character_scale) / 256; mat_final.M[0][2] = (mat_final.M[0][2] * character_scale) / 256; mat_final.M[1][0] = (mat_final.M[1][0] * character_scale) / 256; mat_final.M[1][1] = (mat_final.M[1][1] * character_scale) / 256; mat_final.M[1][2] = (mat_final.M[1][2] * character_scale) / 256; mat_final.M[2][0] = (mat_final.M[2][0] * character_scale) / 256; mat_final.M[2][1] = (mat_final.M[2][1] * character_scale) / 256; mat_final.M[2][2] = (mat_final.M[2][2] * character_scale) / 256; fmatrix[0] = float(mat_final.M[0][0]) * (1.0F / 32768.0F); fmatrix[1] = float(mat_final.M[0][1]) * (1.0F / 32768.0F); fmatrix[2] = float(mat_final.M[0][2]) * (1.0F / 32768.0F); fmatrix[3] = float(mat_final.M[1][0]) * (1.0F / 32768.0F); fmatrix[4] = float(mat_final.M[1][1]) * (1.0F / 32768.0F); fmatrix[5] = float(mat_final.M[1][2]) * (1.0F / 32768.0F); fmatrix[6] = float(mat_final.M[2][0]) * (1.0F / 32768.0F); fmatrix[7] = float(mat_final.M[2][1]) * (1.0F / 32768.0F); fmatrix[8] = float(mat_final.M[2][2]) * (1.0F / 32768.0F); LOG_ENTER ( Figure_Set_Rotation ) POLY_set_local_rotation( off_x, off_y, off_z, fmatrix); LOG_ENTER ( Figure_Set_Rotation ) // Not 100% sure if I'm using character_scalef correctly... // ...but it seems to work OK. ASSERT ( ( character_scalef < 1.2f ) && ( character_scalef > 0.8f ) ); //ASSERT ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ); if ( ( ( ( g_matWorld._43 * 32768.0f ) - ( (m_fObjectBoundingSphereRadius[prim]) * character_scalef ) ) < ( POLY_ZCLIP_PLANE * 32768.0f ) ) ) { // Clipped by Z-plane. Don't set this matrix up, just return. return FALSE; } // // Rotate all the points into the POLY_buffer. // p_obj = &prim_objects[prim]; sp = p_obj->StartPoint; ep = p_obj->EndPoint; POLY_buffer_upto = 0; // Check for being a gun if (prim==256) { i=sp; } else if (prim==258) { // Or a shotgun i=sp+15; } else if (prim==260) { // or an AK i=sp+32; } else { goto no_muzzle_calcs; // which skips... } // // this bit, which only executes if one of the above tests is true. // pp = &POLY_buffer[POLY_buffer_upto]; // no ++, so reused pp->x=AENG_dx_prim_points[i].X; pp->y=AENG_dx_prim_points[i].Y; pp->z=AENG_dx_prim_points[i].Z; MATRIX_MUL( fmatrix, pp->x, pp->y, pp->z); pp->x+=off_x; pp->y+=off_y; pp->z+=off_z; p_thing->Genus.Person->GunMuzzle.X=pp->x*256; p_thing->Genus.Person->GunMuzzle.Y=pp->y*256; p_thing->Genus.Person->GunMuzzle.Z=pp->z*256; // x=pp->x*256; y=pp->y*256; z=pp->z*256; no_muzzle_calcs: #if !USE_TOMS_ENGINE_PLEASE_BOB #error Dont use this rout if USE_TOMS_ENGINE_PLEASE_BOB is not 1 #endif ASSERT ( MM_bLightTableAlreadySetUp ); ASSERT (!WITHIN(prim, 261, 263)); { ASSERT ( MM_bLightTableAlreadySetUp ); LOG_ENTER ( Figure_Build_Matrices ) extern float POLY_cam_matrix_comb[9]; extern float POLY_cam_off_x; extern float POLY_cam_off_y; extern float POLY_cam_off_z; extern D3DMATRIX g_matProjection; extern D3DMATRIX g_matWorld; extern D3DVIEWPORT2 g_viewData; D3DMATRIX matTemp; matTemp._11 = g_matWorld._11*g_matProjection._11 + g_matWorld._12*g_matProjection._21 + g_matWorld._13*g_matProjection._31 + g_matWorld._14*g_matProjection._41; matTemp._12 = g_matWorld._11*g_matProjection._12 + g_matWorld._12*g_matProjection._22 + g_matWorld._13*g_matProjection._32 + g_matWorld._14*g_matProjection._42; matTemp._13 = g_matWorld._11*g_matProjection._13 + g_matWorld._12*g_matProjection._23 + g_matWorld._13*g_matProjection._33 + g_matWorld._14*g_matProjection._43; matTemp._14 = g_matWorld._11*g_matProjection._14 + g_matWorld._12*g_matProjection._24 + g_matWorld._13*g_matProjection._34 + g_matWorld._14*g_matProjection._44; matTemp._21 = g_matWorld._21*g_matProjection._11 + g_matWorld._22*g_matProjection._21 + g_matWorld._23*g_matProjection._31 + g_matWorld._24*g_matProjection._41; matTemp._22 = g_matWorld._21*g_matProjection._12 + g_matWorld._22*g_matProjection._22 + g_matWorld._23*g_matProjection._32 + g_matWorld._24*g_matProjection._42; matTemp._23 = g_matWorld._21*g_matProjection._13 + g_matWorld._22*g_matProjection._23 + g_matWorld._23*g_matProjection._33 + g_matWorld._24*g_matProjection._43; matTemp._24 = g_matWorld._21*g_matProjection._14 + g_matWorld._22*g_matProjection._24 + g_matWorld._23*g_matProjection._34 + g_matWorld._24*g_matProjection._44; matTemp._31 = g_matWorld._31*g_matProjection._11 + g_matWorld._32*g_matProjection._21 + g_matWorld._33*g_matProjection._31 + g_matWorld._34*g_matProjection._41; matTemp._32 = g_matWorld._31*g_matProjection._12 + g_matWorld._32*g_matProjection._22 + g_matWorld._33*g_matProjection._32 + g_matWorld._34*g_matProjection._42; matTemp._33 = g_matWorld._31*g_matProjection._13 + g_matWorld._32*g_matProjection._23 + g_matWorld._33*g_matProjection._33 + g_matWorld._34*g_matProjection._43; matTemp._34 = g_matWorld._31*g_matProjection._14 + g_matWorld._32*g_matProjection._24 + g_matWorld._33*g_matProjection._34 + g_matWorld._34*g_matProjection._44; matTemp._41 = g_matWorld._41*g_matProjection._11 + g_matWorld._42*g_matProjection._21 + g_matWorld._43*g_matProjection._31 + g_matWorld._44*g_matProjection._41; matTemp._42 = g_matWorld._41*g_matProjection._12 + g_matWorld._42*g_matProjection._22 + g_matWorld._43*g_matProjection._32 + g_matWorld._44*g_matProjection._42; matTemp._43 = g_matWorld._41*g_matProjection._13 + g_matWorld._42*g_matProjection._23 + g_matWorld._43*g_matProjection._33 + g_matWorld._44*g_matProjection._43; matTemp._44 = g_matWorld._41*g_matProjection._14 + g_matWorld._42*g_matProjection._24 + g_matWorld._43*g_matProjection._34 + g_matWorld._44*g_matProjection._44; // Now make up the matrices. #if 0 // Officially correct version. DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_viewData.dwHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_viewData.dwY; #else // Version that knows about the letterbox mode hack. extern DWORD g_dw3DStuffHeight; extern DWORD g_dw3DStuffY; DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_dw3DStuffHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_dw3DStuffY; #endif // Set up the matrix. D3DMATRIX *pmat = &(MMBodyParts_pMatrix[iMatrixNum]); pmat->_11 = 0.0f; pmat->_12 = matTemp._11 * (float)dwWidth + matTemp._14 * (float)( dwX + dwWidth ); pmat->_13 = matTemp._12 * - (float)dwHeight + matTemp._14 * (float)( dwY + dwHeight ); pmat->_14 = matTemp._14; pmat->_21 = 0.0f; pmat->_22 = matTemp._21 * (float)dwWidth + matTemp._24 * (float)( dwX + dwWidth ); pmat->_23 = matTemp._22 * - (float)dwHeight + matTemp._24 * (float)( dwY + dwHeight ); pmat->_24 = matTemp._24; pmat->_31 = 0.0f; pmat->_32 = matTemp._31 * (float)dwWidth + matTemp._34 * (float)( dwX + dwWidth ); pmat->_33 = matTemp._32 * - (float)dwHeight + matTemp._34 * (float)( dwY + dwHeight ); pmat->_34 = matTemp._34; // Validation magic number. unsigned long EVal = 0xe0001000; pmat->_41 = *(float *)&EVal; pmat->_42 = matTemp._41 * (float)dwWidth + matTemp._44 * (float)( dwX + dwWidth ); pmat->_43 = matTemp._42 * - (float)dwHeight + matTemp._44 * (float)( dwY + dwHeight ); pmat->_44 = matTemp._44; // 251 is a magic number for the DIP call! const float fNormScale = 251.0f; // Transform the lighting direction(s) by the inverse object matrix to get it into object space. // Assume inverse=transpose. D3DVECTOR vTemp; vTemp.x = MM_vLightDir.x * fmatrix[0] + MM_vLightDir.y * fmatrix[3] + MM_vLightDir.z * fmatrix[6]; vTemp.y = MM_vLightDir.x * fmatrix[1] + MM_vLightDir.y * fmatrix[4] + MM_vLightDir.z * fmatrix[7]; vTemp.z = MM_vLightDir.x * fmatrix[2] + MM_vLightDir.y * fmatrix[5] + MM_vLightDir.z * fmatrix[8]; // Set up the lighting vector. float *pnorm = &(MMBodyParts_pNormal[iMatrixNum<<2]); pnorm[0] = 0.0f; pnorm[1] = vTemp.x * fNormScale; pnorm[2] = vTemp.y * fNormScale; pnorm[3] = vTemp.z * fNormScale; LOG_EXIT ( Figure_Build_Matrices ) } // No environment mapping. ASSERT ( p_thing && ( p_thing->Class != CLASS_VEHICLE ) ); ASSERT ( MM_bLightTableAlreadySetUp ); LOG_EXIT ( Figure_Draw_Prim_Tween ) return TRUE; } // Like FIGURE_draw_prim_tween, but optimised for the person-only case. // Also assumes the lighting has been set up, etc. void FIGURE_draw_prim_tween_person_only( SLONG prim, //SLONG x, //SLONG y, //SLONG z, //SLONG tween, //struct GameKeyFrameElement *anim_info, //struct GameKeyFrameElement *anim_info_next, struct Matrix33 *rot_mat, SLONG off_dx, SLONG off_dy, SLONG off_dz, //ULONG colour, //ULONG specular, SLONG recurse_level, //CMatrix33 *parent_base_mat, //Matrix31 *parent_base_pos, //Matrix33 *parent_curr_mat, //Matrix31 *parent_curr_pos, //Matrix33 *end_mat, //Matrix31 *end_pos, Thing *p_thing //SLONG part_number = 0xffffffff, //ULONG colour_and = 0xffffffff ) { SLONG x = FIGURE_dhpr_data.world_pos->M[0]; SLONG y = FIGURE_dhpr_data.world_pos->M[1]; SLONG z = FIGURE_dhpr_data.world_pos->M[2]; SLONG tween = FIGURE_dhpr_data.tween; struct GameKeyFrameElement *anim_info = &FIGURE_dhpr_data.ae1[FIGURE_dhpr_rdata1[recurse_level].part_number]; struct GameKeyFrameElement *anim_info_next = &FIGURE_dhpr_data.ae2[FIGURE_dhpr_rdata1[recurse_level].part_number]; ULONG colour = FIGURE_dhpr_data.colour; ULONG specular = FIGURE_dhpr_data.specular; CMatrix33 *parent_base_mat = FIGURE_dhpr_rdata1[recurse_level].parent_base_mat; Matrix31 *parent_base_pos = FIGURE_dhpr_rdata1[recurse_level].parent_base_pos; Matrix33 *parent_curr_mat = FIGURE_dhpr_rdata1[recurse_level].parent_current_mat; Matrix31 *parent_curr_pos = FIGURE_dhpr_rdata1[recurse_level].parent_current_pos; Matrix33 *end_mat = &FIGURE_dhpr_rdata2[recurse_level].end_mat; Matrix31 *end_pos = &FIGURE_dhpr_rdata2[recurse_level].end_pos; SLONG part_number = FIGURE_dhpr_rdata1[recurse_level].part_number; //ULONG colour_and = 0xffffffff; SLONG i; SLONG j; SLONG sp; SLONG ep; SLONG p0; SLONG p1; SLONG p2; SLONG p3; SLONG nx; SLONG ny; SLONG nz; SLONG red; SLONG green; SLONG blue; SLONG dprod; SLONG r; SLONG g; SLONG b; SLONG dr; SLONG dg; SLONG db; SLONG face_colour; SLONG page; Matrix31 offset; Matrix33 mat2; Matrix33 mat_final; ULONG qc0; ULONG qc1; ULONG qc2; ULONG qc3; SVector temp; PrimFace4 *p_f4; PrimFace3 *p_f3; PrimObject *p_obj; NIGHT_Found *nf; POLY_Point *pp; POLY_Point *ps; POLY_Point *tri [3]; POLY_Point *quad[4]; SLONG tex_page_offset; LOG_ENTER ( Figure_Draw_Prim_Tween ) tex_page_offset=p_thing->Genus.Person->pcom_colour&0x3; // // Matrix functions we use. // void matrix_transform (Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_transformZMY(Matrix31* result, Matrix33* trans, Matrix31* mat2); void matrix_mult33 (Matrix33* result, Matrix33* mat1, Matrix33* mat2); if (parent_base_mat) { // we've got hierarchy info! Matrix31 p; p.M[0] = anim_info->OffsetX; p.M[1] = anim_info->OffsetY; p.M[2] = anim_info->OffsetZ; HIERARCHY_Get_Body_Part_Offset(&offset, &p, parent_base_mat, parent_base_pos, parent_curr_mat, parent_curr_pos); // pass data up the hierarchy if (end_pos) *end_pos = offset; } else { // process at highter resolution offset.M[0] = (anim_info->OffsetX << 8) + ((anim_info_next->OffsetX + off_dx - anim_info->OffsetX) * tween); offset.M[1] = (anim_info->OffsetY << 8) + ((anim_info_next->OffsetY + off_dy - anim_info->OffsetY) * tween); offset.M[2] = (anim_info->OffsetZ << 8) + ((anim_info_next->OffsetZ + off_dz - anim_info->OffsetZ) * tween); if (end_pos) { *end_pos = offset; } } // convert pos to floating point here to preserve accuracy and prevent overflow. // It's also a shitload faster on P2 and SH4. float off_x = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[0][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[0][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[0][2]) / 32768.f); float off_y = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[1][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[1][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[1][2]) / 32768.f); float off_z = (float(offset.M[0]) / 256.f) * (float(rot_mat->M[2][0]) / 32768.f) + (float(offset.M[1]) / 256.f) * (float(rot_mat->M[2][1]) / 32768.f) + (float(offset.M[2]) / 256.f) * (float(rot_mat->M[2][2]) / 32768.f); SLONG character_scale = person_get_scale(p_thing); float character_scalef = float(character_scale) / 256.f; off_x *= character_scalef; off_y *= character_scalef; off_z *= character_scalef; off_x += float(x); off_y += float(y); off_z += float(z); // // Do everything in floats. // float fmatrix[9]; //SLONG imatrix[9]; // // Create a temporary "tween" matrix between current and next // CMatrix33 m1, m2; GetCMatrix(anim_info, &m1); GetCMatrix(anim_info_next, &m2); CQuaternion::BuildTween(&mat2, &m1, &m2, tween); // pass data up the hierarchy if (end_mat) *end_mat = mat2; // // Apply local rotation matrix to get mat_final that rotates // the point into world space. // matrix_mult33(&mat_final, rot_mat, &mat2); //! yeehaw! mat_final.M[0][0] = (mat_final.M[0][0] * character_scale) / 256; mat_final.M[0][1] = (mat_final.M[0][1] * character_scale) / 256; mat_final.M[0][2] = (mat_final.M[0][2] * character_scale) / 256; mat_final.M[1][0] = (mat_final.M[1][0] * character_scale) / 256; mat_final.M[1][1] = (mat_final.M[1][1] * character_scale) / 256; mat_final.M[1][2] = (mat_final.M[1][2] * character_scale) / 256; mat_final.M[2][0] = (mat_final.M[2][0] * character_scale) / 256; mat_final.M[2][1] = (mat_final.M[2][1] * character_scale) / 256; mat_final.M[2][2] = (mat_final.M[2][2] * character_scale) / 256; fmatrix[0] = float(mat_final.M[0][0]) * (1.0F / 32768.0F); fmatrix[1] = float(mat_final.M[0][1]) * (1.0F / 32768.0F); fmatrix[2] = float(mat_final.M[0][2]) * (1.0F / 32768.0F); fmatrix[3] = float(mat_final.M[1][0]) * (1.0F / 32768.0F); fmatrix[4] = float(mat_final.M[1][1]) * (1.0F / 32768.0F); fmatrix[5] = float(mat_final.M[1][2]) * (1.0F / 32768.0F); fmatrix[6] = float(mat_final.M[2][0]) * (1.0F / 32768.0F); fmatrix[7] = float(mat_final.M[2][1]) * (1.0F / 32768.0F); fmatrix[8] = float(mat_final.M[2][2]) * (1.0F / 32768.0F); #if 0 imatrix[0] = mat_final.M[0][0] * 2; imatrix[1] = mat_final.M[0][1] * 2; imatrix[2] = mat_final.M[0][2] * 2; imatrix[3] = mat_final.M[1][0] * 2; imatrix[4] = mat_final.M[1][1] * 2; imatrix[5] = mat_final.M[1][2] * 2; imatrix[6] = mat_final.M[2][0] * 2; imatrix[7] = mat_final.M[2][1] * 2; imatrix[8] = mat_final.M[2][2] * 2; #endif LOG_ENTER ( Figure_Set_Rotation ) POLY_set_local_rotation( off_x, off_y, off_z, fmatrix); LOG_ENTER ( Figure_Set_Rotation ) // // Rotate all the points into the POLY_buffer. // p_obj = &prim_objects[prim]; sp = p_obj->StartPoint; ep = p_obj->EndPoint; POLY_buffer_upto = 0; // Check for being a gun if (prim==256) { i=sp; } else if (prim==258) { // Or a shotgun i=sp+15; } else if (prim==260) { // or an AK i=sp+32; } else { goto no_muzzle_calcs; // which skips... } // // this bit, which only executes if one of the above tests is true. // pp = &POLY_buffer[POLY_buffer_upto]; // no ++, so reused pp->x=AENG_dx_prim_points[i].X; pp->y=AENG_dx_prim_points[i].Y; pp->z=AENG_dx_prim_points[i].Z; MATRIX_MUL( fmatrix, pp->x, pp->y, pp->z); pp->x+=off_x; pp->y+=off_y; pp->z+=off_z; p_thing->Genus.Person->GunMuzzle.X=pp->x*256; p_thing->Genus.Person->GunMuzzle.Y=pp->y*256; p_thing->Genus.Person->GunMuzzle.Z=pp->z*256; // x=pp->x*256; y=pp->y*256; z=pp->z*256; no_muzzle_calcs: #if !USE_TOMS_ENGINE_PLEASE_BOB #error Dont use this rout if USE_TOMS_ENGINE_PLEASE_BOB is not 1 #endif ASSERT ( MM_bLightTableAlreadySetUp ); if (WITHIN(prim, 261, 263)) { // // This is a muzzle flash! They don't have any lighting! // for (i = sp; i < ep; i++) { ASSERT(WITHIN(POLY_buffer_upto, 0, POLY_BUFFER_SIZE - 1)); pp = &POLY_buffer[POLY_buffer_upto++]; POLY_transform_using_local_rotation( AENG_dx_prim_points[i].X, AENG_dx_prim_points[i].Y, AENG_dx_prim_points[i].Z, pp); pp->colour = 0xff808080; pp->specular = 0xff000000; } for (i = p_obj->StartFace4; i < p_obj->EndFace4; i++) { p_f4 = &prim_faces4[i]; p0 = p_f4->Points[0] - sp; p1 = p_f4->Points[1] - sp; p2 = p_f4->Points[2] - sp; p3 = p_f4->Points[3] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p3, 0, POLY_buffer_upto - 1)); quad[0] = &POLY_buffer[p0]; quad[1] = &POLY_buffer[p1]; quad[2] = &POLY_buffer[p2]; quad[3] = &POLY_buffer[p3]; if (POLY_valid_quad(quad)) { quad[0]->u = float(p_f4->UV[0][0] & 0x3f) * (1.0F / 32.0F); quad[0]->v = float(p_f4->UV[0][1] ) * (1.0F / 32.0F); quad[1]->u = float(p_f4->UV[1][0] ) * (1.0F / 32.0F); quad[1]->v = float(p_f4->UV[1][1] ) * (1.0F / 32.0F); quad[2]->u = float(p_f4->UV[2][0] ) * (1.0F / 32.0F); quad[2]->v = float(p_f4->UV[2][1] ) * (1.0F / 32.0F); quad[3]->u = float(p_f4->UV[3][0] ) * (1.0F / 32.0F); quad[3]->v = float(p_f4->UV[3][1] ) * (1.0F / 32.0F); page = p_f4->UV[0][0] & 0xc0; page <<= 2; page |= p_f4->TexturePage; if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; POLY_add_quad(quad, page, !(p_f4->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } for (i = p_obj->StartFace3; i < p_obj->EndFace3; i++) { p_f3 = &prim_faces3[i]; p0 = p_f3->Points[0] - sp; p1 = p_f3->Points[1] - sp; p2 = p_f3->Points[2] - sp; ASSERT(WITHIN(p0, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p1, 0, POLY_buffer_upto - 1)); ASSERT(WITHIN(p2, 0, POLY_buffer_upto - 1)); tri[0] = &POLY_buffer[p0]; tri[1] = &POLY_buffer[p1]; tri[2] = &POLY_buffer[p2]; if (POLY_valid_triangle(tri)) { tri[0]->u = float(p_f3->UV[0][0] & 0x3f) * (1.0F / 32.0F); tri[0]->v = float(p_f3->UV[0][1] ) * (1.0F / 32.0F); tri[1]->u = float(p_f3->UV[1][0] ) * (1.0F / 32.0F); tri[1]->v = float(p_f3->UV[1][1] ) * (1.0F / 32.0F); tri[2]->u = float(p_f3->UV[2][0] ) * (1.0F / 32.0F); tri[2]->v = float(p_f3->UV[2][1] ) * (1.0F / 32.0F); page = p_f3->UV[0][0] & 0xc0; page <<= 2; page |= p_f3->TexturePage; if(tex_page_offset && page>10*64 && alt_texture[page-10*64]) { page=alt_texture[page-10*64]+tex_page_offset-1; } else page+=FACE_PAGE_OFFSET; POLY_add_triangle(tri, page, !(p_f3->DrawFlags & POLY_FLAG_DOUBLESIDED)); } } LOG_EXIT ( Figure_Draw_Prim_Tween ) return; } else { ASSERT ( MM_bLightTableAlreadySetUp ); LOG_ENTER ( Figure_Build_Matrices ) extern float POLY_cam_matrix_comb[9]; extern float POLY_cam_off_x; extern float POLY_cam_off_y; extern float POLY_cam_off_z; extern D3DMATRIX g_matProjection; extern D3DMATRIX g_matWorld; extern D3DVIEWPORT2 g_viewData; D3DMATRIX matTemp; matTemp._11 = g_matWorld._11*g_matProjection._11 + g_matWorld._12*g_matProjection._21 + g_matWorld._13*g_matProjection._31 + g_matWorld._14*g_matProjection._41; matTemp._12 = g_matWorld._11*g_matProjection._12 + g_matWorld._12*g_matProjection._22 + g_matWorld._13*g_matProjection._32 + g_matWorld._14*g_matProjection._42; matTemp._13 = g_matWorld._11*g_matProjection._13 + g_matWorld._12*g_matProjection._23 + g_matWorld._13*g_matProjection._33 + g_matWorld._14*g_matProjection._43; matTemp._14 = g_matWorld._11*g_matProjection._14 + g_matWorld._12*g_matProjection._24 + g_matWorld._13*g_matProjection._34 + g_matWorld._14*g_matProjection._44; matTemp._21 = g_matWorld._21*g_matProjection._11 + g_matWorld._22*g_matProjection._21 + g_matWorld._23*g_matProjection._31 + g_matWorld._24*g_matProjection._41; matTemp._22 = g_matWorld._21*g_matProjection._12 + g_matWorld._22*g_matProjection._22 + g_matWorld._23*g_matProjection._32 + g_matWorld._24*g_matProjection._42; matTemp._23 = g_matWorld._21*g_matProjection._13 + g_matWorld._22*g_matProjection._23 + g_matWorld._23*g_matProjection._33 + g_matWorld._24*g_matProjection._43; matTemp._24 = g_matWorld._21*g_matProjection._14 + g_matWorld._22*g_matProjection._24 + g_matWorld._23*g_matProjection._34 + g_matWorld._24*g_matProjection._44; matTemp._31 = g_matWorld._31*g_matProjection._11 + g_matWorld._32*g_matProjection._21 + g_matWorld._33*g_matProjection._31 + g_matWorld._34*g_matProjection._41; matTemp._32 = g_matWorld._31*g_matProjection._12 + g_matWorld._32*g_matProjection._22 + g_matWorld._33*g_matProjection._32 + g_matWorld._34*g_matProjection._42; matTemp._33 = g_matWorld._31*g_matProjection._13 + g_matWorld._32*g_matProjection._23 + g_matWorld._33*g_matProjection._33 + g_matWorld._34*g_matProjection._43; matTemp._34 = g_matWorld._31*g_matProjection._14 + g_matWorld._32*g_matProjection._24 + g_matWorld._33*g_matProjection._34 + g_matWorld._34*g_matProjection._44; matTemp._41 = g_matWorld._41*g_matProjection._11 + g_matWorld._42*g_matProjection._21 + g_matWorld._43*g_matProjection._31 + g_matWorld._44*g_matProjection._41; matTemp._42 = g_matWorld._41*g_matProjection._12 + g_matWorld._42*g_matProjection._22 + g_matWorld._43*g_matProjection._32 + g_matWorld._44*g_matProjection._42; matTemp._43 = g_matWorld._41*g_matProjection._13 + g_matWorld._42*g_matProjection._23 + g_matWorld._43*g_matProjection._33 + g_matWorld._44*g_matProjection._43; matTemp._44 = g_matWorld._41*g_matProjection._14 + g_matWorld._42*g_matProjection._24 + g_matWorld._43*g_matProjection._34 + g_matWorld._44*g_matProjection._44; // Now make up the matrices. #if 0 // Officially correct version. DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_viewData.dwHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_viewData.dwY; #else // Version that knows about the letterbox mode hack. extern DWORD g_dw3DStuffHeight; extern DWORD g_dw3DStuffY; DWORD dwWidth = g_viewData.dwWidth >> 1; DWORD dwHeight = g_dw3DStuffHeight >> 1; DWORD dwX = g_viewData.dwX; DWORD dwY = g_dw3DStuffY; #endif MM_pMatrix[0]._11 = 0.0f; MM_pMatrix[0]._12 = matTemp._11 * (float)dwWidth + matTemp._14 * (float)( dwX + dwWidth ); MM_pMatrix[0]._13 = matTemp._12 * - (float)dwHeight + matTemp._14 * (float)( dwY + dwHeight ); MM_pMatrix[0]._14 = matTemp._14; MM_pMatrix[0]._21 = 0.0f; MM_pMatrix[0]._22 = matTemp._21 * (float)dwWidth + matTemp._24 * (float)( dwX + dwWidth ); MM_pMatrix[0]._23 = matTemp._22 * - (float)dwHeight + matTemp._24 * (float)( dwY + dwHeight ); MM_pMatrix[0]._24 = matTemp._24; MM_pMatrix[0]._31 = 0.0f; MM_pMatrix[0]._32 = matTemp._31 * (float)dwWidth + matTemp._34 * (float)( dwX + dwWidth ); MM_pMatrix[0]._33 = matTemp._32 * - (float)dwHeight + matTemp._34 * (float)( dwY + dwHeight ); MM_pMatrix[0]._34 = matTemp._34; // Validation magic number. unsigned long EVal = 0xe0001000; MM_pMatrix[0]._41 = *(float *)&EVal; MM_pMatrix[0]._42 = matTemp._41 * (float)dwWidth + matTemp._44 * (float)( dwX + dwWidth ); MM_pMatrix[0]._43 = matTemp._42 * - (float)dwHeight + matTemp._44 * (float)( dwY + dwHeight ); MM_pMatrix[0]._44 = matTemp._44; // 251 is a magic number for the DIP call! const float fNormScale = 251.0f; // Transform the lighting direction(s) by the inverse object matrix to get it into object space. // Assume inverse=transpose. D3DVECTOR vTemp; vTemp.x = MM_vLightDir.x * fmatrix[0] + MM_vLightDir.y * fmatrix[3] + MM_vLightDir.z * fmatrix[6]; vTemp.y = MM_vLightDir.x * fmatrix[1] + MM_vLightDir.y * fmatrix[4] + MM_vLightDir.z * fmatrix[7]; vTemp.z = MM_vLightDir.x * fmatrix[2] + MM_vLightDir.y * fmatrix[5] + MM_vLightDir.z * fmatrix[8]; MM_pNormal[0] = 0.0f; MM_pNormal[1] = vTemp.x * fNormScale; MM_pNormal[2] = vTemp.y * fNormScale; MM_pNormal[3] = vTemp.z * fNormScale; LOG_EXIT ( Figure_Build_Matrices ) } // The wonderful NEW system! LOG_ENTER ( Figure_Draw_Polys ) #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, FALSE ); #endif // For now, just calculate as-and-when. TomsPrimObject *pPrimObj = &(D3DObj[prim]); if ( pPrimObj->wNumMaterials == 0 ) { // Not initialised. Do so. // It's not fair to count this as part of the drawing! :-) LOG_EXIT ( Figure_Draw_Polys ) FIGURE_generate_D3D_object ( prim ); LOG_ENTER ( Figure_Draw_Polys ) } // Tell the LRU cache we used this one. FIGURE_touch_LRU_of_object ( pPrimObj ); ASSERT ( pPrimObj->pD3DVertices != NULL ); ASSERT ( pPrimObj->pMaterials != NULL ); ASSERT ( pPrimObj->pwListIndices != NULL ); ASSERT ( pPrimObj->pwStripIndices != NULL ); ASSERT ( pPrimObj->wNumMaterials != 0 ); PrimObjectMaterial *pMat = pPrimObj->pMaterials; D3DMULTIMATRIX d3dmm; d3dmm.lpd3dMatrices = MM_pMatrix; d3dmm.lpvLightDirs = MM_pNormal; D3DVERTEX *pVertex = (D3DVERTEX *)pPrimObj->pD3DVertices; UWORD *pwListIndices = pPrimObj->pwListIndices; UWORD *pwStripIndices = pPrimObj->pwStripIndices; for ( int iMatNum = pPrimObj->wNumMaterials; iMatNum > 0; iMatNum-- ) { // Set up the right texture for this material. UWORD wPage = pMat->wTexturePage; UWORD wRealPage = wPage & TEXTURE_PAGE_MASK; if ( wPage & TEXTURE_PAGE_FLAG_JACKET ) { // Find the real jacket page. wRealPage = jacket_lookup [ wRealPage ][GET_SKILL(p_thing)>>2]; wRealPage += FACE_PAGE_OFFSET; } else if ( wPage & TEXTURE_PAGE_FLAG_OFFSET ) { // An "offset" texture. This will be offset by a certain amount to // allow each prim to have different coloured clothes on. if ( tex_page_offset == 0 ) { // No lookup offset. // This has not been offset yet. wRealPage += FACE_PAGE_OFFSET; } else { // Look this up. wRealPage = alt_texture[wRealPage-(10*64)]+tex_page_offset-1; } } #ifdef DEBUG if ( wPage & TEXTURE_PAGE_FLAG_NOT_TEXTURED ) { ASSERT ( wRealPage == POLY_PAGE_COLOUR ); } #endif extern D3DMATRIX g_matWorld; PolyPage *pa = &(POLY_Page[wRealPage]); // Not sure if I'm using character_scalef correctly... ASSERT ( ( character_scalef < 1.2f ) && ( character_scalef > 0.8f ) ); ASSERT ( !pa->RS.NeedsSorting() && ( FIGURE_alpha == 255 ) ); if ( ( ( ( g_matWorld._43 * 32768.0f ) - ( pPrimObj->fBoundingSphereRadius * character_scalef ) ) > ( POLY_ZCLIP_PLANE * 32768.0f ) ) ) { // Non-alpha path. if ( wPage & TEXTURE_PAGE_FLAG_TINT ) { // Tinted colours. d3dmm.lpLightTable = MM_pcFadeTableTint; } else { // Normal. d3dmm.lpLightTable = MM_pcFadeTable; } d3dmm.lpvVertices = pVertex; #if 1 #ifdef DEBUG static int iCounter = 0; if ( iCounter != 0 ) { iCounter--; ASSERT ( iCounter != 0 ); } #endif // Fast as lightning. LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) #if 0 HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); //TRACE("Drew %i vertices, %i indices\n", (int)( pMat->wNumVertices ), (int)( pMat->wNumStripIndices ) ); #else // Use platform-independent version. HRESULT hres; #define SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB defined #ifdef SHOW_ME_FIGURE_DEBUGGING_PLEASE_BOB #ifdef DEBUG #ifdef TARGET_DC #define BUTTON_IS_PRESSED(value) ((value&0x80)!=0) extern DIJOYSTATE the_state; bool bShowDebug = FALSE; if ( BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_LTRIGGER] ) && BUTTON_IS_PRESSED ( the_state.rgbButtons[DI_DC_BUTTON_RTRIGGER] ) ) { DWORD dwColour = (DWORD)pwStripIndices; dwColour = ( dwColour >> 2 ) ^ ( dwColour >> 6 ) ^ ( dwColour ) ^ ( dwColour << 3 ); dwColour = ( dwColour << 9 ) ^ ( dwColour << 19 ) ^ ( dwColour ) ^ ( dwColour << 29 ) ^ ( dwColour >> 3 ); dwColour &= 0x7f7f7f7f; for ( int i = 0; i < 128; i++ ) { d3dmm.lpLightTable[i] = dwColour; } // And NULL texture (i.e. white). the_display.lp_D3D_Device->SetTexture ( 0, NULL ); } #endif #endif #endif //if (pMat->wNumVertices && // pMat->wNumStripIndices) { //TRACE ( "S4" ); hres = DrawIndPrimMM ( (the_display.lp_D3D_Device), D3DFVF_VERTEX, &d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices ); //TRACE ( "F4" ); } #endif #else // Do some performance tracing. #ifndef DTRACE #error Don't use this codepath unless DTRACING, fool! #endif LOG_ENTER ( Figure_Set_RenderState ) pa->RS.SetRenderState ( D3DRENDERSTATE_CULLMODE, D3DCULL_CCW ); pa->RS.SetRenderState ( D3DRENDERSTATE_ALPHABLENDENABLE, FALSE ); pa->RS.SetRenderState ( D3DRENDERSTATE_TEXTUREMAPBLEND, D3DTBLEND_MODULATEALPHA ); pa->RS.SetChanged(); WORD wTempVerts[4]; wTempVerts[0] = 0; wTempVerts[1] = 1; wTempVerts[2] = 2; wTempVerts[3] = -1; (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, 3, wTempVerts, 4, D3DDP_MULTIMATRIX ); LOG_EXIT ( Figure_Set_RenderState ) LOG_ENTER ( Figure_DrawIndPrimMM ) HRESULT hres = (the_display.lp_D3D_Device)->DrawIndexedPrimitive ( D3DPT_TRIANGLELIST, D3DFVF_VERTEX, (void *)&d3dmm, pMat->wNumVertices, pwStripIndices, pMat->wNumStripIndices, D3DDP_MULTIMATRIX ); //TRACE("Drew %i vertices, %i indices\n", (int)( pMat->wNumVertices ), (int)( pMat->wNumStripIndices ) ); #endif // ASSERT ( SUCCEEDED ( hres ) ); //triggers all the time when inside on start of RTA LOG_EXIT ( Figure_DrawIndPrimMM ) } else { // Alpha/clipped path - do with standard non-MM calls. // FIXME. Needs to be done. // Actually, the fast-accept works very well, and it's only when the camera somehow gets REALLY close // that this happens. And actually a pop-reject seems a bit better than a clip. Certainly // there is no visually "right" thing to do. So leave it for now until someone complains. ATF. //TRACE ( "Tried to draw an alpha/clipped prim!" ); } // Next material pVertex += pMat->wNumVertices; pwListIndices += pMat->wNumListIndices; pwStripIndices += pMat->wNumStripIndices; pMat++; } #if 1 // The MM stuff doesn't like specular to be enabled. (the_display.lp_D3D_Device)->SetRenderState ( D3DRENDERSTATE_SPECULARENABLE, TRUE ); #endif LOG_EXIT ( Figure_Draw_Polys ) // No environment mapping. ASSERT ( p_thing && ( p_thing->Class != CLASS_VEHICLE ) ); ASSERT ( MM_bLightTableAlreadySetUp ); LOG_EXIT ( Figure_Draw_Prim_Tween ) }
25.609039
177
0.630322
[ "mesh", "render", "object", "vector", "transform", "3d" ]
d4cd61b4a1fb806f3fb23380a1b59ebeedd4a615
5,080
cpp
C++
src/QtAIV/AIV/nAutoFilterEditorPopup.cpp
Vladimir-Lin/QtAIV
a96b52a1df9c85dbadfc1dfcfc38d60948462c89
[ "MIT" ]
null
null
null
src/QtAIV/AIV/nAutoFilterEditorPopup.cpp
Vladimir-Lin/QtAIV
a96b52a1df9c85dbadfc1dfcfc38d60948462c89
[ "MIT" ]
null
null
null
src/QtAIV/AIV/nAutoFilterEditorPopup.cpp
Vladimir-Lin/QtAIV
a96b52a1df9c85dbadfc1dfcfc38d60948462c89
[ "MIT" ]
null
null
null
#include <qtaiv.h> N::AutoFilterEditorPopup:: AutoFilterEditorPopup (QWidget * parent,Plan * p) : FilterEditorPopupWidget ( parent, p) { m_progress = new QProgressDialog(this); m_progress->setMaximum(100); m_mode = 0; // 0 = Selected values 1 = empty 2 = not empty QVBoxLayout* l = new QVBoxLayout(); l->setContentsMargins(6, 6, 6, 6); QVBoxLayout* lb = new QVBoxLayout(); lb->setSpacing(3); m_emptyToolButton = new QToolButton(this); m_emptyToolButton->setText(tr("Empty")); m_emptyToolButton->setAutoRaise(true); m_emptyToolButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); lb->addWidget(m_emptyToolButton); connect(m_emptyToolButton, SIGNAL(clicked()), this, SLOT(emptyToolButtonClicked())); m_notEmptyToolButton = new QToolButton(this); m_notEmptyToolButton->setText(tr("Not Empty")); m_notEmptyToolButton->setAutoRaise(true); m_notEmptyToolButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); lb->addWidget(m_notEmptyToolButton); l->addLayout(lb); connect(m_notEmptyToolButton, SIGNAL(clicked()), this, SLOT(notEmptyToolButtonClicked())); QFrame* f = new QFrame(this); f->setFrameShape(QFrame::HLine); f->setFrameShadow(QFrame::Sunken); l->addWidget(f); m_lineEdit = new LineEdit(this,plan); m_lineEdit->setMinimumWidth(200); m_lineEdit->setPlaceholderText(tr("Search for")); connect(m_lineEdit, SIGNAL(textEdited(QString)), this, SLOT(searchForTextEdited(QString))); l->addWidget(m_lineEdit); m_listView = new ListView(this,plan); l->addWidget(m_listView); setLayout(l); m_checkStateProxy = new CheckStateProxyModel(this); connect(m_checkStateProxy, SIGNAL(dataChanged(QModelIndex, QModelIndex)), this, SLOT(checkStateProxyDataChanged(QModelIndex, QModelIndex))); m_singleColumnProxy = new SingleColumnProxyModel(this); m_singleValueProxy = new UniqueValuesProxyModel(this); connect(m_singleValueProxy, SIGNAL(progressChanged(int)), this, SLOT(uniqueValueModelProgressChanged(int))); m_singleValueProxy->setEmptyItemsAllowed(false); m_singleColumnProxy->setSourceModel(m_singleValueProxy); m_checkStateProxy->setSourceModel(m_singleColumnProxy); m_listView->setModel(m_checkStateProxy); m_selectCheckBox = new QCheckBox(this); m_selectCheckBox->setText(tr("Select/Deselect all")); m_selectCheckBox->setTristate(true); m_selectCheckBox->installEventFilter(parent); connect(m_selectCheckBox, SIGNAL(stateChanged(int)), this, SLOT(selectCheckBoxStateChanged(int))); l->addWidget(m_selectCheckBox); m_listView->setEditTriggers(QAbstractItemView::NoEditTriggers); m_listView->installEventFilter(parent); } N::AutoFilterEditorPopup::~AutoFilterEditorPopup() { } void N::AutoFilterEditorPopup::checkStateProxyDataChanged(const QModelIndex & topLeft, const QModelIndex & bottomRight) { Q_UNUSED(topLeft); Q_UNUSED(bottomRight); m_selectCheckBox->blockSignals(true); if (m_checkStateProxy->checkedIndexes().size() == 0){ m_selectCheckBox->setCheckState(Qt::Unchecked); } else if(m_checkStateProxy->checkedIndexes().size() == (m_checkStateProxy->checkableColumnsCount() * m_checkStateProxy->rowCount())){ m_selectCheckBox->setCheckState(Qt::Checked); } else { m_selectCheckBox->setCheckState(Qt::PartiallyChecked); } m_selectCheckBox->blockSignals(false); } void N::AutoFilterEditorPopup::emptyToolButtonClicked() { m_mode = 1; emit modeChanged(); } int N::AutoFilterEditorPopup::mode() const { return m_mode; } void N::AutoFilterEditorPopup::notEmptyToolButtonClicked() { m_mode = 2; emit modeChanged(); } void N::AutoFilterEditorPopup::searchForTextEdited(const QString & text) { QModelIndexList mIndexes = m_checkStateProxy->match(m_checkStateProxy->index(0,0), Qt::DisplayRole, text); if (!mIndexes.isEmpty()){ m_listView->setCurrentIndex(mIndexes.first()); } } void N::AutoFilterEditorPopup::selectCheckBoxStateChanged(int state) { if (state == Qt::Checked){ m_checkStateProxy->setAllChecked(true); } else if (state == Qt::Unchecked){ m_checkStateProxy->setAllChecked(false); } else if (state == Qt::PartiallyChecked){ m_selectCheckBox->setChecked(true); } } QVariantList N::AutoFilterEditorPopup::selectedValues(int role) const { QVariantList v; Q_FOREACH(QModelIndex mIndex, m_checkStateProxy->checkedIndexes()){ v.append(mIndex.data(role)); } return v; } void N::AutoFilterEditorPopup::setSelectedValues(const QVariantList & values) { m_checkStateProxy->setCheckedValues(0, values); } void N::AutoFilterEditorPopup::setSourceModel(QAbstractItemModel *model, int column) { m_singleValueProxy->setModelColumn(column); m_singleValueProxy->setSourceModel(model); m_singleColumnProxy->setSourceModelColumn(column); m_singleColumnProxy->sort(0); m_checkStateProxy->setColumnCheckable(0); } void N::AutoFilterEditorPopup::uniqueValueModelProgressChanged(int progress) { m_progress->setValue(progress); }
34.09396
148
0.746654
[ "model" ]
d4cf79d1a3bfe4d5b033cca5efdbf4ee280637d5
3,154
cpp
C++
deps/libgeos/geos/src/triangulate/IncrementalDelaunayTriangulator.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
deps/libgeos/geos/src/triangulate/IncrementalDelaunayTriangulator.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
29
2021-06-03T14:24:01.000Z
2022-03-23T15:43:58.000Z
deps/libgeos/geos/src/triangulate/IncrementalDelaunayTriangulator.cpp
khrushjing/node-gdal-async
6546b0c8690f2db677d5385b40b407523503b314
[ "Apache-2.0" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2012 Excensus LLC. * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * ********************************************************************** * * Last port: triangulate/IncrementalDelaunayTriangulator.java rev. r524 * **********************************************************************/ #include <geos/triangulate/IncrementalDelaunayTriangulator.h> #include <geos/triangulate/quadedge/QuadEdge.h> #include <geos/triangulate/quadedge/QuadEdgeSubdivision.h> #include <geos/triangulate/quadedge/LocateFailureException.h> namespace geos { namespace triangulate { //geos.triangulate using namespace quadedge; IncrementalDelaunayTriangulator::IncrementalDelaunayTriangulator( QuadEdgeSubdivision* p_subdiv) : subdiv(p_subdiv), isUsingTolerance(p_subdiv->getTolerance() > 0.0) { } void IncrementalDelaunayTriangulator::insertSites(const VertexList& vertices) { for(const auto& vertex : vertices) { insertSite(vertex); } } QuadEdge& IncrementalDelaunayTriangulator::insertSite(const Vertex& v) { /* * This code is based on Guibas and Stolfi (1985), with minor modifications * and a bug fix from Dani Lischinski (Graphic Gems 1993). (The modification * I believe is the test for the inserted site falling exactly on an * existing edge. Without this test zero-width triangles have been observed * to be created) */ QuadEdge* e = subdiv->locate(v); if(!e) { throw LocateFailureException("Could not locate vertex."); } if(subdiv->isVertexOfEdge(*e, v)) { // point is already in subdivision. return *e; } else if(subdiv->isOnEdge(*e, v.getCoordinate())) { // the point lies exactly on an edge, so delete the edge // (it will be replaced by a pair of edges which have the point as a vertex) e = &e->oPrev(); subdiv->remove(e->oNext()); } /* * Connect the new point to the vertices of the containing triangle * (or quadrilateral, if the new point fell on an existing edge.) */ QuadEdge* base = &subdiv->makeEdge(e->orig(), v); QuadEdge::splice(*base, *e); QuadEdge* startEdge = base; do { base = &subdiv->connect(*e, base->sym()); e = &base->oPrev(); } while(&e->lNext() != startEdge); // Examine suspect edges to ensure that the Delaunay condition // is satisfied. for(;;) { QuadEdge* t = &e->oPrev(); if(t->dest().rightOf(*e) && v.isInCircle(e->orig(), t->dest(), e->dest())) { QuadEdge::swap(*e); e = &e->oPrev(); } else if(&e->oNext() == startEdge) { return *base; // no more suspect edges. } else { e = &e->oNext().lPrev(); } } } } //namespace geos.triangulate } //namespace goes
29.476636
84
0.594483
[ "geometry" ]
d4d0e6eb09cff4af698e17938d7e5c97a50699da
16,748
cpp
C++
Source/WebCore/bindings/scripts/test/JS/JSTestEventTarget.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestEventTarget.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Source/WebCore/bindings/scripts/test/JS/JSTestEventTarget.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* This file is part of the WebKit open source project. This file has been generated by generate-bindings.pl. DO NOT MODIFY! This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "JSTestEventTarget.h" #include "ActiveDOMObject.h" #include "DOMIsoSubspaces.h" #include "JSDOMAbstractOperations.h" #include "JSDOMBinding.h" #include "JSDOMConstructorNotConstructable.h" #include "JSDOMConvertInterface.h" #include "JSDOMConvertNumbers.h" #include "JSDOMExceptionHandling.h" #include "JSDOMGlobalObject.h" #include "JSDOMOperation.h" #include "JSDOMWrapperCache.h" #include "JSNode.h" #include "ScriptExecutionContext.h" #include "WebCoreJSClientData.h" #include <JavaScriptCore/HeapAnalyzer.h> #include <JavaScriptCore/JSCInlines.h> #include <JavaScriptCore/JSDestructibleObjectHeapCellType.h> #include <JavaScriptCore/PropertyNameArray.h> #include <JavaScriptCore/SubspaceInlines.h> #include <wtf/GetPtr.h> #include <wtf/PointerPreparations.h> #include <wtf/URL.h> namespace WebCore { using namespace JSC; // Functions JSC::EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionItem(JSC::JSGlobalObject*, JSC::CallFrame*); // Attributes JSC::EncodedJSValue jsTestEventTargetConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::PropertyName); bool setJSTestEventTargetConstructor(JSC::JSGlobalObject*, JSC::EncodedJSValue, JSC::EncodedJSValue); class JSTestEventTargetPrototype final : public JSC::JSNonFinalObject { public: using Base = JSC::JSNonFinalObject; static JSTestEventTargetPrototype* create(JSC::VM& vm, JSDOMGlobalObject* globalObject, JSC::Structure* structure) { JSTestEventTargetPrototype* ptr = new (NotNull, JSC::allocateCell<JSTestEventTargetPrototype>(vm.heap)) JSTestEventTargetPrototype(vm, globalObject, structure); ptr->finishCreation(vm); return ptr; } DECLARE_INFO; template<typename CellType, JSC::SubspaceAccess> static JSC::IsoSubspace* subspaceFor(JSC::VM& vm) { STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestEventTargetPrototype, Base); return &vm.plainObjectSpace; } static JSC::Structure* createStructure(JSC::VM& vm, JSC::JSGlobalObject* globalObject, JSC::JSValue prototype) { return JSC::Structure::create(vm, globalObject, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), info()); } private: JSTestEventTargetPrototype(JSC::VM& vm, JSC::JSGlobalObject*, JSC::Structure* structure) : JSC::JSNonFinalObject(vm, structure) { } void finishCreation(JSC::VM&); }; STATIC_ASSERT_ISO_SUBSPACE_SHARABLE(JSTestEventTargetPrototype, JSTestEventTargetPrototype::Base); using JSTestEventTargetConstructor = JSDOMConstructorNotConstructable<JSTestEventTarget>; template<> JSValue JSTestEventTargetConstructor::prototypeForStructure(JSC::VM& vm, const JSDOMGlobalObject& globalObject) { return JSEventTarget::getConstructor(vm, &globalObject); } template<> void JSTestEventTargetConstructor::initializeProperties(VM& vm, JSDOMGlobalObject& globalObject) { putDirect(vm, vm.propertyNames->prototype, JSTestEventTarget::prototype(vm, globalObject), JSC::PropertyAttribute::DontDelete | JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->name, jsNontrivialString(vm, "TestEventTarget"_s), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); putDirect(vm, vm.propertyNames->length, jsNumber(0), JSC::PropertyAttribute::ReadOnly | JSC::PropertyAttribute::DontEnum); } template<> const ClassInfo JSTestEventTargetConstructor::s_info = { "TestEventTarget", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestEventTargetConstructor) }; /* Hash table for prototype */ static const HashTableValue JSTestEventTargetPrototypeTableValues[] = { { "constructor", static_cast<unsigned>(JSC::PropertyAttribute::DontEnum), NoIntrinsic, { (intptr_t)static_cast<PropertySlot::GetValueFunc>(jsTestEventTargetConstructor), (intptr_t) static_cast<PutPropertySlot::PutValueFunc>(setJSTestEventTargetConstructor) } }, { "item", static_cast<unsigned>(JSC::PropertyAttribute::Function), NoIntrinsic, { (intptr_t)static_cast<RawNativeFunction>(jsTestEventTargetPrototypeFunctionItem), (intptr_t) (1) } }, }; const ClassInfo JSTestEventTargetPrototype::s_info = { "TestEventTarget", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestEventTargetPrototype) }; void JSTestEventTargetPrototype::finishCreation(VM& vm) { Base::finishCreation(vm); reifyStaticProperties(vm, JSTestEventTarget::info(), JSTestEventTargetPrototypeTableValues, *this); JSC_TO_STRING_TAG_WITHOUT_TRANSITION(); } const ClassInfo JSTestEventTarget::s_info = { "TestEventTarget", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(JSTestEventTarget) }; JSTestEventTarget::JSTestEventTarget(Structure* structure, JSDOMGlobalObject& globalObject, Ref<TestEventTarget>&& impl) : JSEventTarget(structure, globalObject, WTFMove(impl)) { } void JSTestEventTarget::finishCreation(VM& vm) { Base::finishCreation(vm); ASSERT(inherits(vm, info())); static_assert(!std::is_base_of<ActiveDOMObject, TestEventTarget>::value, "Interface is not marked as [ActiveDOMObject] even though implementation class subclasses ActiveDOMObject."); } JSObject* JSTestEventTarget::createPrototype(VM& vm, JSDOMGlobalObject& globalObject) { return JSTestEventTargetPrototype::create(vm, &globalObject, JSTestEventTargetPrototype::createStructure(vm, &globalObject, JSEventTarget::prototype(vm, globalObject))); } JSObject* JSTestEventTarget::prototype(VM& vm, JSDOMGlobalObject& globalObject) { return getDOMPrototype<JSTestEventTarget>(vm, globalObject); } JSValue JSTestEventTarget::getConstructor(VM& vm, const JSGlobalObject* globalObject) { return getDOMConstructor<JSTestEventTargetConstructor>(vm, *jsCast<const JSDOMGlobalObject*>(globalObject)); } bool JSTestEventTarget::getOwnPropertySlot(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyName propertyName, PropertySlot& slot) { auto* thisObject = jsCast<JSTestEventTarget*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (auto index = parseIndex(propertyName)) { if (index.value() < thisObject->wrapped().length()) { auto value = toJS<IDLInterface<Node>>(*lexicalGlobalObject, *thisObject->globalObject(), thisObject->wrapped().item(index.value())); slot.setValue(thisObject, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly), value); return true; } return JSObject::getOwnPropertySlot(object, lexicalGlobalObject, propertyName, slot); } using GetterIDLType = IDLInterface<Node>; auto getterFunctor = [] (auto& thisObject, auto propertyName) -> Optional<typename GetterIDLType::ImplementationType> { auto result = thisObject.wrapped().namedItem(propertyNameToAtomString(propertyName)); if (!GetterIDLType::isNullValue(result)) return typename GetterIDLType::ImplementationType { GetterIDLType::extractValueFromNullable(result) }; return WTF::nullopt; }; if (auto namedProperty = accessVisibleNamedProperty<OverrideBuiltins::No>(*lexicalGlobalObject, *thisObject, propertyName, getterFunctor)) { auto value = toJS<IDLInterface<Node>>(*lexicalGlobalObject, *thisObject->globalObject(), WTFMove(namedProperty.value())); slot.setValue(thisObject, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly), value); return true; } return JSObject::getOwnPropertySlot(object, lexicalGlobalObject, propertyName, slot); } bool JSTestEventTarget::getOwnPropertySlotByIndex(JSObject* object, JSGlobalObject* lexicalGlobalObject, unsigned index, PropertySlot& slot) { VM& vm = JSC::getVM(lexicalGlobalObject); auto* thisObject = jsCast<JSTestEventTarget*>(object); ASSERT_GC_OBJECT_INHERITS(thisObject, info()); if (LIKELY(index <= MAX_ARRAY_INDEX)) { if (index < thisObject->wrapped().length()) { auto value = toJS<IDLInterface<Node>>(*lexicalGlobalObject, *thisObject->globalObject(), thisObject->wrapped().item(index)); slot.setValue(thisObject, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly), value); return true; } return JSObject::getOwnPropertySlotByIndex(object, lexicalGlobalObject, index, slot); } auto propertyName = Identifier::from(vm, index); using GetterIDLType = IDLInterface<Node>; auto getterFunctor = [] (auto& thisObject, auto propertyName) -> Optional<typename GetterIDLType::ImplementationType> { auto result = thisObject.wrapped().namedItem(propertyNameToAtomString(propertyName)); if (!GetterIDLType::isNullValue(result)) return typename GetterIDLType::ImplementationType { GetterIDLType::extractValueFromNullable(result) }; return WTF::nullopt; }; if (auto namedProperty = accessVisibleNamedProperty<OverrideBuiltins::No>(*lexicalGlobalObject, *thisObject, propertyName, getterFunctor)) { auto value = toJS<IDLInterface<Node>>(*lexicalGlobalObject, *thisObject->globalObject(), WTFMove(namedProperty.value())); slot.setValue(thisObject, static_cast<unsigned>(JSC::PropertyAttribute::ReadOnly), value); return true; } return JSObject::getOwnPropertySlotByIndex(object, lexicalGlobalObject, index, slot); } void JSTestEventTarget::getOwnPropertyNames(JSObject* object, JSGlobalObject* lexicalGlobalObject, PropertyNameArray& propertyNames, EnumerationMode mode) { VM& vm = JSC::getVM(lexicalGlobalObject); auto* thisObject = jsCast<JSTestEventTarget*>(object); ASSERT_GC_OBJECT_INHERITS(object, info()); for (unsigned i = 0, count = thisObject->wrapped().length(); i < count; ++i) propertyNames.add(Identifier::from(vm, i)); for (auto& propertyName : thisObject->wrapped().supportedPropertyNames()) propertyNames.add(Identifier::fromString(vm, propertyName)); JSObject::getOwnPropertyNames(object, lexicalGlobalObject, propertyNames, mode); } template<> inline JSTestEventTarget* IDLOperation<JSTestEventTarget>::cast(JSGlobalObject& lexicalGlobalObject, CallFrame& callFrame) { return jsDynamicCast<JSTestEventTarget*>(JSC::getVM(&lexicalGlobalObject), callFrame.thisValue()); } EncodedJSValue jsTestEventTargetConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, PropertyName) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestEventTargetPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) return throwVMTypeError(lexicalGlobalObject, throwScope); return JSValue::encode(JSTestEventTarget::getConstructor(JSC::getVM(lexicalGlobalObject), prototype->globalObject())); } bool setJSTestEventTargetConstructor(JSGlobalObject* lexicalGlobalObject, EncodedJSValue thisValue, EncodedJSValue encodedValue) { VM& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); auto* prototype = jsDynamicCast<JSTestEventTargetPrototype*>(vm, JSValue::decode(thisValue)); if (UNLIKELY(!prototype)) { throwVMTypeError(lexicalGlobalObject, throwScope); return false; } // Shadowing a built-in constructor return prototype->putDirect(vm, vm.propertyNames->constructor, JSValue::decode(encodedValue)); } static inline JSC::EncodedJSValue jsTestEventTargetPrototypeFunctionItemBody(JSC::JSGlobalObject* lexicalGlobalObject, JSC::CallFrame* callFrame, typename IDLOperation<JSTestEventTarget>::ClassParameter castedThis) { auto& vm = JSC::getVM(lexicalGlobalObject); auto throwScope = DECLARE_THROW_SCOPE(vm); UNUSED_PARAM(throwScope); UNUSED_PARAM(callFrame); auto& impl = castedThis->wrapped(); if (UNLIKELY(callFrame->argumentCount() < 1)) return throwVMError(lexicalGlobalObject, throwScope, createNotEnoughArgumentsError(lexicalGlobalObject)); EnsureStillAliveScope argument0 = callFrame->uncheckedArgument(0); auto index = convert<IDLUnsignedLong>(*lexicalGlobalObject, argument0.value()); RETURN_IF_EXCEPTION(throwScope, encodedJSValue()); RELEASE_AND_RETURN(throwScope, JSValue::encode(toJS<IDLInterface<Node>>(*lexicalGlobalObject, *castedThis->globalObject(), impl.item(WTFMove(index))))); } EncodedJSValue JSC_HOST_CALL jsTestEventTargetPrototypeFunctionItem(JSGlobalObject* lexicalGlobalObject, CallFrame* callFrame) { return IDLOperation<JSTestEventTarget>::call<jsTestEventTargetPrototypeFunctionItemBody>(*lexicalGlobalObject, *callFrame, "item"); } JSC::IsoSubspace* JSTestEventTarget::subspaceForImpl(JSC::VM& vm) { auto& clientData = *static_cast<JSVMClientData*>(vm.clientData); auto& spaces = clientData.subspaces(); if (auto* space = spaces.m_subspaceForTestEventTarget.get()) return space; static_assert(std::is_base_of_v<JSC::JSDestructibleObject, JSTestEventTarget> || !JSTestEventTarget::needsDestruction); if constexpr (std::is_base_of_v<JSC::JSDestructibleObject, JSTestEventTarget>) spaces.m_subspaceForTestEventTarget = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.destructibleObjectHeapCellType.get(), JSTestEventTarget); else spaces.m_subspaceForTestEventTarget = makeUnique<IsoSubspace> ISO_SUBSPACE_INIT(vm.heap, vm.cellHeapCellType.get(), JSTestEventTarget); auto* space = spaces.m_subspaceForTestEventTarget.get(); IGNORE_WARNINGS_BEGIN("unreachable-code") IGNORE_WARNINGS_BEGIN("tautological-compare") if (&JSTestEventTarget::visitOutputConstraints != &JSC::JSCell::visitOutputConstraints) clientData.outputConstraintSpaces().append(space); IGNORE_WARNINGS_END IGNORE_WARNINGS_END return space; } void JSTestEventTarget::analyzeHeap(JSCell* cell, HeapAnalyzer& analyzer) { auto* thisObject = jsCast<JSTestEventTarget*>(cell); analyzer.setWrappedObjectForCell(cell, &thisObject->wrapped()); if (thisObject->scriptExecutionContext()) analyzer.setLabelForCell(cell, "url " + thisObject->scriptExecutionContext()->url().string()); Base::analyzeHeap(cell, analyzer); } #if ENABLE(BINDING_INTEGRITY) #if PLATFORM(WIN) #pragma warning(disable: 4483) extern "C" { extern void (*const __identifier("??_7TestEventTarget@WebCore@@6B@")[])(); } #else extern "C" { extern void* _ZTVN7WebCore15TestEventTargetE[]; } #endif #endif JSC::JSValue toJSNewlyCreated(JSC::JSGlobalObject*, JSDOMGlobalObject* globalObject, Ref<TestEventTarget>&& impl) { #if ENABLE(BINDING_INTEGRITY) const void* actualVTablePointer = getVTablePointer(impl.ptr()); #if PLATFORM(WIN) void* expectedVTablePointer = __identifier("??_7TestEventTarget@WebCore@@6B@"); #else void* expectedVTablePointer = &_ZTVN7WebCore15TestEventTargetE[2]; #endif // If this fails TestEventTarget does not have a vtable, so you need to add the // ImplementationLacksVTable attribute to the interface definition static_assert(std::is_polymorphic<TestEventTarget>::value, "TestEventTarget is not polymorphic"); // If you hit this assertion you either have a use after free bug, or // TestEventTarget has subclasses. If TestEventTarget has subclasses that get passed // to toJS() we currently require TestEventTarget you to opt out of binding hardening // by adding the SkipVTableValidation attribute to the interface IDL definition RELEASE_ASSERT(actualVTablePointer == expectedVTablePointer); #endif return createWrapper<TestEventTarget>(globalObject, WTFMove(impl)); } JSC::JSValue toJS(JSC::JSGlobalObject* lexicalGlobalObject, JSDOMGlobalObject* globalObject, TestEventTarget& impl) { return wrap(lexicalGlobalObject, globalObject, impl); } TestEventTarget* JSTestEventTarget::toWrapped(JSC::VM& vm, JSC::JSValue value) { if (auto* wrapper = jsDynamicCast<JSTestEventTarget*>(vm, value)) return &wrapper->wrapped(); return nullptr; } }
48.126437
265
0.764509
[ "object" ]
d4d7d7b93001829c08f2f6c7cd963b42181b9023
4,130
inl
C++
cflw代码库/cflw工具.inl
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
9
2018-10-18T18:13:14.000Z
2021-07-21T19:55:56.000Z
cflw代码库/cflw工具.inl
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2020-08-18T02:07:09.000Z
2020-08-19T12:50:55.000Z
cflw代码库/cflw工具.inl
cflw/cflw_cpp
4d623480ae51b78ed8292fe689197f03aba85b75
[ "MIT" ]
1
2019-04-22T20:35:04.000Z
2019-04-22T20:35:04.000Z
#pragma once #include "cflw工具.h" #include <math.h> #include "cflw辅助.h" namespace cflw::工具 { //============================================================================== // 计值器 //============================================================================== template<typename t> void C计值器<t>::f清零() { m值数 = 0; } template<typename t> void C计值器<t>::f重置(t a) { m值数 = 0; m间隔 = a; } template<typename t> bool C计值器<t>::f滴答(t a) { m值数 += a; if (m值数 >= m间隔) { m值数 = 0; return true; } else { return false; } } //============================================================================== // 数字与文本的转换 //============================================================================== #define _文本转换模板(t1, t2, f) \ template<> t2 C文本::f转换<t1, t2>(t1 p); #define _文本转换模板_到文本(t, f) _文本转换模板(t, C文本::t字符串, f<t>) #define _文本转换模板_到数字(t, f) _文本转换模板(C文本::t字符串, t, f<t>) _文本转换模板_到文本(unsigned char, f整数_文本) _文本转换模板_到文本(unsigned long, f整数_文本) _文本转换模板_到文本(int, f整数_文本) _文本转换模板_到文本(long long, f整数_文本) _文本转换模板_到文本(float, f浮点数_文本) _文本转换模板_到文本(double, f浮点数_文本) _文本转换模板_到数字(unsigned char, f文本_整数) _文本转换模板_到数字(unsigned long, f文本_整数) _文本转换模板_到数字(int, f文本_整数) _文本转换模板_到数字(long long, f文本_整数) _文本转换模板_到数字(float, f文本_浮点数) _文本转换模板_到数字(double, f文本_浮点数) #undef _文本转换模板 #undef _文本转换模板_到文本 #undef _文本转换模板_到数字 template<typename t> C文本::t字符串 C文本::f整数_文本(t n) { wchar_t v[sizeof(t)*3] = L""; int v修改位 = 0; if (n < 0) { v[v修改位++] = L'-'; n = n * -1; } else if (n == 0) { return L"0"; } int v最高位 = (int)log10(n); while (v最高位 >= 0) { const t v指数 = (t)pow((t)10, v最高位); v[v修改位++] = (wchar_t)(L'0' + n / v指数); n = (n % v指数); v最高位 -= 1; } return {v}; } template<typename t> C文本::t字符串 C文本::f浮点数_文本(t n) { wchar_t v[sizeof(t)*3] = L""; int v有效数字 = sizeof(t) + 2; int v修改位 = 0; //取负号 if (n < 0) { v[v修改位++] = L'-'; n = n * -1; } else if (n == 0) { return L"0"; } int v当前位 = (int)log10(n); int v小数位 = 0; while (v有效数字) { const t v指数 = pow((t)10, v当前位); const t v指数2 = v指数 * 10; t v数字 = (n - floor(n / v指数2) * v指数2) / v指数; //补精度损失 v数字 += FLT_EPSILON; if (v数字 >= 10) { v数字 -= 10; } //写文本 v[v修改位++] = (wchar_t)(L'0' + v数字); if (v当前位 == 0) {//加小数 v小数位 = v修改位++; v[v小数位] = L'.'; } v当前位 -= 1; v有效数字 -= 1; } return {v}; } template<typename t> t C文本::f文本_整数(const t字符串 &s) { t v = 0; int v读取位 = 0; t v符号 = 1; //取负号 if (!辅助::fi无符号(v)) { if (s[v读取位] == L'-') { v符号 = (t)(-1); ++v读取位; } } //计算多少位 int v位数 = 0; while (s[v读取位] >= L'0' && s[v读取位] <= L'9') { ++v位数; ++v读取位; } //溢出判断 if (sizeof(t) * 8 * log10(2) < v位数) { throw; } //赋值 int v当前位 = 0; while (v当前位 < v位数) { v += (t)((s[--v读取位] - L'0') * pow((t)10, v当前位)); ++v当前位; } return v * v符号; } template<typename t> t C文本::f文本_浮点数(const t字符串 &s) { t v = 0; int v读取位 = 0; t v符号 = 1; //取负号 if (!辅助::fi无符号(v)) { if (s[v读取位] == L'-') { v符号 = -1; ++v读取位; } } //计算多少位 int v位数 = 0; int v有效数字 = sizeof(t) + 2; int v小数位置 = -1; while (v位数 <= v有效数字) { const wchar_t v读取字符 = s[v读取位]; if (v读取字符 >= L'0' && v读取字符 <= L'9') { ++v位数; } else if (v读取字符 == L'.') { v小数位置 = v位数; } else { break; } ++v读取位; } //赋值 int v当前位 = 0; while (v当前位 < v位数) { const wchar_t v读取字符 = s[--v读取位]; if (v读取字符 == L'.') { continue; } v += (v读取字符 - L'0') * (t)pow((t)10, v当前位); ++v当前位; } v *= (t)pow((t)10, v小数位置 - v位数); return v * v符号; } //============================================================================== // 空间 //============================================================================== template<typename t> C空间<t>::~C空间() { if (m指针 != nullptr) { delete[] m指针; } } template<typename t> t *C空间<t>::f分配(unsigned int p数量) { if (m分配数量 < p数量) { if (m指针 != nullptr) { delete[] m指针; } m分配数量 = p数量 * 2; m指针 = new t[m分配数量]; } m需要数量 = p数量; return m指针; } //============================================================================== // 树 //============================================================================== template<typename t> C树<t>::C节点::C节点(const t &a值, std::unique_ptr<std::vector<C节点>> &&a叶) : m值(a值), m叶(std::move(a叶)) { } } //namespace cflw::工具
21.510417
91
0.461501
[ "vector" ]
d4dc7d273d0ae5b33eba1e4a63083436af680792
1,039
cpp
C++
src/cppgomoku/policy_functions.cpp
gondhijagapathi/gomoku
572b13736629884e7b7adc5b983d87105734ded5
[ "MIT" ]
null
null
null
src/cppgomoku/policy_functions.cpp
gondhijagapathi/gomoku
572b13736629884e7b7adc5b983d87105734ded5
[ "MIT" ]
null
null
null
src/cppgomoku/policy_functions.cpp
gondhijagapathi/gomoku
572b13736629884e7b7adc5b983d87105734ded5
[ "MIT" ]
null
null
null
#include "cppgomoku/policy_functions.h" namespace pujitha { std::vector<MoveProbPair> rollout_policy_fn(Board &board) { int len = static_cast<int>(board.getAvailables().size()); std::vector<MoveProbPair> policy(len, MoveProbPair()); static std::random_device r; std::default_random_engine generator(r()); std::uniform_real_distribution<float> dist(0.0, 1.0); int index = 0; for (int m: board.getAvailables()) { policy[index].move = m; policy[index++].prob = dist(generator); } return policy; } std::vector<MoveProbPair> MCTS_Expand_policy_fn(Board &board) { int len = static_cast<int>(board.getAvailables().size()); float prob = 1.0 / len; std::vector<MoveProbPair> policy(len, MoveProbPair()); int index = 0; for (int m: board.getAvailables()) { policy[index].move = m; policy[index++].prob = prob; } return policy; } } // gomoku
28.081081
67
0.583253
[ "vector" ]
d4de93bfa97bf268dbee8b0664a584317d62c29d
1,970
cpp
C++
src/ttauri/stencils/pixel_map_stencil.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
src/ttauri/stencils/pixel_map_stencil.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
src/ttauri/stencils/pixel_map_stencil.cpp
jhalakpatel/ttauri
a05ed5db165645422348579cc4a949ef8ac205c7
[ "BSL-1.0" ]
null
null
null
// Copyright Take Vos 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt) #include "pixel_map_stencil.hpp" #include "../GUI/draw_context.hpp" #include "../codec/png.hpp" namespace tt { pixel_map_stencil::pixel_map_stencil(tt::alignment alignment, pixel_map<sfloat_rgba16> &&pixel_map) : image_stencil(alignment), _pixel_map(std::move(pixel_map)) { } pixel_map_stencil::pixel_map_stencil(tt::alignment alignment, pixel_map<sfloat_rgba16> const &pixel_map) : image_stencil(alignment), _pixel_map(pixel_map.copy()) { } pixel_map_stencil::pixel_map_stencil(tt::alignment alignment, URL const &url) : pixel_map_stencil(alignment, png::load(url)) {} void pixel_map_stencil::draw(draw_context context, tt::color color, matrix3 transform) noexcept { if (std::exchange(_data_is_modified, false)) { _backing = narrow_cast<gui_device_vulkan &>(context.device()).imagePipeline->makeImage(_pixel_map.width(), _pixel_map.height()); _backing.upload(_pixel_map); _size_is_modified = true; _position_is_modified = true; } auto layout_is_modified = std::exchange(_size_is_modified, false); layout_is_modified |= std::exchange(_position_is_modified, false); if (layout_is_modified) { _pixel_map_bounding_box = aarectangle{extent2{narrow_cast<float>(_backing.width_in_px), narrow_cast<float>(_backing.height_in_px)}}; _pixel_map_transform = matrix2::uniform(_pixel_map_bounding_box, _rectangle, _alignment); } switch (_backing.state) { case pipeline_image::Image::State::Drawing: context.window().request_redraw(aarectangle{context.transform() * context.clipping_rectangle()}); break; case pipeline_image::Image::State::Uploaded: context.draw_image(_backing, transform * _pixel_map_transform); break; default:; } } } // namespace tt
38.627451
129
0.73401
[ "transform" ]
d4e94de0ff9c9fb74a1e6f3b481febf99f37a78a
22,971
cpp
C++
src/amuse/community/secularmultiple/src/tides.cpp
rknop/amuse
85d5bdcc29cfc87dc69d91c264101fafd6658aec
[ "Apache-2.0" ]
131
2015-06-04T09:06:57.000Z
2022-02-01T12:11:29.000Z
src/amuse/community/secularmultiple/src/tides.cpp
rknop/amuse
85d5bdcc29cfc87dc69d91c264101fafd6658aec
[ "Apache-2.0" ]
690
2015-10-17T12:18:08.000Z
2022-03-31T16:15:58.000Z
src/amuse/community/secularmultiple/src/tides.cpp
rieder/amuse
3ac3b6b8f922643657279ddee5c8ab3fc0440d5e
[ "Apache-2.0" ]
102
2015-01-22T10:00:29.000Z
2022-02-09T13:29:43.000Z
/* */ #include "types.h" #include "tides.h" #include "newtonian.h" /* for orbital_period */ #include <stdio.h> double const MINIMUM_MASS_FOR_RADIATIVE_DAMPING_MSUN = 1.2; // in future: make user-adjustable int const MAIN_SEQUENCE = 1; int const CHeB = 4; int const HeMS = 7; int const HeWD = 10; /* start addition 13-09-2016 */ int const PreMS = 17; /* end addition 13-09-2016 */ bool check_for_radiative_damping(int stellar_type, double mass, double convective_envelope_mass, double convective_envelope_radius) { if ((stellar_type == MAIN_SEQUENCE) && (mass/CONST_MSUN >= MINIMUM_MASS_FOR_RADIATIVE_DAMPING_MSUN)) { return true; } else if ((stellar_type == CHeB) || (stellar_type == HeMS)) { return true; } else { return false; } } bool check_for_convective_damping(int stellar_type) { /* start addition 13-09-2016 */ if (stellar_type == PreMS) { return true; } /* end addition 13-09-2016 */ if (stellar_type < HeWD) { return true; } else { return false; } } double from_k_AM_div_T_to_t_V(double k_AM_div_T, double apsidal_motion_constant) { return c_3div2*(2.0*apsidal_motion_constant + 1.0)/k_AM_div_T; } double compute_t_V(Particle *star, Particle *companion, double semimajor_axis) { int tides_viscous_time_scale_prescription = star->tides_viscous_time_scale_prescription; double t_V = 1.0e10; /* large value by default, i.e. weak tides if tides_viscous_time_scale_prescription is not given the correct value */ if (tides_viscous_time_scale_prescription == 0) { t_V = star->tides_viscous_time_scale; } else if (tides_viscous_time_scale_prescription == 1) { t_V = compute_t_V_hurley ( star->stellar_type, star->mass, star->convective_envelope_mass, companion->mass, semimajor_axis, star->radius, star->convective_envelope_radius, star->luminosity, star->spin_vec_norm, star->tides_gyration_radius, star->tides_apsidal_motion_constant ); } return t_V; } double compute_t_V_hurley ( int stellar_type, double mass, double convective_envelope_mass, double companion_mass, double semimajor_axis, double radius, double convective_envelope_radius, double luminosity, double spin_angular_frequency, double gyration_radius, double apsidal_motion_constant ) { bool USE_RADIATIVE_DAMPING = check_for_radiative_damping(stellar_type,mass,convective_envelope_mass,convective_envelope_radius); bool USE_CONVECTIVE_DAMPING = check_for_convective_damping(stellar_type); double k_AM_div_T,t_V; if (USE_CONVECTIVE_DAMPING == true && ((convective_envelope_mass <= 0.0) || (convective_envelope_radius <= 0.0))) { //printf("to rad \n"); USE_RADIATIVE_DAMPING = true; } if (radius <= 0.0) { return 1.0e100; } //printf("stellar_type %d \n",stellar_type); //printf("USE_RADIATIVE_DAMPING %d \n",USE_RADIATIVE_DAMPING); //printf("USE_CONVECTIVE_DAMPING %d \n",USE_CONVECTIVE_DAMPING); if (USE_RADIATIVE_DAMPING == true) // radiative damping { double E2 = 1.592e-09*pow(mass/CONST_MSUN,2.84); // Hurley prescription; Zahn, 1977, A&A, 57, 383 and 1975, A&A, 41, 329 #ifdef IGNORE // Izzard's prescription not yet implemented else if(stardata->preferences->E2_prescription==E2_IZZARD) { if(stardata->star[star_number].stellar_type<HERTZSPRUNG_GAP) { double fburn=1.0; double x=stardata->star[star_number].aj/stardata->star[star_number].tms; if(x<fburn) { /* log mass and Z */ double logm=log10(stardata->star[star_number].mass); double logz=log10(stardata->common.metallicity); /* fits for am and E20 */ double am = 0.15*sin(3.2*logm)+0.31*logm; double E20 = -1.23250e+01+1.04550e+01*logm-4.15420e-01*logz-7.18650e+00*logm*logm+1.97940e+00*logm*logm*logm; E20=pow(10.0,E20); /* calc log(E2/E20) */ E2 = -pow(x+am,4.0)*pow(MAX(1,x/0.95),30.0); /* hence E2 */ E2 = E20 * pow(10.0,E2); /* verbosity */ /* if(star->starnum==1) { printf("E2 kw=%d I=%g (fburn=%g x=%g E20=%g) H=%g\n", star->stellar_type, E2, fburn,x, E20,E2_Hurley); } */ } else { /* no conv core */ E2=0.0; } } else { E2=0.0; } } #endif k_AM_div_T = E2*pow(1.0 + companion_mass/mass,5.0/6.0)*radius*sqrt(CONST_G*mass/(pow(semimajor_axis,5.0))); t_V = from_k_AM_div_T_to_t_V(k_AM_div_T,apsidal_motion_constant); return t_V; } else if (USE_CONVECTIVE_DAMPING == true) // convective damping { double P_orb = 2.0*M_PI*sqrt((semimajor_axis*semimajor_axis*semimajor_axis)/(CONST_G*(mass + companion_mass))); // printf("a %g\n",semimajor_axis); double P_spin,P_tid; if (spin_angular_frequency == 0.0) { P_tid = P_orb; } else { P_spin = 2.0*M_PI/spin_angular_frequency; P_tid = 1.0/( 1e-10 + fabs( 1.0/P_orb - 1.0/P_spin) ); } double tau_convective = pow( (convective_envelope_mass*convective_envelope_radius*(radius - (1.0/2.0)*convective_envelope_radius))/(3.0*luminosity), 1.0/3.0); //double tau_convective = pow( (convective_envelope_mass*radius*radius)/(3.0*luminosity), 1.0/3.0); // print 'tau',envelope_mass,envelope_mass*envelope_radius*(radius - (1.0/2.0)*envelope_radius)/(3.0*luminosity) double f_convective = pow(P_tid/(2.0*tau_convective),2.0); f_convective = min(1.0,f_convective); k_AM_div_T = (2.0/21.0)*(f_convective/tau_convective)*(convective_envelope_mass/mass); t_V = from_k_AM_div_T_to_t_V(k_AM_div_T,apsidal_motion_constant); //printf("test %g %g %g %g %g %g %g \n",P_spin,P_tid,P_orb,tau_convective,f_convective,k_AM_div_T,t_V); //if ((convective_envelope_mass <= 0.0) || (convective_envelope_radius <= 0.0)) // { // t_V = 1.0e100; // } // printf("test par conv %g %g %g %g %g \n",mass,radius,convective_envelope_mass,convective_envelope_radius,spin_angular_frequency); // printf("test conv %g %g %g %g %g \n",P_orb,tau_convective,P_tid,P_spin,f_convective); return t_V; } else // degenerate damping -- 1984MNRAS.207..433C { double seconds_in_year = 365.25*24.0*3600.0; double tau_degenerate = 1.3e7*seconds_in_year; k_AM_div_T = (1.0/(3.0*tau_degenerate))*gyration_radius*gyration_radius*pow((luminosity/CONST_L_SUN)/(mass/CONST_MSUN),5.0/7.0); t_V = from_k_AM_div_T_to_t_V(k_AM_div_T,apsidal_motion_constant); return t_V; } } double compute_EOM_equilibrium_tide_BO_full(ParticlesMap *particlesMap, int binary_index, int star_index, int companion_index, int include_tidal_friction_terms, int include_tidal_bulges_precession_terms, int include_rotation_precession_terms, double minimum_eccentricity_for_tidal_precession, int tides_method) /* Barker & Ogilvie (2009; http://adsabs.harvard.edu/abs/2009MNRAS.395.2268B) */ /* NOTE: in SecularMultiple, the h-vector is defined as the orbital angular momentum vector, * NOT the SPECIFIC orbital angular momentum vector. Compared to the notation used by Eggleton, * h_vec_SecularMultiple = mu*h_vec_Eggleton where mu = m*M/(m+M) is the reduced mass. * In particular, note the line `star->dspin_vec_dt[i] += -dh_vec_dt_star[i]/I;' */ { // printf("tides BO full\n"); // printf("TIDES %d %d %d\n",binary_index,star_index,companion_index); Particle *binary = (*particlesMap)[binary_index]; Particle *star = (*particlesMap)[star_index]; Particle *companion = (*particlesMap)[companion_index]; /* orbit quantities */ double e = binary->e; double e_p2 = binary->e_p2; double a = binary->a; double h = binary->h; double *e_vec = binary->e_vec; double *h_vec = binary->h_vec; double *e_vec_unit = binary->e_vec_unit; double *h_vec_unit = binary->h_vec_unit; double j = binary->j; double j_p2 = binary->j_p2; double j_p3 = binary->j_p3; double j_p4 = binary->j_p4; double j_p8 = j_p4*j_p4; double j_p10 = j_p2*j_p8; double j_p13 = j_p3*j_p10; double j_p4_inv = 1.0/j_p4; double j_p10_inv = 1.0/j_p10; double j_p13_inv = 1.0/j_p13; double P_orb = compute_orbital_period(binary); double n = 2.0*M_PI/P_orb; /* mean motion */ /* stellar properties */ double *spin_vec = star->spin_vec; double M = star->mass; double m = companion->mass; double R = star->radius; double k_AM = star->tides_apsidal_motion_constant; double rg = star->tides_gyration_radius; double t_V = compute_t_V(star,companion,a); star->tides_viscous_time_scale = t_V; if (t_V!=t_V) { printf("ERRORRRR\n"); printf("t_V %g \n",t_V); printf("st %d\n",star->stellar_type); printf("pr %d\n",star->tides_viscous_time_scale_prescription); printf("M %g\n",M); printf("star->convective_envelope_mass %g\n",star->convective_envelope_mass); printf("m %g\n",m); printf("a %g\n",a); printf("R %g\n",R); printf("star->convective_envelope_radius %g\n",star->convective_envelope_radius); printf("star->luminosity %g\n",star->luminosity); } if (1==0) { printf("t_V %g \n",t_V); printf("st %d\n",star->stellar_type); printf("pr %d\n",star->tides_viscous_time_scale_prescription); printf("M %g\n",M); printf("star->convective_envelope_mass %d\n",star->convective_envelope_mass); printf("m %g\n",m); printf("a %g\n",a); printf("R %g\n",R); printf("star->convective_envelope_radius %g\n",star->convective_envelope_radius); printf("star->luminosity %g\n",star->luminosity); } double tau = 3.0*(1.0 + 1.0/(2.0*k_AM))*R*R*R/(CONST_G*M*t_V); double I = rg*M*R*R; // moment of intertia double R_div_a = R/a; double R_div_a_p5 = pow(R_div_a,5.0); double t_f_inv = 3.0*k_AM*tau*n*n*(m/M)*R_div_a_p5; double f_tides1 = f_tides1_function_BO(e_p2,j_p10_inv,j_p13_inv); double f_tides2 = f_tides2_function_BO(e_p2,j_p10_inv,j_p13_inv); double f_tides3 = f_tides3_function_BO(e_p2,j_p10_inv,j_p13_inv); double f_tides4 = f_tides4_function_BO(e_p2,j_p10_inv,j_p13_inv); double f_tides5 = f_tides5_function_BO(e_p2,j_p10_inv,j_p13_inv); double spin_vec_dot_e_vec = dot3(spin_vec,e_vec); double spin_vec_dot_h_vec = dot3(spin_vec,h_vec); double q_vec_unit[3]; cross3(h_vec_unit,e_vec_unit,q_vec_unit); double spin_vec_dot_e_vec_unit = dot3(spin_vec,e_vec_unit); double spin_vec_dot_h_vec_unit = dot3(spin_vec,h_vec_unit); double spin_vec_dot_q_vec_unit = dot3(spin_vec,q_vec_unit); double mu = m*M/(m+M); double C = m*k_AM*R_div_a_p5/(mu*n); double C_rot; double X_rot = 0.0; double Y_rot = 0.0; double Z_rot = 0.0; double Z_TB = 0.0; if (include_rotation_precession_terms == 1) { if (tides_method == 1) { C_rot = C*j_p4_inv*spin_vec_dot_h_vec_unit; X_rot = -C_rot*spin_vec_dot_e_vec_unit; Y_rot = -C_rot*spin_vec_dot_q_vec_unit; } // printf("e %g q %g \n",spin_vec_dot_e_vec_unit/norm3(spin_vec),spin_vec_dot_q_vec_unit/norm3(spin_vec)); Z_rot = C*c_1div2*j_p4_inv*(2.0*spin_vec_dot_h_vec_unit*spin_vec_dot_h_vec_unit - spin_vec_dot_q_vec_unit*spin_vec_dot_q_vec_unit - spin_vec_dot_e_vec_unit*spin_vec_dot_e_vec_unit); // printf("1 %g 2 %g 3 %g\n",2.0*spin_vec_dot_h_vec_unit*spin_vec_dot_h_vec_unit ,- spin_vec_dot_q_vec_unit*spin_vec_dot_q_vec_unit ,- spin_vec_dot_e_vec_unit*spin_vec_dot_e_vec_unit); // printf("X %g Y %g Z %g\n",X_rot,Y_rot,Z_rot); } if (include_tidal_bulges_precession_terms == 1) { Z_TB = C*15.0*n*n*(mu/M)*f_tides2; } double X = X_rot; double Y = Y_rot; double Z = Z_rot + Z_TB; //printf("M %g m %g R %g k_AM %g a %g e %g Z %g Z_rot %g Z_TB %g\n",M,R,k_AM,a,e,Z,Z_rot,Z_TB); double dh_vec_dt_star_i; for (int i=0; i<3; i++) { if (include_tidal_friction_terms == 1) { dh_vec_dt_star_i = -t_f_inv*( (h/(2.0*n))*(spin_vec_dot_e_vec*f_tides5*e_vec[i] - spin_vec[i]*f_tides3) \ + h_vec[i]*(f_tides4 - spin_vec_dot_h_vec*f_tides2/(2.0*n*h)) ); binary->dh_vec_dt[i] += dh_vec_dt_star_i; binary->de_vec_dt[i] += -(t_f_inv/h)*( spin_vec_dot_e_vec*f_tides2*h_vec[i]/(2.0*n) \ + 9.0*e_vec[i]*(f_tides1*h - c_11div18*spin_vec_dot_h_vec*f_tides2/n) ); star->dspin_vec_dt[i] += -dh_vec_dt_star_i/I; //printf("test %g %g\n",spin_vec_dot_e_vec*f_tides5*e_vec[i] - spin_vec[i]*f_tides3); } if (include_rotation_precession_terms == 1 || include_tidal_bulges_precession_terms == 1) { if (e >= minimum_eccentricity_for_tidal_precession) { binary->de_vec_dt[i] += e*(Z*q_vec_unit[i] - Y*h_vec_unit[i]); dh_vec_dt_star_i = h*(-X*q_vec_unit[i] + Y*e_vec_unit[i]); binary->dh_vec_dt[i] += dh_vec_dt_star_i; star->dspin_vec_dt[i] += -dh_vec_dt_star_i/I; // printf("ok %d %d\n",include_rotation_precession_terms,include_tidal_bulges_precession_terms); } } } // printf("I %g %g %g %g\n",rg,M,R,Q_prime); // printf("f dh_vec_dt %g %g %g\n",binary->dh_vec_dt[0],binary->dh_vec_dt[1],binary->dh_vec_dt[2]); // printf("f dspin_vec_dt %g %g %g\n",star->dspin_vec_dt[0],star->dspin_vec_dt[1],star->dspin_vec_dt[2]); return 0; } double f_tides1_function_BO(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p13_inv*(1.0 + e_p2*(c_15div4 + e_p2*(c_15div8 + e_p2*c_5div64))); } double f_tides2_function_BO(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(1.0 + e_p2*(c_3div2 + e_p2*c_1div8)); } double f_tides3_function_BO(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(1.0 + e_p2*(c_9div2 + e_p2*c_5div8)); } double f_tides4_function_BO(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p13_inv*(1.0 + e_p2*(c_15div2 + e_p2*(c_45div8 + e_p2*c_5div16))); } double f_tides5_function_BO(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(3.0 + c_1div2*e_p2); } double compute_EOM_equilibrium_tide(ParticlesMap *particlesMap, int binary_index, int star_index, int companion_index, int include_tidal_friction_terms, int include_tidal_bulges_precession_terms, int include_rotation_precession_terms, double minimum_eccentricity_for_tidal_precession) /* Equilibrium tide in vector form adopted from Eggleton & Kisseleva 1998 */ /* NOTE: in SecularMultiple, the h-vector is defined as the orbital angular momentum vector, * NOT the SPECIFIC orbital angular momentum vector. Compared to the notation used by Eggleton, * h_vec_SecularMultiple = mu*h_vec_Eggleton where mu = m*M/(m+M) is the reduced mass. * In particular, note the line `star->dspin_vec_dt[i] += -dh_vec_dt_star[i]/I;' */ { // printf("tides EK \n"); // printf("TIDES %d %d %d\n",binary_index,star_index,companion_index); Particle *binary = (*particlesMap)[binary_index]; Particle *star = (*particlesMap)[star_index]; Particle *companion = (*particlesMap)[companion_index]; /* orbit quantities */ double e = binary->e; double e_p2 = binary->e_p2; double a = binary->a; double h = binary->h; double *e_vec = binary->e_vec; double *h_vec = binary->h_vec; double *e_vec_unit = binary->e_vec_unit; double *h_vec_unit = binary->h_vec_unit; double j = binary->j; double j_p2 = binary->j_p2; double j_p3 = binary->j_p3; double j_p4 = binary->j_p4; double j_p8 = j_p4*j_p4; double j_p10 = j_p2*j_p8; double j_p13 = j_p3*j_p10; double j_p4_inv = 1.0/j_p4; double j_p10_inv = 1.0/j_p10; double j_p13_inv = 1.0/j_p13; double P_orb = compute_orbital_period(binary); double n = 2.0*M_PI/P_orb; /* mean motion */ /* stellar properties */ double *spin_vec = star->spin_vec; double M = star->mass; double m = companion->mass; double mu = m*M/(m+M); double R = star->radius; double k_AM = star->tides_apsidal_motion_constant; double t_V = compute_t_V(star,companion,a); star->tides_viscous_time_scale = t_V; double rg = star->tides_gyration_radius; double I = rg*M*R*R; // moment of intertia double R_div_a = R/a; double R_div_a_p5 = pow(R_div_a,5.0); double R_div_a_p8 = pow(R_div_a,8.0); double t_f_inv = (9.0/t_V)*R_div_a_p8*((M+m)*m/(M*M))*(1.0 + 2.0*k_AM)*(1.0 + 2.0*k_AM); double q_vec_unit[3]; cross3(h_vec_unit,e_vec_unit,q_vec_unit); double spin_vec_dot_e_vec_unit = dot3(spin_vec,e_vec_unit); double spin_vec_dot_h_vec_unit = dot3(spin_vec,h_vec_unit); double spin_vec_dot_q_vec_unit = dot3(spin_vec,q_vec_unit); double V,W,X,Y,Z; VWXYZ_tides_function( include_tidal_friction_terms, include_tidal_bulges_precession_terms, include_rotation_precession_terms, minimum_eccentricity_for_tidal_precession, \ t_f_inv,k_AM, \ m, M, mu, n, R_div_a_p5, \ e, e_p2, j_p4_inv, j_p10_inv, j_p13_inv, \ spin_vec_dot_h_vec_unit, spin_vec_dot_e_vec_unit, spin_vec_dot_q_vec_unit, \ &V, &W, &X, &Y, &Z); //printf("t_f_inv V %g W %g X %g Y %g Z %g\n",t_f_inv,V,W,X,Y,Z); // printf("js %g %g %g\n",j_p10_inv,j_p13_inv); // printf("fs %g %g %g %g %g \n",f_tides1,f_tides2,f_tides3,f_tides4,f_tides5); double dh_vec_dt_star[3]; for (int i=0; i<3; i++) { dh_vec_dt_star[i] = h*( Y*e_vec_unit[i] - W*h_vec_unit[i] - X*q_vec_unit[i] ); binary->dh_vec_dt[i] += dh_vec_dt_star[i]; binary->de_vec_dt[i] += e*( -V*e_vec_unit[i] - Y*h_vec_unit[i] + Z*q_vec_unit[i] ); star->dspin_vec_dt[i] += -dh_vec_dt_star[i]/I; /* conservation of total angular momentum (orbit+spin) */ // printf("test %g %g\n",I*spin_vec[2], h_vec[2]); // printf("test2 %g %g %g\n",I*spin_vec[0] + h_vec[0],I*spin_vec[1] + h_vec[1],I*spin_vec[2] + h_vec[2]); // printf("test2 %g %g %g\n",I*spin_vec[0] + mu*h_vec[0],I*spin_vec[1] + mu*h_vec[1],I*spin_vec[2] + mu*h_vec[2]); } // double omega = norm3(spin_vec); // double h2 = sqrt(CONST_G*(M+m)*a*(1.0-e*e)); // printf("R %g\n",h/(mu*h2)); // printf("H%g H_a %g H_b %g\n",mu*h2 + I*omega, mu*h2, I*omega); // printf("H%g H_a %g H_b %g\n",mu*h + I*omega, mu*h, I*omega); // printf("I %g %g %g %g\n",rg,M,R,Q_prime); // printf("f dh_vec_dt %g %g %g\n",binary->dh_vec_dt[0],binary->dh_vec_dt[1],binary->dh_vec_dt[2]); // printf("f dspin_vec_dt %g %g %g\n",star->dspin_vec_dt[0],star->dspin_vec_dt[1],star->dspin_vec_dt[2]); return 0; } double f_tides1_function(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p13_inv*(1.0 + e_p2*(c_15div4 + e_p2*(c_15div8 + e_p2*c_5div64))); } double f_tides2_function(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(1.0 + e_p2*(c_3div2 + e_p2*c_1div8)); } double f_tides3_function(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p13_inv*(1.0 + e_p2*(c_15div2 + e_p2*(c_45div8 + e_p2*c_5div16))); } double f_tides4_function(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(1.0 + e_p2*(3.0 + e_p2*c_3div8)); } double f_tides5_function(double e_p2, double j_p10_inv, double j_p13_inv) { return j_p10_inv*(1.0 + e_p2*(c_9div2 + e_p2*c_5div8)); } int VWXYZ_tides_function ( int include_tidal_friction_terms, int include_tidal_bulges_precession_terms, int include_rotation_precession_terms, double minimum_eccentricity_for_tidal_precession, \ double t_f_inv, double k_AM, \ double m, double M, double mu, double n, double R_div_a_p5, \ double e, double e_p2, double j_p4_inv, double j_p10_inv,double j_p13_inv, \ double spin_vec_dot_h_vec_unit, double spin_vec_dot_e_vec_unit,double spin_vec_dot_q_vec_unit, \ double* V, double* W, double* X, double* Y, double* Z ) { *V = 0.0; *W = 0.0; *X = 0.0; *Y = 0.0; *Z = 0.0; double f2 = f_tides2_function(e_p2,j_p10_inv,j_p13_inv); /* needed for both pure tidal dissipation and pure tidal bulges terms */ // if (e < minimum_eccentricity_for_tidal_precession) // { // return 0; // } if (include_tidal_friction_terms == 1) { double f1 = f_tides1_function(e_p2,j_p10_inv,j_p13_inv); double f3 = f_tides3_function(e_p2,j_p10_inv,j_p13_inv); double f4 = f_tides4_function(e_p2,j_p10_inv,j_p13_inv); double f5 = f_tides5_function(e_p2,j_p10_inv,j_p13_inv); *V += 9.0*t_f_inv*(f1 - c_11div18*(spin_vec_dot_h_vec_unit/n)*f2); *W += t_f_inv*(f3 - (spin_vec_dot_h_vec_unit/n)*f4); *X += -t_f_inv*spin_vec_dot_q_vec_unit*f5/(2.0*n); *Y += t_f_inv*spin_vec_dot_e_vec_unit*f2/(2.0*n); // printf("TF X %g Y %g V %g W %g\n",*X,*Y,*Z,*V,*W); } if (e < minimum_eccentricity_for_tidal_precession) { return 0; } if ((include_tidal_bulges_precession_terms == 1) || (include_rotation_precession_terms) == 1) { double C = m*k_AM*R_div_a_p5/(mu*n); if (include_tidal_bulges_precession_terms == 1) { *Z += C*15.0*n*n*(mu/M)*f2; // printf("include_tidal_bulges_precession_terms Z %g\n",*Z); } if (include_rotation_precession_terms == 1) { double C_XY = -C*spin_vec_dot_h_vec_unit*j_p4_inv; *X += C_XY*spin_vec_dot_e_vec_unit; *Y += C_XY*spin_vec_dot_q_vec_unit; // printf("ROT X %g Y %g Z %g\n",C_XY*spin_vec_dot_e_vec_unit,C_XY*spin_vec_dot_q_vec_unit,C*c_1div2*j_p4_inv*(2.0*spin_vec_dot_h_vec_unit*spin_vec_dot_h_vec_unit - spin_vec_dot_q_vec_unit*spin_vec_dot_q_vec_unit - spin_vec_dot_e_vec_unit*spin_vec_dot_e_vec_unit)); // // printf("Z1 %g\n",*Z); *Z += C*c_1div2*j_p4_inv*(2.0*spin_vec_dot_h_vec_unit*spin_vec_dot_h_vec_unit - spin_vec_dot_q_vec_unit*spin_vec_dot_q_vec_unit - spin_vec_dot_e_vec_unit*spin_vec_dot_e_vec_unit); // printf("Z2 %g\n",*Z); // printf("O %g %g %g\n",spin_vec_dot_h_vec_unit,spin_vec_dot_e_vec_unit,spin_vec_dot_q_vec_unit); // printf("include_rotation_precession_terms Z %g\n",*Z); } } return 0; }
36.7536
310
0.650734
[ "vector" ]
d4edf4f88830d25831a64346099b66baf742ef1a
485
cpp
C++
src/test.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
src/test.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
src/test.cpp
tairaO/CarND-Unscented-Kalman-Filter-Project
cd7b489060ec9c55d72e25b49b5e0fd920d8fddb
[ "MIT" ]
null
null
null
#include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include <math.h> #include "ukf.h" #include "tools.h" using namespace std; int main() { // Create a Kalman Filter instance UKF ukf; // used to compute the RMSE later Tools tools; vector<VectorXd> estimations; vector<VectorXd> ground_truth; MeasurementPackage meas_package; meas_package. //Call ProcessMeasurment(meas_package) for Kalman filter ukf.ProcessMeasurement(meas_package); return 0; }
16.724138
58
0.725773
[ "vector" ]
d4f94388bad8e739f49123eafe567546e4587f4a
12,837
cc
C++
src/Pattern4GPUCartesian.cc
cea-hpc/pattern4gpu
bf606708b6a8bad1041369814e8443b7f1dedcef
[ "Apache-2.0" ]
null
null
null
src/Pattern4GPUCartesian.cc
cea-hpc/pattern4gpu
bf606708b6a8bad1041369814e8443b7f1dedcef
[ "Apache-2.0" ]
null
null
null
src/Pattern4GPUCartesian.cc
cea-hpc/pattern4gpu
bf606708b6a8bad1041369814e8443b7f1dedcef
[ "Apache-2.0" ]
null
null
null
#include "Pattern4GPUModule.h" #include "ViewInDir.h" #include "cartesian/CartesianMeshProperties.h" #include "cartesian/CartesianItemSorter.h" #include "cartesian/FactCartDirectionMng.h" #include "arcane/VariableView.h" #include "cartesian/CartTypes.h" #include "cartesian/CartesianMeshT.h" #include "arcane/IParallelMng.h" #define P4GPU_PROFILING // Pour activer le profiling #include "P4GPUTimer.h" /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ /*! * \brief Initialisation du maillage cartésien */ /*---------------------------------------------------------------------------*/ void Pattern4GPUModule:: initCartMesh() { PROF_ACC_BEGIN(__FUNCTION__); Cartesian::CartesianMeshProperties cart_mesh_prop(mesh()); if (cart_mesh_prop.isPureCartesianMesh()) { info() << "Maillage cartésien détecté, tri cartésien des faces"; Cartesian::CartesianItemSorter cart_sorter(mesh()); cart_sorter.sortFaces(); m_cartesian_mesh = CartesianInterface::ICartesianMesh::getReference(mesh(), true); m_cartesian_mesh->computeDirections(); } else { info() << "Maillage non cartésien"; } PROF_ACC_END; } /*---------------------------------------------------------------------------*/ /*! * \brief Initialisation du maillage cartésien */ /*---------------------------------------------------------------------------*/ void Pattern4GPUModule:: initForVol() { PROF_ACC_BEGIN(__FUNCTION__); const VariableNodeReal3& node_coord = defaultMesh()->nodesCoordinates(); Cartesian::CartesianMeshProperties cart_mesh_prop(mesh()); ARCANE_ASSERT(cart_mesh_prop.isPureCartesianMesh(), ("Maillage cartésien obligatoire, ce n'est pas le cas")); // Calcul du pas d'espace dans chaque direction // D'abord les coordonnées min et max Cartesian::FactCartDirectionMng fact_cart_dm(subDomain()->defaultMesh()); auto* cart_grid=fact_cart_dm.cartesianGrid(); const auto& cart_num_node=cart_grid->cartNumNode(); // Numérotation cartésienne aux noeuds auto loc_first_id=cart_num_node.firstId(); // Id du noeud "en bas à gauche" auto loc_last_id=loc_first_id+cart_num_node.nbItem()-1; // Id du noeud "en haut à droite" auto node_dm=fact_cart_dm.nodeDirection(0); Node first_node=node_dm.toNode(loc_first_id); Node last_node=node_dm.toNode(loc_last_id); Real3 loc_min_c3=node_coord[first_node]; // plus petites coordonnées du sous-domaine Real3 loc_max_c3=node_coord[last_node]; // plus grandes coordonnées du sous-domaine Real3 glob_min_c3=defaultMesh()->parallelMng()->reduce(Parallel::ReduceMin, loc_min_c3); Real3 glob_max_c3=defaultMesh()->parallelMng()->reduce(Parallel::ReduceMax, loc_max_c3); // Puis il faut le nb total de mailles dans chaque direction const UniqueIdType3& glob_ncell3=cart_mesh_prop.globalNbCell3(); // Hypothèse : maillage régulier Real3 space_step3=glob_max_c3-glob_min_c3; space_step3.x/=Real(glob_ncell3[0]); space_step3.y/=Real(glob_ncell3[1]); space_step3.z/=Real(glob_ncell3[2]); debug() << "Nb de mailles globales dans domaine calcul : (" << glob_ncell3[0] << ", " << glob_ncell3[1] << ", " << glob_ncell3[2] << ")"; debug() << "Coordonnées min/max : " << " (" << glob_min_c3.x << ", " << glob_min_c3.y << ", " << glob_min_c3.z << ")," << " (" << glob_max_c3.x << ", " << glob_max_c3.y << ", " << glob_max_c3.z << ")"; debug() << "Pas d'espace par direction : " << " (" << space_step3.x << ", " << space_step3.y << ", " << space_step3.z << ")"; // m_cart_space_step est le pas d'espace // Hypothèse : maillage régulier m_cart_space_step.fill(space_step3); // Récupération des coordonnées des noeuds et construction des coordonnées "déformées" // on en profite pour calculer les vitesses aux noeuds m_global_deltat=1.e-6; // On impose le pas de temps qu'on relira avec globalDeltaT() const Real inv_dt=1./globalDeltaT(); ENUMERATE_NODE(node_i, allNodes()) { const Real3& c=node_coord[node_i]; // "Déformation" ou déplacement du noeud Real3 def3=0.1*space_step3; // maximum 10% d'une maille dans chaque direction // calcul d'un vecteur directeur unitaire en coordonnées sphériques Real cos_th=cos(10*c.x+15*c.y+13*c.z); // garantit une valeur dans [-1,+1] Real sin_th=math::sqrt(1-cos_th*cos_th); // garantit une valeur dans [0,+1] Real phi=(c.x+1)*(c.y+1)*(c.z+1); def3.x *= sin_th*cos(phi); def3.y *= sin_th*sin(phi); def3.z *= cos_th; // Les variables d'intérêt m_car_node_coord[node_i]=c; m_def_node_coord[node_i]=c+def3; m_node_velocity[node_i]=inv_dt*def3; } // Ce sont les variables à calculer m_dir_trans_area_left.fill(-1.); m_face_velocity_left.fill(-1.); m_dir_def_coord_left.fill(-1.); m_dir_car_coord_left.fill(-1.); m_dir_vol1_left.fill(-1.); m_dir_vol2_left.fill(-1.); m_dir_trans_area_right.fill(-2.); m_face_velocity_right.fill(-2.); m_dir_def_coord_right.fill(-2.); m_dir_car_coord_right.fill(-2.); m_dir_vol1_right.fill(-2.); m_dir_vol2_right.fill(-2.); PROF_ACC_END; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ template<typename CartesianMeshT, template<class> class ViewInDirReal > void Pattern4GPUModule:: _computeVolDir(const Integer dir, const Real dt) { PROF_ACC_BEGIN(__FUNCTION__); Integer dir_perp_0=(dir+1)%3; Integer dir_perp_1=(dir+2)%3; using CellDirectionMngType = typename CartesianMeshT::CellDirectionMngType; using FaceDirectionMngType = typename CartesianMeshT::FaceDirectionMngType; using ConnectivityCellNode = typename CartesianMeshT::ConnectivityCellNode; using ConnectivityCellFaceNode = typename CartesianMeshT::ConnectivityCellFaceNode; using CellGroupType = typename CartesianMeshT::CellGroupType; CartesianMeshT cart_mesh_t(m_cartesian_mesh); // Recuperation de toutes les mailles cartesiennes dans la direction dir CellDirectionMngType&& cart_cell_dm = cart_mesh_t.cellDirection(dir); const CellGroupType&& dirCartCellGroup = cart_cell_dm.allCells(); ConnectivityCellFaceNode&& cart_conn_cfn = cart_mesh_t.connectivityCellFaceNode(dir); // Vues en lecture dans une direction pour des variables vectorielles // Attention, des copies peuvent exister en fonctions de l'implem. de la vue ViewInDirReal<Cell> in_cart_space_step_dir_perp0(m_cart_space_step, dir_perp_0); ViewInDirReal<Cell> in_cart_space_step_dir_perp1(m_cart_space_step, dir_perp_1); ViewInDirReal<Node> in_node_velocity_dir(m_node_velocity, dir); ViewInDirReal<Node> in_def_node_coord_dir(m_def_node_coord, dir); ViewInDirReal<Node> in_car_node_coord_dir(m_car_node_coord, dir); // Vues "a la C" de tableaux bien ordonnes auto v_dir_trans_area_left = viewInOut(m_dir_trans_area_left); auto v_dir_trans_area_right = viewInOut(m_dir_trans_area_right); auto v_face_velocity_left = viewInOut(m_face_velocity_left); auto v_face_velocity_right = viewInOut(m_face_velocity_right); auto v_dir_def_coord_left = viewInOut(m_dir_def_coord_left); auto v_dir_car_coord_left = viewInOut(m_dir_car_coord_left); auto v_dir_def_coord_right = viewInOut(m_dir_def_coord_right); auto v_dir_car_coord_right = viewInOut(m_dir_car_coord_right); auto v_dir_vol1_left = viewInOut(m_dir_vol1_left); auto v_dir_vol1_right = viewInOut(m_dir_vol1_right); auto v_dir_vol2_left = viewInOut(m_dir_vol2_left); auto v_dir_vol2_right = viewInOut(m_dir_vol2_right); const Integer nb_node_on_face = cart_conn_cfn.nbNode(); const Real nb_node_inverse = 1.0 / nb_node_on_face; // Un calcul elementaire pour une maille pour la direction dir pour un cote donne auto lbd_dirvol = [&cart_conn_cfn, dt, nb_node_on_face, nb_node_inverse, &in_cart_space_step_dir_perp0, &in_cart_space_step_dir_perp1, &in_node_velocity_dir, &in_def_node_coord_dir, &in_car_node_coord_dir]( const CellLocalId &cell_id, const auto &cart_cell_i, auto &v_dir_trans_area, auto &v_face_velocity, auto &v_dir_def_coord, auto &v_dir_car_coord, auto &v_dir_vol1, auto &v_dir_vol2 ) { // calcul de l'aire transversale const Real trans_area = in_cart_space_step_dir_perp0[cell_id] * in_cart_space_step_dir_perp1[cell_id]; v_dir_trans_area[cell_id] = trans_area; // Passage maille => noeuds sur la face dans la direction cart_conn_cfn.initCartCell(cart_cell_i); // Modification de l'aire transversale Real face_velocity = 0.; Real def_coord = 0.; Real car_coord = 0.; for(Integer inode = 0 ; inode < nb_node_on_face ; inode++) { const auto node_id{cart_conn_cfn.node(inode)}; face_velocity += in_node_velocity_dir[node_id]; def_coord += in_def_node_coord_dir[node_id]; car_coord += in_car_node_coord_dir[node_id]; } face_velocity *= nb_node_inverse; def_coord *= nb_node_inverse; car_coord *= nb_node_inverse; v_face_velocity[cell_id] = face_velocity; v_dir_def_coord[cell_id] = def_coord; v_dir_car_coord[cell_id] = car_coord; v_dir_vol1[cell_id] = dt * face_velocity * trans_area; v_dir_vol2[cell_id] = v_dir_vol1[cell_id]; }; P4GPU_DECLARE_TIMER(subDomain(), Loop_Cell1); P4GPU_START_TIMER(Loop_Cell1); // On va d'abord effectuer tous les calculs a gauche, puis on recopiera a droite sauf pour la deniere rangee cart_conn_cfn.initSide(MS_previous); // Hypothese forte : les mailles doivent etre parcourues de facon cartesienne // Pour un plan donne, pour une ligne donnee, parcours des mailles d'une ligne ENUMERATE_AUTO_CELL(cell_i, dirCartCellGroup) { CellLocalId cell_id(cell_i.localId()); // Acces "previous" et grandeurs a gauche lbd_dirvol(cell_id, cell_i, v_dir_trans_area_left, v_face_velocity_left, v_dir_def_coord_left, v_dir_car_coord_left, v_dir_vol1_left, v_dir_vol2_left ); } // Fin ENUMERATE_CELL // Maintenant, on recupere les valeurs a droite, sauf pour la derniere rangee ou l'on effectue le calcul cart_conn_cfn.initSide(MS_next); ENUMERATE_AUTO_CELL(cell_i, dirCartCellGroup) { CellLocalId cell_id(cell_i.localId()); const auto &&dir_cell = cart_cell_dm[cell_i]; // <=> cart_cell_dm.cell(cell_i...) CellLocalId next_cell_id(dir_cell.next()); // La maille apres la cellule courante if (next_cell_id >= 0) { // J'ai une maille a ma droite // J'affecte dans MA valeur de droite la valeur de gauche de ma maille de droite v_dir_trans_area_right[cell_id] = v_dir_trans_area_left[next_cell_id]; v_face_velocity_right[cell_id] = v_face_velocity_left[next_cell_id]; v_dir_def_coord_right[cell_id] = v_dir_def_coord_left[next_cell_id]; v_dir_car_coord_right[cell_id] = v_dir_car_coord_left[next_cell_id]; v_dir_vol1_right[cell_id] = v_dir_vol1_left[next_cell_id]; v_dir_vol2_right[cell_id] = v_dir_vol2_left[next_cell_id]; } else { // Je suis sur la derniere rangee, je calcule // Acces "next" et grandeurs a droite lbd_dirvol(cell_id, cell_i, v_dir_trans_area_right, v_face_velocity_right, v_dir_def_coord_right, v_dir_car_coord_right, v_dir_vol1_right, v_dir_vol2_right ); } } // Fin ENUMERATE_CELL P4GPU_STOP_TIMER(Loop_Cell1); PROF_ACC_END; } /*---------------------------------------------------------------------------*/ /* Parcours toutes les directions et appele _computeVolDir */ /*---------------------------------------------------------------------------*/ void Pattern4GPUModule:: computeVol() { PROF_ACC_BEGIN(__FUNCTION__); Real dt=globalDeltaT(); //#define SOA #ifdef SOA // On recupere les valeurs par direction #define VIEW_IN_DIR_REAL ViewInDirReal_SoA #else // Vue sur les tableaux en Real3 (AoS) #define VIEW_IN_DIR_REAL ViewInDirReal_AoS #endif Cartesian::FactCartDirectionMng fact_cart_dm(subDomain()->defaultMesh()); bool is_cartesian_mesh = fact_cart_dm.isPureCartesianMesh(); //bool is_cartesian_mesh = false; for(Integer dir=0 ; dir<mesh()->dimension() ; ++dir) { if (is_cartesian_mesh) { _computeVolDir<CartCartesianMeshT, VIEW_IN_DIR_REAL>(dir, dt); } else { _computeVolDir<UnstructCartesianMeshT, VIEW_IN_DIR_REAL>(dir, dt); } } PROF_ACC_END; } /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
39.990654
139
0.673989
[ "mesh" ]
d4f990de6aeb4f0e6c706fd750fafefed99fb435
1,181
cpp
C++
performance/fbe_serialize.cpp
chronoxor/CppSerialization
3c20f98194dd5187afccc4dd0f4874721a95eb79
[ "MIT" ]
94
2017-03-19T09:47:07.000Z
2022-03-14T18:45:13.000Z
performance/fbe_serialize.cpp
chronoxor/CppSerialization
3c20f98194dd5187afccc4dd0f4874721a95eb79
[ "MIT" ]
1
2019-01-01T15:33:25.000Z
2019-01-02T03:14:33.000Z
performance/fbe_serialize.cpp
chronoxor/CppSerialization
3c20f98194dd5187afccc4dd0f4874721a95eb79
[ "MIT" ]
31
2017-10-24T17:28:13.000Z
2022-01-19T00:34:04.000Z
// // Created by Ivan Shynkarenka on 08.05.2018 // #include "benchmark/cppbenchmark.h" #include "../proto/trade.h" class SerializationFixture { protected: FBE::trade::AccountModel writer; TradeProto::Account account; SerializationFixture() : account(1, "Test", "USD", 1000) { // Create a new account with some orders account.Orders.emplace_back(TradeProto::Order(1, "EURUSD", TradeProto::OrderSide::BUY, TradeProto::OrderType::MARKET, 1.23456, 1000)); account.Orders.emplace_back(TradeProto::Order(2, "EURUSD", TradeProto::OrderSide::SELL, TradeProto::OrderType::LIMIT, 1.0, 100)); account.Orders.emplace_back(TradeProto::Order(3, "EURUSD", TradeProto::OrderSide::BUY, TradeProto::OrderType::STOP, 1.5, 10)); } }; BENCHMARK_FIXTURE(SerializationFixture, "FastBinaryEncoding-Serialize") { // Serialize the account to the FBE stream writer.reset(); size_t model_begin = writer.create_begin(); account.Serialize(writer.model); size_t serialized = writer.create_end(model_begin); context.metrics().AddBytes(serialized); context.metrics().SetCustom("Size", (unsigned)serialized); } BENCHMARK_MAIN()
31.918919
142
0.709568
[ "model" ]
d4f9efbc2ad9afc3022f7ce9a7c717952ab288e6
5,506
cpp
C++
Solutions to exercises/Ch8/Soln8_07.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
Solutions to exercises/Ch8/Soln8_07.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
Solutions to exercises/Ch8/Soln8_07.cpp
salomarx/Visual_studio_2008_for_C_plus
5ff62b7e7f6232df38152390cc56c2d394567cab
[ "MIT" ]
null
null
null
// Ex8_07.cpp : main project file. // A ref class with the same functionality as the Ex8_08 example in Chapter 8. #include "stdafx.h" using namespace System; ref class Box { public: Box() { Box(1.0, 1.0, 1.0); } Box(double lv, double wv, double hv) { lv = lv <= 0.0 ? 1.0 : lv; // Ensure positive wv = wv <= 0.0 ? 1.0 : wv; // dimensions for hv = hv <= 0.0 ? 1.0 : hv; // the object lngth = lv>wv ? lv : wv; // Ensure that wdth = wv<lv ? wv : lv; // length >= width hght = hv; } double Volume() { return lngth*wdth*hght; } property double height { double get() { return hght; } } property double width { double get() { return wdth; } } property double length { double get() { return lngth; } } // Overloaded addition operator Box^ operator+(Box^ box) { // New object has larger length and width of the two, // and sum of the two heights return gcnew Box(lngth > box->lngth ? lngth : box->lngth, wdth > box->wdth ? wdth : box->wdth, hght + box->hght); } // Divide one box into another int operator/(Box^ box) { // Temporary for number in horizontal plane this way int tc1 = 0; // Temporary for number in a plane that way int tc2 = 0; tc1 = safe_cast<int>(lngth/box->lngth)* safe_cast<int>(wdth/box->wdth); // to fit this way tc2 = safe_cast<int>(lngth/box->wdth)* safe_cast<int>(wdth/box->lngth); // and that way //Return best fit return static_cast<int>(hght/box->hght)*(tc1>tc2 ? tc1 : tc2); } // Post-multiply a box by an integer Box^ operator*(int n) { if(n%2 == 0) return gcnew Box(lngth, 2.0*wdth, (n/2)*hght); // n even else return gcnew Box(lngth, wdth, n*hght); // n odd } // Operator to return the free volume in a packed Box double operator%(Box^ box) { return Volume() - (this/box)*box->Volume(); } // Function for testing if a Box object is >= a constant bool operator>=(double value) { return value <= this; } // Function for testing if a Box object is <= a constant bool operator<=(double value) { return value >= this; } // Function for testing if a constant is > a Box object static bool operator>(double value, Box^ box) { return value > box->Volume(); } // Function for testing if a constant is < Box object static bool operator<(double value, Box^ box) { return value < box->Volume(); } // Function for testing if a Box object is > a constant static bool operator>(Box^ box, double value) { return value < box; } // Function for testing if a Box object is < a constant static bool operator<(Box^ box, double value) { return value > box; } // Function for testing if a constant is >= a Box object static bool operator>=(double value, Box^ box) { return value >= box->Volume(); } // Function for testing if a constant is <= a Box object static bool operator<=(double value, Box^ box) { return value <= box->Volume(); } // Function for testing if a constant is == Box object static bool operator==(double value, Box^ box) { return value == box->Volume(); } // Function for testing if Box object is == a constant static bool operator==(Box^ box, double value) { return value == box; } // CBox multiply operator n*aBox static Box^ operator*(int n, Box^ box) { return box*n; } private: double lngth; // Length of a box in inches double wdth; // Width of a box in inches double hght; // Height of a box in inches }; int main(array<System::String ^> ^args) { Box^ candy = gcnew Box(1.5, 1.0, 1.0); // Candy definition Box^ candyBox = gcnew Box(7.0, 4.5, 2.0); // Candy box definition Box^ carton = gcnew Box(30.0, 18.0, 18.0); // Carton definition // Calculate candies per candy box int numCandies = candyBox/candy; // Calculate candy boxes per carton int numCboxes = carton/candyBox; // Calculate wasted carton space double space = carton%candyBox; Console::WriteLine(L"There are {0} candies per candy box", numCandies); Console::WriteLine(L"For the standard boxes there are {0} candy boxes per carton", numCboxes); Console::WriteLine(L"with {0} cubic inches wasted.", space); Console::Write(L"CUSTOM CANDY BOX ANALYSIS (No Waste)"); // Try the whole range of custom candy boxes for(double length = 3.0 ; length <= 7.5 ; length += 0.5) for(double width = 3.0 ; width <= 5.0 ; width += 0.5) for(double height = 1.0 ; height <= 2.5 ; height += 0.5) { // Create new box each cycle Box^ tryBox = gcnew Box(length, width, height); if(carton%tryBox < tryBox->Volume() && tryBox % candy == 0.0 && tryBox/candy >= 30) { Console::Write(L"\n\nTrial Box L = {0}", tryBox->length); Console::WriteLine(L" W = {0} H = {1}", tryBox->width, tryBox->height); Console::Write(L"Trial Box contains {0} candies", tryBox/candy); Console::WriteLine(L" and a carton contains {0} candy boxes.", carton/tryBox); } } Console::WriteLine(); return 0; }
30.588889
97
0.575191
[ "object" ]
be056037adb511498acdc5efc97688d581b03164
3,735
cxx
C++
plots/Volume/moc_QvisCMap2Display.cxx
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
plots/Volume/moc_QvisCMap2Display.cxx
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
plots/Volume/moc_QvisCMap2Display.cxx
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'QvisCMap2Display.h' ** ** Created: Wed Nov 4 16:18:50 2015 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "QvisCMap2Display.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'QvisCMap2Display.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QvisCMap2Display[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 3, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 3, // signalCount // signals: signature, parameters, type, tag, flags 17, 37, 37, 37, 0x05, 38, 61, 37, 37, 0x05, 64, 61, 37, 37, 0x05, 0 // eod }; static const char qt_meta_stringdata_QvisCMap2Display[] = { "QvisCMap2Display\0widgetListChanged()\0" "\0selectWidget(WidgetID)\0id\0" "widgetChanged(WidgetID)\0" }; void QvisCMap2Display::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); QvisCMap2Display *_t = static_cast<QvisCMap2Display *>(_o); switch (_id) { case 0: _t->widgetListChanged(); break; case 1: _t->selectWidget((*reinterpret_cast< WidgetID(*)>(_a[1]))); break; case 2: _t->widgetChanged((*reinterpret_cast< WidgetID(*)>(_a[1]))); break; default: ; } } } const QMetaObjectExtraData QvisCMap2Display::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject QvisCMap2Display::staticMetaObject = { { &QGLWidget::staticMetaObject, qt_meta_stringdata_QvisCMap2Display, qt_meta_data_QvisCMap2Display, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &QvisCMap2Display::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *QvisCMap2Display::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *QvisCMap2Display::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QvisCMap2Display)) return static_cast<void*>(const_cast< QvisCMap2Display*>(this)); return QGLWidget::qt_metacast(_clname); } int QvisCMap2Display::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QGLWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 3) qt_static_metacall(this, _c, _id, _a); _id -= 3; } return _id; } // SIGNAL 0 void QvisCMap2Display::widgetListChanged() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } // SIGNAL 1 void QvisCMap2Display::selectWidget(WidgetID _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 1, _a); } // SIGNAL 2 void QvisCMap2Display::widgetChanged(WidgetID _t1) { void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 2, _a); } QT_END_MOC_NAMESPACE
31.125
96
0.637483
[ "object" ]
be0a1263fdfc90a864ffe4d7210db530fea388d2
4,070
cpp
C++
src/Engine/Graphic/Skybox.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Engine/Graphic/Skybox.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
src/Engine/Graphic/Skybox.cpp
Jino42/stf
f10ddaf4eb0a7ba94e6f9bb7d6b2191ca3a0b3db
[ "Unlicense" ]
null
null
null
#include "Skybox.hpp" #include <cassert> #include <fstream> #include <iostream> #include <memory> #include <string> #include <stb_image.h> #include <vector> #include <glm/glm.hpp> Skybox::Skybox(std::string const &pathShader, std::string const &pathDirectorySkyBox, std::list< std::string > const &skyboxFile) { if (skyboxFile.size() < SKYBOX_NUMBER_OF_FACES) throw (Skybox::ConstructorException("Missing file during construct Skybox")); shader_.attach(pathShader + ".vert"); shader_.attach(pathShader + ".frag"); shader_.link(); glGenTextures(1, &textureSkyBox_); glBindTexture(GL_TEXTURE_CUBE_MAP, textureSkyBox_); int width, height, nrChannels; std::list<std::string>::const_iterator it = skyboxFile.begin(); for (unsigned int i = 0; i < SKYBOX_NUMBER_OF_FACES && it != skyboxFile.end(); i++, it++) { unsigned char *data = stbi_load((pathDirectorySkyBox + *it).c_str(), &width, &height, &nrChannels, 0); if (data) { std::cout << "loadSkyBox_ : " << (pathDirectorySkyBox + *it).c_str() << std::endl; glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } else { stbi_image_free(data); throw (Skybox::ConstructorException(std::string("loadSkyBox_ : ") + pathDirectorySkyBox + (*it).c_str() + " failed.")); } stbi_image_free(data); } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glGenVertexArrays(1, &skyboxVAO_); glGenBuffers(1, &skyboxVBO_); glBindVertexArray(skyboxVAO_); glBindBuffer(GL_ARRAY_BUFFER, skyboxVBO_); glBufferData(GL_ARRAY_BUFFER, sizeof(skyboxVertices_), &skyboxVertices_, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), nullptr); } Skybox::~Skybox() noexcept = default; void Skybox::render(glm::mat4 const &view, glm::mat4 const &projection) { /* Remove Translation */ glm::mat4 viewWithoutTranslation = glm::mat4(glm::mat3(view)); glDepthFunc(GL_LEQUAL); shader_.activate(); shader_.setMat4("view", viewWithoutTranslation); shader_.setMat4("projection", projection); glBindVertexArray(skyboxVAO_); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, textureSkyBox_); glDrawArrays(GL_TRIANGLES, 0, 36); glBindVertexArray(0); } float Skybox::skyboxVertices_[6 * 6 * 3] = { -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f }; Skybox::ConstructorException::~ConstructorException(void) noexcept{} Skybox::ConstructorException::ConstructorException(void) noexcept : invalid_argument(this->_error), _error("You make a ConstructorException") {} Skybox::ConstructorException::ConstructorException(std::string s) noexcept : invalid_argument(s), _error(s) { } Skybox::ConstructorException::ConstructorException(Skybox::ConstructorException const &src) noexcept : invalid_argument(this->_error), _error(src._error) { this->_error = src._error; } const char *Skybox::ConstructorException::what() const noexcept { return (this->_error.c_str()); }
31.550388
122
0.683784
[ "render", "vector" ]
be0bf6705bccd7fd53031e44da9f4c4e19e8bc25
13,986
cpp
C++
src/os/windows/windows.cpp
lukedan/codepad
b2d85554a0fb910dd4d45831a364ce7dfb56efb2
[ "Apache-2.0" ]
42
2017-05-26T15:56:44.000Z
2022-02-24T13:57:40.000Z
src/os/windows/windows.cpp
lukedan/codepad
b2d85554a0fb910dd4d45831a364ce7dfb56efb2
[ "Apache-2.0" ]
5
2018-08-12T01:57:48.000Z
2022-01-20T04:55:40.000Z
src/os/windows/windows.cpp
lukedan/codepad
b2d85554a0fb910dd4d45831a364ce7dfb56efb2
[ "Apache-2.0" ]
4
2020-03-27T12:51:53.000Z
2022-03-26T04:29:30.000Z
// Copyright (c) the Codepad contributors. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE.txt in the project root for license information. /// \file /// Implementation of miscellaneous platform-specific functions. #include <ShObjIdl.h> #include <Shlwapi.h> #include <processthreadsapi.h> #include <commdlg.h> #include "codepad/ui/manager.h" #include "codepad/os/windows/misc.h" #include "codepad/os/windows/window.h" #ifdef _MSC_VER # define CP_CAN_DETECT_MEMORY_LEAKS # define _CRTDBG_MAP_ALLOC # include <crtdbg.h> namespace codepad::os { namespace _details { /// Enables the detection of memory leaks under Windows when compiled with MSVC. void _enable_mem_leak_detection() { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); } } } #endif namespace codepad::os { void initialize(int, char**) { #if defined(CP_CHECK_USAGE_ERRORS) && defined(CP_CAN_DETECT_MEMORY_LEAKS) _details::_enable_mem_leak_detection(); #endif // set DPI awareness // TODO will this work under win7? _details::winapi_check(SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)); #ifdef ENABLE_VIRTUAL_TERMINAL_PROCESSING // enable console output coloring HANDLE hstderr = GetStdHandle(STD_ERROR_HANDLE); _details::winapi_check(hstderr != INVALID_HANDLE_VALUE); DWORD mode; _details::winapi_check(GetConsoleMode(hstderr, &mode)); _details::winapi_check(SetConsoleMode(hstderr, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING)); #endif } #ifdef CP_USE_LEGACY_OPEN_FILE_DIALOG std::vector<std::filesystem::path> file_dialog::show_open_dialog(const ui::window *parent, type type) { const std::size_t file_buffer_size = 1000; OPENFILENAME ofn; TCHAR file[file_buffer_size]; memset(&ofn, 0, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = parent ? _details::cast_window_impl(parent->get_impl()).get_native_handle() : nullptr; ofn.lpstrFile = file; ofn.lpstrFile[0] = '\0'; ofn.nMaxFile = file_buffer_size; ofn.lpstrFilter = TEXT("All files\0*.*\0"); ofn.nFilterIndex = 0; ofn.lpstrFileTitle = nullptr; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = nullptr; if (type == type::multiple_selection) { ofn.Flags |= OFN_ALLOWMULTISELECT | OFN_EXPLORER; } if (GetOpenFileName(&ofn) == TRUE) { if ( ofn.nFileOffset == 0 || ofn.lpstrFile[ofn.nFileOffset - 1] != '\0' || type == type::single_selection ) { return { std::filesystem::path(ofn.lpstrFile) }; } std::filesystem::path wd(ofn.lpstrFile); std::vector<std::filesystem::path> paths; const TCHAR *cur = ofn.lpstrFile + ofn.nFileOffset; for (; *cur != 0; ++cur) { paths.push_back(wd / cur); for (; *cur != 0; ++cur) { } } return paths; } return {}; } #else class dialog_event_handler : public IFileDialogEvents, public IFileDialogControlEvents { public: // IUnknown methods IFACEMETHODIMP QueryInterface(REFIID riid, void** ppv) { static const QITAB qit[] = { QITABENT(dialog_event_handler, IFileDialogEvents), QITABENT(dialog_event_handler, IFileDialogControlEvents), { 0 }, }; return QISearch(this, qit, riid, ppv); } IFACEMETHODIMP_(ULONG) AddRef() { return InterlockedIncrement(&_cRef); } IFACEMETHODIMP_(ULONG) Release() { long cRef = InterlockedDecrement(&_cRef); if (!cRef) { delete this; } return cRef; } // IFileDialogEvents methods IFACEMETHODIMP OnFileOk(IFileDialog*) override { return S_OK; }; IFACEMETHODIMP OnFolderChange(IFileDialog*) override { return S_OK; }; IFACEMETHODIMP OnFolderChanging(IFileDialog*, IShellItem*) override { return S_OK; }; IFACEMETHODIMP OnSelectionChange(IFileDialog*) override { return S_OK; }; IFACEMETHODIMP OnShareViolation(IFileDialog*, IShellItem*, FDE_SHAREVIOLATION_RESPONSE*) override { return S_OK; }; IFACEMETHODIMP OnTypeChange(IFileDialog*) override { return S_OK; } IFACEMETHODIMP OnOverwrite(IFileDialog*, IShellItem*, FDE_OVERWRITE_RESPONSE*) override { return S_OK; }; // IFileDialogControlEvents methods IFACEMETHODIMP OnItemSelected(IFileDialogCustomize*, DWORD, DWORD) override { return S_OK; } IFACEMETHODIMP OnButtonClicked(IFileDialogCustomize*, DWORD) override { return S_OK; }; IFACEMETHODIMP OnCheckButtonToggled(IFileDialogCustomize*, DWORD, BOOL) override { return S_OK; }; IFACEMETHODIMP OnControlActivating(IFileDialogCustomize*, DWORD) override { return S_OK; }; private: long _cRef = 1; }; void create_dialog_event_handler(REFIID riid, void **ppv) { *ppv = nullptr; dialog_event_handler *pDialogEventHandler = new (std::nothrow) dialog_event_handler(); _details::com_check(pDialogEventHandler->QueryInterface(riid, ppv)); pDialogEventHandler->Release(); } std::vector<std::filesystem::path> file_dialog::show_open_dialog(const ui::window *parent, type type) { const COMDLG_FILTERSPEC file_types = { TEXT("All files"), TEXT("*.*") }; _details::com_usage uses_com; IFileOpenDialog *dialog = nullptr; IFileDialogEvents *devents = nullptr; DWORD cookie, options; _details::com_check(CoCreateInstance( CLSID_FileOpenDialog, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&dialog) )); create_dialog_event_handler(IID_PPV_ARGS(&devents)); _details::com_check(dialog->Advise(devents, &cookie)); _details::com_check(dialog->GetOptions(&options)); options |= FOS_FORCEFILESYSTEM; if (type == type::multiple_selection) { options |= FOS_ALLOWMULTISELECT; } else { options &= ~FOS_ALLOWMULTISELECT; } _details::com_check(dialog->SetOptions(options)); _details::com_check(dialog->SetFileTypes(1, &file_types)); _details::com_check(dialog->SetFileTypeIndex(1)); // this index is one-based HRESULT res = dialog->Show( parent ? _details::cast_window_impl(parent->get_impl()).get_native_handle() : nullptr ); // gather result std::vector<std::filesystem::path> result; if (res != HRESULT_FROM_WIN32(ERROR_CANCELLED)) { _details::com_check(res); IShellItemArray *files = nullptr; DWORD count; _details::com_check(dialog->GetResults(&files)); _details::com_check(files->GetCount(&count)); result.reserve(count); for (DWORD i = 0; i < count; ++i) { IShellItem *item; _details::com_check(files->GetItemAt(i, &item)); LPWSTR path = nullptr; _details::com_check(item->GetDisplayName(SIGDN_FILESYSPATH, &path)); result.push_back(std::filesystem::path(path)); CoTaskMemFree(path); } files->Release(); } dialog->Unadvise(cookie); devents->Release(); dialog->Release(); return result; } #endif void clipboard::set_text(std::u8string_view text) { // see also utf8_to_wstring // allocate global memory for text std::size_t utf16_length = 1; // the number of uint16_t's to allocate for the buffer if (text.size() > 0) { // MultiByteToWideChar doesn't deal with zero-length strings int nchars = MultiByteToWideChar( CP_UTF8, 0, reinterpret_cast<const char*>(text.data()), static_cast<int>(text.size()), nullptr, 0 ); _details::winapi_check(nchars); utf16_length = static_cast<std::size_t>(nchars) + 1; } HGLOBAL buffer = GlobalAlloc(GMEM_MOVEABLE, utf16_length * sizeof(std::uint16_t)); _details::winapi_check(buffer); _details::winapi_check(GlobalLock(buffer)); { if (text.size() > 0) { // convert to utf16 assert_true_sys( MultiByteToWideChar( CP_UTF8, 0, reinterpret_cast<const char*>(text.data()), static_cast<int>(text.size()), static_cast<LPWSTR>(buffer), static_cast<int>(utf16_length) ) == utf16_length - 1, "failed to convert string from utf8 to utf16 for clipboard" ); } static_cast<std::uint16_t*>(buffer)[utf16_length - 1] = 0; // null terminator } assert_true_sys(GlobalUnlock(buffer) == 0, "failed to unlock memory"); assert_true_sys(GetLastError() != NO_ERROR, "failed to unlock memory"); _details::winapi_check(OpenClipboard(nullptr)); _details::winapi_check(SetClipboardData(CF_UNICODETEXT, buffer)); _details::winapi_check(CloseClipboard()); // chrome didn't free the buffer } bool clipboard::is_text_available() { return IsClipboardFormatAvailable(CF_UNICODETEXT); } std::optional<std::u8string> clipboard::get_text() { _details::winapi_check(OpenClipboard(nullptr)); HANDLE handle = GetClipboardData(CF_UNICODETEXT); if (handle == nullptr) { // failed to get data _details::winapi_check(CloseClipboard()); return std::nullopt; } _details::winapi_check(GlobalLock(handle)); std::u8string result = _details::wstring_to_utf8(static_cast<LPCWSTR>(handle)); _details::winapi_check(GlobalUnlock(handle)); _details::winapi_check(CloseClipboard()); return result; } double system_parameters::get_drag_deadzone_radius() { return std::abs(GetSystemMetrics(SM_CXDRAG)); } std::size_t system_parameters::get_console_width() { HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE); os::_details::winapi_check(out != nullptr); os::_details::winapi_check(out != INVALID_HANDLE_VALUE); CONSOLE_SCREEN_BUFFER_INFO info; os::_details::winapi_check(GetConsoleScreenBufferInfo(out, &info)); return static_cast<std::size_t>(info.srWindow.Right - info.srWindow.Left + 1); } namespace _details { void quote_cmd_arg(std::u8string_view arg, std::wstring &append_to, bool force) { bool has_meta = force; // first decode the argument std::u32string decoded; decoded.reserve(arg.size()); for (auto it = arg.begin(); it != arg.end(); ) { codepoint cp; if (!encodings::utf8::next_codepoint(it, arg.end(), cp)) { cp = unicode::replacement_character; } has_meta = has_meta || (cp == U' ' || cp == U'\t' || cp == U'\n' || cp == U'\v' || cp == U'"'); decoded.push_back(static_cast<char32_t>(cp)); } // no meta characters, append directly if (!has_meta) { for (char32_t c : decoded) { auto str = encodings::utf16<>::encode_codepoint(c); append_to.append(std::wstring_view( reinterpret_cast<const wchar_t*>(str.data()), str.size() / 2 )); } return; } append_to.push_back(L'"'); for (auto it = decoded.begin(); ; ++it) { std::size_t num_backslashes = 0; while (it != decoded.end() && *it == U'\\') { ++it; ++num_backslashes; } if (it == decoded.end()) { // escape all backslashes, but let the terminating double quotation mark we add below be // interpreted as a metacharacter append_to.append(num_backslashes * 2, L'\\'); break; } else if (*it == U'"') { // escape all backslashes and the following double quotation mark append_to.append(num_backslashes * 2 + 1, L'\\'); append_to.push_back(L'"'); } else { // backslashes aren't special here append_to.append(num_backslashes, L'\\'); auto str = encodings::utf16<>::encode_codepoint(*it); append_to.append(std::wstring_view( reinterpret_cast<const wchar_t*>(str.data()), str.size() / 2 )); } } append_to.push_back(L'"'); } } } #ifdef CP_LOG_STACKTRACE # ifdef _MSC_VER # pragma comment(lib, "dbghelp.lib") # ifdef UNICODE # define DBGHELP_TRANSLATE_TCHAR # endif # include <DbgHelp.h> namespace codepad { void logger::log_entry::append_stacktrace() { constexpr static DWORD max_frames = 1000; constexpr static std::size_t max_symbol_length = 1000; void *frames[max_frames]; HANDLE proc = GetCurrentProcess(); unsigned char symmem[sizeof(SYMBOL_INFO) + max_symbol_length * sizeof(TCHAR)]; auto syminfo = reinterpret_cast<PSYMBOL_INFO>(symmem); syminfo->MaxNameLen = max_symbol_length; syminfo->SizeOfStruct = sizeof(SYMBOL_INFO); IMAGEHLP_LINE64 lineinfo; lineinfo.SizeOfStruct = sizeof(lineinfo); DWORD line_disp; assert_true_sys( SymInitialize(GetCurrentProcess(), nullptr, true), "failed to initialize symbols" ); WORD numframes = CaptureStackBackTrace(0, max_frames, frames, nullptr); _contents << "\n-- stacktrace --\n"; for (WORD i = 0; i < numframes; ++i) { auto addr = reinterpret_cast<DWORD64>(frames[i]); std::u8string func = u8"??", file = func; std::string line = "??"; // FIXME this is really ugly if (SymFromAddr(proc, addr, nullptr, syminfo)) { func = os::_details::wstring_to_utf8(syminfo->Name); } if (SymGetLineFromAddr64(proc, addr, &line_disp, &lineinfo)) { file = os::_details::wstring_to_utf8(lineinfo.FileName); line = std::to_string(lineinfo.LineNumber); } *this << " " << func << "(0x" << frames[i] << ") @" << file << ":" << line << "\n"; } _contents << "\n-- stacktrace --\n"; assert_true_sys(SymCleanup(GetCurrentProcess()), "failed to clean up symbols"); } } # else namespace codepad { void logger::log_entry::append_stacktrace() { _contents << "\n-- [stacktrace not supported] --\n"; } } # endif #endif namespace codepad::ui { /*font_parameters font_manager::get_default_ui_font_parameters() { NONCLIENTMETRICS ncmetrics; ncmetrics.cbSize = sizeof(ncmetrics); _details::winapi_check(SystemParametersInfo(SPI_GETNONCLIENTMETRICS, sizeof(ncmetrics), &ncmetrics, 0)); const LOGFONT &logfnt = ncmetrics.lfMenuFont; HFONT fnt = CreateFontIndirect(&logfnt); _details::winapi_check(fnt); HDC dc = GetDC(nullptr); _details::winapi_check(dc); HGDIOBJ original = SelectObject(dc, fnt); _details::gdi_check(original); TEXTMETRIC metrics; _details::winapi_check(GetTextMetrics(dc, &metrics)); POINT pts[2]; pts[0].y = 0; pts[1].y = metrics.tmHeight - metrics.tmInternalLeading; _details::winapi_check(LPtoDP(dc, pts, 2)); _details::gdi_check(SelectObject(dc, original)); _details::winapi_check(DeleteObject(fnt)); return font_parameters( os::_details::wstring_to_utf8(logfnt.lfFaceName), static_cast<std::size_t>(pts[1].y - pts[0].y), (logfnt.lfWeight > FW_REGULAR ? font_style::bold : font_style::normal) | (logfnt.lfItalic ? font_style::italic : font_style::normal) ); }*/ }
32.601399
111
0.70449
[ "vector" ]
be0ea395c49562c7fedb0889e9b19e133e56157e
5,079
cpp
C++
Game/Source/Scene.cpp
Taks7/GameDevelopment1
f4104c7052d7e4deeecd03a065def7c584d69b1e
[ "MIT" ]
null
null
null
Game/Source/Scene.cpp
Taks7/GameDevelopment1
f4104c7052d7e4deeecd03a065def7c584d69b1e
[ "MIT" ]
null
null
null
Game/Source/Scene.cpp
Taks7/GameDevelopment1
f4104c7052d7e4deeecd03a065def7c584d69b1e
[ "MIT" ]
null
null
null
#include "App.h" #include "Input.h" #include "Textures.h" #include "Audio.h" #include "Render.h" #include "Window.h" #include "Scene.h" #include "Map.h" #include "ModulePhysics.h" #include "ModulePlayer.h" #include "ModuleFadeToBlack.h" #include "Defs.h" #include "Log.h" Scene::Scene() : Module() { name.Create("scene"); } // Destructor Scene::~Scene() {} // Called before render is available bool Scene::Awake(pugi::xml_node& config) { LOG("Loading Scene"); bool ret = true; return ret; } // Called before the first frame bool Scene::Start() { /*app->render->camera.w = 200; app->render->camera.h = 200; app->render->camera.x = -600; app->render->camera.y = -1200;*/ app->audio->PlayMusic("Assets/audio/music/GamePlaySEGASonic.ogg"); background = app->tex->Load("Assets/maps/backgroundPlatformerGameFinal.png"); app->map->Enable(); // L03: DONE: Load map app->map->Load("tileMap1.tmx"); app->player->Enable(); app->map->Colliders(); app->render->camera.x = app->map->MapToWorld(0, 0).x; app->render->camera.y = app->map->MapToWorld(0, -130).y; return true; } // Called each loop iteration bool Scene::PreUpdate() { return true; } // Called each loop iteration bool Scene::Update(float dt) { if (app->player->horizonalCamera == false) { app->render->camera.x = -(app->player->pbody->body->GetPosition().x * 100) + 630; } if (app->player->verticalCamera == false) { app->render->camera.y = -(app->player->pbody->body->GetPosition().y * 100) + 450; } // L02: DONE 3: Request Load / Save when pressing L/S if(app->input->GetKey(SDL_SCANCODE_F6) == KEY_DOWN) LoadGameRequest(); if(app->input->GetKey(SDL_SCANCODE_F5) == KEY_DOWN) SaveGameRequest(); if(app->input->GetKey(SDL_SCANCODE_UP) == KEY_REPEAT) app->render->camera.y -= 4; if(app->input->GetKey(SDL_SCANCODE_DOWN) == KEY_REPEAT) app->render->camera.y += 4; if(app->input->GetKey(SDL_SCANCODE_LEFT) == KEY_REPEAT) app->render->camera.x -= 4; if(app->input->GetKey(SDL_SCANCODE_RIGHT) == KEY_REPEAT) app->render->camera.x += 4; if (app->input->GetKey(SDL_SCANCODE_F9) == KEY_REPEAT) app->map->debugColliders = !app->map->debugColliders; /*if (camera.y <= 0 || camera.h >= -720) { if(camera.y >= 0) camera.y = 0; if (camera.y <= -2319) camera.y = -2319; } if (camera.x <= 0 || camera.x >= -1280) { if (camera.x >= 0) camera.x = 0; if (camera.x <= -4476) camera.x = -4476; }*/ //app->render->DrawTexture(img, 380, 100); // Placeholder not needed any more // Draw map // L03: DONE 7: Set the window title with map/tileset info SString title("Map:%dx%d Tiles:%dx%d Tilesets:%d", app->map->mapData.width, app->map->mapData.height, app->map->mapData.tileWidth, app->map->mapData.tileHeight, app->map->mapData.tilesets.count()); app->win->SetTitle("Platform Game - LEVEL 1"); app->render->DrawTexture(background, -300, 1240, NULL, 0.75f); app->map->Draw(); return true; } // Called each loop iteration bool Scene::PostUpdate() { bool ret = true; if(app->input->GetKey(SDL_SCANCODE_ESCAPE) == KEY_DOWN) ret = false; return ret; } // Called before quitting bool Scene::CleanUp() { LOG("Freeing scene"); app->tex->UnLoad(background); app->map->Disable(); return true; } void Scene::SaveGameRequest() { pugi::xml_document saveFile; pugi::xml_parse_result result = saveFile.load_file("save_game.xml"); pugi::xml_node save_node; pugi::xml_node level; pugi::xml_node player; pugi::xml_node camera; if (result == NULL) { pugi::xml_node declaration = saveFile.append_child(pugi::node_declaration); declaration.append_attribute("version") = "1.0"; save_node = saveFile.append_child("game_state"); level = save_node.append_child("level"); level.append_attribute("value"); player = save_node.append_child("player"); player.append_attribute("x"); player.append_attribute("y"); player.append_attribute("state"); camera = save_node.append_child("camera"); camera.append_attribute("x"); camera.append_attribute("y"); } else { save_node = saveFile.child("game_state"); level = save_node.child("level"); player = save_node.child("player"); camera = save_node.child("camera"); } level.attribute("value") = level; app->player->SavePlayer(player); camera.attribute("x") = app->render->camera.x; camera.attribute("y") = app->render->camera.y; saveFile.save_file("save_game.xml"); /*app->fadeToBlack->FadeToBlack(this, this);*/ } void Scene::LoadGameRequest() { pugi::xml_document saveFile; pugi::xml_parse_result result = saveFile.load_file("save_game.xml"); if (result != NULL) { pugi::xml_node save_node = saveFile.child("game_state"); pugi::xml_node level = save_node.child("level"); pugi::xml_node player = save_node.child("player"); playerPosition.x = player.attribute("x").as_int(); playerPosition.y = player.attribute("y").as_int(); pugi::xml_node camera = save_node.child("camera"); cameraPosition.x = camera.attribute("x").as_int(); cameraPosition.y = camera.attribute("y").as_int(); fromGameSaved = true; } }
22.9819
83
0.675133
[ "render" ]
be0fbe0796e7c7018cb68fd4885b31840707c350
280
cpp
C++
Chapter2/Hello/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
34
2016-10-03T01:39:25.000Z
2022-03-01T03:21:41.000Z
Chapter2/Hello/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
null
null
null
Chapter2/Hello/MainWindow.cpp
PacktPublishing/Cpp-Windows-Programming
9fa69bd9d7706ae205d0e6c2214c7f001c4533f3
[ "MIT" ]
31
2016-09-02T08:56:01.000Z
2022-03-12T20:15:21.000Z
#include "..\\SmallWindows\\SmallWindows.h" #include "HelloWindow.h" void MainWindow(vector<String> /* argumentList */, WindowShow windowShow) { Application::ApplicationName() = TEXT("Hello"); Application::MainWindowPtr() = new HelloWindow(windowShow); }
28
50
0.685714
[ "vector" ]
be169edce2884f6f083537279e1da6836a5c5575
8,313
cpp
C++
Programming-in-Qt/Qt_Basic/10Qt_Coin/playerscence.cpp
huruiyi/Programming-in-Qt
5d7f1e6048f4cbc4076e9d222a95c1f68c79942b
[ "MIT" ]
null
null
null
Programming-in-Qt/Qt_Basic/10Qt_Coin/playerscence.cpp
huruiyi/Programming-in-Qt
5d7f1e6048f4cbc4076e9d222a95c1f68c79942b
[ "MIT" ]
null
null
null
Programming-in-Qt/Qt_Basic/10Qt_Coin/playerscence.cpp
huruiyi/Programming-in-Qt
5d7f1e6048f4cbc4076e9d222a95c1f68c79942b
[ "MIT" ]
1
2019-07-19T22:36:30.000Z
2019-07-19T22:36:30.000Z
#include "playerscence.h" #include "mypushbutton.h" #include <QApplication> #include <QTimer> #include <QLabel> #include <QPainter> #include <QMenuBar> #include <QMenu> #include <QAction> #include <QFont> #include <QVector> #include <QDebug> #include <QPropertyAnimation> #include <QSound> #include <QMouseEvent> #include "mycoin.h" #include "dataconfig.h" PlayerScence::PlayerScence(QWidget *parent) : QMainWindow(parent) { } void PlayerScence::paintEvent(QPaintEvent *) { QPainter * painter=new QPainter(this); QPixmap pixmap; pixmap.load(":/res/OtherSceneBg.png"); painter->drawPixmap(0,0,this->width(),this->height(),pixmap); pixmap.load(":/res/Title.png"); pixmap= pixmap.scaled(pixmap.width()*0.6,pixmap.height()*0.6); painter->drawPixmap(40,30,pixmap.width(),pixmap.height(),pixmap); } PlayerScence::PlayerScence(int levelIdnex) { this->setWindowFlags(Qt::FramelessWindowHint); this->levelIdnex=levelIdnex; this->setFixedSize(320,588); this->setWindowTitle("翻金币"); this->setWindowIcon(QPixmap(":/res/Coin0001.png")); QMenuBar * bar=this->menuBar(); this->setMenuBar(bar); QMenu * startMen= bar->addMenu("开始"); QAction *quitAction=startMen->addAction("退出"); connect(quitAction,&QAction::triggered,[=](){ this->close(); }); MyPushButton *backButton=new MyPushButton(":/res/BackButton.png",":/res/BackButtonSelected.png"); backButton->setParent(this); backButton->move(this->width()-backButton->width(),this->height()-backButton->height()); connect(backButton,&MyPushButton::clicked,[=](){ QSound::play(":/res/BackButtonSound.wav"); emit this->ShowLevelScence(); }); QLabel *label=new QLabel(this); QString levelInfo=QString("Level %1").arg(this->levelIdnex); QPalette palette; palette.setColor(QPalette::WindowText,QColor(245,232,191)); label->setPalette(palette); label->setFont(QFont("微软雅黑",14,3,false)); label->setText(levelInfo); //label->move(20,this->height()-label->height()); label->setGeometry(QRect(30, this->height() - 50,120, 50)); dataConfig config; QVector<QVector<int>> data= config.mData[this->levelIdnex]; for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { this->gameArray[i][j]=data[i][j]; } } this->isWin = true; winLabel = new QLabel; QPixmap tmpPix; tmpPix.load(":/res/LevelCompletedDialogBg.png"); winLabel->setGeometry(0,0,tmpPix.width(),tmpPix.height()); winLabel->setPixmap(tmpPix); winLabel->setParent(this); winLabel->move( (this->width() - tmpPix.width())*0.5 , -tmpPix.height()); //创建金币背景图标 for(int i = 0 ; i < 4;i++) { for(int j = 0 ; j < 4;j++) { //创建背景图 利用QLabel QLabel *bg = new QLabel; bg->setGeometry(0,0,50,50); //设置大小 并且放到左上角 bg->setParent(this); bg->setPixmap(QPixmap(":/res/BoardNode.png")); bg->move(57 + i*50,200+j*50); //背景位置设置 //创建金币按钮 //初始化界面 QString str; if(this->gameArray[i][j] == 1) { str = ":/res/Coin0001.png"; } else { str = ":/res/Coin0008.png"; } MyCoin * coin = new MyCoin(str); coin->setParent(this); coin->move(59 + i*50,204+j*50); coin->posX = i; coin->posY = j; coin->flag = gameArray[i][j]; coinArray[i][j] = coin; //监听金币点击的信号 connect(coin,&MyCoin::clicked,[=](){ QSound::play(":/res/ConFlipSound.wav"); qDebug()<<"监听金币点击的信号:"<<this->x()<<" "<<this->y()<<" "<<this->isWin; coin->changeFlag(); //二维数组也跟着同步修改数据 gameArray[i][j] = gameArray[i][j]== 1 ? 0 : 1; for(int i = 0 ; i< 4;i++) { for(int j = 0 ; j< 4;j++) { coinArray[i][j]->isWin = true; } } //周围金币延时翻转 QTimer::singleShot(300,this,[=](){ QSound::play(":/res/ConFlipSound.wav"); qDebug()<<"周围金币延时翻转:"<<this->x()<<" "<<this->y()<<" "<<this->isWin; if(coin->posX + 1 <= 3) //0 1 2 3 是可以翻转的下标 { //右侧翻转条件 coinArray[coin->posX+1][coin->posY]->changeFlag(); gameArray[coin->posX+1][coin->posY] = gameArray[coin->posX+1][coin->posY]== 1 ? 0 : 1; } if(coin->posX - 1 >= 0) { //左侧翻转条件 coinArray[coin->posX-1][coin->posY]->changeFlag(); gameArray[coin->posX-1][coin->posY] = gameArray[coin->posX-1][coin->posY]== 1 ? 0 : 1; } if(coin->posY + 1 <=3) { //下侧翻转条件 coinArray[coin->posX][coin->posY+1]->changeFlag(); gameArray[coin->posX][coin->posY+1] = gameArray[coin->posX][coin->posY+1]== 1 ? 0 : 1; } if(coin->posY -1 >=0) { //上侧翻转条件 coinArray[coin->posX][coin->posY-1]->changeFlag(); gameArray[coin->posX][coin->posY-1] = gameArray[coin->posX][coin->posY-1]== 1 ? 0 : 1; } this->isWin=true; for(int ix=0;ix <4;ix++) { for(int jy=0;jy<4;jy++) { if(coinArray[ix][jy]->flag==false) { this->isWin=false; break; } } } if(this->isWin) { QSound::play(":/res/LevelWinSound.wav"); for(int ix=0;ix <4;ix++) { for(int jy=0;jy<4;jy++) { coinArray[ix][jy]->isWin=true; } } QPropertyAnimation * animation1 = new QPropertyAnimation(winLabel,"geometry"); animation1->setDuration(1000); animation1->setStartValue(QRect(winLabel->x(),winLabel->y(),winLabel->width(),winLabel->height())); animation1->setEndValue(QRect(winLabel->x(),winLabel->y()+114,winLabel->width(),winLabel->height())); animation1->setEasingCurve(QEasingCurve::OutBounce); animation1->start(); } else { for(int ix=0;ix <4;ix++) { for(int jy=0;jy<4;jy++) { coinArray[ix][jy]->isWin=false; } } } }); }); } } } void PlayerScence::mousePressEvent(QMouseEvent *event) { QPointF wpos= event->windowPos(); QPointF spos= event->screenPos(); QPointF lpos= event->localPos(); mMoveing = true; QPoint globalPos=event->globalPos(); qDebug()<<globalPos.x()<< " "<<globalPos.y()<<" "<<globalPos.rx()<<" "<<globalPos.ry()<<" "<<this->x()<<" "<<this->y(); mMovePosition = globalPos - pos(); return QWidget::mousePressEvent(event); } void PlayerScence::mouseMoveEvent(QMouseEvent *event) { if (mMoveing && (event->buttons() && Qt::LeftButton) && (event->globalPos()-mMovePosition).manhattanLength() > QApplication::startDragDistance()) { move(event->globalPos()-mMovePosition); mMovePosition = event->globalPos() - pos(); } return QWidget::mouseMoveEvent(event); } void PlayerScence::mouseReleaseEvent(QMouseEvent *event) { mMoveing = false; }
33.385542
128
0.47528
[ "geometry" ]
be1a29815e9677315be136a7cd83c5855b273511
4,487
cpp
C++
src/Utils/Utils/Scf/LcaoUtils/MolecularOrbitalsManipulation.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/Scf/LcaoUtils/MolecularOrbitalsManipulation.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
src/Utils/Utils/Scf/LcaoUtils/MolecularOrbitalsManipulation.cpp
DockBio/utilities
213ed5ac2a64886b16d0fee1fcecb34d36eea9e9
[ "BSD-3-Clause" ]
null
null
null
/** * @file * @copyright This code is licensed under the 3-clause BSD license.\n * Copyright ETH Zurich, Laboratory for Physical Chemistry, Reiher Group.\n * See LICENSE.txt for details. */ #include <Utils/DataStructures/MolecularOrbitals.h> #include <Utils/Scf/LcaoUtils/MolecularOrbitalsManipulation.h> namespace Scine { namespace Utils { namespace LcaoUtils { MolecularOrbitals MolecularOrbitalsManipulation::createRestrictedWithSwaps(const MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Swap>& swaps) { MolecularOrbitals mo = orbitals; swapRestricted(mo, swaps); return mo; } MolecularOrbitals MolecularOrbitalsManipulation::createUnrestrictedWithSwaps( const MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Swap>& alphaSwaps, const std::vector<MolecularOrbitalsManipulation::Swap>& betaSwaps) { MolecularOrbitals mo = orbitals; swapUnrestricted(mo, alphaSwaps, betaSwaps); return mo; } MolecularOrbitals MolecularOrbitalsManipulation::createRestrictedWithMixes(const MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Mix>& mixes) { MolecularOrbitals mo = orbitals; mixRestricted(mo, mixes); return mo; } MolecularOrbitals MolecularOrbitalsManipulation::createUnrestrictedWithMixes( const MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Mix>& alphaMixes, const std::vector<MolecularOrbitalsManipulation::Mix>& betaMixes) { MolecularOrbitals mo = orbitals; mixUnrestricted(mo, alphaMixes, betaMixes); return mo; } void MolecularOrbitalsManipulation::swapRestricted(MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Swap>& swaps) { swapOrbitalCoefficients(orbitals.restrictedMatrix(), swaps); } void MolecularOrbitalsManipulation::swapUnrestricted(MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Swap>& alphaSwaps, const std::vector<MolecularOrbitalsManipulation::Swap>& betaSwaps) { swapOrbitalCoefficients(orbitals.alphaMatrix(), alphaSwaps); swapOrbitalCoefficients(orbitals.betaMatrix(), betaSwaps); } void MolecularOrbitalsManipulation::mixRestricted(MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Mix>& mixes) { mixOrbitalCoefficients(orbitals.restrictedMatrix(), mixes); } void MolecularOrbitalsManipulation::mixUnrestricted(MolecularOrbitals& orbitals, const std::vector<MolecularOrbitalsManipulation::Mix>& alphaMixes, const std::vector<MolecularOrbitalsManipulation::Mix>& betaMixes) { mixOrbitalCoefficients(orbitals.alphaMatrix(), alphaMixes); mixOrbitalCoefficients(orbitals.betaMatrix(), betaMixes); } void MolecularOrbitalsManipulation::swapOrbitalCoefficients(Eigen::MatrixXd& coefficientMatrix, const std::vector<MolecularOrbitalsManipulation::Swap>& swaps) { for (const auto& s : swaps) coefficientMatrix.col(s.orbital1_).swap(coefficientMatrix.col(s.orbital2_)); } void MolecularOrbitalsManipulation::mixOrbitalCoefficients(Eigen::MatrixXd& coefficientMatrix, const std::vector<MolecularOrbitalsManipulation::Mix>& mixes) { Eigen::VectorXd temporaryOrbitalCoefficients(coefficientMatrix.rows()); for (const auto& m : mixes) { // NB: for the second orbital, we substract the second term to ensure that the two new orbitals will still be // orthonormal. temporaryOrbitalCoefficients = coefficientMatrix.col(m.orbital1_); coefficientMatrix.col(m.orbital1_) = coefficientMatrix.col(m.orbital1_) * std::cos(m.angleInRad_) + coefficientMatrix.col(m.orbital2_) * std::sin(m.angleInRad_); coefficientMatrix.col(m.orbital2_) = coefficientMatrix.col(m.orbital2_) * std::cos(m.angleInRad_) - temporaryOrbitalCoefficients * std::sin(m.angleInRad_); } } } // namespace LcaoUtils } // namespace Utils } // namespace Scine
47.734043
124
0.68665
[ "vector" ]
be22fa2215a98deec29ef736a7083cc462dae4d2
52,583
cc
C++
src/main/cpp/src/genomicsdb/genomicsdb_iterators.cc
robbdi/GenomicsDB
55734f6298ee8ab273a7e2a0b8a6691209472d06
[ "Intel", "MIT" ]
null
null
null
src/main/cpp/src/genomicsdb/genomicsdb_iterators.cc
robbdi/GenomicsDB
55734f6298ee8ab273a7e2a0b8a6691209472d06
[ "Intel", "MIT" ]
null
null
null
src/main/cpp/src/genomicsdb/genomicsdb_iterators.cc
robbdi/GenomicsDB
55734f6298ee8ab273a7e2a0b8a6691209472d06
[ "Intel", "MIT" ]
null
null
null
/** * The MIT License (MIT) * Copyright (c) 2016 Intel Corporation * Copyright (c) 2020 Omics Data Automation, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "genomicsdb_iterators.h" #include "variant_cell.h" #include "variant_query_config.h" #define VERIFY_OR_THROW(X) if(!(X)) throw GenomicsDBIteratorException(#X); #if defined(DO_PROFILING) && defined(COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW) #define COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW_HISTOGRAM_BIN_SIZE 1ull #endif SingleCellTileDBIterator::SingleCellTileDBIterator(TileDB_CTX* tiledb_ctx, const VidMapper* vid_mapper, const VariantArraySchema& variant_array_schema, const std::string& array_path, const VariantQueryConfig& query_config, const size_t buffer_size) : SingleCellTileDBIterator(tiledb_ctx, 0, vid_mapper, variant_array_schema, array_path, query_config, buffer_size) {} SingleCellTileDBIterator::SingleCellTileDBIterator(TileDB_CTX* tiledb_ctx, const TileDB_Array* tiledb_array, const VidMapper* vid_mapper, const VariantArraySchema& variant_array_schema, const std::string& array_path, const VariantQueryConfig& query_config, const size_t buffer_size) : m_variant_array_schema(&variant_array_schema), m_query_config(&query_config), m_cell(new GenomicsDBColumnarCell(this)), m_tiledb_array(tiledb_array), m_owned_tiledb_array(0), m_query_column_interval_idx(0u), m_first_read_from_TileDB(true), m_done_reading_from_TileDB(false), m_in_find_intersecting_intervals_mode(false), m_in_simple_traversal_mode(false), m_at_new_query_column_interval(true), m_live_cell_markers(query_config.get_num_queried_attributes()+1u, query_config.get_num_rows_to_query()), //+1 for coords m_num_queried_rows_initialized(0), m_PQ_live_cell_markers() { #ifdef DO_PROFILING memset(m_num_cells_traversed_stats, 0, GenomicsDBIteratorStatsEnum::NUM_STATS*sizeof(uint64_t)); //No point in tracking beyond 10K cell segments m_useless_cell_interval_lengths_histogram.resize(10000u, 0ull); m_num_cells_traversed_in_find_intersecting_intervals_mode_histogram.resize(query_config.get_num_rows_to_query(), 0ull); #ifdef COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW m_cell_counts_since_last_cell_from_same_row.resize(query_config.get_num_rows_to_query(), 0ull); #endif //COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW #ifdef PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL m_num_observed_row_idxs_in_curr_window = 0ull; m_num_observed_cells_in_curr_window = 0ull; m_row_idx_to_num_observed_cells_in_curr_window.resize(query_config.get_num_rows_to_query(), 0ull); #endif //PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL #endif //DO_PROFILING const auto& attribute_ids = query_config.get_query_attributes_schema_idxs(); std::vector<const char*> attribute_names(attribute_ids.size()+1u); //+1 for the COORDS m_query_attribute_idx_vec.resize(attribute_ids.size()+1u);//+1 for the COORDS m_query_attribute_idx_num_cells_to_increment_vec.resize(attribute_ids.size()+1u, 0u); m_query_attribute_idx_to_tiledb_buffer_idx.resize(attribute_ids.size()+1u);//+1 for the COORDS for (auto i=0ull; i<attribute_ids.size(); ++i) { auto schema_idx = attribute_ids[i]; attribute_names[i] = m_variant_array_schema->attribute_name(schema_idx).c_str(); m_query_attribute_idx_to_tiledb_buffer_idx[i] = m_buffer_pointers.size(); auto is_variable_length_field = m_variant_array_schema->is_variable_length_field(schema_idx); //TileDB does not have a way to distinguish between char, string and int8_t fields //Hence, a series of possibly messy checks here assert(vid_mapper); const auto* vid_field_info = vid_mapper->get_field_info(attribute_names[i]); auto curr_type_index = (vid_field_info && vid_field_info->get_genomicsdb_type().get_tuple_element_bcf_ht_type(0u) == BCF_HT_FLAG) ? std::type_index(typeid(bool)) : m_variant_array_schema->type(schema_idx); //GenomicsDBColumnarField m_fields.emplace_back(curr_type_index, is_variable_length_field ? BCF_VL_VAR : BCF_VL_FIXED, m_variant_array_schema->val_num(schema_idx), buffer_size); //Buffer pointers and size m_buffer_pointers.push_back(0); m_buffer_sizes.push_back(0); m_skip_counts.push_back(0u); if (is_variable_length_field) { m_buffer_pointers.push_back(0); m_buffer_sizes.push_back(0); m_skip_counts.push_back(0u); } } //Co-ordinates auto coords_idx = attribute_ids.size(); attribute_names[coords_idx] = TILEDB_COORDS; m_query_attribute_idx_to_tiledb_buffer_idx[coords_idx] = m_buffer_pointers.size(); //GenomicsDBColumnarField m_fields.emplace_back(m_variant_array_schema->dim_type(), BCF_VL_FIXED, m_variant_array_schema->dim_length(), buffer_size); //Buffer pointers and size for COORDS m_buffer_pointers.push_back(0); m_buffer_sizes.push_back(0); m_skip_counts.push_back(0u); //Set row idx for live cell markers for (auto i=0ull; i<query_config.get_num_rows_to_query(); ++i) m_live_cell_markers.set_row_idx(i, query_config.get_array_row_idx_for_query_row_idx(i)); //END query idx assert(m_query_config->is_defined_query_idx_for_known_field_enum(GVCF_END_IDX)); m_END_query_idx = m_query_config->get_query_idx_for_known_field_enum(GVCF_END_IDX); assert(m_END_query_idx < m_fields.size() && m_END_query_idx == 0u); //END must always be the first field //first read begin_new_query_column_interval(tiledb_ctx, array_path.c_str(), &attribute_names); } SingleCellTileDBIterator::~SingleCellTileDBIterator() { if (m_cell) delete m_cell; m_cell = 0; if (m_owned_tiledb_array) tiledb_array_finalize(m_owned_tiledb_array); m_owned_tiledb_array = 0; m_tiledb_array = 0; #ifdef DO_PROFILING std::cerr << "Iterator stats"; for (auto i=0u; i<GenomicsDBIteratorStatsEnum::NUM_STATS; ++i) std::cerr << "," << m_num_cells_traversed_stats[i]; std::cerr << "\n"; std::cerr << "Useless cell segment lengths histogram\n"; for (auto i=0ull; i<m_useless_cell_interval_lengths_histogram.size(); ++i) std::cerr << i << " " <<m_useless_cell_interval_lengths_histogram[i]<<"\n"; auto num_live_list_entries = 0ull; auto num_free_list_entries = 0ull; for (const auto& field : m_fields) { num_free_list_entries += field.get_free_buffer_list_length(); num_live_list_entries += field.get_live_buffer_list_length(); } std::cerr << "Buffer_lists_lengths final "<<num_free_list_entries <<" "<<num_live_list_entries <<"\n"; std::cerr << "Histogram:\n"; for (auto val : m_num_cells_traversed_in_find_intersecting_intervals_mode_histogram) std::cerr << val << "\n"; #ifdef COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW std::cerr << "COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW histogram\n"; for (auto i=0ull; i<m_histogram_cell_counts_since_last_cell_from_same_row.size(); ++i) std::cerr << COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW_HISTOGRAM_BIN_SIZE*(i+1ull) << " " << m_histogram_cell_counts_since_last_cell_from_same_row[i] << "\n"; m_histogram_cell_counts_since_last_cell_from_same_row.clear(); m_cell_counts_since_last_cell_from_same_row.clear(); #endif //COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW_HISTOGRAM_BIN_SIZE #ifdef PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL //Final window if (m_num_observed_cells_in_curr_window > 0u) std::cerr << m_observed_cells_in_curr_window[0].second << '\t' << INT64_MAX-1 << '\t' << m_num_observed_cells_in_curr_window << '\n'; #endif //PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL #endif //DO_PROFILING } inline bool SingleCellTileDBIterator::keep_advancing_in_find_intersecting_intervals_mode() const { return (!m_done_reading_from_TileDB && (m_num_queried_rows_initialized < m_query_config->get_num_rows_to_query())); } void SingleCellTileDBIterator::begin_new_query_column_interval(TileDB_CTX* tiledb_ctx, const char* array_path, std::vector<const char*>* attribute_names) { do { //This can happen iff in the previous iteration intersecting intervals were searched OR //full array scan is requested and this is the first time a read is being performed if (m_in_find_intersecting_intervals_mode || (m_first_read_from_TileDB && (m_query_config->get_num_column_intervals() == 0u))) move_into_simple_traversal_mode(); else { reset_for_next_query_interval(); //If first read, do the read without worrying about m_query_column_interval_idx if (!m_first_read_from_TileDB) { //Move to next interval ++m_query_column_interval_idx; //If no more query intervals remaining - exit if (m_query_column_interval_idx >= m_query_config->get_num_column_intervals()) { m_done_reading_from_TileDB = true; return; } } m_in_find_intersecting_intervals_mode = true; } auto smallest_row_idx_in_array = m_query_config->get_smallest_row_idx_in_array(); //Range of the query int64_t query_range[4] = { smallest_row_idx_in_array, static_cast<int64_t>(m_query_config->get_num_rows_in_array()+smallest_row_idx_in_array-1), //inclusive bounds 0, INT64_MAX-1 }; if (m_query_config->get_num_column_intervals() > 0u) { assert(m_query_column_interval_idx < m_query_config->get_num_column_intervals()); query_range[2] = m_query_config->get_column_begin(m_query_column_interval_idx); if (m_in_simple_traversal_mode) query_range[3] = m_query_config->get_column_end(m_query_column_interval_idx); } auto status = -1; if (m_tiledb_array == 0) { assert(array_path && attribute_names && tiledb_ctx); /* Initialize the array in READ mode. */ status = tiledb_array_init( tiledb_ctx, &m_owned_tiledb_array, array_path, TILEDB_ARRAY_READ, reinterpret_cast<const void*>(query_range), &((*attribute_names)[0]), attribute_names->size()); if (status != TILEDB_OK) throw GenomicsDBIteratorException(std::string("Error while initializing TileDB array object") + "\nTileDB error message : "+tiledb_errmsg); m_tiledb_array = m_owned_tiledb_array; } else { //TileDB_Array object is provided by caller and this is the first read, reset attributes to query if (m_first_read_from_TileDB) { assert(attribute_names); status = tiledb_array_reset_attributes(m_tiledb_array, &((*attribute_names)[0]), attribute_names->size()); if (status == TILEDB_OK && !m_query_config->get_query_filter().empty()) { status = tiledb_array_apply_filter(m_tiledb_array, m_query_config->get_query_filter().c_str()); } if (status != TILEDB_OK) throw GenomicsDBIteratorException(std::string("Error while initializing attributes for the TileDB array object") + "\nTileDB error message : "+tiledb_errmsg); } status = tiledb_array_reset_subarray(m_tiledb_array, reinterpret_cast<const void*>(query_range)); if (status != TILEDB_OK) throw GenomicsDBIteratorException(std::string("Error in tiledb_array_reset_subarray()") + "\nTileDB error message : "+tiledb_errmsg); } read_from_TileDB(false); m_first_read_from_TileDB = false; if (!m_done_reading_from_TileDB) { //This is useful when a subset of rows is queried - skip rows not part of query advance_to_next_useful_cell(0u); //Dealing with new query interval begin if (m_in_find_intersecting_intervals_mode) { #ifdef DO_PROFILING auto num_useless_cells_traversed = m_num_cells_traversed_stats[GenomicsDBIteratorStatsEnum::NUM_USELESS_CELLS_IN_FIND_INTERSECTING_INTERVALS_MODE]; #endif //Array done or all initialized - exit loop while (keep_advancing_in_find_intersecting_intervals_mode()) { #ifdef DO_PROFILING assert(m_num_queried_rows_initialized < m_query_config->get_num_rows_to_query()); m_num_cells_traversed_in_find_intersecting_intervals_mode_histogram[m_num_queried_rows_initialized] += (m_num_cells_traversed_stats[GenomicsDBIteratorStatsEnum::NUM_USELESS_CELLS_IN_FIND_INTERSECTING_INTERVALS_MODE] - num_useless_cells_traversed); num_useless_cells_traversed = m_num_cells_traversed_stats[GenomicsDBIteratorStatsEnum::NUM_USELESS_CELLS_IN_FIND_INTERSECTING_INTERVALS_MODE]; #endif handle_current_cell_in_find_intersecting_intervals_mode(); if (keep_advancing_in_find_intersecting_intervals_mode()) advance_to_next_useful_cell(1u); } #ifdef DO_PROFILING auto num_live_list_entries = 0ull; auto num_free_list_entries = 0ull; for (const auto& field : m_fields) { num_free_list_entries += field.get_free_buffer_list_length(); num_live_list_entries += field.get_live_buffer_list_length(); } std::cerr << "Buffer_lists_lengths end_of_intersecting_intervals_mode "<<num_free_list_entries <<" "<<num_live_list_entries <<"\n"; #endif } } //If done reading current column interval, move to next query column interval, if any remaining OR //if in find intersecting intervals mode, switch to simple traversal in the next iteration } while ((m_done_reading_from_TileDB && m_PQ_live_cell_markers.empty() && (m_query_column_interval_idx+1u) < m_query_config->get_num_column_intervals()) || m_in_find_intersecting_intervals_mode); } void SingleCellTileDBIterator::move_into_simple_traversal_mode() { //Move into simple traversal mode m_done_reading_from_TileDB = false; m_in_find_intersecting_intervals_mode = false; m_in_simple_traversal_mode = true; //Query all attributes m_query_attribute_idx_vec.resize(m_fields.size()); for (auto i=0u; i<m_fields.size(); ++i) m_query_attribute_idx_vec[i] = i; } void SingleCellTileDBIterator::reset_for_next_query_interval() { m_done_reading_from_TileDB = false; m_in_find_intersecting_intervals_mode = false; m_in_simple_traversal_mode = false; m_at_new_query_column_interval = true; //Reset markers assert(m_PQ_live_cell_markers.empty()); m_live_cell_markers.reset(); m_num_queried_rows_initialized = 0u; //Move all buffers to free list - moving to the next query interval for (auto& field : m_fields) field.move_all_buffers_from_live_list_to_free_list(); //Query all attributes m_query_attribute_idx_vec.resize(m_fields.size()); for (auto i=0u; i<m_fields.size(); ++i) m_query_attribute_idx_vec[i] = i; } void SingleCellTileDBIterator::read_from_TileDB(const bool skip_cells) { //Zero out all buffer sizes memset(&(m_buffer_sizes[0]), 0, m_buffer_sizes.size()*sizeof(size_t)); //Zero out skip counts m_skip_counts.assign(m_skip_counts.size(), 0u); //Only set non-0 buffer sizes for attributes for which we wish to get more data for (auto i=0ull; i<m_query_attribute_idx_vec.size(); ++i) { auto query_idx = m_query_attribute_idx_vec[i]; assert(static_cast<size_t>(query_idx) < m_fields.size()); auto& genomicsdb_columnar_field = m_fields[query_idx]; //Get a free buffer and move it to the live list - buffer gets added to tail of live list genomicsdb_columnar_field.move_buffer_to_live_list(genomicsdb_columnar_field.get_or_allocate_free_buffer()); //Always read new data into tail auto* genomicsdb_buffer_ptr = genomicsdb_columnar_field.get_live_buffer_list_tail(); assert(genomicsdb_buffer_ptr); assert(static_cast<size_t>(query_idx) < m_query_attribute_idx_to_tiledb_buffer_idx.size()); auto buffer_idx = m_query_attribute_idx_to_tiledb_buffer_idx[query_idx]; assert(buffer_idx < m_buffer_pointers.size()); auto skip_count = skip_cells ? m_query_attribute_idx_num_cells_to_increment_vec[i] : 0ull; //For variable length field, first the offsets buffer if (genomicsdb_columnar_field.is_variable_length_field()) { m_buffer_pointers[buffer_idx] = reinterpret_cast<void*>(genomicsdb_buffer_ptr->get_offsets_pointer()); m_buffer_sizes[buffer_idx] = genomicsdb_buffer_ptr->get_offsets_size_in_bytes(); m_skip_counts[buffer_idx] = skip_count; ++buffer_idx; assert(buffer_idx < m_buffer_pointers.size()); } m_buffer_pointers[buffer_idx] = reinterpret_cast<void*>(genomicsdb_buffer_ptr->get_raw_pointer()); m_buffer_sizes[buffer_idx] = genomicsdb_buffer_ptr->get_data_vector_size_in_bytes(); m_skip_counts[buffer_idx] = skip_count; } auto status = tiledb_array_skip_and_read(m_tiledb_array, &(m_buffer_pointers[0]), &(m_buffer_sizes[0]), &(m_skip_counts[0u])); if (status != TILEDB_OK) throw GenomicsDBIteratorException(std::string("Error while reading from TileDB array ") + "\nTileDB error message : "+tiledb_errmsg); #ifdef DEBUG auto num_done_fields = 0u; //tiledb_array_skip_and_read must have skipped all cells that needed to be skipped for (auto val : m_skip_counts) assert(val == 0u); #endif //Set number of live entries in each buffer for (auto i=0ull; i<m_query_attribute_idx_vec.size(); ++i) { auto query_idx = m_query_attribute_idx_vec[i]; auto& genomicsdb_columnar_field = m_fields[query_idx]; auto* genomicsdb_buffer_ptr = genomicsdb_columnar_field.get_live_buffer_list_tail(); auto buffer_idx = m_query_attribute_idx_to_tiledb_buffer_idx[query_idx]; //tiledb_array_skip_and_read() must have taken care of this assert(m_skip_counts[buffer_idx] == 0u); m_query_attribute_idx_num_cells_to_increment_vec[i] = 0u; //index i, not query_idx //For variable length field, first the offsets buffer auto filled_buffer_size = m_buffer_sizes[buffer_idx]; auto num_live_entries = 0u; if (genomicsdb_columnar_field.is_variable_length_field()) { num_live_entries = filled_buffer_size/sizeof(size_t); genomicsdb_buffer_ptr->set_num_live_entries(num_live_entries); //Append size of the variable length field genomicsdb_buffer_ptr->set_offset(num_live_entries, m_buffer_sizes[buffer_idx+1u]); //tiledb_array_skip_and_read() must have taken care of this assert(m_skip_counts[buffer_idx+1u] == 0u); } else { num_live_entries = filled_buffer_size/ (genomicsdb_columnar_field.get_fixed_length_field_size_in_bytes()); genomicsdb_buffer_ptr->set_num_live_entries(num_live_entries); } //Marks data as valid/invalid genomicsdb_columnar_field.set_valid_vector_in_live_buffer_list_tail_ptr(); if (num_live_entries == 0u) { #ifdef DEBUG ++num_done_fields; #endif m_done_reading_from_TileDB = true; genomicsdb_columnar_field.move_buffer_to_free_list(genomicsdb_buffer_ptr); } } #ifdef DEBUG //The way the code is written, the final call to read_from_TileDB() will attempt to //fetch data for all queried fields. TileDB should return 0 for all fields. Hence, either all //queried fields return with 0 size or have some data to process assert(num_done_fields == 0u || (num_done_fields == m_query_attribute_idx_vec.size() && m_done_reading_from_TileDB)); #endif } void SingleCellTileDBIterator::initialize_live_cell_marker_from_tail(const size_t row_query_idx, const int64_t* coords, const int64_t END_field_value) { const auto row_idx = coords[0]; const auto coords_column = coords[1]; assert(m_query_config->is_queried_array_row_idx(row_idx)); assert(m_live_cell_markers.get_row_idx(row_query_idx) == row_idx); //Set initialized m_live_cell_markers.set_initialized(row_query_idx, true); m_live_cell_markers.set_valid(row_query_idx, true); m_live_cell_markers.set_column_interval(row_query_idx, coords_column, END_field_value); //Track offsets for each field and keep the buffer alive for (auto i=0u; i<m_fields.size(); ++i) { auto& genomicsdb_columnar_field = m_fields[i]; auto* genomicsdb_buffer_ptr = genomicsdb_columnar_field.get_live_buffer_list_tail(); assert(genomicsdb_buffer_ptr); m_live_cell_markers.set_field_marker(i, row_query_idx, genomicsdb_buffer_ptr, genomicsdb_columnar_field.get_curr_index_in_live_list_tail()); genomicsdb_buffer_ptr->increment_num_live_entries(); } } void SingleCellTileDBIterator::decrement_num_live_entries_in_live_cell_marker(const size_t row_query_idx) { assert(m_live_cell_markers.is_valid(row_query_idx) && m_live_cell_markers.is_initialized(row_query_idx)); for (auto i=0u; i<m_fields.size(); ++i) { auto* buffer_ptr = m_live_cell_markers.get_buffer(i, row_query_idx); buffer_ptr->decrement_num_live_entries(1u); if (buffer_ptr->get_num_live_entries() == 0u) m_fields[i].move_buffer_to_free_list(buffer_ptr); } m_live_cell_markers.set_valid(row_query_idx, false); m_live_cell_markers.set_initialized(row_query_idx, false); } void SingleCellTileDBIterator::handle_current_cell_in_find_intersecting_intervals_mode() { assert(m_in_find_intersecting_intervals_mode && !m_done_reading_from_TileDB); auto& coords_columnar_field = m_fields[m_fields.size()-1u]; auto* coords = reinterpret_cast<int64_t*>( coords_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( coords_columnar_field.get_live_buffer_list_tail(), coords_columnar_field.get_curr_index_in_live_list_tail() ) ); auto& END_columnar_field = m_fields[m_END_query_idx]; auto& END_field_value = *(reinterpret_cast<int64_t*>( END_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( END_columnar_field.get_live_buffer_list_tail(), END_columnar_field.get_curr_index_in_live_list_tail() ) )); auto row_idx = coords[0]; auto row_query_idx = m_query_config->get_query_row_idx_for_array_row_idx(row_idx); //should not be initialize already assert(!(m_live_cell_markers.is_initialized(row_query_idx))); //Reference - value gets modified auto& coords_column = coords[1]; assert(m_query_column_interval_idx < m_query_config->get_num_column_intervals()); auto query_interval_begin = m_query_config->get_column_begin(m_query_column_interval_idx); //Only deal with intervals that begin before query_interval_begin and intersect it assert(is_duplicate_cell_at_end_position_that_begins_before_query_interval(coords_column, END_field_value, query_interval_begin)); std::swap(coords_column, END_field_value); initialize_live_cell_marker_from_tail(row_query_idx, coords, END_field_value); //Add to PQ m_PQ_live_cell_markers.push(ColumnRowQueryIdxPair(coords[1], row_query_idx)); ++m_num_queried_rows_initialized; } const SingleCellTileDBIterator& SingleCellTileDBIterator::operator++() { //Intervals intersecting the column begin still exist in PQ if (!m_PQ_live_cell_markers.empty()) { auto row_query_idx = m_PQ_live_cell_markers.top().second; m_PQ_live_cell_markers.pop(); //Decrease #live entries and move to free list if needed decrement_num_live_entries_in_live_cell_marker(row_query_idx); m_at_new_query_column_interval = false; if (!m_PQ_live_cell_markers.empty()) return *this; //Done processing PQ cells //Note that begin_new_query_column_interval() moves into simple traversal mode //immediately after processing cells that intersect with query column interval begin //If m_done_reading_from_TileDB, this means that no cells in the current query interval //were available in the simple traversal mode. Move to next column interval if (m_done_reading_from_TileDB) begin_new_query_column_interval(); } else { assert(m_in_simple_traversal_mode); m_at_new_query_column_interval = false; auto increment_done = advance_to_next_useful_cell(1u); //TileDB couldn't provide > 1 cell, must move to next column interval if (!increment_done) begin_new_query_column_interval(); } return *this; } bool SingleCellTileDBIterator::advance_to_next_useful_cell(const uint64_t min_num_cells_to_increment) { uint64_t num_cells_incremented = 0ull; auto increment_done = advance_coords_and_END_till_useful_cell_found(min_num_cells_to_increment, num_cells_incremented); //Don't bother with rest of the fields since TileDB couldn't provide >= min_num_cells_to_increment if (!increment_done) return false; if (num_cells_incremented > 0u) { #ifdef DO_PROFILING increment_num_cells_traversed_stats(num_cells_incremented); #endif advance_fields_other_than_coords_END(num_cells_incremented); } return true; } //Advance iterator till a useful cell is found //A cell is "useful" iff //its row is part of the queried rows && ( //(in simple traversal mode - END >= begin) || //(in find intersecting intervals mode - !initialized)) bool SingleCellTileDBIterator::advance_coords_and_END_till_useful_cell_found( const uint64_t min_num_cells_to_increment, uint64_t& num_cells_incremented) { num_cells_incremented = 0ull; auto hitting_useless_cells = true; const auto& coords_columnar_field = m_fields[m_fields.size()-1u]; assert(m_END_query_idx < m_fields.size()); const auto& END_columnar_field = m_fields[m_END_query_idx]; auto num_cells_to_advance_in_next_iteration = min_num_cells_to_increment; const auto subset_of_rows_queried = m_query_config->get_num_rows_to_query() < m_query_config->get_num_rows_in_array(); while (hitting_useless_cells && !m_done_reading_from_TileDB) { //TODO: opportunity for vectorization //in simple mode, create bitvector Columnar[COORDS[1]] <= Columnar[END] //find first bit != 0, num_cells_to_advance == index of first bit #if defined(DO_PROFILING) && defined(PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL) update_sliding_window_to_profile_num_cells_to_traverse(coords_columnar_field); #endif auto increment_done = advance_coords_and_END(num_cells_to_advance_in_next_iteration); //TileDB couldn't provide > num_cells_to_advance_in_next_iteration if (!increment_done) return false; num_cells_incremented += num_cells_to_advance_in_next_iteration; num_cells_to_advance_in_next_iteration = 1u; //single cell stepping const auto* coords = reinterpret_cast<const int64_t*>( coords_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( coords_columnar_field.get_live_buffer_list_tail(), coords_columnar_field.get_curr_index_in_live_list_tail() ) ); //std::cerr << "COORDS "<<coords[0] <<" "<<coords[1] << "\n"; //TileDB doesn't have a good way of requesting a subset of rows //Skip over rows that are not part of the query if coords are part of the queried attributes //in this round if (subset_of_rows_queried && !(m_query_config->is_queried_array_row_idx(coords[0]))) hitting_useless_cells = true; else { auto coords_column = coords[1]; assert(END_columnar_field.get_live_buffer_list_tail()->get_num_unprocessed_entries() > 0u); auto END_field_value = *(reinterpret_cast<const int64_t*>( END_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( END_columnar_field.get_live_buffer_list_tail(), END_columnar_field.get_curr_index_in_live_list_tail() ) )); if (m_in_simple_traversal_mode) { //keep incrementing iterator if hitting duplicates at end in simple traversal mode hitting_useless_cells = is_duplicate_cell_at_end_position(coords_column, END_field_value); #if defined(DO_PROFILING) && defined(COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW) auto row_query_idx = m_query_config->get_query_row_idx_for_array_row_idx(coords[0]); auto histogram_bin_idx = (m_cell_counts_since_last_cell_from_same_row[row_query_idx]/ COUNT_NUM_CELLS_BETWEEN_TWO_CELLS_FROM_THE_SAME_ROW_HISTOGRAM_BIN_SIZE); if (histogram_bin_idx >= m_histogram_cell_counts_since_last_cell_from_same_row.size()) m_histogram_cell_counts_since_last_cell_from_same_row.resize(histogram_bin_idx+1ull, 0ull); ++(m_histogram_cell_counts_since_last_cell_from_same_row[histogram_bin_idx]); for (auto i=0ull; i<m_cell_counts_since_last_cell_from_same_row.size(); ++i) ++(m_cell_counts_since_last_cell_from_same_row[i]); m_cell_counts_since_last_cell_from_same_row[row_query_idx] = 0ull; #endif } else { assert(m_in_find_intersecting_intervals_mode); auto row_idx = coords[0]; assert(row_idx >= m_query_config->get_smallest_row_idx_in_array()); auto row_query_idx = m_query_config->get_query_row_idx_for_array_row_idx(row_idx); assert(m_live_cell_markers.get_row_idx(row_query_idx) == row_idx); //if the row is already initialized in the find intersecting intervals mode, can skip //this cell if (m_live_cell_markers.is_initialized(row_query_idx)) hitting_useless_cells = true; else { assert(m_query_column_interval_idx < m_query_config->get_num_column_intervals()); auto query_interval_begin = m_query_config->get_column_begin(m_query_column_interval_idx); //Interval that begins before the queried column interval begin and intersects it //This is a valid interval for the query and must be handled by //handle_current_cell_in_find_intersecting_intervals_mode if (is_duplicate_cell_at_end_position_that_begins_before_query_interval(coords_column, END_field_value, query_interval_begin)) { //do not set initialized to true here, handle_current_cell_in_find_intersecting_intervals_mode will //do it hitting_useless_cells = false; } else { m_live_cell_markers.set_initialized(row_query_idx, true); //Non-intersecting cell, mark initialized ++m_num_queried_rows_initialized; hitting_useless_cells = keep_advancing_in_find_intersecting_intervals_mode(); } } } } } //Increment was successful iff didn't hit the end of the array return !m_done_reading_from_TileDB; } //Advance iterator for coords and END fields bool SingleCellTileDBIterator::advance_coords_and_END(const uint64_t num_cells_to_advance) { auto curr_query_column_interval_idx = m_query_column_interval_idx; if (num_cells_to_advance == 0u) return true; //2 = coords and END m_query_attribute_idx_vec.resize(2u); //no heap operations here m_query_attribute_idx_num_cells_to_increment_vec.resize(2u); m_query_attribute_idx_vec[0u] = m_fields.size()-1u; //coords m_query_attribute_idx_vec[1u] = m_END_query_idx; m_query_attribute_idx_num_cells_to_increment_vec[0u] = num_cells_to_advance; m_query_attribute_idx_num_cells_to_increment_vec[1u] = num_cells_to_advance; increment_iterator_within_live_buffer_list_tail_ptr_for_fields(); //some fields have exhausted buffers, need to fetch from TileDB while (!m_query_attribute_idx_vec.empty()) { read_from_TileDB(false); assert(curr_query_column_interval_idx == m_query_column_interval_idx); //read_from_TileDB() might have determined that no more cells exist for the current query //interval if (m_done_reading_from_TileDB) return false; increment_iterator_within_live_buffer_list_tail_ptr_for_fields(); } return true; } void SingleCellTileDBIterator::advance_fields_other_than_coords_END(const uint64_t num_cells_to_increment) { auto curr_query_column_interval_idx = m_query_column_interval_idx; //Increment iterator for other fields //All fields other than coords and END m_query_attribute_idx_vec.resize(m_fields.size()-2u); //END must be the first field assert(m_END_query_idx == 0u); for (auto i=0u; i<m_query_attribute_idx_vec.size(); ++i) m_query_attribute_idx_vec[i] = i+1u; //END is the first field - ignore //-2 - ignore coords and END m_query_attribute_idx_num_cells_to_increment_vec.resize(m_fields.size()-2u); //For all fields, #cells to skip == num_cells_to_increment initially m_query_attribute_idx_num_cells_to_increment_vec.assign( m_query_attribute_idx_num_cells_to_increment_vec.size(), num_cells_to_increment); increment_iterator_within_live_buffer_list_tail_ptr_for_fields(); //some fields have exhausted buffers, need to fetch from TileDB while (!m_query_attribute_idx_vec.empty()) { read_from_TileDB(true); //TODO: either all fields are done reading or none are - is that right? //also, same column interval being queried assert(!m_done_reading_from_TileDB && m_query_column_interval_idx == curr_query_column_interval_idx); #ifdef DEBUG //After the skip cells API is implemented, there shouldn't be any attributes //whose cells need to be skipped after a call to read_from_TileDB() for (auto i=0u; i<m_query_attribute_idx_vec.size(); ++i) assert(m_query_attribute_idx_num_cells_to_increment_vec[i] == 0u); #endif m_query_attribute_idx_vec.resize(0u); //no more attributes to query after skip //increment_iterator_within_live_buffer_list_tail_ptr_for_fields(); } #ifdef DEBUG for (auto i=0u; i<m_fields.size(); ++i) assert(m_fields[i].get_live_buffer_list_tail() && m_fields[i].get_live_buffer_list_tail()->get_num_unprocessed_entries()); #endif } void SingleCellTileDBIterator::print(const int field_query_idx, std::ostream& fptr) const { assert(static_cast<const size_t>(field_query_idx) < m_fields.size()); auto& genomicsdb_columnar_field = m_fields[field_query_idx]; auto x = get_buffer_and_index(field_query_idx); genomicsdb_columnar_field.print_data_in_buffer_at_index(fptr, x.first, x.second); } void SingleCellTileDBIterator::increment_iterator_within_live_buffer_list_tail_ptr_for_fields() { auto next_iteration_num_query_attributes = 0u; for (auto i=0u; i<m_query_attribute_idx_vec.size(); ++i) { assert(next_iteration_num_query_attributes <= i); assert(static_cast<size_t>(m_query_attribute_idx_vec[i]) < m_fields.size()); auto& genomicsdb_columnar_field = m_fields[m_query_attribute_idx_vec[i]]; auto* genomicsdb_buffer_ptr = genomicsdb_columnar_field.get_live_buffer_list_tail(); //TODO: either all fields are done reading or none are - is that right? if (genomicsdb_buffer_ptr) { auto unprocessed_entries_delta = std::min(m_query_attribute_idx_num_cells_to_increment_vec[i], genomicsdb_buffer_ptr->get_num_unprocessed_entries()); genomicsdb_columnar_field.advance_curr_index_in_live_list_tail(unprocessed_entries_delta); genomicsdb_buffer_ptr->decrement_num_live_entries(unprocessed_entries_delta); genomicsdb_buffer_ptr->decrement_num_unprocessed_entries(unprocessed_entries_delta); if (genomicsdb_buffer_ptr->get_num_live_entries() == 0ull) //no more live entries, move buffer to free list genomicsdb_columnar_field.move_buffer_to_free_list(genomicsdb_buffer_ptr); //buffer completely processed, add attribute to next round of fetch from TileDB if (genomicsdb_buffer_ptr->get_num_unprocessed_entries() == 0ull) { m_query_attribute_idx_vec[next_iteration_num_query_attributes] = m_query_attribute_idx_vec[i]; m_query_attribute_idx_num_cells_to_increment_vec[next_iteration_num_query_attributes] = m_query_attribute_idx_num_cells_to_increment_vec[i] - unprocessed_entries_delta; ++next_iteration_num_query_attributes; } } } m_query_attribute_idx_vec.resize(next_iteration_num_query_attributes); //no heap operations occur here } void SingleCellTileDBIterator::print_ALT(const int field_query_idx, std::ostream& fptr) const { assert(static_cast<const size_t>(field_query_idx) < m_fields.size()); auto& genomicsdb_columnar_field = m_fields[field_query_idx]; auto x = get_buffer_and_index(field_query_idx); genomicsdb_columnar_field.print_ALT_data_in_buffer_at_index(fptr, x.first, x.second); } void SingleCellTileDBIterator::print_csv(const int field_query_idx, std::ostream& fptr) const { assert(static_cast<const size_t>(field_query_idx) < m_fields.size()); auto& genomicsdb_columnar_field = m_fields[field_query_idx]; auto x = get_buffer_and_index(field_query_idx); genomicsdb_columnar_field.print_data_in_buffer_at_index_as_csv(fptr, x.first, x.second); } #ifdef DO_PROFILING void SingleCellTileDBIterator::increment_num_cells_traversed_stats(const uint64_t num_cells_incremented) { m_num_cells_traversed_stats[GenomicsDBIteratorStatsEnum::TOTAL_CELLS_TRAVERSED] += num_cells_incremented; if (m_in_find_intersecting_intervals_mode) m_num_cells_traversed_stats[GenomicsDBIteratorStatsEnum::NUM_CELLS_TRAVERSED_IN_FIND_INTERSECTING_INTERVALS_MODE] += num_cells_incremented; auto num_useless_cells = (num_cells_incremented - 1ull); m_num_cells_traversed_stats[m_in_find_intersecting_intervals_mode ? GenomicsDBIteratorStatsEnum::NUM_USELESS_CELLS_IN_FIND_INTERSECTING_INTERVALS_MODE : GenomicsDBIteratorStatsEnum::NUM_USELESS_CELLS_IN_SIMPLE_TRAVERSAL_MODE] += num_useless_cells; auto idx = std::min<uint64_t>(num_useless_cells, m_useless_cell_interval_lengths_histogram.size()-1u); ++(m_useless_cell_interval_lengths_histogram[idx]); } #endif #if defined(DO_PROFILING) && defined(PROFILE_NUM_CELLS_TO_TRAVERSE_AT_EVERY_QUERY_INTERVAL) void SingleCellTileDBIterator::update_sliding_window_to_profile_num_cells_to_traverse( const GenomicsDBColumnarField& coords_columnar_field) { const auto* curr_coords = reinterpret_cast<const int64_t*>( coords_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( coords_columnar_field.get_live_buffer_list_tail(), coords_columnar_field.get_curr_index_in_live_list_tail() ) ); auto curr_row_idx = curr_coords[0]; auto num_observed_cells_in_curr_window_for_row_idx_before_increment = m_row_idx_to_num_observed_cells_in_curr_window[curr_row_idx]; ++(m_row_idx_to_num_observed_cells_in_curr_window[curr_row_idx]); ++m_num_observed_cells_in_curr_window; m_observed_cells_in_curr_window.emplace_back(curr_row_idx, curr_coords[1]); //no cells for this row were seen in the current window before this cell //Check if window is "complete" if (num_observed_cells_in_curr_window_for_row_idx_before_increment == 0u) { ++m_num_observed_row_idxs_in_curr_window; if (m_num_observed_row_idxs_in_curr_window == m_query_config->get_num_rows_to_query()) std::cerr << m_observed_cells_in_curr_window[0].second << '\t' << curr_coords[1] << '\t' << m_num_observed_cells_in_curr_window << '\n'; //Current sliding window is "complete" - move left edge of window //Complete == contains at least 1 cell from every row auto window_left_idx = 0ull; auto last_column = -1ll; //One row has no cells in window OR //Cells in the same column while (m_num_observed_row_idxs_in_curr_window == m_query_config->get_num_rows_to_query() || (window_left_idx < m_observed_cells_in_curr_window.size() && last_column == m_observed_cells_in_curr_window[window_left_idx].second)) { const auto& left_cell_pair = m_observed_cells_in_curr_window[window_left_idx]; auto left_row_idx = left_cell_pair.first; --(m_row_idx_to_num_observed_cells_in_curr_window[left_row_idx]); //No cells for this row left in the window if (m_row_idx_to_num_observed_cells_in_curr_window[left_row_idx] == 0u) --m_num_observed_row_idxs_in_curr_window; ++window_left_idx; last_column = left_cell_pair.second; } //Delete cells from the left of the window if (window_left_idx > 0u) { m_observed_cells_in_curr_window.erase(m_observed_cells_in_curr_window.begin(), m_observed_cells_in_curr_window.begin()+window_left_idx); assert(window_left_idx <= m_num_observed_cells_in_curr_window); m_num_observed_cells_in_curr_window -= window_left_idx; } } } #endif //GVCF iterator GenomicsDBGVCFIterator::GenomicsDBGVCFIterator(TileDB_CTX* tiledb_ctx, const VidMapper* vid_mapper, const VariantArraySchema& variant_array_schema, const std::string& array_path, const VariantQueryConfig& query_config, const size_t buffer_size) : GenomicsDBGVCFIterator(tiledb_ctx, 0, vid_mapper, variant_array_schema, array_path, query_config, buffer_size) {} #define INIT_INVALID_HISTOGRAM_NUM_BINS 20u GenomicsDBGVCFIterator::GenomicsDBGVCFIterator(TileDB_CTX* tiledb_ctx, const TileDB_Array* tiledb_array, const VidMapper* vid_mapper, const VariantArraySchema& variant_array_schema, const std::string& array_path, const VariantQueryConfig& query_config, const size_t buffer_size) : SingleCellTileDBIterator(tiledb_ctx, tiledb_array, vid_mapper, variant_array_schema, array_path, query_config, buffer_size), m_current_start_position(-1ll), m_current_end_position(-1ll), m_next_start_position(-1ll), m_cell(new GenomicsDBGVCFCell(this)), m_alleles_combiner(query_config.get_num_rows_to_query()) #ifdef DO_PROFILING , m_num_times_initialized(INIT_INVALID_HISTOGRAM_NUM_BINS, 0u), m_num_times_invalidated(INIT_INVALID_HISTOGRAM_NUM_BINS, 0u), m_bin_size((m_query_config->get_num_rows_to_query()+INIT_INVALID_HISTOGRAM_NUM_BINS-1)/INIT_INVALID_HISTOGRAM_NUM_BINS) #endif { m_REF_query_idx = m_query_config->get_query_idx_for_known_field_enum(GVCF_REF_IDX); m_ALT_query_idx = m_query_config->get_query_idx_for_known_field_enum(GVCF_ALT_IDX); //Constructor for SingleCellTileDBIterator invokes SingleCellTileDBIterator::begin_new_query_column_interval() //So, it's safe to call GenomicsDBGVCFIterator::begin_new_query_column_interval() begin_new_query_column_interval(); } GenomicsDBGVCFIterator::~GenomicsDBGVCFIterator() { if(m_cell) delete m_cell; m_cell = 0; #ifdef DO_PROFILING std::cerr << "INIT INVALID HISTOGRAM\n"; for(auto i=0u;i<INIT_INVALID_HISTOGRAM_NUM_BINS;++i) std::cerr << i*m_bin_size << " "<<m_num_times_initialized[i] << " " <<m_num_times_invalidated[i] <<"\n"; #endif } template<> void GenomicsDBGVCFIterator::update_num_deletions_and_MNVs<true>(const size_t row_query_idx) { const auto REF_ptr_length_pair = get_raw_pointer_and_length_for_query_idx(row_query_idx, m_REF_query_idx); const auto ALT_ptr_length_pair = get_raw_pointer_and_length_for_query_idx(row_query_idx, m_ALT_query_idx); STRING_VIEW REF(reinterpret_cast<const char*>(REF_ptr_length_pair.first), REF_ptr_length_pair.second); STRING_VIEW delimited_ALT(reinterpret_cast<const char*>(ALT_ptr_length_pair.first), ALT_ptr_length_pair.second); m_alleles_combiner.insert_allele_info(row_query_idx, REF, delimited_ALT, (m_live_cell_markers.get_begin(row_query_idx) < m_current_start_position)); } template<> void GenomicsDBGVCFIterator::update_num_deletions_and_MNVs<false>(const size_t row_query_idx) { m_alleles_combiner.remove_allele_info(row_query_idx); } void GenomicsDBGVCFIterator::begin_new_query_column_interval() { //Assumes SingleCellTileDBIterator::begin_new_query_column_interval is already invoked //Hence, the two loops execute only when SingleCellTileDBIterator::begin_new_query_column_interval //has determined that there is valid data to work on if(SingleCellTileDBIterator::end()) return; m_alleles_combiner.reset_for_next_query_interval(); const auto& coords_columnar_field = m_fields.back(); const auto& END_columnar_field = m_fields[m_END_query_idx]; m_current_start_position = (m_query_config->get_num_column_intervals() == 0u) ? -1ll : m_query_config->get_column_begin(m_query_column_interval_idx); m_query_interval_limit = (m_query_config->get_num_column_intervals() == 0u) ? m_variant_array_schema->dim_domains()[1].second : m_query_config->get_column_end(m_query_column_interval_idx); //m_current_start_position might have to be updated if //(a) there are no intersecting intervals for query interval begin AND //(b) there's valid data in simple traversal mode if(m_PQ_live_cell_markers.empty() && !m_done_reading_from_TileDB) m_current_start_position = (reinterpret_cast<const int64_t*>( coords_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( coords_columnar_field.get_live_buffer_list_tail(), coords_columnar_field.get_curr_index_in_live_list_tail() ) ))[1]; //All elements of m_PQ_live_cell_markers begin before the query interval //and intersect the query interval - hence, the m_current_start_position //of all elements of PQ is simply the start of the query interval while(!m_PQ_live_cell_markers.empty()) { auto row_query_idx = m_PQ_live_cell_markers.top().second; m_PQ_live_cell_markers.pop(); update_num_deletions_and_MNVs<true>(row_query_idx); m_end_set.insert(GVCFEndSetElementTy(m_live_cell_markers.get_end(row_query_idx), row_query_idx)); } //There might be more elements which start at query interval begin //which are accessed in simple traversal mode m_alleles_combiner.reset_before_adding_new_sample_info_at_current_position(); fill_end_set_in_simple_traversal_mode(); m_alleles_combiner.finished_updating_allele_info_for_current_position(); } const GenomicsDBGVCFIterator& GenomicsDBGVCFIterator::operator++() { assert(!m_end_set.empty()); m_current_start_position = m_current_end_position+1; //Past the limit, clean-up end set and move to next interval if(m_current_start_position > m_query_interval_limit) m_current_start_position = INT64_MAX; auto iter = m_end_set.begin(); #ifdef DO_PROFILING auto num_times_invalidated = 0ull; #endif //Remove all entries that finish at or before m_current_end_position for(;iter!=m_end_set.end();++iter) { auto min_end_element = *iter; const auto END_field_value = min_end_element.first; const auto row_query_idx = min_end_element.second; if(END_field_value < m_current_start_position) { update_num_deletions_and_MNVs<false>(row_query_idx); decrement_num_live_entries_in_live_cell_marker(row_query_idx); #ifdef DO_PROFILING ++num_times_invalidated; #endif } else break; } #ifdef DO_PROFILING ++(m_num_times_invalidated[num_times_invalidated/m_bin_size]); #endif if(iter == m_end_set.end()) { //all entries have END <= m_current_end_position m_end_set.clear(); m_current_start_position = m_next_start_position; } else m_end_set.erase(m_end_set.begin(), iter); m_alleles_combiner.reset_before_adding_new_sample_info_at_current_position(); if(m_current_start_position == m_next_start_position) fill_end_set_in_simple_traversal_mode(); else { assert(!m_end_set.empty() || m_current_start_position == INT64_MAX); update_current_end_position(); } //No more valid data - move to next query interval if needed if(m_end_set.empty() && m_done_reading_from_TileDB) { SingleCellTileDBIterator::begin_new_query_column_interval(); GenomicsDBGVCFIterator::begin_new_query_column_interval(); } m_alleles_combiner.finished_updating_allele_info_for_current_position(); m_at_new_query_column_interval = false; return *this; } void GenomicsDBGVCFIterator::fill_end_set_in_simple_traversal_mode() { //We keep searching till we find a cell whose start position is > m_current_start_position //or no more cells exist for current query interval m_next_start_position = -1; const auto& coords_columnar_field = m_fields.back(); const auto& END_columnar_field = m_fields[m_END_query_idx]; #ifdef DO_PROFILING auto num_times_initialized = 0ull; #endif while(!m_done_reading_from_TileDB && m_next_start_position == -1) { const auto* coords = reinterpret_cast<const int64_t*>( coords_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( coords_columnar_field.get_live_buffer_list_tail(), coords_columnar_field.get_curr_index_in_live_list_tail() ) ); const auto END_field_value = *(reinterpret_cast<const int64_t*>( END_columnar_field.get_raw_pointer_to_data_in_buffer_at_index( END_columnar_field.get_live_buffer_list_tail(), END_columnar_field.get_curr_index_in_live_list_tail() ) )); const auto row_query_idx = m_query_config->get_query_row_idx_for_array_row_idx(coords[0]); if(coords[1] == m_current_start_position) { assert(m_live_cell_markers.get_row_idx(row_query_idx) == coords[0]); //Handle overlapping intervals - this row already has an entry in the set if(m_live_cell_markers.is_valid(row_query_idx)) { //Remove from m_end_set auto iter = m_end_set.find(GVCFEndSetElementTy(m_live_cell_markers.get_end(row_query_idx), row_query_idx)); assert(iter != m_end_set.end()); m_end_set.erase(iter); update_num_deletions_and_MNVs<false>(row_query_idx); //Decrement num live entries decrement_num_live_entries_in_live_cell_marker(row_query_idx); } //Add new cell, initialize live marker from tail of buffer and increment live entries initialize_live_cell_marker_from_tail(row_query_idx, coords, END_field_value); update_num_deletions_and_MNVs<true>(row_query_idx); m_end_set.insert(GVCFEndSetElementTy(END_field_value, row_query_idx)); advance_to_next_useful_cell(1u); #ifdef DO_PROFILING ++num_times_initialized; #endif } else m_next_start_position = coords[1]; } #ifdef DO_PROFILING ++(m_num_times_initialized[num_times_initialized/m_bin_size]); #endif update_current_end_position(); } void GenomicsDBGVCFIterator::update_current_end_position() { if(m_next_start_position < 0) { if(m_query_config->get_num_column_intervals() == 0u) { auto& dim_domains = m_variant_array_schema->dim_domains(); m_next_start_position = dim_domains[1].second; } else m_next_start_position = m_query_config->get_column_end(m_query_column_interval_idx); //to avoid wrap-around m_next_start_position = std::min(m_next_start_position, INT64_MAX-1)+1; } if(m_alleles_combiner.get_num_calls_with_deletions_or_MNVs() > 0u) m_current_end_position = m_current_start_position; //to put spanning deletions else { const auto min_END_field_value = m_end_set.empty() ? INT64_MAX : (*(m_end_set.begin())).first; m_current_end_position = std::min(min_END_field_value, m_next_start_position-1); } }
51.805911
140
0.756081
[ "object", "vector" ]
be2d0afe86cf740805fc015e7443e2a24fd2371e
21,007
cpp
C++
src/test_application/activescenes/scenarios_redstone.cpp
Capital-Asterisk/redstone-osp
3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6
[ "MIT" ]
null
null
null
src/test_application/activescenes/scenarios_redstone.cpp
Capital-Asterisk/redstone-osp
3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6
[ "MIT" ]
null
null
null
src/test_application/activescenes/scenarios_redstone.cpp
Capital-Asterisk/redstone-osp
3f86cf6f9d26f596f3b7f8ee9d66743ac8c82db6
[ "MIT" ]
null
null
null
/** * Open Space Program * Copyright © 2019-2021 Open Space Program Project * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "scenarios.h" #include "CameraController.h" #include "redstone_osp.h" #include "scene_physics.h" // also happens to include mesh owning #include "common_scene.h" #include "common_renderer_gl.h" #include "../ActiveApplication.h" #include <osp/Active/basic.h> #include <osp/Active/drawing.h> #include <osp/Active/SysHierarchy.h> #include <osp/Active/SysRender.h> #include <osp/Active/opengl/SysRenderGL.h> #include <osp/Shaders/Flat.h> #include <osp/Shaders/Phong.h> #include <osp/Shaders/MeshVisualizer.h> #include <osp/Resource/resources.h> #include <longeron/id_management/refcount.hpp> #include <osp/logging.h> #include <Magnum/GL/Renderer.h> #include <Magnum/GL/DefaultFramebuffer.h> #include <Magnum/Math/Color.h> #include <atomic> #include <tuple> #include <unordered_map> using Magnum::Trade::MeshData; using Magnum::Trade::ImageData2D; using osp::Vector3l; using osp::Matrix3; using osp::Matrix4; // for the 0xrrggbb_rgbf and angle literals using namespace Magnum::Math::Literals; namespace testapp::redstone { auto const gc_meshsUsed = std::array{ "Redstone/redstone.gltf:Block", "Redstone/redstone.gltf:TorchLit", "Redstone/redstone.gltf:Repeater", "Redstone/redstone.gltf:Torch", "Redstone/redstone.gltf:ShortTorch", "Redstone/redstone.gltf:RepeaterLit", "Redstone/redstone.gltf:ShortTorchLit", "Redstone/redstone.gltf:Lamp", "Redstone/redstone.gltf:LampLit", "Redstone/redstone.gltf:Comparator", "Redstone/redstone.gltf:ComparatorLit", "Redstone/redstone.gltf:DustStraight", "Redstone/redstone.gltf:Dust", "Redstone/redstone.gltf:DustRt", "Redstone/redstone.gltf:DustBk", "Redstone/redstone.gltf:DustLf", "Redstone/redstone.gltf:DustFd", "Redstone/redstone.gltf:LeverBlock", "Redstone/redstone.gltf:Lever", "Redstone/redstone.gltf:LeverLit" }; /** * @brief State of the entire engine test scene */ struct RedstoneTestScene : RedstoneScene { // Crosshair osp::active::ActiveEnt m_cube; osp::active::TexId m_blockTexture; int m_matFlat{0}; int m_matWireframe{0}; }; void Redstone::setup_scene(CommonTestScene &rScene, osp::PkgId pkg) { using namespace osp::active; auto &rScnPhys = rScene.emplace<scenes::PhysicsData>(); auto &rScnRs = rScene.emplace<RedstoneTestScene>(); rScene.m_onCleanup.push_back(&scenes::PhysicsData::cleanup); osp::Resources &rResources = *rScene.m_pResources; // Convenient function to get a reference-counted mesh owner auto const quick_add_mesh = [&rScene, &rResources, pkg] (std::string_view name) -> MeshIdOwner_t { osp::ResId const res = rResources.find(osp::restypes::gc_mesh, pkg, name); assert(res != lgrn::id_null<osp::ResId>()); MeshId const meshId = SysRender::own_mesh_resource(rScene.m_drawing, rScene.m_drawingRes, rResources, res); return rScene.m_drawing.m_meshRefCounts.ref_add(meshId); }; // Allocate space to fit all materials rScnRs.m_matFlat = rScene.m_materialCount++; rScnRs.m_matWireframe = rScene.m_materialCount++; rScene.m_drawing.m_materials.resize(rScene.m_materialCount); // Create hierarchy root entity rScene.m_hierRoot = rScene.m_activeIds.create(); rScene.m_basic.m_hierarchy.emplace(rScene.m_hierRoot); // Create camera entity ActiveEnt camEnt = rScene.m_activeIds.create(); // Create camera transform and draw transform ACompTransform &rCamTf = rScene.m_basic.m_transform.emplace(camEnt); rCamTf.m_transform.translation().z() = 25; // Create camera component ACompCamera &rCamComp = rScene.m_basic.m_camera.emplace(camEnt); rCamComp.m_far = 1u << 24; rCamComp.m_near = 1.0f; rCamComp.m_fov = 45.0_degf; // Add camera to hierarchy SysHierarchy::add_child( rScene.m_basic.m_hierarchy, rScene.m_hierRoot, camEnt); // Make a cube rScnRs.m_cube = rScene.m_activeIds.create(); // Add cube mesh to cube rScene.m_drawing.m_mesh.emplace( rScnRs.m_cube, quick_add_mesh("cubewire") ); rScene.m_drawing.m_meshDirty.push_back(rScnRs.m_cube); // Add flat material to cube { MaterialData &rMatFlat = rScene.m_drawing.m_materials[rScnRs.m_matFlat]; rMatFlat.m_comp.emplace(rScnRs.m_cube); rMatFlat.m_added.push_back(rScnRs.m_cube); } // Add transform and draw transform rScene.m_basic.m_transform.emplace(rScnRs.m_cube, ACompTransform{ Matrix4::scaling(Vector3{0.5}) }); // Make cube green rScene.m_drawing.m_color.emplace(rScnRs.m_cube, 0x67ff00ff_rgbaf); // Add opaque and visible component rScene.m_drawing.m_opaque.emplace(rScnRs.m_cube); rScene.m_drawing.m_visible.emplace(rScnRs.m_cube); // Add cube to hierarchy, parented to root SysHierarchy::add_child( rScene.m_basic.m_hierarchy, rScene.m_hierRoot, rScnRs.m_cube); // Create floor mesh entity ActiveEnt floorMesh = rScene.m_activeIds.create(); // Add grid mesh to floor mesh rScene.m_drawing.m_mesh.emplace( floorMesh, quick_add_mesh("grid64wire")); rScene.m_drawing.m_meshDirty.push_back(floorMesh); // Add mesh flat material to floor mesh { MaterialData &rMatFlat = rScene.m_drawing.m_materials[rScnRs.m_matFlat]; rMatFlat.m_comp.emplace(floorMesh); rMatFlat.m_added.push_back(floorMesh); } // Make floor grey rScene.m_drawing.m_color.emplace(floorMesh, 0x808080ff_rgbaf); // Add transform, draw transform, opaque, and visible rScene.m_basic.m_transform.emplace( floorMesh, ACompTransform{Matrix4::translation({32.0f, 0.0f, 32.0f}) * Matrix4::rotationX(-90.0_degf) * Matrix4::scaling({32.0f, 32.0f, 0.0f})}); rScene.m_drawing.m_opaque.emplace(floorMesh); rScene.m_drawing.m_visible.emplace(floorMesh); // Add floor root to hierarchy root SysHierarchy::add_child( rScene.m_basic.m_hierarchy, rScene.m_hierRoot, floorMesh); // Allocate spaces for a few chunks rScnRs.m_chunks.m_ids.reserve(32); size_t const capacity = rScnRs.m_chunks.m_ids.capacity(); rScnRs.m_chunks.m_dirty.resize(capacity); rScnRs.m_blkTypeUpdates.resize(capacity); //rScene.m_chunks.m_blkTypeConnect.resize(capacity); rScnRs.m_chunks.m_blkTypes.resize(capacity); rScnRs.m_chunks.m_connect.resize(capacity); rScnRs.m_chunkDusts.m_dusts.resize(capacity); rScnRs.m_chkNotify.resize(capacity); // Create single chunk rScnRs.m_singleChunk = rScnRs.m_chunks.m_ids.create(); rScnRs.m_chunks.m_coordToChunk.emplace(ChunkCoord_t{0, 0, 0}, rScnRs.m_singleChunk); rScnRs.m_chunks.m_connect.at(0).m_blkPublish.ids_reserve(gc_chunkSize); rScnRs.m_chkNotify.at(0).m_notifySlots.at(0).resize(gc_chunkSize); rScnRs.m_blkTypeUpdates.at(0).m_changed.resize(gc_chunkSize); // Allocate buffers used by the single chunk //rScene.m_chunks.m_blkTypeConnect[0][rScene.m_blkTypeIds.id_of("dust")] // .m_connect.resize(gc_chunkSize); rScnRs.m_chunkDusts.m_dusts[0] = Array<BlkRsDust>{Corrade::DirectInit, gc_chunkSize}; // Fill single chunk with air rScnRs.m_chunks.m_blkTypes[0] = Array<BlkTypeId>{Corrade::DirectInit, gc_chunkSize, g_blkTypeIds.id_of("air")}; // Keep track of meshes for (std::string_view const str : gc_meshsUsed) { rScnPhys.m_namedMeshs.emplace(str, quick_add_mesh(str)); } osp::ResId const texRes = rResources.find(osp::restypes::gc_texture, pkg, "Redstone/redstone.gltf:unnamed-0"); rScnRs.m_blockTexture = SysRender::own_texture_resource(rScene.m_drawing, rScene.m_drawingRes, *rScene.m_pResources, texRes); } osp::active::ActiveEnt add_mesh_quick(CommonTestScene &rScene, osp::active::ActiveEnt parent, Matrix4 const& tf, osp::active::MeshId mesh) { using namespace osp::active; auto &rScnRs = rScene.get<RedstoneTestScene>(); ActiveEnt ent = rScene.m_activeIds.create(); // Add cube mesh to cube rScene.m_drawing.m_mesh.emplace( ent, rScene.m_drawing.m_meshRefCounts.ref_add(mesh) ); rScene.m_drawing.m_meshDirty.push_back(ent); // Add block texture rScene.m_drawing.m_diffuseTex.emplace( ent, rScene.m_drawing.m_texRefCounts.ref_add(rScnRs.m_blockTexture) ); rScene.m_drawing.m_diffuseDirty.push_back(ent); // Add common material to cube MaterialData &rMatCommon = rScene.m_drawing.m_materials[rScnRs.m_matFlat]; rMatCommon.m_comp.emplace(ent); rMatCommon.m_added.push_back(ent); // Add transform and draw transform rScene.m_basic.m_transform.emplace( ent, ACompTransform{tf} ); // Add opaque and visible component rScene.m_drawing.m_opaque.emplace(ent); rScene.m_drawing.m_visible.emplace(ent); // Add cube to hierarchy, parented to root SysHierarchy::add_child( rScene.m_basic.m_hierarchy, parent, ent); return ent; } //----------------------------------------------------------------------------- void chunk_update_visuals(CommonTestScene &rScene, ChunkId chkId) { using namespace osp::active; auto &rScnRs = rScene.get<RedstoneTestScene>(); auto &rScnPhys = rScene.get<scenes::PhysicsData>(); TmpChkBlkTypeUpd const& blkTypeUpd = rScnRs.m_blkTypeUpdates[size_t(chkId)]; ACtxVxRsDusts::ChkDust_t const &rDusts = rScnRs.m_chunkDusts.m_dusts.at(size_t(chkId)); // Create models Vector3 chunkOffset{0}; // TODO // Create redstone dust models if (auto it = blkTypeUpd.m_perType.find(g_blkTypeIds.id_of("dust")); it != blkTypeUpd.m_perType.end()) { for (size_t blockId : it->second.m_added) { BlkRsDust const dust = rDusts[blockId]; EMultiDirs const dir = dust.m_connected; //int const dirCount = std::bitset<8>(int(dust.m_connected)).count(); Vector3 const pos = Vector3(index_to_pos(blockId)) + Vector3{0.5, 0.5, 0.5}; Matrix4 tf = Matrix4::translation(pos); bool line = false; if (dir == (EMultiDir::POS_X | EMultiDir::NEG_X)) { // X-aligned line tf = tf * Matrix4::rotationY(90.0_degf); line = true; } else if (dir == (EMultiDir::POS_Z | EMultiDir::NEG_Z)) { // Z-aligned line line = true; } MeshId const rootMesh = line ? rScnPhys.m_namedMeshs.at("Redstone/redstone.gltf:DustStraight") : rScnPhys.m_namedMeshs.at("Redstone/redstone.gltf:Dust"); ActiveEnt const meshEnt = add_mesh_quick(rScene, rScene.m_hierRoot, tf, rootMesh); if (!line) { // put meshes for 4 sides using side_t = std::pair<EMultiDir, std::string_view>; auto const sides = { side_t{EMultiDir::POS_X, "Redstone/redstone.gltf:DustLf"}, side_t{EMultiDir::NEG_X, "Redstone/redstone.gltf:DustRt"}, side_t{EMultiDir::POS_Z, "Redstone/redstone.gltf:DustFd"}, side_t{EMultiDir::NEG_Z, "Redstone/redstone.gltf:DustBk"}, }; for (side_t const side : sides) { if (dir & side.first) { add_mesh_quick(rScene, meshEnt, Matrix4{}, rScnPhys.m_namedMeshs.at(side.second)); } } } rScene.m_drawing.m_color.emplace(meshEnt, 0x880000ff_rgbaf); } } // Create redstone torch models if (auto it = blkTypeUpd.m_perType.find(g_blkTypeIds.id_of("torch")); it != blkTypeUpd.m_perType.end()) { for (size_t blockId : it->second.m_added) { Vector3 const pos = Vector3(index_to_pos(blockId)) + Vector3{0.5, 0.5, 0.5}; add_mesh_quick(rScene, rScene.m_hierRoot, Matrix4::translation(pos), rScnPhys.m_namedMeshs.at("Redstone/redstone.gltf:Torch")); } } } void world_update_visuals(CommonTestScene& rScene) { auto &rScnRs = rScene.get<RedstoneTestScene>(); // Clear all drawing-related dirty flags osp::active::SysRender::clear_dirty_all(rScene.m_drawing); for (std::size_t chunkId : rScnRs.m_chunks.m_dirty) { chunk_update_visuals(rScene, ChunkId(chunkId)); } } //----------------------------------------------------------------------------- /** * @brief Update an EngineTestScene, this just rotates the cube * * @param rScene [ref] scene to update */ void update_test_scene(CommonTestScene& rScene, float delta) { using namespace osp::active; // Sort hierarchy, required by renderer SysHierarchy::sort(rScene.m_basic.m_hierarchy); } //----------------------------------------------------------------------------- // Everything below here is for rendering /** * @brief Data needed to render the EngineTestScene */ struct RedstoneRenderer { RedstoneRenderer(ActiveApplication &rApp) : m_camCtrl(rApp.get_input_handler()) , m_controls(&rApp.get_input_handler()) , m_btnPlaceDust(m_controls.button_subscribe("rs_place_dust")) , m_btnPlaceTorch(m_controls.button_subscribe("rs_place_torch")) { } ACtxCameraController m_camCtrl; osp::shader::ACtxDrawFlat m_flat; osp::shader::ACtxDrawMeshVisualizer m_wireframe; osp::input::ControlSubscriber m_controls; osp::input::EButtonControlIndex m_btnPlaceDust; osp::input::EButtonControlIndex m_btnPlaceTorch; }; ChkBlkPlacements_t place_user_blocks(CommonTestScene& rScene, CommonSceneRendererGL& rRenderer) { auto &rRenderRs = rRenderer.get<RedstoneRenderer>(); Magnum::Vector3i const tgt{rRenderRs.m_camCtrl.m_target.value()}; Magnum::Matrix4 const &camTf = rScene.m_basic.m_transform.get(rRenderer.m_camera).m_transform; Vector3 const lookDir = -camTf.backward(); ChkBlkPlacements_t blkPlacements; for (osp::input::ButtonControlEvent const& event : rRenderRs.m_controls.button_events()) { using osp::input::EButtonControlEvent; if (event.m_index == rRenderRs.m_btnPlaceDust && event.m_event == EButtonControlEvent::Triggered) { // Place dust blkPlacements[g_blkTypeIds.id_of("dust")].push_back( ChkBlkPlace{ tgt, lookDir } ); OSP_LOG_INFO("Place Dust: ({}, {}, {})", tgt.x(), tgt.y(), tgt.z()); } if (event.m_index == rRenderRs.m_btnPlaceTorch && event.m_event == EButtonControlEvent::Triggered) { // Place torch blkPlacements[g_blkTypeIds.id_of("torch")].push_back( ChkBlkPlace{ tgt, lookDir } ); OSP_LOG_INFO("Place Torch: ({}, {}, {})", tgt.x(), tgt.y(), tgt.z()); } } return blkPlacements; } static void sync(CommonSceneRendererGL& rRenderer, CommonTestScene& rScene) { using namespace osp::active; using namespace osp::shader; auto &rRenderRs = rRenderer.get<RedstoneRenderer>(); auto &rScnRs = rScene.get<RedstoneTestScene>(); RenderGroup &rGroupFwdOpaque = rRenderer.m_renderGroups.m_groups["fwd_opaque"]; // Assign Phong shader to entities with the gc_mat_common material, and put // results into the fwd_opaque render group { MaterialData const &rMatFlat = rScene.m_drawing.m_materials[rScnRs.m_matFlat]; assign_flat( rMatFlat.m_added, &rGroupFwdOpaque.m_entities, nullptr, rScene.m_drawing.m_opaque, rRenderer.m_renderGl.m_diffuseTexId, rRenderRs.m_flat); SysRender::assure_draw_transforms( rScene.m_basic.m_hierarchy, rRenderer.m_renderGl.m_drawTransform, std::cbegin(rMatFlat.m_added), std::cend(rMatFlat.m_added)); } // Same thing but with MeshVisualizer and gc_mat_visualizer { MaterialData const &rMatVisualizer = rScene.m_drawing.m_materials[rScene.m_matVisualizer]; assign_visualizer( rMatVisualizer.m_added, rGroupFwdOpaque.m_entities, rRenderRs.m_wireframe); SysRender::assure_draw_transforms( rScene.m_basic.m_hierarchy, rRenderer.m_renderGl.m_drawTransform, std::cbegin(rMatVisualizer.m_added), std::cend(rMatVisualizer.m_added)); } } void Redstone::setup_renderer_gl(CommonSceneRendererGL& rRenderer, CommonTestScene& rScene, ActiveApplication& rApp) noexcept { using namespace osp::active; using namespace osp::shader; auto &rRenderRs = rRenderer.emplace<RedstoneRenderer>(rApp); // Setup Flat shaders rRenderRs.m_flat.m_shaderDiffuse = Flat{Flat::Flag::Textured | Flat::Flag::AlphaMask}; rRenderRs.m_flat.m_shaderUntextured = Flat{}; rRenderRs.m_flat.assign_pointers(rRenderer.m_renderGl, rApp.get_render_gl()); rRenderRs.m_flat.m_pColor = &rScene.m_drawing.m_color; // Create MeshVisualizer shader intended for wireframe rRenderRs.m_wireframe.m_shader = MeshVisualizer{ MeshVisualizer::Flag::Wireframe }; rRenderRs.m_wireframe.m_shader .setColor(0x00000000_rgbaf) .setWireframeColor(0xffffffffff_rgbaf); rRenderRs.m_wireframe.m_wireframeOnly = true; rRenderRs.m_wireframe.assign_pointers( rRenderer.m_renderGl, rApp.get_render_gl()); // Select first camera for rendering ActiveEnt const camEnt = rScene.m_basic.m_camera.at(0); rRenderer.m_camera = camEnt; rScene.m_basic.m_camera.get(camEnt).set_aspect_ratio( osp::Vector2(Magnum::GL::defaultFramebuffer.viewport().size())); SysRender::add_draw_transforms_recurse( rScene.m_basic.m_hierarchy, rRenderer.m_renderGl.m_drawTransform, camEnt); rRenderRs.m_camCtrl.m_target = osp::Vector3{}; rRenderRs.m_camCtrl.m_up = osp::Vector3{0.0f, 1.0f, 0.0f}; rRenderer.m_onCustomDraw = [] ( CommonSceneRendererGL& rRenderer, CommonTestScene& rScene, ActiveApplication& rApp, float delta) noexcept { auto &rRenderRs = rRenderer.get<RedstoneRenderer>(); auto &rScnRs = rScene.get<RedstoneTestScene>(); sync(rRenderer, rScene); ACompTransform &rCamTf = rScene.m_basic.m_transform.get(rRenderer.m_camera); // Move camera SysCameraController::update_view(rRenderRs.m_camCtrl, rCamTf, delta); SysCameraController::update_move( rRenderRs.m_camCtrl, rCamTf, delta, true); // Move cursor cube to camera target Magnum::Vector3i const tgt{rRenderRs.m_camCtrl.m_target.value()}; ACompTransform &rCubeTf = rScene.m_basic.m_transform.get(rScnRs.m_cube); bool const targetValid = (tgt.x() >= 0 && tgt.y() >= 0 && tgt.z() >= 0); rCubeTf.m_transform.translation() = targetValid ? Vector3{tgt} + Vector3{0.5f, 0.5f, 0.5f} : Vector3{-2000}; // Get blocks to place this frame ChkBlkPlacements_t blkPlacements = place_user_blocks(rScene, rRenderer); // Accumolated list of block changes this frame, so far only 1 std::array< std::pair<ChunkId, ChkBlkPlacements_t>, 1> changesArray {{ {rScnRs.m_singleChunk, std::move(blkPlacements)} }}; update_blocks(rScnRs, changesArray); // # Update models // * Syncs voxel data with OSP entities world_update_visuals(rScene); update_test_scene(rScene, delta); }; } } // namespace testapp::redstone
34.837479
157
0.666302
[ "mesh", "render", "transform" ]
be30ac9ce24be88a54e317c9a6e3ee5d2b0c011b
5,299
cpp
C++
src/unitiger/hydro_impl/flux_kernel_interface.cpp
STEllAR-GROUP/octotiger
bf8dcfa4d3607244983d2ba66f2cbbab2477f468
[ "BSL-1.0" ]
35
2016-11-17T22:35:11.000Z
2022-01-24T19:07:36.000Z
src/unitiger/hydro_impl/flux_kernel_interface.cpp
STEllAR-GROUP/octotiger
bf8dcfa4d3607244983d2ba66f2cbbab2477f468
[ "BSL-1.0" ]
123
2016-11-17T21:29:25.000Z
2022-03-03T21:40:04.000Z
src/unitiger/hydro_impl/flux_kernel_interface.cpp
STEllAR-GROUP/octotiger
bf8dcfa4d3607244983d2ba66f2cbbab2477f468
[ "BSL-1.0" ]
10
2018-11-28T18:17:42.000Z
2022-01-25T12:52:37.000Z
#include "octotiger/unitiger/hydro_impl/flux_kernel_interface.hpp" // Scalar kernel template <> inline void select_wrapper<double, bool>( double_t& target, const bool cond, const double& tmp1, const double& tmp2) { target = cond ? tmp1 : tmp2; } template <> inline double max_wrapper<double>(const double& tmp1, const double& tmp2) { return std::max(tmp1, tmp2); } template <> inline double min_wrapper<double>(const double& tmp1, const double& tmp2) { return std::min(tmp1, tmp2); } template <> inline double sqrt_wrapper<double>(const double& tmp1) { return std::sqrt(tmp1); } template <> inline double pow_wrapper<double>(const double& tmp1, const double& tmp2) { return std::pow(tmp1, tmp2); } template <> inline double asin_wrapper<double>(const double& tmp1) { return std::asin(tmp1); } template <> inline bool skippable<double>(const double& tmp1) { return !tmp1; } timestep_t flux_kernel_interface(const hydro::recon_type<NDIM>& Q, hydro::flux_type& F, hydro::x_type& X, safe_real omega, const size_t nf_) { // input Q, X // output F timestep_t ts; ts.a = 0.0; // bunch of small helpers static const cell_geometry<3, 8> geo; static constexpr auto faces = geo.face_pts(); static constexpr auto weights = geo.face_weight(); static constexpr auto xloc = geo.xloc(); double p, v, v0, c; const auto A_ = physics<NDIM>::A_; const auto B_ = physics<NDIM>::B_; double current_amax = 0.0; size_t current_max_index = 0; size_t current_d = 0; size_t current_dim = 0; const auto dx = X[0][geo.H_DNX] - X[0][0]; std::vector<double> UR(nf_), UL(nf_), this_flux(nf_); std::array<double, NDIM> x; std::array<double, NDIM> vg; for (int dim = 0; dim < NDIM; dim++) { const auto indices = geo.get_indexes(3, geo.face_pts()[dim][0]); std::array<int, NDIM> lbs = {3, 3, 3}; std::array<int, NDIM> ubs = {geo.H_NX - 3, geo.H_NX - 3, geo.H_NX - 3}; for (int dimension = 0; dimension < NDIM; dimension++) { ubs[dimension] = geo.xloc()[geo.face_pts()[dim][0]][dimension] == -1 ? (geo.H_NX - 3 + 1) : (geo.H_NX - 3); lbs[dimension] = geo.xloc()[geo.face_pts()[dim][0]][dimension] == +1 ? (3 - 1) : 3; } // zero-initialize F for (int f = 0; f < nf_; f++) { #pragma ivdep for (const auto& i : indices) { F[dim][f][i] = 0.0; } } for (int fi = 0; fi < geo.NFACEDIR; fi++) { // 9 safe_real ap = 0.0, am = 0.0; // final am ap for this i safe_real this_ap, this_am; // tmps safe_real this_amax; const auto d = faces[dim][fi]; const auto flipped_dim = geo.flip_dim(d, dim); // std::cout << "--Face:" << fi << "----------------------------------" << std::endl; for (size_t ix = lbs[0]; ix < ubs[0]; ix++) { for (size_t iy = lbs[1]; iy < geo.H_NX; iy++) { for (size_t iz = lbs[2]; iz < geo.H_NX; iz++) { if (iy >= ubs[1] || iz >= ubs[2]) continue; const size_t i = ix * geo.H_NX * geo.H_NX + iy * geo.H_NX + iz; // why store this? for (int f = 0; f < nf_; f++) { UR[f] = Q[f][d][i]; UL[f] = Q[f][flipped_dim][i - geo.H_DN[dim]]; } for (int dim = 0; dim < NDIM; dim++) { x[dim] = X[dim][i] + 0.5 * xloc[d][dim] * dx; } vg[0] = -omega * (X[1][i] + 0.5 * xloc[d][1] * dx); vg[1] = +omega * (X[0][i] + 0.5 * xloc[d][0] * dx); vg[2] = 0.0; this_amax = inner_flux_loop<double>(omega, nf_, A_, B_, UR.data(), UL.data(), this_flux.data(), x.data(), vg.data(), ap, am, dim, d, dx, physics<NDIM>::fgamma_, physics<NDIM>::de_switch_1); if (this_amax > current_amax) { current_amax = this_amax; current_max_index = i; current_d = d; current_dim = dim; } #pragma ivdep for (int f = 0; f < nf_; f++) { // field update from flux F[dim][f][i] += weights[fi] * this_flux[f]; } } // end z } // end y } // end x } // end dirs } // end dim ts.a = current_amax; ts.x = X[0][current_max_index]; ts.y = X[1][current_max_index]; ts.z = X[2][current_max_index]; const auto flipped_dim = geo.flip_dim(current_d, current_dim); for (int f = 0; f < nf_; f++) { UR[f] = Q[f][current_d][current_max_index]; UL[f] = Q[f][flipped_dim][current_max_index - geo.H_DN[current_dim]]; } ts.ul = UL; ts.ur = UR; ts.dim = current_dim; return ts; }
38.122302
97
0.4816
[ "vector" ]
be31a56219059db3bb982419e02ab02abf7cb31d
37,242
cc
C++
services/network/public/cpp/cors/cors_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-10-18T02:33:40.000Z
2020-10-18T02:33:40.000Z
services/network/public/cpp/cors/cors_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2021-05-17T16:28:52.000Z
2021-05-21T22:42:22.000Z
services/network/public/cpp/cors/cors_unittest.cc
DamieFC/chromium
54ce2d3c77723697efd22cfdb02aea38f9dfa25c
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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 "services/network/public/cpp/cors/cors.h" #include <limits.h> #include "base/test/metrics/histogram_tester.h" #include "build/build_config.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" #include "url/origin.h" namespace network { namespace cors { namespace { using CorsTest = testing::Test; // Tests if CheckAccess detects kWildcardOriginNotAllowed error correctly. TEST_F(CorsTest, CheckAccessDetectsWildcardOriginNotAllowed) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); const std::string allow_all_header("*"); // Access-Control-Allow-Origin '*' works. absl::optional<CorsErrorStatus> error1 = CheckAccess(response_url, allow_all_header /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); EXPECT_FALSE(error1); // Access-Control-Allow-Origin '*' should not be allowed if credentials mode // is kInclude. absl::optional<CorsErrorStatus> error2 = CheckAccess(response_url, allow_all_header /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kInclude, origin); ASSERT_TRUE(error2); EXPECT_EQ(mojom::CorsError::kWildcardOriginNotAllowed, error2->cors_error); } // Tests if CheckAccess detects kMissingAllowOriginHeader error correctly. TEST_F(CorsTest, CheckAccessDetectsMissingAllowOriginHeader) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); // Access-Control-Allow-Origin is missed. absl::optional<CorsErrorStatus> error = CheckAccess(response_url, absl::nullopt /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(error); EXPECT_EQ(mojom::CorsError::kMissingAllowOriginHeader, error->cors_error); } // Tests if CheckAccess detects kMultipleAllowOriginValues error // correctly. TEST_F(CorsTest, CheckAccessDetectsMultipleAllowOriginValues) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); const std::string space_separated_multiple_origins( "http://example.com http://another.example.com"); absl::optional<CorsErrorStatus> error1 = CheckAccess( response_url, space_separated_multiple_origins /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(error1); EXPECT_EQ(mojom::CorsError::kMultipleAllowOriginValues, error1->cors_error); const std::string comma_separated_multiple_origins( "http://example.com,http://another.example.com"); absl::optional<CorsErrorStatus> error2 = CheckAccess( response_url, comma_separated_multiple_origins /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(error2); EXPECT_EQ(mojom::CorsError::kMultipleAllowOriginValues, error2->cors_error); } // Tests if CheckAccess detects kInvalidAllowOriginValue error correctly. TEST_F(CorsTest, CheckAccessDetectsInvalidAllowOriginValue) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); absl::optional<CorsErrorStatus> error = CheckAccess( response_url, std::string("invalid.origin") /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(error); EXPECT_EQ(mojom::CorsError::kInvalidAllowOriginValue, error->cors_error); EXPECT_EQ("invalid.origin", error->failed_parameter); } // Tests if CheckAccess detects kAllowOriginMismatch error correctly. TEST_F(CorsTest, CheckAccessDetectsAllowOriginMismatch) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); absl::optional<CorsErrorStatus> error1 = CheckAccess(response_url, origin.Serialize() /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_FALSE(error1); absl::optional<CorsErrorStatus> error2 = CheckAccess( response_url, std::string("http://not.google.com") /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(error2); EXPECT_EQ(mojom::CorsError::kAllowOriginMismatch, error2->cors_error); EXPECT_EQ("http://not.google.com", error2->failed_parameter); // Allow "null" value to match serialized unique origins. const std::string null_string("null"); const url::Origin null_origin; EXPECT_EQ(null_string, null_origin.Serialize()); absl::optional<CorsErrorStatus> error3 = CheckAccess(response_url, null_string /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, null_origin); EXPECT_FALSE(error3); } // Tests if CheckAccess detects kInvalidAllowCredentials error correctly. TEST_F(CorsTest, CheckAccessDetectsInvalidAllowCredential) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); absl::optional<CorsErrorStatus> error1 = CheckAccess(response_url, origin.Serialize() /* allow_origin_header */, std::string("true") /* allow_credentials_header */, network::mojom::CredentialsMode::kInclude, origin); ASSERT_FALSE(error1); absl::optional<CorsErrorStatus> error2 = CheckAccess(response_url, origin.Serialize() /* allow_origin_header */, std::string("fuga") /* allow_credentials_header */, network::mojom::CredentialsMode::kInclude, origin); ASSERT_TRUE(error2); EXPECT_EQ(mojom::CorsError::kInvalidAllowCredentials, error2->cors_error); EXPECT_EQ("fuga", error2->failed_parameter); } // Should match unexposed enum in cors.cc enum class AccessCheckResult { kPermitted = 0, kNotPermitted = 1, kPermittedInPreflight = 2, kNotPermittedInPreflight = 3, kMaxValue = kNotPermittedInPreflight, }; constexpr char kAccessCheckHistogram[] = "Net.Cors.AccessCheckResult"; constexpr char kAccessCheckHistogramNotSecure[] = "Net.Cors.AccessCheckResult.NotSecureRequestor"; TEST_F(CorsTest, CheckAccessLogsAllowMetricsSecureOrigin) { base::HistogramTester histogram_tester; const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("https://google.com")); CheckAccess(response_url, origin.Serialize() /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); histogram_tester.ExpectUniqueSample(kAccessCheckHistogram, AccessCheckResult::kPermitted, 1); histogram_tester.ExpectTotalCount(kAccessCheckHistogramNotSecure, 0); } TEST_F(CorsTest, CheckAccessLogsBlockMetricsSecureOrigin) { base::HistogramTester histogram_tester; const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("https://google.com")); CheckAccess(response_url, std::string("https://not.google.com") /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); histogram_tester.ExpectUniqueSample(kAccessCheckHistogram, AccessCheckResult::kNotPermitted, 1); histogram_tester.ExpectTotalCount(kAccessCheckHistogramNotSecure, 0); } TEST_F(CorsTest, CheckAccessLogsAllowMetricsInsecureOrigin) { base::HistogramTester histogram_tester; const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); CheckAccess(response_url, origin.Serialize() /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); histogram_tester.ExpectUniqueSample(kAccessCheckHistogram, AccessCheckResult::kPermitted, 1); histogram_tester.ExpectUniqueSample(kAccessCheckHistogramNotSecure, AccessCheckResult::kPermitted, 1); } TEST_F(CorsTest, CheckAccessLogsBlockMetricsInsecureOrigin) { base::HistogramTester histogram_tester; const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); CheckAccess(response_url, std::string("http://not.google.com") /* allow_origin_header */, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); histogram_tester.ExpectUniqueSample(kAccessCheckHistogram, AccessCheckResult::kNotPermitted, 1); histogram_tester.ExpectUniqueSample(kAccessCheckHistogramNotSecure, AccessCheckResult::kNotPermitted, 1); } // Tests if CheckRedirectLocation detects kCorsDisabledScheme and // kRedirectContainsCredentials errors correctly. TEST_F(CorsTest, CheckRedirectLocation) { struct TestCase { GURL url; mojom::RequestMode request_mode; bool cors_flag; bool tainted; absl::optional<CorsErrorStatus> expectation; }; const auto kCors = mojom::RequestMode::kCors; const auto kCorsWithForcedPreflight = mojom::RequestMode::kCorsWithForcedPreflight; const auto kNoCors = mojom::RequestMode::kNoCors; const url::Origin origin = url::Origin::Create(GURL("http://example.com/")); const GURL same_origin_url("http://example.com/"); const GURL cross_origin_url("http://example2.com/"); const GURL data_url("data:,Hello"); const GURL same_origin_url_with_user("http://yukari@example.com/"); const GURL same_origin_url_with_pass("http://:tamura@example.com/"); const GURL cross_origin_url_with_user("http://yukari@example2.com/"); const GURL cross_origin_url_with_pass("http://:tamura@example2.com/"); const auto ok = absl::nullopt; const CorsErrorStatus kCorsDisabledScheme( mojom::CorsError::kCorsDisabledScheme); const CorsErrorStatus kRedirectContainsCredentials( mojom::CorsError::kRedirectContainsCredentials); TestCase cases[] = { // "cors", no credentials information {same_origin_url, kCors, false, false, ok}, {cross_origin_url, kCors, false, false, ok}, {data_url, kCors, false, false, ok}, {same_origin_url, kCors, true, false, ok}, {cross_origin_url, kCors, true, false, ok}, {data_url, kCors, true, false, ok}, {same_origin_url, kCors, false, true, ok}, {cross_origin_url, kCors, false, true, ok}, {data_url, kCors, false, true, ok}, {same_origin_url, kCors, true, true, ok}, {cross_origin_url, kCors, true, true, ok}, {data_url, kCors, true, true, ok}, // "cors" with forced preflight, no credentials information {same_origin_url, kCorsWithForcedPreflight, false, false, ok}, {cross_origin_url, kCorsWithForcedPreflight, false, false, ok}, {data_url, kCorsWithForcedPreflight, false, false, ok}, {same_origin_url, kCorsWithForcedPreflight, true, false, ok}, {cross_origin_url, kCorsWithForcedPreflight, true, false, ok}, {data_url, kCorsWithForcedPreflight, true, false, ok}, {same_origin_url, kCorsWithForcedPreflight, false, true, ok}, {cross_origin_url, kCorsWithForcedPreflight, false, true, ok}, {data_url, kCorsWithForcedPreflight, false, true, ok}, {same_origin_url, kCorsWithForcedPreflight, true, true, ok}, {cross_origin_url, kCorsWithForcedPreflight, true, true, ok}, {data_url, kCorsWithForcedPreflight, true, true, ok}, // "no-cors", no credentials information {same_origin_url, kNoCors, false, false, ok}, {cross_origin_url, kNoCors, false, false, ok}, {data_url, kNoCors, false, false, ok}, {same_origin_url, kNoCors, false, true, ok}, {cross_origin_url, kNoCors, false, true, ok}, {data_url, kNoCors, false, true, ok}, // with credentials information (same origin) {same_origin_url_with_user, kCors, false, false, ok}, {same_origin_url_with_user, kCors, true, false, kRedirectContainsCredentials}, {same_origin_url_with_user, kCors, true, true, kRedirectContainsCredentials}, {same_origin_url_with_user, kNoCors, false, false, ok}, {same_origin_url_with_user, kNoCors, false, true, ok}, {same_origin_url_with_pass, kCors, false, false, ok}, {same_origin_url_with_pass, kCors, true, false, kRedirectContainsCredentials}, {same_origin_url_with_pass, kCors, true, true, kRedirectContainsCredentials}, {same_origin_url_with_pass, kNoCors, false, false, ok}, {same_origin_url_with_pass, kNoCors, false, true, ok}, // with credentials information (cross origin) {cross_origin_url_with_user, kCors, false, false, kRedirectContainsCredentials}, {cross_origin_url_with_user, kCors, true, false, kRedirectContainsCredentials}, {cross_origin_url_with_user, kCors, true, true, kRedirectContainsCredentials}, {cross_origin_url_with_user, kNoCors, false, true, ok}, {cross_origin_url_with_user, kNoCors, false, false, ok}, {cross_origin_url_with_pass, kCors, false, false, kRedirectContainsCredentials}, {cross_origin_url_with_pass, kCors, true, false, kRedirectContainsCredentials}, {cross_origin_url_with_pass, kCors, true, true, kRedirectContainsCredentials}, {cross_origin_url_with_pass, kNoCors, false, true, ok}, {cross_origin_url_with_pass, kNoCors, false, false, ok}, }; for (const auto& test : cases) { SCOPED_TRACE(testing::Message() << "url: " << test.url << ", request mode: " << test.request_mode << ", origin: " << origin << ", cors_flag: " << test.cors_flag << ", tainted: " << test.tainted); EXPECT_EQ(test.expectation, CheckRedirectLocation(test.url, test.request_mode, origin, test.cors_flag, test.tainted)); } } TEST_F(CorsTest, CheckPreflightAccessDetectsErrorStatus) { const GURL response_url("http://example.com/data"); const url::Origin origin = url::Origin::Create(GURL("http://google.com")); const std::string allow_all_header("*"); // Status 200-299 should pass. EXPECT_FALSE( CheckPreflightAccess(response_url, 200, allow_all_header, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin)); EXPECT_FALSE( CheckPreflightAccess(response_url, 299, allow_all_header, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin)); // Status 300 should fail. absl::optional<CorsErrorStatus> invalid_status_error = CheckPreflightAccess(response_url, 300, allow_all_header, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(invalid_status_error); EXPECT_EQ(mojom::CorsError::kPreflightInvalidStatus, invalid_status_error->cors_error); // Status 0 should fail too. invalid_status_error = CheckPreflightAccess(response_url, 0, allow_all_header, absl::nullopt /* allow_credentials_header */, network::mojom::CredentialsMode::kOmit, origin); ASSERT_TRUE(invalid_status_error); EXPECT_EQ(mojom::CorsError::kPreflightInvalidStatus, invalid_status_error->cors_error); } TEST_F(CorsTest, CheckExternalPreflightErrors) { EXPECT_FALSE(CheckExternalPreflight(std::string("true"))); absl::optional<CorsErrorStatus> error2 = CheckExternalPreflight(absl::nullopt); ASSERT_TRUE(error2); EXPECT_EQ(mojom::CorsError::kPreflightMissingAllowExternal, error2->cors_error); EXPECT_EQ("", error2->failed_parameter); absl::optional<CorsErrorStatus> error3 = CheckExternalPreflight(std::string("TRUE")); ASSERT_TRUE(error3); EXPECT_EQ(mojom::CorsError::kPreflightInvalidAllowExternal, error3->cors_error); EXPECT_EQ("TRUE", error3->failed_parameter); } TEST_F(CorsTest, SafelistedMethod) { // Method check should be case-insensitive. EXPECT_TRUE(IsCorsSafelistedMethod("get")); EXPECT_TRUE(IsCorsSafelistedMethod("Get")); EXPECT_TRUE(IsCorsSafelistedMethod("GET")); EXPECT_TRUE(IsCorsSafelistedMethod("HEAD")); EXPECT_TRUE(IsCorsSafelistedMethod("POST")); EXPECT_FALSE(IsCorsSafelistedMethod("OPTIONS")); } TEST_F(CorsTest, SafelistedHeader) { // See SafelistedAccept/AcceptLanguage/ContentLanguage/ContentType also. EXPECT_TRUE(IsCorsSafelistedHeader("accept", "foo")); EXPECT_FALSE(IsCorsSafelistedHeader("foo", "bar")); EXPECT_FALSE(IsCorsSafelistedHeader("user-agent", "foo")); } TEST_F(CorsTest, SafelistedAccept) { EXPECT_TRUE(IsCorsSafelistedHeader("accept", "text/html")); EXPECT_TRUE(IsCorsSafelistedHeader("AccepT", "text/html")); constexpr char kAllowed[] = "\t !#$%&'*+,-./0123456789;=" "ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; for (int i = 0; i < 128; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); char c = static_cast<char>(i); // 1 for the trailing null character. auto* end = kAllowed + base::size(kAllowed) - 1; EXPECT_EQ(std::find(kAllowed, end, c) != end, IsCorsSafelistedHeader("accept", std::string(1, c))); EXPECT_EQ(std::find(kAllowed, end, c) != end, IsCorsSafelistedHeader("AccepT", std::string(1, c))); } for (int i = 128; i <= 255; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); char c = static_cast<char>(static_cast<unsigned char>(i)); EXPECT_TRUE(IsCorsSafelistedHeader("accept", std::string(1, c))); EXPECT_TRUE(IsCorsSafelistedHeader("AccepT", std::string(1, c))); } EXPECT_TRUE(IsCorsSafelistedHeader("accept", std::string(128, 'a'))); EXPECT_FALSE(IsCorsSafelistedHeader("accept", std::string(129, 'a'))); EXPECT_TRUE(IsCorsSafelistedHeader("AccepT", std::string(128, 'a'))); EXPECT_FALSE(IsCorsSafelistedHeader("AccepT", std::string(129, 'a'))); } TEST_F(CorsTest, SafelistedAcceptLanguage) { EXPECT_TRUE(IsCorsSafelistedHeader("accept-language", "en,ja")); EXPECT_TRUE(IsCorsSafelistedHeader("aCcEPT-lAngUAge", "en,ja")); constexpr char kAllowed[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz *,-.;="; for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); char c = static_cast<char>(i); // 1 for the trailing null character. auto* end = kAllowed + base::size(kAllowed) - 1; EXPECT_EQ(std::find(kAllowed, end, c) != end, IsCorsSafelistedHeader("aCcEPT-lAngUAge", std::string(1, c))); } EXPECT_TRUE(IsCorsSafelistedHeader("accept-language", std::string(128, 'a'))); EXPECT_FALSE( IsCorsSafelistedHeader("accept-language", std::string(129, 'a'))); EXPECT_TRUE(IsCorsSafelistedHeader("aCcEPT-lAngUAge", std::string(128, 'a'))); EXPECT_FALSE( IsCorsSafelistedHeader("aCcEPT-lAngUAge", std::string(129, 'a'))); } TEST_F(CorsTest, SafelistedSecCHPrefersColorScheme) { EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-Prefers-Color-Scheme", "\"Prefers-Color-Scheme!\"")); } TEST_F(CorsTest, SafelistedSecCHLang) { EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-Lang", "\"en\", \"de\"")); // TODO(mkwst): Validate that `Sec-CH-Lang` is a structured header. // https://crbug.com/924969 } TEST_F(CorsTest, SafelistedSecCHUA) { EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-UA", "\"User Agent!\"")); EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-UA-Platform", "\"Platform!\"")); EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-UA-Platform-Version", "\"Platform-Version!\"")); EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-UA-Arch", "\"Architecture!\"")); EXPECT_TRUE(IsCorsSafelistedHeader("Sec-CH-UA-Model", "\"Model!\"")); // TODO(mkwst): Validate that `Sec-CH-UA-*` is a structured header. // https://crbug.com/924969 } TEST_F(CorsTest, SafelistedContentLanguage) { EXPECT_TRUE(IsCorsSafelistedHeader("content-language", "en,ja")); EXPECT_TRUE(IsCorsSafelistedHeader("cONTent-LANguaGe", "en,ja")); constexpr char kAllowed[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz *,-.;="; for (int i = CHAR_MIN; i <= CHAR_MAX; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); char c = static_cast<char>(i); // 1 for the trailing null character. auto* end = kAllowed + base::size(kAllowed) - 1; EXPECT_EQ(std::find(kAllowed, end, c) != end, IsCorsSafelistedHeader("content-language", std::string(1, c))); EXPECT_EQ(std::find(kAllowed, end, c) != end, IsCorsSafelistedHeader("cONTent-LANguaGe", std::string(1, c))); } EXPECT_TRUE( IsCorsSafelistedHeader("content-language", std::string(128, 'a'))); EXPECT_FALSE( IsCorsSafelistedHeader("content-language", std::string(129, 'a'))); EXPECT_TRUE( IsCorsSafelistedHeader("cONTent-LANguaGe", std::string(128, 'a'))); EXPECT_FALSE( IsCorsSafelistedHeader("cONTent-LANguaGe", std::string(129, 'a'))); } TEST_F(CorsTest, SafelistedContentType) { constexpr char kAllowed[] = "\t !#$%&'*+,-./0123456789;=" "ABCDEFGHIJKLMNOPQRSTUVWXYZ^_`abcdefghijklmnopqrstuvwxyz|~"; for (int i = 0; i < 128; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); const char c = static_cast<char>(i); // 1 for the trailing null character. const auto* const end = kAllowed + base::size(kAllowed) - 1; const bool is_allowed = std::find(kAllowed, end, c) != end; const std::string value = std::string("text/plain; charset=") + c; EXPECT_EQ(is_allowed, IsCorsSafelistedHeader("content-type", value)); EXPECT_EQ(is_allowed, IsCorsSafelistedHeader("cONtent-tYPe", value)); } for (int i = 128; i <= 255; ++i) { SCOPED_TRACE(testing::Message() << "c = static_cast<char>(" << i << ")"); char c = static_cast<char>(static_cast<unsigned char>(i)); const std::string value = std::string("text/plain; charset=") + c; EXPECT_TRUE(IsCorsSafelistedHeader("content-type", value)); EXPECT_TRUE(IsCorsSafelistedHeader("ConTEnt-Type", value)); } EXPECT_TRUE(IsCorsSafelistedHeader("content-type", "text/plain")); EXPECT_TRUE(IsCorsSafelistedHeader("CoNtEnt-TyPE", "text/plain")); EXPECT_TRUE( IsCorsSafelistedHeader("content-type", "text/plain; charset=utf-8")); EXPECT_TRUE( IsCorsSafelistedHeader("content-type", " text/plain ; charset=UTF-8")); EXPECT_TRUE( IsCorsSafelistedHeader("content-type", "text/plain; param=BOGUS")); EXPECT_TRUE(IsCorsSafelistedHeader("content-type", "application/x-www-form-urlencoded")); EXPECT_TRUE(IsCorsSafelistedHeader("content-type", "multipart/form-data")); EXPECT_TRUE(IsCorsSafelistedHeader("content-type", "Text/plain")); EXPECT_TRUE(IsCorsSafelistedHeader("content-type", "tEXT/PLAIN")); EXPECT_FALSE(IsCorsSafelistedHeader("content-type", "text/html")); EXPECT_FALSE(IsCorsSafelistedHeader("CoNtEnt-TyPE", "text/html")); EXPECT_FALSE(IsCorsSafelistedHeader("content-type", "image/png")); EXPECT_FALSE(IsCorsSafelistedHeader("CoNtEnt-TyPE", "image/png")); EXPECT_TRUE(IsCorsSafelistedHeader( "content-type", "text/plain; charset=" + std::string(108, 'a'))); EXPECT_TRUE(IsCorsSafelistedHeader( "cONTent-tYPE", "text/plain; charset=" + std::string(108, 'a'))); EXPECT_FALSE(IsCorsSafelistedHeader( "content-type", "text/plain; charset=" + std::string(109, 'a'))); EXPECT_FALSE(IsCorsSafelistedHeader( "cONTent-tYPE", "text/plain; charset=" + std::string(109, 'a'))); } TEST_F(CorsTest, CheckCorsClientHintsSafelist) { EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "abc")); EXPECT_TRUE(IsCorsSafelistedHeader("device-memory", "1.25")); EXPECT_TRUE(IsCorsSafelistedHeader("DEVICE-memory", "1.25")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "1.25-2.5")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "-1.25")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "1e2")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "inf")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "-2.3")); EXPECT_FALSE(IsCorsSafelistedHeader("device-memory", "NaN")); EXPECT_FALSE(IsCorsSafelistedHeader("DEVICE-memory", "1.25.3")); EXPECT_FALSE(IsCorsSafelistedHeader("DEVICE-memory", "1.")); EXPECT_FALSE(IsCorsSafelistedHeader("DEVICE-memory", ".1")); EXPECT_FALSE(IsCorsSafelistedHeader("DEVICE-memory", ".")); EXPECT_TRUE(IsCorsSafelistedHeader("DEVICE-memory", "1")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "abc")); EXPECT_TRUE(IsCorsSafelistedHeader("dpr", "1.25")); EXPECT_TRUE(IsCorsSafelistedHeader("Dpr", "1.25")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "1.25-2.5")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "-1.25")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "1e2")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "inf")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "-2.3")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "NaN")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "1.25.3")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", "1.")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", ".1")); EXPECT_FALSE(IsCorsSafelistedHeader("dpr", ".")); EXPECT_TRUE(IsCorsSafelistedHeader("dpr", "1")); EXPECT_FALSE(IsCorsSafelistedHeader("width", "")); EXPECT_FALSE(IsCorsSafelistedHeader("width", "abc")); EXPECT_TRUE(IsCorsSafelistedHeader("width", "125")); EXPECT_TRUE(IsCorsSafelistedHeader("width", "1")); EXPECT_TRUE(IsCorsSafelistedHeader("WIDTH", "125")); EXPECT_FALSE(IsCorsSafelistedHeader("width", "125.2")); EXPECT_FALSE(IsCorsSafelistedHeader("width", "-125")); EXPECT_TRUE(IsCorsSafelistedHeader("width", "2147483648")); EXPECT_FALSE(IsCorsSafelistedHeader("viewport-width", "")); EXPECT_FALSE(IsCorsSafelistedHeader("viewport-width", "abc")); EXPECT_TRUE(IsCorsSafelistedHeader("viewport-width", "125")); EXPECT_TRUE(IsCorsSafelistedHeader("viewport-width", "1")); EXPECT_TRUE(IsCorsSafelistedHeader("viewport-Width", "125")); EXPECT_FALSE(IsCorsSafelistedHeader("viewport-width", "125.2")); EXPECT_TRUE(IsCorsSafelistedHeader("viewport-width", "2147483648")); } TEST_F(CorsTest, CorsUnsafeRequestHeaderNames) { // Needed because initializer list is not allowed for a macro argument. using List = std::vector<std::string>; // Empty => Empty EXPECT_EQ(CorsUnsafeRequestHeaderNames({}), List({})); // Some headers are safelisted. EXPECT_EQ(CorsUnsafeRequestHeaderNames({{"content-type", "text/plain"}, {"dpr", "12345"}, {"aCCept", "en,ja"}, {"accept-charset", "utf-8"}, {"uSer-Agent", "foo"}, {"hogE", "fuga"}}), List({"accept-charset", "user-agent", "hoge"})); // All headers are not safelisted. EXPECT_EQ( CorsUnsafeRequestHeaderNames({{"content-type", "text/html"}, {"dpr", "123-45"}, {"aCCept", "en,ja"}, {"accept-charset", "utf-8"}, {"uSer-Agent", "foo"}, {"hogE", "fuga"}}), List({"content-type", "dpr", "accept-charset", "user-agent", "hoge"})); // |safelistValueSize| is 1024. EXPECT_EQ( CorsUnsafeRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(108, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(126, '1')}, {"hogE", "fuga"}}), List({"hoge"})); // |safelistValueSize| is 1025. EXPECT_EQ( CorsUnsafeRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(108, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(127, '1')}, {"hogE", "fuga"}}), List({"hoge", "content-type", "accept", "accept-language", "content-language", "dpr", "device-memory", "save-data", "viewport-width", "width"})); // |safelistValueSize| is 897 because "content-type" is not safelisted. EXPECT_EQ( CorsUnsafeRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(128, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(127, '1')}, {"hogE", "fuga"}}), List({"content-type", "hoge"})); } TEST_F(CorsTest, CorsUnsafeNotForbiddenRequestHeaderNames) { // Needed because initializer list is not allowed for a macro argument. using List = std::vector<std::string>; // Empty => Empty EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({}, false /* is_revalidating */), List({})); // "user-agent" is NOT forbidden per spec, but forbidden in Chromium. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({{"content-type", "text/plain"}, {"dpr", "12345"}, {"aCCept", "en,ja"}, {"accept-charset", "utf-8"}, {"uSer-Agent", "foo"}, {"hogE", "fuga"}}, false /* is_revalidating */), List({"hoge"})); EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({{"content-type", "text/html"}, {"dpr", "123-45"}, {"aCCept", "en,ja"}, {"accept-charset", "utf-8"}, {"hogE", "fuga"}}, false /* is_revalidating */), List({"content-type", "dpr", "hoge"})); // |safelistValueSize| is 1024. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(108, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(126, '1')}, {"accept-charset", "utf-8"}, {"hogE", "fuga"}}, false /* is_revalidating */), List({"hoge"})); // |safelistValueSize| is 1025. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(108, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(127, '1')}, {"accept-charset", "utf-8"}, {"hogE", "fuga"}}, false /* is_revalidating */), List({"hoge", "content-type", "accept", "accept-language", "content-language", "dpr", "device-memory", "save-data", "viewport-width", "width"})); // |safelistValueSize| is 897 because "content-type" is not safelisted. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames( {{"content-type", "text/plain; charset=" + std::string(128, '1')}, {"accept", std::string(128, '1')}, {"accept-language", std::string(128, '1')}, {"content-language", std::string(128, '1')}, {"dpr", std::string(128, '1')}, {"device-memory", std::string(128, '1')}, {"save-data", "on"}, {"viewport-width", std::string(128, '1')}, {"width", std::string(127, '1')}, {"accept-charset", "utf-8"}, {"hogE", "fuga"}}, false /* is_revalidating */), List({"content-type", "hoge"})); } TEST_F(CorsTest, CorsUnsafeNotForbiddenRequestHeaderNamesWithRevalidating) { // Needed because initializer list is not allowed for a macro argument. using List = std::vector<std::string>; // Empty => Empty EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({}, true /* is_revalidating */), List({})); // These three headers will be ignored. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({{"If-MODifIED-since", "x"}, {"iF-nONE-MATCh", "y"}, {"CACHE-ContrOl", "z"}}, true /* is_revalidating */), List({})); // Without is_revalidating set, these three headers will not be safelisted. EXPECT_EQ( CorsUnsafeNotForbiddenRequestHeaderNames({{"If-MODifIED-since", "x"}, {"iF-nONE-MATCh", "y"}, {"CACHE-ContrOl", "z"}}, false /* is_revalidating */), List({"if-modified-since", "if-none-match", "cache-control"})); } TEST_F(CorsTest, NoCorsSafelistedHeaderName) { EXPECT_TRUE(IsNoCorsSafelistedHeaderName("accept")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("AcCePT")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("accept-language")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("acCEPt-lAnguage")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("content-language")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("coNTENt-lAnguage")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("content-type")); EXPECT_TRUE(IsNoCorsSafelistedHeaderName("CONTENT-TYPE")); EXPECT_FALSE(IsNoCorsSafelistedHeaderName("range")); EXPECT_FALSE(IsNoCorsSafelistedHeaderName("cookie")); EXPECT_FALSE(IsNoCorsSafelistedHeaderName("foobar")); } TEST_F(CorsTest, PrivilegedNoCorsHeaderName) { EXPECT_TRUE(IsPrivilegedNoCorsHeaderName("range")); EXPECT_TRUE(IsPrivilegedNoCorsHeaderName("RanGe")); EXPECT_FALSE(IsPrivilegedNoCorsHeaderName("content-type")); EXPECT_FALSE(IsPrivilegedNoCorsHeaderName("foobar")); EXPECT_FALSE(IsPrivilegedNoCorsHeaderName("cookie")); } TEST_F(CorsTest, IsForbiddenMethod) { EXPECT_TRUE(IsForbiddenMethod("connect")); EXPECT_TRUE(IsForbiddenMethod("CONNECT")); EXPECT_TRUE(IsForbiddenMethod("Connect")); EXPECT_TRUE(IsForbiddenMethod("CoNnEcT")); EXPECT_FALSE(IsForbiddenMethod("C0NNECT")); EXPECT_TRUE(IsForbiddenMethod("trace")); EXPECT_TRUE(IsForbiddenMethod("track")); EXPECT_FALSE(IsForbiddenMethod("trac")); EXPECT_FALSE(IsForbiddenMethod("tracz")); } } // namespace } // namespace cors } // namespace network
44.86988
80
0.654396
[ "vector", "model" ]
be3733e0af1dada4ce85e649d55b656f3b1f99df
2,519
cpp
C++
aws-cpp-sdk-workdocs/source/model/Participants.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-workdocs/source/model/Participants.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-workdocs/source/model/Participants.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/workdocs/model/Participants.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace WorkDocs { namespace Model { Participants::Participants() : m_usersHasBeenSet(false), m_groupsHasBeenSet(false) { } Participants::Participants(JsonView jsonValue) : m_usersHasBeenSet(false), m_groupsHasBeenSet(false) { *this = jsonValue; } Participants& Participants::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Users")) { Array<JsonView> usersJsonList = jsonValue.GetArray("Users"); for(unsigned usersIndex = 0; usersIndex < usersJsonList.GetLength(); ++usersIndex) { m_users.push_back(usersJsonList[usersIndex].AsObject()); } m_usersHasBeenSet = true; } if(jsonValue.ValueExists("Groups")) { Array<JsonView> groupsJsonList = jsonValue.GetArray("Groups"); for(unsigned groupsIndex = 0; groupsIndex < groupsJsonList.GetLength(); ++groupsIndex) { m_groups.push_back(groupsJsonList[groupsIndex].AsObject()); } m_groupsHasBeenSet = true; } return *this; } JsonValue Participants::Jsonize() const { JsonValue payload; if(m_usersHasBeenSet) { Array<JsonValue> usersJsonList(m_users.size()); for(unsigned usersIndex = 0; usersIndex < usersJsonList.GetLength(); ++usersIndex) { usersJsonList[usersIndex].AsObject(m_users[usersIndex].Jsonize()); } payload.WithArray("Users", std::move(usersJsonList)); } if(m_groupsHasBeenSet) { Array<JsonValue> groupsJsonList(m_groups.size()); for(unsigned groupsIndex = 0; groupsIndex < groupsJsonList.GetLength(); ++groupsIndex) { groupsJsonList[groupsIndex].AsObject(m_groups[groupsIndex].Jsonize()); } payload.WithArray("Groups", std::move(groupsJsonList)); } return payload; } } // namespace Model } // namespace WorkDocs } // namespace Aws
24.940594
90
0.719333
[ "model" ]
be37e450fbd591683d13c38512155fd4b03475ef
49,004
cc
C++
media/gpu/android/media_codec_video_decoder.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
media/gpu/android/media_codec_video_decoder.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
media/gpu/android/media_codec_video_decoder.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2016 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 "media/gpu/android/media_codec_video_decoder.h" #include <memory> #include "base/android/build_info.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/memory/weak_ptr.h" #include "base/metrics/histogram_macros.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "media/base/android/media_codec_bridge_impl.h" #include "media/base/android/media_codec_util.h" #include "media/base/async_destroy_video_decoder.h" #include "media/base/bind_to_current_loop.h" #include "media/base/decoder_buffer.h" #include "media/base/media_log.h" #include "media/base/media_switches.h" #include "media/base/scoped_async_trace.h" #include "media/base/status.h" #include "media/base/supported_video_decoder_config.h" #include "media/base/video_codecs.h" #include "media/base/video_decoder_config.h" #include "media/base/video_frame.h" #include "media/base/video_util.h" #include "media/gpu/android/android_video_surface_chooser.h" #include "media/gpu/android/codec_allocator.h" #include "media/media_buildflags.h" #if BUILDFLAG(USE_PROPRIETARY_CODECS) #include "media/base/android/extract_sps_and_pps.h" #endif namespace media { namespace { void OutputBufferReleased(bool using_async_api, base::RepeatingClosure pump_cb, bool is_drained_or_draining) { // The asynchronous API doesn't need pumping upon calls to ReleaseOutputBuffer // unless we're draining or drained. if (using_async_api && !is_drained_or_draining) return; pump_cb.Run(); } bool IsSurfaceControlEnabled(const gpu::GpuFeatureInfo& info) { return info.status_values[gpu::GPU_FEATURE_TYPE_ANDROID_SURFACE_CONTROL] == gpu::kGpuFeatureStatusEnabled; } std::vector<SupportedVideoDecoderConfig> GetSupportedConfigsInternal( DeviceInfo* device_info) { std::vector<SupportedVideoDecoderConfig> supported_configs; if (device_info->IsVp8DecoderAvailable()) { // For unencrypted content, require that the size is at least 360p and that // the MediaCodec implementation is hardware; otherwise fall back to libvpx. if (!device_info->IsDecoderKnownUnaccelerated(kCodecVP8)) { supported_configs.emplace_back(VP8PROFILE_ANY, VP8PROFILE_ANY, gfx::Size(480, 360), gfx::Size(3840, 2160), false, // allow_encrypted false); // require_encrypted } // Encrypted content must be decoded by MediaCodec. supported_configs.emplace_back(VP8PROFILE_ANY, VP8PROFILE_ANY, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted true); // require_encrypted } // TODO(dalecurtis): This needs to actually check the profiles available. This // can be done by calling MediaCodecUtil::AddSupportedCodecProfileLevels. if (device_info->IsVp9DecoderAvailable()) { const bool is_sw = device_info->IsDecoderKnownUnaccelerated(kCodecVP9); std::vector<CodecProfileLevel> profiles; // Support for VP9.2, VP9.3 was not added until Nougat. if (device_info->SdkVersion() >= base::android::SDK_VERSION_NOUGAT) device_info->AddSupportedCodecProfileLevels(&profiles); // If we think a VP9 decoder is available, but we didn't get any profiles // returned, just assume support for vp9.0 only. if (profiles.empty()) profiles.push_back({kCodecVP9, VP9PROFILE_PROFILE0, 0}); for (const auto& p : profiles) { if (p.codec != kCodecVP9) continue; // We don't compile support into libvpx for these profiles, so allow them // for all resolutions. See notes on H264 profiles below for more detail. if (p.profile > VP9PROFILE_PROFILE1) { supported_configs.emplace_back(p.profile, p.profile, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted false); // require_encrypted supported_configs.emplace_back(p.profile, p.profile, gfx::Size(0, 0), gfx::Size(2160, 3840), true, // allow_encrypted false); // require_encrypted continue; } // For unencrypted vp9.0 and vp9.1 content, require that the size is at // least 360p and that the MediaCodec implementation is hardware; // otherwise fall back to libvpx. if (!is_sw) { supported_configs.emplace_back( p.profile, p.profile, gfx::Size(480, 360), gfx::Size(3840, 2160), false, // allow_encrypted false); // require_encrypted supported_configs.emplace_back( p.profile, p.profile, gfx::Size(360, 480), gfx::Size(2160, 3840), false, // allow_encrypted false); // require_encrypted } // Encrypted content must be decoded by MediaCodec. supported_configs.emplace_back(p.profile, p.profile, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted true); // require_encrypted supported_configs.emplace_back(p.profile, p.profile, gfx::Size(0, 0), gfx::Size(2160, 3840), true, // allow_encrypted true); // require_encrypted } } if (device_info->IsAv1DecoderAvailable()) { // Technically we should check which profiles are supported, but since we // don't have an AV1 SW decoder, just allow them all. See notes below for // H264 profiles on the reasons why. supported_configs.emplace_back(AV1PROFILE_MIN, AV1PROFILE_MAX, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted false); // require_encrypted supported_configs.emplace_back(AV1PROFILE_MIN, AV1PROFILE_MAX, gfx::Size(0, 0), gfx::Size(2160, 3840), true, // allow_encrypted false); // require_encrypted } #if BUILDFLAG(USE_PROPRIETARY_CODECS) // MediaCodec is only guaranteed to support baseline, but some devices may // support others. Advertise support for all H.264 profiles and let the // MediaCodec fail when decoding if it's not actually supported. It's assumed // that there is not software fallback for H.264 on Android. supported_configs.emplace_back(H264PROFILE_MIN, H264PROFILE_MAX, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted false); // require_encrypted supported_configs.emplace_back(H264PROFILE_MIN, H264PROFILE_MAX, gfx::Size(0, 0), gfx::Size(2160, 3840), true, // allow_encrypted false); // require_encrypted #if BUILDFLAG(ENABLE_PLATFORM_HEVC) supported_configs.emplace_back(HEVCPROFILE_MIN, HEVCPROFILE_MAX, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted false); // require_encrypted #endif #if BUILDFLAG(ENABLE_PLATFORM_DOLBY_VISION) // Technically we should check which profiles are supported, but we can // allow them all like we do with H264 codec. supported_configs.emplace_back(DOLBYVISION_PROFILE4, DOLBYVISION_PROFILE9, gfx::Size(0, 0), gfx::Size(3840, 2160), true, // allow_encrypted false); // require_encrypted supported_configs.emplace_back(DOLBYVISION_PROFILE4, DOLBYVISION_PROFILE9, gfx::Size(0, 0), gfx::Size(2160, 3840), true, // allow_encrypted false); // require_encrypted #endif #endif // #if BUILDFLAG(USE_PROPRIETARY_CODECS) return supported_configs; } } // namespace // When re-initializing the codec changes the resolution to be more than // |kReallocateThreshold| times the old one, force a codec reallocation to // update the hints that we provide to MediaCodec. crbug.com/989182 . constexpr static float kReallocateThreshold = 4; // static PendingDecode PendingDecode::CreateEos() { return {DecoderBuffer::CreateEOSBuffer(), base::DoNothing()}; } PendingDecode::PendingDecode(scoped_refptr<DecoderBuffer> buffer, VideoDecoder::DecodeCB decode_cb) : buffer(std::move(buffer)), decode_cb(std::move(decode_cb)) {} PendingDecode::PendingDecode(PendingDecode&& other) = default; PendingDecode::~PendingDecode() = default; // static std::vector<SupportedVideoDecoderConfig> MediaCodecVideoDecoder::GetSupportedConfigs() { static const auto configs = GetSupportedConfigsInternal(DeviceInfo::GetInstance()); return configs; } MediaCodecVideoDecoder::MediaCodecVideoDecoder( const gpu::GpuPreferences& gpu_preferences, const gpu::GpuFeatureInfo& gpu_feature_info, std::unique_ptr<MediaLog> media_log, DeviceInfo* device_info, CodecAllocator* codec_allocator, std::unique_ptr<AndroidVideoSurfaceChooser> surface_chooser, AndroidOverlayMojoFactoryCB overlay_factory_cb, RequestOverlayInfoCB request_overlay_info_cb, std::unique_ptr<VideoFrameFactory> video_frame_factory) : media_log_(std::move(media_log)), codec_allocator_(codec_allocator), request_overlay_info_cb_(std::move(request_overlay_info_cb)), is_surface_control_enabled_(IsSurfaceControlEnabled(gpu_feature_info)), surface_chooser_helper_( std::move(surface_chooser), base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceVideoOverlays), base::FeatureList::IsEnabled(media::kUseAndroidOverlayAggressively), is_surface_control_enabled_), video_frame_factory_(std::move(video_frame_factory)), overlay_factory_cb_(std::move(overlay_factory_cb)), device_info_(device_info), enable_threaded_texture_mailboxes_( gpu_preferences.enable_threaded_texture_mailboxes), allow_nonsecure_overlays_( base::FeatureList::IsEnabled(media::kAllowNonSecureOverlays)) { DVLOG(2) << __func__; surface_chooser_helper_.chooser()->SetClientCallbacks( base::BindRepeating(&MediaCodecVideoDecoder::OnSurfaceChosen, weak_factory_.GetWeakPtr()), base::BindRepeating(&MediaCodecVideoDecoder::OnSurfaceChosen, weak_factory_.GetWeakPtr(), nullptr)); } std::unique_ptr<VideoDecoder> MediaCodecVideoDecoder::Create( const gpu::GpuPreferences& gpu_preferences, const gpu::GpuFeatureInfo& gpu_feature_info, std::unique_ptr<MediaLog> media_log, DeviceInfo* device_info, CodecAllocator* codec_allocator, std::unique_ptr<AndroidVideoSurfaceChooser> surface_chooser, AndroidOverlayMojoFactoryCB overlay_factory_cb, RequestOverlayInfoCB request_overlay_info_cb, std::unique_ptr<VideoFrameFactory> video_frame_factory) { auto* decoder = new MediaCodecVideoDecoder( gpu_preferences, gpu_feature_info, std::move(media_log), device_info, codec_allocator, std::move(surface_chooser), std::move(overlay_factory_cb), std::move(request_overlay_info_cb), std::move(video_frame_factory)); return std::make_unique<AsyncDestroyVideoDecoder<MediaCodecVideoDecoder>>( base::WrapUnique(decoder)); } MediaCodecVideoDecoder::~MediaCodecVideoDecoder() { DVLOG(2) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::~MediaCodecVideoDecoder"); ReleaseCodec(); } void MediaCodecVideoDecoder::DestroyAsync( std::unique_ptr<MediaCodecVideoDecoder> decoder) { DVLOG(1) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::Destroy"); DCHECK(decoder); // This will be destroyed by a call to |DeleteSoon| // in |OnCodecDrained|. auto* self = decoder.release(); // Cancel pending callbacks. // // WARNING: This will lose the callback we've given to MediaCodecBridge for // asynchronous notifications; so we must not leave this function with any // work necessary from StartTimerOrPumpCodec(). self->weak_factory_.InvalidateWeakPtrs(); if (self->media_crypto_context_) { // Cancel previously registered callback (if any). self->event_cb_registration_.reset(); self->media_crypto_context_->SetMediaCryptoReadyCB(base::NullCallback()); self->media_crypto_context_ = nullptr; } // Mojo callbacks require that they're run before destruction. if (self->reset_cb_) std::move(self->reset_cb_).Run(); // Cancel callbacks we no longer want. self->codec_allocator_weak_factory_.InvalidateWeakPtrs(); self->CancelPendingDecodes(DecodeStatus::ABORTED); self->StartDrainingCodec(DrainType::kForDestroy); // Per the WARNING above. Validate that no draining work remains. if (self->using_async_api_) DCHECK(!self->drain_type_.has_value()); } void MediaCodecVideoDecoder::Initialize(const VideoDecoderConfig& config, bool low_delay, CdmContext* cdm_context, InitCB init_cb, const OutputCB& output_cb, const WaitingCB& waiting_cb) { DCHECK(output_cb); DCHECK(waiting_cb); const bool first_init = !decoder_config_.IsValidConfig(); DVLOG(1) << (first_init ? "Initializing" : "Reinitializing") << " MCVD with config: " << config.AsHumanReadableString() << ", cdm_context = " << cdm_context; if (!config.IsValidConfig()) { MEDIA_LOG(INFO, media_log_) << "Video configuration is not valid: " << config.AsHumanReadableString(); DVLOG(1) << "Invalid configuration."; BindToCurrentLoop(std::move(init_cb)) .Run(StatusCode::kDecoderUnsupportedConfig); return; } // Tests override the DeviceInfo, so if an override is provided query the // configs as they look under that DeviceInfo. If not, use the default method // which is statically cached for faster Initialize(). const auto configs = device_info_ == DeviceInfo::GetInstance() ? GetSupportedConfigs() : GetSupportedConfigsInternal(device_info_); if (!IsVideoDecoderConfigSupported(configs, config)) { DVLOG(1) << "Unsupported configuration."; MEDIA_LOG(INFO, media_log_) << "Video configuration is not valid: " << config.AsHumanReadableString(); BindToCurrentLoop(std::move(init_cb)) .Run(StatusCode::kDecoderUnsupportedConfig); return; } // Disallow codec changes when reinitializing. if (!first_init && decoder_config_.codec() != config.codec()) { DVLOG(1) << "Codec changed: cannot reinitialize"; MEDIA_LOG(INFO, media_log_) << "Cannot change codec during re-init: " << decoder_config_.AsHumanReadableString() << " -> " << config.AsHumanReadableString(); BindToCurrentLoop(std::move(init_cb)) .Run(StatusCode::kDecoderCantChangeCodec); return; } decoder_config_ = config; surface_chooser_helper_.SetVideoRotation( decoder_config_.video_transformation().rotation); output_cb_ = output_cb; waiting_cb_ = waiting_cb; #if BUILDFLAG(USE_PROPRIETARY_CODECS) if (config.codec() == kCodecH264) ExtractSpsAndPps(config.extra_data(), &csd0_, &csd1_); #endif // We only support setting CDM at first initialization. Even if the initial // config is clear, we'll still try to set CDM since we may switch to an // encrypted config later. if (first_init && cdm_context && cdm_context->GetMediaCryptoContext()) { DCHECK(media_crypto_.is_null()); SetCdm(cdm_context, std::move(init_cb)); return; } if (config.is_encrypted() && media_crypto_.is_null()) { DVLOG(1) << "No MediaCrypto to handle encrypted config"; MEDIA_LOG(INFO, media_log_) << "No MediaCrypto to handle encrypted config"; BindToCurrentLoop(std::move(init_cb)) .Run(StatusCode::kDecoderMissingCdmForEncryptedContent); return; } // Do the rest of the initialization lazily on the first decode. BindToCurrentLoop(std::move(init_cb)).Run(OkStatus()); const int width = config.coded_size().width(); // On re-init, reallocate the codec if the size has changed too much. // Restrict this behavior to Q, where the behavior changed. if (first_init) { last_width_ = width; } else if (width > last_width_ * kReallocateThreshold && device_info_ && device_info_->SdkVersion() > base::android::SDK_VERSION_P) { // Reallocate the codec the next time we queue input, once there are no // outstanding output buffers. Note that |deferred_flush_pending_| might // already be set, which is fine. We're just upgrading the flush. // // If the codec IsDrained(), then we'll flush anyway. However, just to be // sure, request a deferred flush. deferred_flush_pending_ = true; deferred_reallocation_pending_ = true; last_width_ = width; } // else leave |last_width_| unmodified, since we're re-using the codec. } void MediaCodecVideoDecoder::SetCdm(CdmContext* cdm_context, InitCB init_cb) { DVLOG(1) << __func__; DCHECK(cdm_context) << "No CDM provided"; DCHECK(cdm_context->GetMediaCryptoContext()); media_crypto_context_ = cdm_context->GetMediaCryptoContext(); // CdmContext will always post the registered callback back to this thread. event_cb_registration_ = cdm_context->RegisterEventCB(base::BindRepeating( &MediaCodecVideoDecoder::OnCdmContextEvent, weak_factory_.GetWeakPtr())); // The callback will be posted back to this thread via BindToCurrentLoop. media_crypto_context_->SetMediaCryptoReadyCB(media::BindToCurrentLoop( base::BindOnce(&MediaCodecVideoDecoder::OnMediaCryptoReady, weak_factory_.GetWeakPtr(), std::move(init_cb)))); } void MediaCodecVideoDecoder::OnMediaCryptoReady( InitCB init_cb, JavaObjectPtr media_crypto, bool requires_secure_video_codec) { DVLOG(1) << __func__ << ": requires_secure_video_codec = " << requires_secure_video_codec; DCHECK(state_ == State::kInitializing); DCHECK(media_crypto); if (media_crypto->is_null()) { media_crypto_context_->SetMediaCryptoReadyCB(base::NullCallback()); media_crypto_context_ = nullptr; if (decoder_config_.is_encrypted()) { LOG(ERROR) << "MediaCrypto is not available"; EnterTerminalState(State::kError, "MediaCrypto is not available"); std::move(init_cb).Run(StatusCode::kDecoderMissingCdmForEncryptedContent); return; } // MediaCrypto is not available, but the stream is clear. So we can still // play the current stream. But if we switch to an encrypted stream playback // will fail. std::move(init_cb).Run(OkStatus()); return; } media_crypto_ = *media_crypto; requires_secure_codec_ = requires_secure_video_codec; // Request a secure surface in all cases. For L3, it's okay if we fall back // to TextureOwner rather than fail composition. For L1, it's required. surface_chooser_helper_.SetSecureSurfaceMode( requires_secure_video_codec ? SurfaceChooserHelper::SecureSurfaceMode::kRequired : SurfaceChooserHelper::SecureSurfaceMode::kRequested); // Signal success, and create the codec lazily on the first decode. std::move(init_cb).Run(OkStatus()); } void MediaCodecVideoDecoder::OnCdmContextEvent(CdmContext::Event event) { DVLOG(2) << __func__; if (event != CdmContext::Event::kHasAdditionalUsableKey) return; waiting_for_key_ = false; StartTimerOrPumpCodec(); } void MediaCodecVideoDecoder::StartLazyInit() { DVLOG(2) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::StartLazyInit"); lazy_init_pending_ = false; // Only ask for promotion hints if we can actually switch surfaces, since we // wouldn't be able to do anything with them. Also, if threaded texture // mailboxes are enabled, then we turn off overlays anyway. const bool want_promotion_hints = device_info_->IsSetOutputSurfaceSupported() && !enable_threaded_texture_mailboxes_; VideoFrameFactory::OverlayMode overlay_mode = VideoFrameFactory::OverlayMode::kDontRequestPromotionHints; if (is_surface_control_enabled_) { overlay_mode = requires_secure_codec_ ? VideoFrameFactory::OverlayMode::kSurfaceControlSecure : VideoFrameFactory::OverlayMode::kSurfaceControlInsecure; } else if (want_promotion_hints) { overlay_mode = VideoFrameFactory::OverlayMode::kRequestPromotionHints; } // Regardless of whether we're using SurfaceControl or Dialog overlays, don't // allow any overlays in A/B power testing mode, unless this requires a // secure surface. Don't fail the playback for power testing. if (!requires_secure_codec_ && !allow_nonsecure_overlays_) overlay_mode = VideoFrameFactory::OverlayMode::kDontRequestPromotionHints; video_frame_factory_->Initialize( overlay_mode, base::BindRepeating( &MediaCodecVideoDecoder::OnVideoFrameFactoryInitialized, weak_factory_.GetWeakPtr())); } void MediaCodecVideoDecoder::OnVideoFrameFactoryInitialized( scoped_refptr<gpu::TextureOwner> texture_owner) { DVLOG(2) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::OnVideoFrameFactoryInitialized"); if (!texture_owner) { EnterTerminalState(State::kError, "Could not allocated TextureOwner"); return; } texture_owner_bundle_ = new CodecSurfaceBundle(std::move(texture_owner)); // This is for A/B power testing only. Turn off Dialog-based overlays in // power testing mode, unless we need them for L1 content. // See https://crbug.com/1081346 . const bool allowed_for_experiment = requires_secure_codec_ || allow_nonsecure_overlays_; // Overlays are disabled when |enable_threaded_texture_mailboxes| is true // (http://crbug.com/582170). if (enable_threaded_texture_mailboxes_ || !device_info_->SupportsOverlaySurfaces() || !allowed_for_experiment) { OnSurfaceChosen(nullptr); return; } // Request OverlayInfo updates. Initialization continues on the first one. bool restart_for_transitions = !device_info_->IsSetOutputSurfaceSupported(); std::move(request_overlay_info_cb_) .Run(restart_for_transitions, base::BindRepeating(&MediaCodecVideoDecoder::OnOverlayInfoChanged, weak_factory_.GetWeakPtr())); } void MediaCodecVideoDecoder::OnOverlayInfoChanged( const OverlayInfo& overlay_info) { DVLOG(2) << __func__; DCHECK(device_info_->SupportsOverlaySurfaces()); DCHECK(!enable_threaded_texture_mailboxes_); if (InTerminalState()) return; bool overlay_changed = !overlay_info_.RefersToSameOverlayAs(overlay_info); overlay_info_ = overlay_info; surface_chooser_helper_.SetIsFullscreen(overlay_info_.is_fullscreen); surface_chooser_helper_.SetIsPersistentVideo( overlay_info_.is_persistent_video); surface_chooser_helper_.UpdateChooserState( overlay_changed ? base::make_optional(CreateOverlayFactoryCb()) : base::nullopt); } void MediaCodecVideoDecoder::OnSurfaceChosen( std::unique_ptr<AndroidOverlay> overlay) { DVLOG(2) << __func__; DCHECK(state_ == State::kInitializing || device_info_->IsSetOutputSurfaceSupported()); TRACE_EVENT1("media", "MediaCodecVideoDecoder::OnSurfaceChosen", "overlay", overlay ? "yes" : "no"); if (overlay) { overlay->AddSurfaceDestroyedCallback( base::BindOnce(&MediaCodecVideoDecoder::OnSurfaceDestroyed, weak_factory_.GetWeakPtr())); target_surface_bundle_ = new CodecSurfaceBundle(std::move(overlay)); } else { target_surface_bundle_ = texture_owner_bundle_; } // If we were waiting for our first surface during initialization, then // proceed to create a codec. if (state_ == State::kInitializing) { state_ = State::kRunning; CreateCodec(); } } void MediaCodecVideoDecoder::OnSurfaceDestroyed(AndroidOverlay* overlay) { DVLOG(2) << __func__; DCHECK_NE(state_, State::kInitializing); TRACE_EVENT0("media", "MediaCodecVideoDecoder::OnSurfaceDestroyed"); // If SetOutputSurface() is not supported we only ever observe destruction of // a single overlay so this must be the one we're using. In this case it's // the responsibility of our consumer to destroy us for surface transitions. // TODO(liberato): This might not be true for L1 / L3, since our caller has // no idea that this has happened. We should unback the frames here. This // might work now that we have CodecImageGroup -- verify this. if (!device_info_->IsSetOutputSurfaceSupported()) { EnterTerminalState(State::kSurfaceDestroyed, "Surface destroyed"); return; } // Reset the target bundle if it is the one being destroyed. if (target_surface_bundle_ && target_surface_bundle_->overlay() == overlay) target_surface_bundle_ = texture_owner_bundle_; // Transition the codec away from the overlay if necessary. This must be // complete before this function returns. if (SurfaceTransitionPending()) TransitionToTargetSurface(); } bool MediaCodecVideoDecoder::SurfaceTransitionPending() { return codec_ && codec_->SurfaceBundle() != target_surface_bundle_; } void MediaCodecVideoDecoder::TransitionToTargetSurface() { DVLOG(2) << __func__; DCHECK(SurfaceTransitionPending()); DCHECK(device_info_->IsSetOutputSurfaceSupported()); if (!codec_->SetSurface(target_surface_bundle_)) { video_frame_factory_->SetSurfaceBundle(nullptr); EnterTerminalState(State::kError, "Could not switch codec output surface"); return; } video_frame_factory_->SetSurfaceBundle(target_surface_bundle_); CacheFrameInformation(); } void MediaCodecVideoDecoder::CreateCodec() { DCHECK(!codec_); DCHECK(target_surface_bundle_); DCHECK_EQ(state_, State::kRunning); auto config = std::make_unique<VideoCodecConfig>(); if (requires_secure_codec_) config->codec_type = CodecType::kSecure; config->codec = decoder_config_.codec(); config->csd0 = csd0_; config->csd1 = csd1_; config->surface = target_surface_bundle_->GetJavaSurface(); config->media_crypto = media_crypto_; config->initial_expected_coded_size = decoder_config_.coded_size(); config->container_color_space = decoder_config_.color_space_info(); config->hdr_metadata = decoder_config_.hdr_metadata(); // Use the asynchronous API if we can. if (device_info_->IsAsyncApiSupported()) { using_async_api_ = true; config->on_buffers_available_cb = BindToCurrentLoop( base::BindRepeating(&MediaCodecVideoDecoder::StartTimerOrPumpCodec, weak_factory_.GetWeakPtr())); } // Note that this might be the same surface bundle that we've been using, if // we're reinitializing the codec without changing surfaces. That's fine. video_frame_factory_->SetSurfaceBundle(target_surface_bundle_); codec_allocator_->CreateMediaCodecAsync( base::BindOnce(&MediaCodecVideoDecoder::OnCodecConfiguredInternal, codec_allocator_weak_factory_.GetWeakPtr(), codec_allocator_, target_surface_bundle_), std::move(config)); } // static void MediaCodecVideoDecoder::OnCodecConfiguredInternal( base::WeakPtr<MediaCodecVideoDecoder> weak_this, CodecAllocator* codec_allocator, scoped_refptr<CodecSurfaceBundle> surface_bundle, std::unique_ptr<MediaCodecBridge> codec) { if (!weak_this) { if (codec) { codec_allocator->ReleaseMediaCodec( std::move(codec), base::BindOnce( &base::SequencedTaskRunner::ReleaseSoon<CodecSurfaceBundle>, base::SequencedTaskRunnerHandle::Get(), FROM_HERE, std::move(surface_bundle))); } return; } weak_this->OnCodecConfigured(std::move(surface_bundle), std::move(codec)); } void MediaCodecVideoDecoder::OnCodecConfigured( scoped_refptr<CodecSurfaceBundle> surface_bundle, std::unique_ptr<MediaCodecBridge> codec) { DCHECK(!codec_); DCHECK_EQ(state_, State::kRunning); if (!codec) { EnterTerminalState(State::kError, "Unable to allocate codec"); return; } codec_ = std::make_unique<CodecWrapper>( CodecSurfacePair(std::move(codec), std::move(surface_bundle)), base::BindRepeating(&OutputBufferReleased, using_async_api_, BindToCurrentLoop(base::BindRepeating( &MediaCodecVideoDecoder::StartTimerOrPumpCodec, weak_factory_.GetWeakPtr()))), base::SequencedTaskRunnerHandle::Get()); // If the target surface changed while codec creation was in progress, // transition to it immediately. // Note: this can only happen if we support SetOutputSurface() because if we // don't OnSurfaceDestroyed() cancels codec creations, and // |surface_chooser_| doesn't change the target surface. if (SurfaceTransitionPending()) TransitionToTargetSurface(); // Cache the frame information that goes with this codec. CacheFrameInformation(); StartTimerOrPumpCodec(); } void MediaCodecVideoDecoder::Decode(scoped_refptr<DecoderBuffer> buffer, DecodeCB decode_cb) { DVLOG(3) << __func__ << ": " << buffer->AsHumanReadableString(); if (state_ == State::kError) { std::move(decode_cb).Run(DecodeStatus::DECODE_ERROR); return; } pending_decodes_.emplace_back(std::move(buffer), std::move(decode_cb)); if (state_ == State::kInitializing) { if (lazy_init_pending_) StartLazyInit(); return; } PumpCodec(true); } void MediaCodecVideoDecoder::FlushCodec() { DVLOG(2) << __func__; // If a deferred flush was pending, then it isn't anymore. deferred_flush_pending_ = false; // Release and re-allocate the codec, if needed, for a resolution change. // This also counts as a flush. Note that we could also stop / configure / // start the codec, but there's a fair bit of complexity in that. Timing // tests didn't show any big advantage. During a resolution change, the time // between the next time we queue an input buffer and the next time we get an // output buffer were: // // flush only: 0.04 s // stop / configure / start: 0.026 s // release / create: 0.03 s // // So, it seems that flushing the codec defers some work (buffer reallocation // or similar) that ends up on the critical path. I didn't verify what // happens when we're flushing without a resolution change, nor can I quite // explain how anything can be done off the critical path when a flush is // deferred to the first queued input. if (deferred_reallocation_pending_) { deferred_reallocation_pending_ = false; ReleaseCodec(); CreateCodec(); } if (!codec_ || codec_->IsFlushed()) return; DVLOG(2) << "Flushing codec"; if (!codec_->Flush()) EnterTerminalState(State::kError, "Codec flush failed"); } void MediaCodecVideoDecoder::PumpCodec(bool force_start_timer) { DVLOG(4) << __func__; bool did_work = false, did_input = false, did_output = false; do { did_input = QueueInput(); did_output = DequeueOutput(); if (did_input || did_output) did_work = true; } while (did_input || did_output); if (using_async_api_) return; if (did_work || force_start_timer) StartTimerOrPumpCodec(); else StopTimerIfIdle(); } void MediaCodecVideoDecoder::StartTimerOrPumpCodec() { DVLOG(4) << __func__; if (state_ != State::kRunning) return; if (using_async_api_) { PumpCodec(false); return; } idle_timer_ = base::ElapsedTimer(); // Poll at 10ms somewhat arbitrarily. // TODO: Don't poll on new devices; use the callback API. // TODO: Experiment with this number to save power. Since we already pump the // codec in response to receiving a decode and output buffer release, polling // at this frequency is likely overkill in the steady state. const auto kPollingPeriod = base::TimeDelta::FromMilliseconds(10); if (!pump_codec_timer_.IsRunning()) { pump_codec_timer_.Start( FROM_HERE, kPollingPeriod, base::BindRepeating(&MediaCodecVideoDecoder::PumpCodec, base::Unretained(this), false)); } } void MediaCodecVideoDecoder::StopTimerIfIdle() { DVLOG(4) << __func__; DCHECK(!using_async_api_); // Stop the timer if we've been idle for one second. Chosen arbitrarily. const auto kTimeout = base::TimeDelta::FromSeconds(1); if (idle_timer_.Elapsed() > kTimeout) { DVLOG(2) << "Stopping timer; idle timeout hit"; pump_codec_timer_.Stop(); // Draining for destroy can no longer proceed if the timer is stopping, // because no more Decode() calls can be made, so complete it now to avoid // leaking |this|. if (drain_type_ == DrainType::kForDestroy) OnCodecDrained(); } } bool MediaCodecVideoDecoder::QueueInput() { DVLOG(4) << __func__; if (!codec_ || waiting_for_key_) return false; // If the codec is drained, flush it when there is a pending decode and no // unreleased output buffers. This lets us avoid both unbacking frames when we // flush, and flushing unnecessarily, like at EOS. // // Often, we'll elide the eos to drain the codec, but we want to pretend that // we did. In this case, we should also flush. if (codec_->IsDrained() || deferred_flush_pending_) { if (!codec_->HasUnreleasedOutputBuffers() && !pending_decodes_.empty()) { FlushCodec(); return true; } return false; } if (pending_decodes_.empty()) return false; PendingDecode& pending_decode = pending_decodes_.front(); auto status = codec_->QueueInputBuffer(*pending_decode.buffer); DVLOG((status == CodecWrapper::QueueStatus::kTryAgainLater || status == CodecWrapper::QueueStatus::kOk ? 3 : 2)) << "QueueInput(" << pending_decode.buffer->AsHumanReadableString() << ") status=" << static_cast<int>(status); switch (status) { case CodecWrapper::QueueStatus::kOk: break; case CodecWrapper::QueueStatus::kTryAgainLater: return false; case CodecWrapper::QueueStatus::kNoKey: // Retry when a key is added. waiting_for_key_ = true; waiting_cb_.Run(WaitingReason::kNoDecryptionKey); return false; case CodecWrapper::QueueStatus::kError: EnterTerminalState(State::kError, "QueueInputBuffer failed"); return false; } if (pending_decode.buffer->end_of_stream()) { // The VideoDecoder interface requires that the EOS DecodeCB is called after // all decodes before it are delivered, so we have to save it and call it // when the EOS is dequeued. DCHECK(!eos_decode_cb_); eos_decode_cb_ = std::move(pending_decode.decode_cb); } else { std::move(pending_decode.decode_cb).Run(DecodeStatus::OK); } pending_decodes_.pop_front(); return true; } bool MediaCodecVideoDecoder::DequeueOutput() { DVLOG(4) << __func__; if (!codec_ || codec_->IsDrained() || waiting_for_key_) return false; // If a surface transition is pending, wait for all outstanding buffers to be // released before doing the transition. This is necessary because the // VideoFrames corresponding to these buffers have metadata flags specific to // the surface type, and changing the surface before they're rendered would // invalidate them. if (SurfaceTransitionPending()) { if (!codec_->HasUnreleasedOutputBuffers()) { TransitionToTargetSurface(); return true; } return false; } base::TimeDelta presentation_time; bool eos = false; std::unique_ptr<CodecOutputBuffer> output_buffer; auto status = codec_->DequeueOutputBuffer(&presentation_time, &eos, &output_buffer); switch (status) { case CodecWrapper::DequeueStatus::kOk: break; case CodecWrapper::DequeueStatus::kTryAgainLater: return false; case CodecWrapper::DequeueStatus::kError: DVLOG(1) << "DequeueOutputBuffer() error"; EnterTerminalState(State::kError, "DequeueOutputBuffer failed"); return false; } DVLOG(3) << "DequeueOutputBuffer(): pts=" << (eos ? "EOS" : std::to_string(presentation_time.InMilliseconds())); if (eos) { if (eos_decode_cb_) { // Schedule the EOS DecodeCB to run after all previous frames. video_frame_factory_->RunAfterPendingVideoFrames( base::BindOnce(&MediaCodecVideoDecoder::RunEosDecodeCb, weak_factory_.GetWeakPtr(), reset_generation_)); } if (drain_type_) OnCodecDrained(); // We don't flush the drained codec immediately because it might be // backing unrendered frames near EOS. It's flushed lazily in QueueInput(). return false; } // If we're draining for reset or destroy we can discard |output_buffer| // without rendering it. This is also true if we elided the drain itself, // and deferred a flush that would have happened when the drain completed. if (drain_type_ || deferred_flush_pending_) return true; // Record the frame type that we're sending and some information about why. UMA_HISTOGRAM_ENUMERATION( "Media.AVDA.FrameInformation", cached_frame_information_, static_cast<int>( SurfaceChooserHelper::FrameInformation::FRAME_INFORMATION_MAX) + 1); // PRESUBMIT_IGNORE_UMA_MAX gfx::Rect visible_rect(output_buffer->size()); std::unique_ptr<ScopedAsyncTrace> async_trace = ScopedAsyncTrace::CreateIfEnabled( "MediaCodecVideoDecoder::CreateVideoFrame"); // Make sure that we're notified when this is rendered. Otherwise, if we're // waiting for all output buffers to drain so that we can swap the output // surface, we might not realize that we may continue. If we're using // SurfaceControl overlays, then this isn't needed; there is never a surface // transition anyway. if (!is_surface_control_enabled_) { output_buffer->set_render_cb(BindToCurrentLoop( base::BindOnce(&MediaCodecVideoDecoder::StartTimerOrPumpCodec, weak_factory_.GetWeakPtr()))); } video_frame_factory_->CreateVideoFrame( std::move(output_buffer), presentation_time, GetNaturalSize(visible_rect, decoder_config_.GetPixelAspectRatio()), CreatePromotionHintCB(), base::BindOnce(&MediaCodecVideoDecoder::ForwardVideoFrame, weak_factory_.GetWeakPtr(), reset_generation_, std::move(async_trace), base::TimeTicks::Now())); return true; } void MediaCodecVideoDecoder::RunEosDecodeCb(int reset_generation) { // Both of the following conditions are necessary because: // * In an error state, the reset generations will match but |eos_decode_cb_| // will be aborted. // * After a Reset(), the reset generations won't match, but we might already // have a new |eos_decode_cb_| for the new generation. if (reset_generation == reset_generation_ && eos_decode_cb_) std::move(eos_decode_cb_).Run(DecodeStatus::OK); } void MediaCodecVideoDecoder::ForwardVideoFrame( int reset_generation, std::unique_ptr<ScopedAsyncTrace> async_trace, base::TimeTicks started_at, scoped_refptr<VideoFrame> frame) { DVLOG(3) << __func__ << " : " << (frame ? frame->AsHumanReadableString() : "null"); // Record how long this frame was pending. const base::TimeDelta duration = base::TimeTicks::Now() - started_at; UMA_HISTOGRAM_CUSTOM_TIMES("Media.MCVD.ForwardVideoFrameTiming", duration, base::TimeDelta::FromMilliseconds(1), base::TimeDelta::FromMilliseconds(100), 25); // No |frame| indicates an error creating it. if (!frame) { DLOG(ERROR) << __func__ << " |frame| is null"; EnterTerminalState(State::kError, "Could not create VideoFrame"); return; } if (reset_generation == reset_generation_) { // TODO(liberato): We might actually have a SW decoder. Consider setting // this to false if so, especially for higher bitrates. frame->metadata().power_efficient = true; output_cb_.Run(std::move(frame)); } } // Our Reset() provides a slightly stronger guarantee than VideoDecoder does. // After |closure| runs: // 1) no VideoFrames from before the Reset() will be output, and // 2) no DecodeCBs (including EOS) from before the Reset() will be run. void MediaCodecVideoDecoder::Reset(base::OnceClosure closure) { DVLOG(2) << __func__; DCHECK(!reset_cb_); reset_generation_++; reset_cb_ = std::move(closure); CancelPendingDecodes(DecodeStatus::ABORTED); StartDrainingCodec(DrainType::kForReset); } void MediaCodecVideoDecoder::StartDrainingCodec(DrainType drain_type) { DVLOG(2) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::StartDrainingCodec"); DCHECK(pending_decodes_.empty()); // It's okay if there's already a drain ongoing. We'll only enqueue an EOS if // the codec isn't already draining. drain_type_ = drain_type; // We can safely invalidate outstanding buffers for both types of drain, and // doing so can only make the drain complete quicker. Note that we do this // even if we're eliding the drain, since we're either going to flush the // codec or destroy it. While we're not required to do this, it might affect // stability if we don't (https://crbug.com/869365). AVDA, in particular, // dropped all pending codec output buffers when starting a reset (seek) or // a destroy. if (codec_) codec_->DiscardOutputBuffers(); // Skip the drain if possible. Only VP8 codecs need draining because // they can hang in release() or flush() otherwise // (http://crbug.com/598963). // TODO(watk): Strongly consider blocking VP8 (or specific MediaCodecs) // instead. Draining is responsible for a lot of complexity. if (decoder_config_.codec() != kCodecVP8 || !codec_ || codec_->IsFlushed() || codec_->IsDrained() || using_async_api_) { // If the codec isn't already drained or flushed, then we have to remember // that we owe it a flush. We also have to remember not to deliver any // output buffers that might still be in progress in the codec. deferred_flush_pending_ = codec_ && !codec_->IsDrained() && !codec_->IsFlushed(); OnCodecDrained(); return; } // Queue EOS if the codec isn't already processing one. if (!codec_->IsDraining()) pending_decodes_.push_back(PendingDecode::CreateEos()); PumpCodec(true); } void MediaCodecVideoDecoder::OnCodecDrained() { DVLOG(2) << __func__; TRACE_EVENT0("media", "MediaCodecVideoDecoder::OnCodecDrained"); DrainType drain_type = *drain_type_; drain_type_.reset(); if (drain_type == DrainType::kForDestroy) { // Post the delete in case the caller uses |this| after we return. base::SequencedTaskRunnerHandle::Get()->DeleteSoon(FROM_HERE, this); return; } std::move(reset_cb_).Run(); // Flush the codec unless (a) it's already flushed, (b) it's drained and the // flush will be handled automatically on the next decode, or (c) we've // elided the eos and want to defer the flush. if (codec_ && !codec_->IsFlushed() && !codec_->IsDrained() && !deferred_flush_pending_) { FlushCodec(); } } void MediaCodecVideoDecoder::EnterTerminalState(State state, const char* reason) { DVLOG(2) << __func__ << " " << static_cast<int>(state) << " " << reason; MEDIA_LOG(INFO, media_log_) << "Entering Terminal State: " << reason; state_ = state; DCHECK(InTerminalState()); // Cancel pending codec creation. codec_allocator_weak_factory_.InvalidateWeakPtrs(); pump_codec_timer_.Stop(); ReleaseCodec(); target_surface_bundle_ = nullptr; texture_owner_bundle_ = nullptr; if (state == State::kError) CancelPendingDecodes(DecodeStatus::DECODE_ERROR); if (drain_type_) OnCodecDrained(); } bool MediaCodecVideoDecoder::InTerminalState() { return state_ == State::kSurfaceDestroyed || state_ == State::kError; } void MediaCodecVideoDecoder::CancelPendingDecodes(DecodeStatus status) { for (auto& pending_decode : pending_decodes_) std::move(pending_decode.decode_cb).Run(status); pending_decodes_.clear(); if (eos_decode_cb_) std::move(eos_decode_cb_).Run(status); } void MediaCodecVideoDecoder::ReleaseCodec() { if (!codec_) return; auto pair = codec_->TakeCodecSurfacePair(); codec_ = nullptr; codec_allocator_->ReleaseMediaCodec( std::move(pair.first), base::BindOnce( &base::SequencedTaskRunner::ReleaseSoon<CodecSurfaceBundle>, base::SequencedTaskRunnerHandle::Get(), FROM_HERE, std::move(pair.second))); } AndroidOverlayFactoryCB MediaCodecVideoDecoder::CreateOverlayFactoryCb() { if (!overlay_factory_cb_ || !overlay_info_.HasValidRoutingToken()) return AndroidOverlayFactoryCB(); return base::BindRepeating(overlay_factory_cb_, *overlay_info_.routing_token); } VideoDecoderType MediaCodecVideoDecoder::GetDecoderType() const { return VideoDecoderType::kMediaCodec; } bool MediaCodecVideoDecoder::NeedsBitstreamConversion() const { return true; } bool MediaCodecVideoDecoder::CanReadWithoutStalling() const { // MediaCodec gives us no indication that it will stop producing outputs // until we provide more inputs or release output buffers back to it, so // we have to always return false. // TODO(watk): This puts all MCVD playbacks into low delay mode (i.e., the // renderer won't try to preroll). Ideally we'd be smarter about // this and attempt preroll but be able to give up if we can't produce // enough frames. return false; } int MediaCodecVideoDecoder::GetMaxDecodeRequests() const { // We indicate that we're done decoding a frame as soon as we submit it to // MediaCodec so the number of parallel decode requests just sets the upper // limit of the size of our pending decode queue. return 2; } PromotionHintAggregator::NotifyPromotionHintCB MediaCodecVideoDecoder::CreatePromotionHintCB() { // Right now, we don't request promotion hints. This is only used by SOP. // While we could simplify it a bit, this is the general form that we'll use // when handling promotion hints. // Note that this keeps only a wp to the surface bundle via |layout_cb|. It // also continues to work even if |this| is destroyed; images might want to // move an overlay around even after MCVD has been torn down. For example // inline L1 content will fall into this case. return BindToCurrentLoop(base::BindRepeating( [](base::WeakPtr<MediaCodecVideoDecoder> mcvd, CodecSurfaceBundle::ScheduleLayoutCB layout_cb, PromotionHintAggregator::Hint hint) { // If we're promotable, and we have a surface bundle, then also // position the overlay. We could do this even if the overlay is // not promotable, but it wouldn't have any visible effect. if (hint.is_promotable) layout_cb.Run(hint.screen_rect); // Notify MCVD about the promotion hint, so that it can decide if it // wants to switch to / from an overlay. if (mcvd) mcvd->NotifyPromotionHint(hint); }, weak_factory_.GetWeakPtr(), codec_->SurfaceBundle()->GetScheduleLayoutCB())); } bool MediaCodecVideoDecoder::IsUsingOverlay() const { return codec_ && codec_->SurfaceBundle() && codec_->SurfaceBundle()->overlay(); } void MediaCodecVideoDecoder::NotifyPromotionHint( PromotionHintAggregator::Hint hint) { surface_chooser_helper_.NotifyPromotionHintAndUpdateChooser(hint, IsUsingOverlay()); } void MediaCodecVideoDecoder::CacheFrameInformation() { cached_frame_information_ = surface_chooser_helper_.ComputeFrameInformation(IsUsingOverlay()); } } // namespace media
39.808286
80
0.692127
[ "vector" ]
be3b066af17289ae6730b0564b3721a95d7b1f19
2,588
cpp
C++
HSDDPSolver/source/ReferenceGen.cpp
ROAM-Lab-ND/MHPC_Minimal_Env
6e61fc1b25920605f1074a30b872a5cb6aa9de19
[ "MIT" ]
1
2022-03-03T02:48:42.000Z
2022-03-03T02:48:42.000Z
HSDDPSolver/source/ReferenceGen.cpp
ROAM-Lab-ND/MHPC_Minimal_Env
6e61fc1b25920605f1074a30b872a5cb6aa9de19
[ "MIT" ]
null
null
null
HSDDPSolver/source/ReferenceGen.cpp
ROAM-Lab-ND/MHPC_Minimal_Env
6e61fc1b25920605f1074a30b872a5cb6aa9de19
[ "MIT" ]
1
2022-03-27T08:26:37.000Z
2022-03-27T08:26:37.000Z
#include "ReferenceGen.h" #include <iostream> template <typename T> ReferenceGen<T>::ReferenceGen(int n_WBphases, int n_FBphases, vector<ModelState<T, xsize_WB, usize_WB, ysize_WB> *> &ref_WB, vector<ModelState<T, xsize_FB, usize_FB, ysize_FB> *> &ref_FB, T dt_WB, T dt_FB, DVec<int> mode_seq, DVec<int> N_TIMESTEPS, T vel_cmd, T height_cmd) { Initialization(n_WBphases, n_FBphases, ref_WB, ref_FB, dt_WB, dt_FB, mode_seq, N_TIMESTEPS, vel_cmd, height_cmd); } template <typename T> void ReferenceGen<T>::Initialization(int n_WBphases, int n_FBphases, vector<ModelState<T, xsize_WB, usize_WB, ysize_WB> *> &ref_WB, vector<ModelState<T, xsize_FB, usize_FB, ysize_FB> *> &ref_FB, T dt_WB, T dt_FB, DVec<int> mode_seq, DVec<int> N_TIMESTEPS, T vel_cmd, T height_cmd) { _n_WBphases = n_WBphases; _n_FBphases = n_FBphases; _ref_WB = ref_WB; _ref_FB = ref_FB; _dt_WB = dt_WB; _dt_FB = dt_FB; _n_phases = n_WBphases + n_FBphases; _mode_seq = mode_seq; _N_TIMESTEPS = N_TIMESTEPS; _vel_cmd = vel_cmd; _height_cmd = height_cmd; _GRF = 8.252 * 9.81; std::memset(&_xref_WB_term[0], 0, 4 * sizeof(VecM<T, xsize_WB>)); _xref_WB_term[0] << 0, -0.1432, -PI / 25, 0.35 * PI, -0.65 * PI, 0.35 * PI, -0.6 * PI, _vel_cmd, 1, 0, 0, 0, 0, 0; _xref_WB_term[1] << 0, -0.1418, PI / 35, 0.2 * PI, -0.58 * PI, 0.25 * PI, -0.7 * PI, _vel_cmd, -1, 0, 0, 0, 0, 0; _xref_WB_term[2] << 0, -0.1325, -PI / 40, 0.33 * PI, -0.48 * PI, 0.33 * PI, -0.75 * PI, _vel_cmd, 1, 0, 0, 0, 0, 0; _xref_WB_term[3] << 0, -0.1490, -PI / 25, 0.35 * PI, -0.7 * PI, 0.25 * PI, -0.60 * PI, _vel_cmd, -1, 0, 0, 0, 0, 0; _qjoint_bias << 0.3 * PI, -0.7 * PI, 0.3 * PI, -0.7 * PI; _qd_joint_bias.setZero(); // allocate memory for forward position reference trajectory if (nullptr != _pos_ref) free_memory(); _pos_ref = new T *[_n_phases]; for (size_t pidx(0); pidx < _n_phases; pidx++) { _pos_ref[pidx] = new T[N_TIMESTEPS_MAX]; } } template class ReferenceGen<double>;
37.507246
99
0.50425
[ "vector" ]
be4235b372b9a9b2c40c5e8a5fafa4cdeb08fa4d
5,019
cc
C++
examples/workbook/art-workbook/IterativeAlgDevel/MakeCombinationsV1_module.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
examples/workbook/art-workbook/IterativeAlgDevel/MakeCombinationsV1_module.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
null
null
null
examples/workbook/art-workbook/IterativeAlgDevel/MakeCombinationsV1_module.cc
JeffersonLab/ARIEL
49054ac62a84d48e269f7171daabb98e12a0be90
[ "BSD-3-Clause" ]
2
2020-09-26T01:37:11.000Z
2021-05-03T13:02:24.000Z
// // Make combinations for oppositely charged pairs of particles. // This is the starting version of the module. // #include "toyExperiment/Geometry/Geometry.h" #include "toyExperiment/PDT/PDT.h" #include "toyExperiment/RecoDataProducts/FittedHelixDataCollection.h" #include "toyExperiment/Reconstruction/FittedHelix.h" #include "art/Framework/Core/EDProducer.h" #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Principal/Event.h" #include "art_root_io/TFileService.h" #include "TH1F.h" #include <string> using CLHEP::HepLorentzVector; using CLHEP::HepSymMatrix; namespace tex { class MakeCombinations : public art::EDProducer { public: explicit MakeCombinations(fhicl::ParameterSet const& pset); void beginJob(); void beginRun(art::Run&); void produce(art::Event& event); private: art::InputTag fitsTag_; art::ServiceHandle<art::TFileService> tfs_; double bz_; double mka_; double mphi_; TH1F* hMass_; TH1F* hSigM_; TH1F* hPull_; }; } tex::MakeCombinations::MakeCombinations(fhicl::ParameterSet const& pset): art::EDProducer{pset}, fitsTag_( pset.get<std::string>("fitterInputTag") ), tfs_(), bz_(), mka_(493.677), mphi_(1019.455), hMass_(nullptr), hSigM_(nullptr), hPull_(nullptr){ } void tex::MakeCombinations::beginJob() { hMass_ = tfs_->make<TH1F>("Mass", "Reconstructed mass;[MeV]", 100, 1010., 1030. ); hSigM_ = tfs_->make<TH1F>("SigM", "Reconstructed sigma(Mass);[MeV]", 100, 0., 5. ); hPull_ = tfs_->make<TH1F>("Pull", "Mass (Reco-Gen)/sigma", 100, -5., 5. ); } void tex::MakeCombinations::beginRun(art::Run&){ bz_ = art::ServiceHandle<Geometry>()->bz(); } void tex::MakeCombinations::produce(art::Event& event){ // Get the fitted helices from the event. auto const fitsHandle = event.getValidHandle<FittedHelixDataCollection>(fitsTag_); FittedHelixDataCollection const& fits(*fitsHandle); // We will eventually create our new, empty data product here. // Loop over all unique pairs of tracks. // Pay careful attention to the form of the loop! We only want 'i' to go // up to i = (number of tracks) - 1. But we don't want wrong behavior // if (number of tracks) == 0, so we have to write the loop carefully. for ( size_t i = 0; i+1 < fits.size(); ++i ) { FittedHelix fit1 { fits[i], bz_ }; // Get the parameters for track 1 HepLorentzVector p1 { fit1.lorentzAtPoca(mka_) }; HepSymMatrix cov1 { fit1.lorentzAtPocaCov(mka_) }; for ( size_t j=i+1; j<fits.size(); ++j){ FittedHelix fit2 { fits[j], bz_ }; // Skip a pair of tracks if the sum of their charges isn't zero. // We have to be careful about floating point math and exact // equality tests! if ( std::abs(fit1.q()+fit2.q()) > 0.5 ) continue; // Get the parameters for track 2 HepLorentzVector p2 { fit2.lorentzAtPoca(mka_) }; HepSymMatrix cov2 { fit2.lorentzAtPocaCov(mka_) }; // For the two track system, compute the invariant mass, the error // and the pull from the MC truth. // Momentum and covariance matrix are just sums of the two // inputs... HepLorentzVector p3 = p1 + p2; HepSymMatrix cov3 = cov1 + cov2; double m = p3.mag(); // To get the squared error on the mass, we need: // 1) derivatives the the mass with respect to the 4-vector // components. // // 2) to calculate the vector * matrix * vector product that // yields the square of the uncertainty in the mass. // // 3) if the matrix was not ill-conditioned, the value from (2) // will be positive; again, we have to be careful with the // floating point math, even if the matrix was ill-conditioned. // Derivatives of the mass wrt the 4-vector components. double dm[4]; dm[0] = -p3.x()/m; dm[1] = -p3.y()/m; dm[2] = -p3.z()/m; dm[3] = p3.e()/m; // Error squared on the mass: vector * matrix * vector // calculation. double vm = dm[0]*dm[0]*cov3[0][0] + dm[1]*dm[1]*cov3[1][1] + dm[2]*dm[2]*cov3[2][2] + dm[3]*dm[3]*cov3[3][3] + 2.* ( dm[0]*dm[1]*cov3[0][1] + dm[0]*dm[2]*cov3[0][2] + dm[0]*dm[3]*cov3[0][3] + dm[1]*dm[2]*cov3[1][2] + dm[1]*dm[3]*cov3[1][3] + dm[2]*dm[3]*cov3[2][3] ); // Make sure to deal with ill-conditioned answer. double sigm = ( vm > 0. ) ? sqrt(vm) : 0.; double mpull = (sigm > 0 ) ? (( m-mphi_)/sigm) : -10.; hMass_->Fill(m); hSigM_->Fill(sigm); hPull_->Fill(mpull); // Here we will want to add our new combination to the data // product we're accumulating. } // end inner loop over tracks } // end outer loop over tracks // Here we should be putting a data product into the Event. } // end produce DEFINE_ART_MODULE(tex::MakeCombinations)
29.523529
91
0.619446
[ "geometry", "vector" ]
be485de5b035fc722c8af3d69952dc0bc88fe55b
8,981
hpp
C++
src/args.hpp
kbjakex/ttk91-interpreter
488ce58941cb34e59a252e20457fb1e35e9a21ee
[ "MIT" ]
null
null
null
src/args.hpp
kbjakex/ttk91-interpreter
488ce58941cb34e59a252e20457fb1e35e9a21ee
[ "MIT" ]
null
null
null
src/args.hpp
kbjakex/ttk91-interpreter
488ce58941cb34e59a252e20457fb1e35e9a21ee
[ "MIT" ]
2
2021-12-12T20:35:05.000Z
2021-12-13T08:14:26.000Z
#pragma once #include <optional> #include <vector> #include <string_view> #include <cstring> // std::strlen() #include <unordered_map> #include <unordered_set> #include <stdexcept> // std::invalid_argument #include <iostream> #include <cstdlib> // std::exit() #include <charconv> // std::from_chars() #include <type_traits> // std::is_same_v #include "types.hpp" // whether `-abc` should be equivalent to `-a -b -c` #define USE_FLAG_COMBOS 0 namespace Detail { inline bool equals_lowercase(std::string_view lhs, std::string_view rhs) { if (lhs.length() != rhs.length()) return false; for (std::size_t i = 0; i < lhs.length(); ++i) { if (std::tolower(lhs[i]) != std::tolower(rhs[i])) return false; } return true; } template<typename T> bool parse_num_to(std::string_view string, T *out) { T temp; const auto result = std::from_chars(string.data(), string.data() + string.length(), temp); if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range) { return false; } *out = temp; return true; } } namespace ArgParsers { template<typename T> bool parse_to(std::string_view string, T *out); // Signed ints template<> bool parse_to<i8>(std::string_view string, i8 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<i16>(std::string_view string, i16 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<i32>(std::string_view string, i32 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<i64>(std::string_view string, i64 *out) { return Detail::parse_num_to(string, out); } // Unsigned ints template<> bool parse_to<u8>(std::string_view string, u8 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<u16>(std::string_view string, u16 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<u32>(std::string_view string, u32 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<u64>(std::string_view string, u64 *out) { return Detail::parse_num_to(string, out); } template<> bool parse_to<bool>(std::string_view string, bool *out) { using namespace Detail; if (string == "0" || equals_lowercase(string, "false")) { *out = false; return true; } if (string == "1" || equals_lowercase(string, "true")) { *out = true; return true; } return false; } template<> bool parse_to<std::string_view>(std::string_view string, std::string_view *out) { *out = string; return true; } } class Args { using CallbackFn = void(void*, std::string_view, std::string_view, std::optional<std::string_view>); struct Arg { std::optional<std::string_view> error_msg; CallbackFn *callback; void *out_ptr; bool is_flag; }; public: struct ParseResult { std::vector<std::string_view> remaining_args; std::vector<std::string_view> unrecognized_options; }; static Args parser() { return Args(); } template<typename T> Args &add_arg(std::string_view short_form, std::string_view long_form, T &out, std::optional<std::string_view> error_msg) { if (short_form.empty() && long_form.empty()) { throw std::invalid_argument("can't have both short and long forms of an argument empty"); } auto arg = Arg { .error_msg = error_msg, .callback = [](void *raw_out_ptr, std::string_view option, std::string_view val, std::optional<std::string_view> error_msg) { T *out_ptr = static_cast<T*>(raw_out_ptr); if (!ArgParsers::parse_to(val, out_ptr)) { if (error_msg) std::cout << error_msg.value() << "\n"; else std::cout << "Failed to parse value \"" << val << "\" for option \"" << option << "\"\n"; std::exit(0); } }, .out_ptr = &out, .is_flag = std::is_same_v<T, bool>, }; if (!short_form.empty()) arg_map.insert({ short_form, arg }); if (!long_form.empty()) arg_map.insert({ long_form, arg }); return *this; } template<typename T> Args &add_arg(std::string_view short_form, std::string_view long_form, T &out) { return add_arg(short_form, long_form, out, std::nullopt); } template<typename T> Args &add_arg(std::string_view long_form, T &out, std::optional<std::string_view> error_msg) { return add_arg("", long_form, out, error_msg); } template<typename T> Args &add_arg(std::string_view long_form, T &out) { return add_arg(long_form, out, std::nullopt); } ParseResult parse(std::size_t argc, char **argv) { auto result = ParseResult{}; if (argc == 1) return result; std::string_view input = to_str_view(argv[1]); // Skip 0 (application name) for (std::size_t i = 1; i < argc; ++i) { if (input == "--") { // rest are positional args and not parsed for (std::size_t j = i + 1; j < argc; ++j) { result.remaining_args.push_back(to_str_view(argv[j])); } break; } const auto next = to_str_view(argv[i + 1]); auto next_opt = next.empty() ? std::nullopt : std::optional{ next }; // Empty if i + 1 == argc parse_input(input, next_opt, result); if (!next_opt) { // Either 'input' (at i) was the last one, or there was a next one (at i+1) which was consumed by parse_input. // Next index of interest is i+2. if (i + 2 >= argc) break; input = to_str_view(argv[i + 2]); i += 1; // The loop body will increment it again continue; } input = next; } return result; } private: static std::string_view to_str_view(const char *c_str) { if (!c_str) return {}; return std::string_view(c_str, std::strlen(c_str)); } void parse_input(std::string_view input, std::optional<std::string_view> &next, ParseResult &result) { if (!input.starts_with("-")) { result.remaining_args.push_back(input); return; } input = input.substr(1); bool long_form = false; if (input.starts_with("-")) { long_form = true; input = input.substr(1); } if (long_form) { // --flag, --option, --option="true", --option "true", --option=true parse_option(input, next, result); } else { // -v, -O, -fgh, -v="1", -v "1", -v=1 // Also allows forms such as `-wall // Every letter can be a flag, so check all parse_short_options(input, next, result); } } void parse_short_options(std::string_view option, std::optional<std::string_view> &next, ParseResult &result) { if (const auto idx = option.find_first_of('='); idx != option.npos || next.has_value()) { parse_option(option, next, result); return; } #if USE_FLAG_COMBOS == 1 for (std::size_t i = 0; i < option.length(); ++i) { parse_option(option.substr(i, 1), std::nullopt, result); } #else return parse_option(option, next, result); #endif } void parse_option(std::string_view option, std::optional<std::string_view> next, ParseResult &result) { auto value = std::string_view{}; if (const auto idx = option.find_first_of('='); idx != option.npos) { value = option.substr(idx + 1); option = option.substr(0, idx); } bool has_value = !value.empty(); // Note consequences: `v=` is considered to have no value. if (auto it = arg_map.find(option); it != arg_map.end()) { const Arg &mapping = it->second; if (!has_value) { if (mapping.is_flag) value = "1"; else if (next.has_value()) { value = next.value(); next.reset(); } } (mapping.callback)(mapping.out_ptr, option, value, mapping.error_msg); return; } result.unrecognized_options.push_back(option); } std::unordered_map<std::string_view, Arg> arg_map; };
33.262963
138
0.550161
[ "vector" ]
be4d8d6130afde4fe79db9d866cfd33f25ca013f
3,619
cc
C++
emr/src/model/GetHdfsCapacityStatisticInfoResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
emr/src/model/GetHdfsCapacityStatisticInfoResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
emr/src/model/GetHdfsCapacityStatisticInfoResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/emr/model/GetHdfsCapacityStatisticInfoResult.h> #include <json/json.h> using namespace AlibabaCloud::Emr; using namespace AlibabaCloud::Emr::Model; GetHdfsCapacityStatisticInfoResult::GetHdfsCapacityStatisticInfoResult() : ServiceResult() {} GetHdfsCapacityStatisticInfoResult::GetHdfsCapacityStatisticInfoResult(const std::string &payload) : ServiceResult() { parse(payload); } GetHdfsCapacityStatisticInfoResult::~GetHdfsCapacityStatisticInfoResult() {} void GetHdfsCapacityStatisticInfoResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allHdfsCapacityListNode = value["HdfsCapacityList"]["ClusterStatHdfsCapacity"]; for (auto valueHdfsCapacityListClusterStatHdfsCapacity : allHdfsCapacityListNode) { ClusterStatHdfsCapacity hdfsCapacityListObject; if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityTotal"].isNull()) hdfsCapacityListObject.capacityTotal = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityTotal"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityTotalGB"].isNull()) hdfsCapacityListObject.capacityTotalGB = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityTotalGB"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsed"].isNull()) hdfsCapacityListObject.capacityUsed = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsed"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsedGB"].isNull()) hdfsCapacityListObject.capacityUsedGB = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsedGB"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityRemaining"].isNull()) hdfsCapacityListObject.capacityRemaining = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityRemaining"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityRemainingGB"].isNull()) hdfsCapacityListObject.capacityRemainingGB = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityRemainingGB"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsedNonDfs"].isNull()) hdfsCapacityListObject.capacityUsedNonDfs = std::stol(valueHdfsCapacityListClusterStatHdfsCapacity["CapacityUsedNonDfs"].asString()); if(!valueHdfsCapacityListClusterStatHdfsCapacity["ClusterBizId"].isNull()) hdfsCapacityListObject.clusterBizId = valueHdfsCapacityListClusterStatHdfsCapacity["ClusterBizId"].asString(); if(!valueHdfsCapacityListClusterStatHdfsCapacity["DateTime"].isNull()) hdfsCapacityListObject.dateTime = valueHdfsCapacityListClusterStatHdfsCapacity["DateTime"].asString(); hdfsCapacityList_.push_back(hdfsCapacityListObject); } } std::vector<GetHdfsCapacityStatisticInfoResult::ClusterStatHdfsCapacity> GetHdfsCapacityStatisticInfoResult::getHdfsCapacityList()const { return hdfsCapacityList_; }
48.905405
138
0.820392
[ "vector", "model" ]
be4eee896bf5d86c88bdedd493d5f5becf53a9b1
3,402
hxx
C++
opencascade/VrmlConverter_Projector.hxx
valgur/OCP
2f7d9da73a08e4ffe80883614aedacb27351134f
[ "Apache-2.0" ]
117
2020-03-07T12:07:05.000Z
2022-03-27T07:35:22.000Z
opencascade/VrmlConverter_Projector.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
66
2019-12-20T16:07:36.000Z
2022-03-15T21:56:10.000Z
opencascade/VrmlConverter_Projector.hxx
CadQuery/cpp-py-bindgen
66e7376d3a27444393fc99acbdbef40bbc7031ae
[ "Apache-2.0" ]
76
2020-03-16T01:47:46.000Z
2022-03-21T16:37:07.000Z
// Created on: 1997-06-06 // Created by: Alexander BRIVIN // Copyright (c) 1997-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _VrmlConverter_Projector_HeaderFile #define _VrmlConverter_Projector_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <HLRAlgo_Projector.hxx> #include <Vrml_PerspectiveCamera.hxx> #include <Vrml_OrthographicCamera.hxx> #include <Vrml_DirectionalLight.hxx> #include <Vrml_PointLight.hxx> #include <Vrml_SpotLight.hxx> #include <VrmlConverter_TypeOfCamera.hxx> #include <VrmlConverter_TypeOfLight.hxx> #include <Vrml_MatrixTransform.hxx> #include <Standard_Transient.hxx> #include <TopTools_Array1OfShape.hxx> #include <Standard_OStream.hxx> class HLRAlgo_Projector; class VrmlConverter_Projector; DEFINE_STANDARD_HANDLE(VrmlConverter_Projector, Standard_Transient) //! defines projector and calculates properties of cameras and lights from Vrml //! ( OrthograpicCamera, PerspectiveCamera, DirectionalLight, PointLight, SpotLight //! and MatrixTransform ) to display all scene shapes with arbitrary locations //! for requested the Projection Vector, High Point Direction and the Focus //! and adds them ( method Add ) to anOSream. class VrmlConverter_Projector : public Standard_Transient { public: Standard_EXPORT VrmlConverter_Projector(const TopTools_Array1OfShape& Shapes, const Standard_Real Focus, const Standard_Real DX, const Standard_Real DY, const Standard_Real DZ, const Standard_Real XUp, const Standard_Real YUp, const Standard_Real ZUp, const VrmlConverter_TypeOfCamera Camera = VrmlConverter_NoCamera, const VrmlConverter_TypeOfLight Light = VrmlConverter_NoLight); Standard_EXPORT void SetCamera (const VrmlConverter_TypeOfCamera aCamera); Standard_EXPORT VrmlConverter_TypeOfCamera Camera() const; Standard_EXPORT void SetLight (const VrmlConverter_TypeOfLight aLight); Standard_EXPORT VrmlConverter_TypeOfLight Light() const; //! Adds into anOStream if they are defined in Create. //! PerspectiveCamera, //! OrthographicCamera, //! DirectionLight, //! PointLight, //! SpotLight //! with MatrixTransform from VrmlConverter; Standard_EXPORT void Add (Standard_OStream& anOStream) const; Standard_EXPORT HLRAlgo_Projector Projector() const; DEFINE_STANDARD_RTTIEXT(VrmlConverter_Projector,Standard_Transient) private: HLRAlgo_Projector myProjector; Vrml_PerspectiveCamera myPerspectiveCamera; Vrml_OrthographicCamera myOrthographicCamera; Vrml_DirectionalLight myDirectionalLight; Vrml_PointLight myPointLight; Vrml_SpotLight mySpotLight; VrmlConverter_TypeOfCamera myTypeOfCamera; VrmlConverter_TypeOfLight myTypeOfLight; Vrml_MatrixTransform myMatrixTransform; }; #endif // _VrmlConverter_Projector_HeaderFile
36.191489
383
0.808054
[ "vector" ]
be5060bfb569001a4778c603b2761a753e98fed3
5,559
cpp
C++
Source/GUI/Qt/export.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
743
2015-01-13T23:16:53.000Z
2022-03-31T22:56:27.000Z
Source/GUI/Qt/export.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
317
2015-07-28T17:50:14.000Z
2022-03-08T02:41:19.000Z
Source/GUI/Qt/export.cpp
buckmelanoma/MediaInfo
cf38b0e3d0e6ee2565f49276f423a5792ed62962
[ "BSD-2-Clause" ]
134
2015-01-30T05:33:51.000Z
2022-03-21T09:39:38.000Z
/* Copyright (c) MediaArea.net SARL. All Rights Reserved. * * Use of this source code is governed by a BSD-style license that can * be found in the License.html file in the root of the source tree. */ #include "export.h" #include "translate.h" #include "ui_export.h" #include <QFileDialog> #include <QMessageBox> #include "configtreetext.h" #include "mainwindow.h" Export::Export(QString filename, int mode, QWidget *parent) : QDialog(parent), ui(new Ui::Export), path(filename) { ui->setupUi(this); #if defined(_WIN32) && defined(WINAPI_FAMILY) && (WINAPI_FAMILY==WINAPI_FAMILY_APP) // Workaround render bug QString style = "QComboBox QAbstractItemView { border: 1px solid gray }"; ui->comboBoxConfig->setStyleSheet(style); ui->comboBoxMode->setStyleSheet(style); #else setWindowTitle("Export"); #endif for(int i=0;i<Export::NB_EXPORT_MODE;i++) { ui->comboBoxMode->addItem(name(i),i); if(i==mode) ui->comboBoxMode->setCurrentIndex(ui->comboBoxMode->count()-1); } ConfigTreeText::fillComboBox(ui->comboBoxConfig); } Export::~Export() { delete ui; } void Export::changeEvent(QEvent *e) { QDialog::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } int Export::getExportMode() { return ui->comboBoxMode->itemData(ui->comboBoxMode->currentIndex()).toInt(); } int Export::getExportConfig() { if(ui->comboBoxConfig->isEnabled()) return ui->comboBoxConfig->itemData(ui->comboBoxConfig->currentIndex()).toInt(); else return 0; } QString Export::getFileName() { return path; } QIODevice::OpenMode Export::getOpenMode() { if(ui->appendToFile->isChecked()) return QIODevice::Append; else return QIODevice::WriteOnly; } bool Export::isAdvancedChecked() { return ui->checkBoxAdvanced->isChecked(); } QString Export::extension(int mode) { switch(mode) { default: case TEXT: return "txt"; break; case HTML: return "html"; break; case XML: case PBCORE: case PBCORE2: case MPEG7: case NISO_Z39_87: case FIMS_1_1: case FIMS_1_2: case FIMS_1_3: case EBUCORE_1_5: case EBUCORE_1_6: case EBUCORE_1_8_ps: case EBUCORE_1_8_sp: return "xml"; break; case JSON: case EBUCORE_1_8_ps_JSON: case EBUCORE_1_8_sp_JSON: return "json"; break; } } QString Export::extensionName(int mode) { switch(mode) { default: case TEXT: return tr("Text"); break; case HTML: return "HTML"; break; case XML: case PBCORE: case PBCORE2: case MPEG7: case NISO_Z39_87: case FIMS_1_1: case FIMS_1_2: case FIMS_1_3: case EBUCORE_1_5: case EBUCORE_1_6: case EBUCORE_1_8_ps: case EBUCORE_1_8_sp: return "XML"; break; case JSON: case EBUCORE_1_8_ps_JSON: case EBUCORE_1_8_sp_JSON: return "JSON"; break; } } QString Export::name(int mode) { switch(mode) { default: case TEXT: return Tr("Text"); break; case HTML: return Tr("HTML"); break; case XML: return Tr("XML"); break; case JSON: return Tr("JSON"); break; case PBCORE: return Tr("PBCore"); break; case PBCORE2: return Tr("PBCore 2"); break; case MPEG7: return Tr("MPEG-7"); break; case EBUCORE_1_5: return Tr("EBUCore 1.5"); break; case EBUCORE_1_6: return Tr("EBUCore 1.6"); break; case EBUCORE_1_8_ps: return Tr("EBUCore 1.8 parameter then segment"); break; case EBUCORE_1_8_sp: return Tr("EBUCore 1.8 segment then parameter"); break; case EBUCORE_1_8_ps_JSON: return Tr("EBUCore 1.8 parameter then segment (JSON output)"); break; case EBUCORE_1_8_sp_JSON: return Tr("EBUCore 1.8 segment then parameter (JSON output)"); break; case FIMS_1_1: return Tr("FIMS 1.1"); break; case FIMS_1_2: return Tr("FIMS 1.2"); break; case FIMS_1_3: return Tr("FIMS 1.3"); break; case NISO_Z39_87: return Tr("NISO Z39.87"); break; } } void Export::on_comboBoxMode_currentIndexChanged(int index) { QStringList filename = path.split("."); filename[filename.size()-1] = extension(index); path = filename.join("."); switch(index) { default: case TEXT: ui->comboBoxConfig->setDisabled(ui->checkBoxAdvanced->isChecked()); ui->checkBoxAdvanced->setEnabled(true); break; case XML: case JSON: case PBCORE: case PBCORE2: case MPEG7: case EBUCORE_1_5: case EBUCORE_1_6: case EBUCORE_1_8_ps: case EBUCORE_1_8_sp: case EBUCORE_1_8_ps_JSON: case EBUCORE_1_8_sp_JSON: case FIMS_1_1: case FIMS_1_2: case FIMS_1_3: case NISO_Z39_87: ui->comboBoxConfig->setEnabled(false); ui->checkBoxAdvanced->setEnabled(false); break; case HTML: ui->comboBoxConfig->setEnabled(false); ui->checkBoxAdvanced->setEnabled(true); break; } } void Export::on_checkBoxAdvanced_toggled(bool checked) { ui->comboBoxConfig->setEnabled( (!checked) && (ui->comboBoxMode->itemData(ui->comboBoxMode->currentIndex()).toInt()==TEXT) ); } void Export::on_buttonBox_accepted() { path = QFileDialog::getSaveFileName(this,tr("Save File"),QDir(path).absolutePath(), QString(tr("%1 files (*.%2)")).arg(extensionName(getExportMode()), extension(getExportMode()))); }
25.153846
184
0.642382
[ "render", "solid" ]
be521c79f4971e5166478443ae615829a7defe55
3,282
hpp
C++
PSME/application/include/psme/rest/model/handlers/manager_handler.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/application/include/psme/rest/model/handlers/manager_handler.hpp
opencomputeproject/DM-Redfish-PSME
912f7b6abf5b5c2aae33c75497de4753281c6a51
[ "Apache-2.0" ]
null
null
null
PSME/application/include/psme/rest/model/handlers/manager_handler.hpp
opencomputeproject/DM-Redfish-PSME
912f7b6abf5b5c2aae33c75497de4753281c6a51
[ "Apache-2.0" ]
1
2021-03-24T19:37:58.000Z
2021-03-24T19:37:58.000Z
/*! * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ #pragma once #include "agent-framework/module/model/manager.hpp" #include "agent-framework/module/requests/common/get_manager_info.hpp" #include "agent-framework/module/requests/common/get_managers_collection.hpp" namespace psme { namespace rest { namespace model { namespace handler { using ManagerHandlerBase = GenericHandler< agent_framework::model::requests::GetManagerInfo, agent_framework::model::Manager, IdPolicy<agent_framework::model::enums::Component::Manager, NumberingZone::SHARED>>; /*! @brief ManagerHandler template specialization */ class ManagerHandler : public ManagerHandlerBase { public: ManagerHandler() : ManagerHandlerBase() {} virtual ~ManagerHandler(); protected: template<typename T> using Array = agent_framework::model::attribute::Array<T>; using Managers = Array<agent_framework::model::attribute::ManagerEntry>; using SubcomponentEntry = agent_framework::model::attribute::SubcomponentEntry; Array<SubcomponentEntry> fetch_sibling_uuid_list(Context& ctx, const std::string& parent_uuid, const std::string& collection_name) override { try { if (Component::None == ctx.get_parent_component()) { log_debug(GET_LOGGER("rest"), ctx.indent << "[" << static_cast<char>(ctx.mode) << "] " << "Fetching list of all managers from agent " << ctx.agent->get_gami_id()); agent_framework::model::requests::GetManagersCollection collection{}; auto manager_entries = ctx.agent->execute<Managers>( collection); // Convert array of ManagerEntry to Array of SubcomponentEntry Array<SubcomponentEntry> res; for (const auto& entry : manager_entries) { res.add_entry(entry.get_manager()); } return res; } else { return ManagerHandlerBase::fetch_sibling_uuid_list(ctx, parent_uuid, collection_name); } } catch (const jsonrpc::JsonRpcException& e) { log_error(GET_LOGGER("rest"), ctx.indent << "[" << static_cast<char>(ctx.mode) << "] " << "Agent exception while fetching list of all components of " "type [" << component_s() << "] for parent " << parent_uuid <<e.what()); return Array<SubcomponentEntry>(); } } }; ManagerHandler::~ManagerHandler() {} } } } }
34.547368
92
0.630713
[ "model" ]
be539429588d9b0d444997fc54f22bdc264e9704
10,249
cpp
C++
implementations/ugene/src/plugins/api_tests/src/core/datatype/udr/UdrSchemaUnitTests.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/api_tests/src/core/datatype/udr/UdrSchemaUnitTests.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins/api_tests/src/core/datatype/udr/UdrSchemaUnitTests.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2020 UniPro <ugene@unipro.ru> * http://ugene.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "UdrSchemaUnitTests.h" #include <U2Core/AppContext.h> #include <U2Core/U2OpStatusUtils.h> #include <U2Core/U2SafePoints.h> #include <U2Core/UdrRecord.h> #include <U2Core/UdrSchemaRegistry.h> namespace U2 { namespace { UdrSchema getTestSchema() { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("name1", UdrSchema::INTEGER, UdrSchema::INDEXED), os); schema.addField(UdrSchema::FieldDesc("name2", UdrSchema::BLOB, UdrSchema::NOT_INDEXED), os); schema.addField(UdrSchema::FieldDesc("name3", UdrSchema::STRING), os); schema.addField(UdrSchema::FieldDesc("name4", UdrSchema::DOUBLE), os); SAFE_POINT_OP(os, schema); return schema; } UdrSchema getTestSchema2() { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("name1", UdrSchema::INTEGER, UdrSchema::INDEXED), os); schema.addField(UdrSchema::FieldDesc("name2", UdrSchema::INTEGER, UdrSchema::NOT_INDEXED), os); schema.addField(UdrSchema::FieldDesc("name3", UdrSchema::STRING), os); schema.addField(UdrSchema::FieldDesc("name4", UdrSchema::DOUBLE), os); SAFE_POINT_OP(os, schema); return schema; } } // namespace IMPLEMENT_TEST(UdrSchemaUnitTests, addField_RecordId) { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc(UdrSchema::RECORD_ID_FIELD_NAME, UdrSchema::INTEGER), os); CHECK_TRUE(os.hasError(), "record_id field"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addField_Object) { U2OpStatusImpl os; UdrSchema schema("id", true); schema.addField(UdrSchema::FieldDesc(UdrSchema::OBJECT_FIELD_NAME, UdrSchema::INTEGER), os); CHECK_TRUE(os.hasError(), "duplicate name"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addField_DuplicateName) { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("name", UdrSchema::INTEGER), os); CHECK_NO_ERROR(os); schema.addField(UdrSchema::FieldDesc("name", UdrSchema::INTEGER), os); CHECK_TRUE(os.hasError(), "duplicate name"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addField_IncorrectName) { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("field 1", UdrSchema::INTEGER), os); CHECK_TRUE(os.hasError(), "incorrect name"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addField_BLOB_1_not_indexed) { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("name", UdrSchema::BLOB, UdrSchema::NOT_INDEXED), os); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, addField_BLOB_2_indexed) { U2OpStatusImpl os; UdrSchema schema("id"); schema.addField(UdrSchema::FieldDesc("name", UdrSchema::BLOB, UdrSchema::INDEXED), os); CHECK_TRUE(os.hasError(), "indexed BLOB"); } IMPLEMENT_TEST(UdrSchemaUnitTests, getField_OutOfRange_1_negative) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); schema.getField(-10, os); CHECK_TRUE(os.hasError(), "out of range"); } IMPLEMENT_TEST(UdrSchemaUnitTests, getField_OutOfRange_2_greater) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); schema.getField(10, os); CHECK_TRUE(os.hasError(), "out of range"); } IMPLEMENT_TEST(UdrSchemaUnitTests, getField_Range) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); schema.getField(1, os); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, getField_Data) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); UdrSchema::FieldDesc field1 = schema.getField(0, os); CHECK_NO_ERROR(os); CHECK_TRUE("name1" == field1.getName(), "name 1"); CHECK_TRUE(UdrSchema::INTEGER == field1.getDataType(), "dataType 1"); CHECK_TRUE(UdrSchema::INDEXED == field1.getIndexType(), "indexType 1"); UdrSchema::FieldDesc field2 = schema.getField(1, os); CHECK_NO_ERROR(os); CHECK_TRUE("name2" == field2.getName(), "name 2"); CHECK_TRUE(UdrSchema::BLOB == field2.getDataType(), "dataType 2"); CHECK_TRUE(UdrSchema::NOT_INDEXED == field2.getIndexType(), "indexType 2"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_DuplicateField_1) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 0 << 0; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "duplicate fields"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_DuplicateField_2) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 0 << 2 << 0; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "duplicate fields"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_OutOfRange_1) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 3 << 4; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "out of range"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_OutOfRange_2) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 0 << 2 << 3 << 4; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "out of range"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_OutOfRange_3_negative) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 2 << -1; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "out of range"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_SingleColumn) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 0; schema.addMultiIndex(index, os); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_AllColumns) { U2OpStatusImpl os; UdrSchema schema = getTestSchema2(); QList<int> index; index << 0 << 1 << 2 << 3; schema.addMultiIndex(index, os); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_BackOrder) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 3 << 0; schema.addMultiIndex(index, os); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_DuplicateIndex) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 3 << 0; schema.addMultiIndex(index, os); CHECK_NO_ERROR(os); schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "duplicate index"); } IMPLEMENT_TEST(UdrSchemaUnitTests, addMultiIndex_BLOB) { U2OpStatusImpl os; UdrSchema schema = getTestSchema(); QList<int> index; index << 0 << 1; schema.addMultiIndex(index, os); CHECK_TRUE(os.hasError(), "indexed BLOB"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_Double_getInt) { UdrValue v(51.0); U2OpStatusImpl os; v.getInt(os); CHECK_TRUE(os.hasError(), "no error"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_String_getDouble) { UdrValue v(QString("test")); U2OpStatusImpl os; v.getDouble(os); CHECK_TRUE(os.hasError(), "no error"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_Null_getInt) { UdrValue v; U2OpStatusImpl os; v.getInt(os); CHECK_TRUE(os.hasError(), "no error"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_Null_getString) { UdrValue v; U2OpStatusImpl os; v.getString(os); CHECK_TRUE(os.hasError(), "no error"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_Double_getDouble) { UdrValue v(102.0); U2OpStatusImpl os; CHECK_TRUE(102.0 == v.getDouble(os), "data mismatch"); CHECK_NO_ERROR(os); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrValue_String_getDataId) { UdrValue v(QString("id")); U2OpStatusImpl os; v.getDataId(os); CHECK_TRUE(os.hasError(), "no error"); } IMPLEMENT_TEST(UdrSchemaUnitTests, isCorrectName_CorrectName) { CHECK_TRUE(UdrSchemaRegistry::isCorrectName("name_Of_the_id_is_Correct_0001"), "name is correct"); } IMPLEMENT_TEST(UdrSchemaUnitTests, isCorrectName_FirstDigit) { CHECK_FALSE(UdrSchemaRegistry::isCorrectName("51"), "first digit"); } IMPLEMENT_TEST(UdrSchemaUnitTests, isCorrectName_FirstUnderscore) { CHECK_TRUE(UdrSchemaRegistry::isCorrectName("_Name_51"), "first underscore is correct"); } IMPLEMENT_TEST(UdrSchemaUnitTests, isCorrectName_HasSpaces) { CHECK_FALSE(UdrSchemaRegistry::isCorrectName("name 1"), "has spaces"); } IMPLEMENT_TEST(UdrSchemaUnitTests, registerSchema_IncorrectName) { UdrSchema schema("schema 1"); U2OpStatusImpl os; AppContext::getUdrSchemaRegistry()->registerSchema(&schema, os); CHECK_TRUE(os.hasError(), "registered"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrSchema_ObjectReference) { UdrSchema schema("id", true); CHECK_TRUE(1 == schema.size(), "wrong size"); CHECK_TRUE(schema.hasObjectReference(), "object reference"); U2OpStatusImpl os; UdrSchema::FieldDesc field = schema.getField(0, os); CHECK_NO_ERROR(os); CHECK_TRUE(UdrSchema::OBJECT_FIELD_NAME == field.getName(), "name"); CHECK_TRUE(UdrSchema::ID == field.getDataType(), "dataType"); CHECK_TRUE(UdrSchema::INDEXED == field.getIndexType(), "indexType"); } IMPLEMENT_TEST(UdrSchemaUnitTests, UdrSchema_NoObjectReference) { UdrSchema schema("id"); CHECK_TRUE(0 == schema.size(), "wrong size"); CHECK_FALSE(schema.hasObjectReference(), "no object reference"); } } // namespace U2
31.151976
102
0.717924
[ "object" ]
be5b36c652b47f84571562abf15a983d8b3f407e
16,715
cc
C++
src/googleapis/client/transport/http_scribe.cc
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
264
2015-01-20T12:08:14.000Z
2022-03-28T17:58:30.000Z
src/googleapis/client/transport/http_scribe.cc
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
52
2015-01-01T10:25:31.000Z
2019-06-26T21:40:40.000Z
src/googleapis/client/transport/http_scribe.cc
jeramy-chen/google-api-cpp-client
27fee6855ab0e40e718cbba5738a259cee8c9bda
[ "Apache-2.0" ]
126
2015-01-03T05:39:20.000Z
2022-02-08T06:52:10.000Z
/* * \copyright Copyright 2013 Google Inc. All Rights Reserved. * \license @{ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @} */ #include <deque> #include <set> #include <string> using std::string; #include <vector> #include "googleapis/client/data/data_reader.h" #include "googleapis/client/transport/http_request.h" #include "googleapis/client/transport/http_request_batch.h" #include "googleapis/client/transport/http_response.h" #include "googleapis/client/transport/http_scribe.h" #include "googleapis/client/util/date_time.h" #include "googleapis/client/util/uri_utils.h" #include "googleapis/base/integral_types.h" #include <glog/logging.h> #include "googleapis/base/macros.h" #include "googleapis/strings/strcat.h" #include "googleapis/strings/stringpiece.h" namespace googleapis { namespace { using client::DataReader; const StringPiece kCensored("CENSORED"); // Make sure we have a value at base + offset. // We are looking for a complete match of a json value. // Json values are in the form ' : \"<value>\". // ^ ^ // start ----+ +---- end bool FindValueRangeWithQuotes( const char* base, int64 offset, int64* start, int64* end) { const char* pc = base + offset; while (*pc <= ' ' && *pc) { ++pc; } if (*pc != ':') { // perhaps this is a ',' because the tag was the value. return false; } ++pc; while (*pc <= ' ' && *pc) { ++pc; } char quote = *pc; if (quote != '\"' && quote != '\'') { return false; } *start = pc - base; for (++pc; *pc != quote && *pc; ++pc) { if (*pc == '\\') { ++pc; if (!*pc) break; // not well formed but keep it anyway. } } if (*pc) ++pc; // keep closing quote. *end = pc - base; return true; } string CensorAllJsonValuesForTagHelper( const string& json, const StringPiece& tag, bool* censored) { string result; int64 offset = 0; while (offset < json.size()) { int64 found = json.find(tag.data(), offset, tag.size()); if (found == string::npos) { result.append(json.c_str() + offset); break; } int64 start_quote; int64 end_quote; int64 end_tag = found + tag.size(); result.append(json.c_str() + offset, end_tag - offset); if (!FindValueRangeWithQuotes( json.c_str(), end_tag, &start_quote, &end_quote)) { offset = end_tag; continue; } StrAppend(&result, StringPiece(json.c_str() + end_tag, start_quote - end_tag), "\"", kCensored, "\""); *censored = true; offset = end_quote; } return result; } string ReadSnippet(int64 max_len, DataReader* reader) { string result; bool elide = false; if (reader->offset() != 0) { reader->Reset(); } reader->ReadToString(max_len, &result); if (reader->error()) { result = StrCat("ERROR: ", reader->status().error_message()); elide = result.size() > max_len; } else { elide = !reader->done(); } if (!reader->Reset()) { LOG(WARNING) << "Censor could not reset the request reader."; } if (elide) { const char kEllipse[] = "..."; if (max_len > 3) { result.erase(max_len - 3); result.append(kEllipse); } else { result = string(kEllipse, max_len); } } return result; } } // anonymous namespace namespace client { HttpScribeCensor::HttpScribeCensor() { censored_url_prefixes_.insert("https://accounts.google.com"); censored_query_param_names_.insert("access_token"); censored_query_param_names_.insert("refresh_token"); censored_query_param_names_.insert("client_secret"); censored_query_param_names_.insert("Passwd"); censored_request_header_names_.insert(HttpRequest::HttpHeader_AUTHORIZATION); } HttpScribeCensor::~HttpScribeCensor() {} string HttpScribeCensor::GetCensoredUrl( const HttpRequest& request, bool* censored) const { if (request.scribe_restrictions() & HttpScribe::FLAG_NO_URL) { *censored = true; return "URL was not made available"; } ParsedUrl parsed_url(request.url()); string censored_query = GetCensoredUrlQuery(parsed_url, censored); // Build normal url parts up to the query parameters. // NOTE(user): 20130520 // We're assuming there's nothing sensitive in the path. string censored_url = StrCat(ParsedUrl::SegmentOrEmpty(!parsed_url.scheme().empty(), parsed_url.scheme(), "://"), parsed_url.netloc(), parsed_url.path(), ParsedUrl::SegmentOrEmpty(!parsed_url.params().empty(), ";", parsed_url.params()), ParsedUrl::SegmentOrEmpty(!censored_query.empty(), "?", censored_query), ParsedUrl::SegmentOrEmpty(!parsed_url.fragment().empty(), "#", parsed_url.fragment()));; return censored_url; } string HttpScribeCensor::GetCensoredRequestHeaderValue( const HttpRequest& request, const string& name, const string& value, bool* censored) const { if (request.scribe_restrictions() & HttpScribe::FLAG_NO_REQUEST_HEADERS) { *censored = true; return "Request headers was not made available"; } if (censored_request_header_names_.find(name) != censored_request_header_names_.end()) { *censored = true; return kCensored.as_string(); } *censored = false; return value; } string HttpScribeCensor::GetCensoredResponseHeaderValue( const HttpRequest& request, const string& name, const string& value, bool* censored) const { if (request.scribe_restrictions() & HttpScribe::FLAG_NO_RESPONSE_HEADERS) { *censored = true; return "Request headers was not made available"; } if (censored_response_header_names_.find(name) != censored_response_header_names_.end()) { *censored = true; return kCensored.as_string(); } *censored = false; return value; } string HttpScribeCensor::GetCensoredRequestContent( const HttpRequest& request, int64 max_len, int64* original_size, bool* censored) const { *censored = false; DataReader* reader = request.content_reader(); if (!reader) { *original_size = 0; return ""; } *original_size = reader->TotalLengthIfKnown(); if (request.scribe_restrictions() & HttpScribe::FLAG_NO_REQUEST_PAYLOAD) { *censored = true; return "Request payload was not made available"; } string result; if (IsSensitiveContent(request.url())) { *censored = true; if (max_len < kCensored.size()) { result = string(kCensored.data(), max_len); } else { result = kCensored.as_string(); } } else { result = ReadSnippet(max_len, reader); const string* content_type_ptr = request.FindHeaderValue( HttpRequest::HttpHeader_CONTENT_TYPE); StringPiece content_type; if (content_type_ptr) { content_type = *content_type_ptr; } if (content_type.starts_with(HttpRequest::ContentType_FORM_URL_ENCODED)) { // Jam this payload into a bogus url and censor it using the // query parameter mechanism. string fake_url = StrCat("http://netloc?", result); ParsedUrl parsed_url(fake_url); result = GetCensoredUrlQuery(parsed_url, censored); } } return result; } string HttpScribeCensor::GetCensoredResponseBody( const HttpRequest& request, int64 max_len, int64* original_size, bool* censored) const { *censored = false; DataReader* reader = request.response()->body_reader(); if (!reader) { *original_size = 0; return ""; } *original_size = reader->TotalLengthIfKnown(); if (request.scribe_restrictions() & HttpScribe::FLAG_NO_RESPONSE_PAYLOAD) { *censored = true; return "Response payload was not made available"; } string result; if (IsSensitiveContent(request.url())) { *censored = true; if (max_len < kCensored.size()) { result = string(kCensored.data(), max_len); } else { result = kCensored.as_string(); } } else { result = ReadSnippet(max_len, reader); const string* content_type_ptr = request.response()->FindHeaderValue( HttpRequest::HttpHeader_CONTENT_TYPE); StringPiece content_type; if (content_type_ptr) { content_type = *content_type_ptr; } if (content_type.starts_with(HttpRequest::ContentType_JSON)) { // We're not going to parse into json for now because when we render // the result back we'll lose the original formatting. result = CensorAllJsonValuesForTagHelper( result, "\"refresh_token\"", censored); result = CensorAllJsonValuesForTagHelper( result, "\"access_token\"", censored); } } return result; } string HttpScribeCensor::GetCensoredUrlQuery( const ParsedUrl& parsed_url, bool* censored) const { *censored = false; const char* sep = ""; // Check each query parameter for censoring. const std::vector<ParsedUrl::QueryParameterAssignment>& params = parsed_url.GetQueryParameterAssignments(); string censored_query; for (std::vector<ParsedUrl::QueryParameterAssignment>::const_iterator it = params.begin(); it != params.end(); ++it) { const StringPiece& name = it->first; const StringPiece& value = it->second; StrAppend(&censored_query, sep, name); if (!value.empty()) { if (censored_query_param_names_.find(name.as_string()) != censored_query_param_names_.end()) { *censored = true; StrAppend(&censored_query, "=", kCensored); } else { StrAppend(&censored_query, "=", value); } } sep = "&"; } return censored_query; } bool HttpScribeCensor::IsSensitiveContent(const string& url) const { StringPiece check(url); for (std::set<string>::const_iterator it = censored_url_prefixes_.begin(); it != censored_url_prefixes_.end(); ++it) { if (check.starts_with(*it)) return true; } return false; } HttpEntryScribe::Entry::Entry( HttpEntryScribe* scribe, const HttpRequest* request) : scribe_(scribe), request_(request), batch_(NULL), received_request_(false), received_batch_(false) { DateTime now_time; now_time.GetTimeval(&timeval_); } HttpEntryScribe::Entry::Entry( HttpEntryScribe* scribe, const HttpRequestBatch* batch) : scribe_(scribe), request_(&batch->http_request()), batch_(batch), received_request_(false), received_batch_(false) { DateTime now_time; now_time.GetTimeval(&timeval_); } HttpEntryScribe::Entry::~Entry() { } void HttpEntryScribe::Entry::CancelAndDestroy() { delete this; } int64 HttpEntryScribe::Entry::MicrosElapsed() const { struct timeval now; DateTime now_time; now_time.GetTimeval(&now); int64 delta_s = now.tv_sec - timeval_.tv_sec; int64 delta_us = now.tv_usec - timeval_.tv_usec; return delta_us + 1000000 * delta_s; } HttpScribe::HttpScribe(HttpScribeCensor* censor) : censor_(censor), max_snippet_(kint64max) { } HttpScribe::~HttpScribe() { } HttpEntryScribe::HttpEntryScribe(HttpScribeCensor* censor) : HttpScribe(censor) { } HttpEntryScribe::~HttpEntryScribe() { DiscardQueue(); } void HttpEntryScribe::AboutToSendRequest(const HttpRequest* request) { GetEntry(request)->Sent(request); } void HttpEntryScribe::AboutToSendRequestBatch(const HttpRequestBatch* batch) { GetBatchEntry(batch)->SentBatch(batch); } // This class is used to provide common code where we implement // regular Entry and BatchEntry essentially the same way but they use // different entry constructors or lookup methods. class HttpEntryScribe::Internal { public: static HttpEntryScribe::Entry* GetEntryHelper( HttpEntryScribe* scribe, const HttpRequest* request, const HttpRequestBatch* batch) { MutexLock l(&scribe->mutex_); EntryMap::iterator it = scribe->map_.find(request); if (it != scribe->map_.end()) return it->second; HttpEntryScribe::Entry* entry = batch ? scribe->NewBatchEntry(batch) : scribe->NewEntry(request); VLOG(1) << "Adding " << entry; scribe->map_.insert(std::make_pair(request, entry)); scribe->queue_.push_back(entry); VLOG(1) << "Added " << entry << " as " << scribe->queue_.size(); return entry; } static HttpEntryScribe::Entry* GetEntry( HttpEntryScribe* scribe, const HttpRequest* request) { return GetEntryHelper(scribe, request, NULL); } static HttpEntryScribe::Entry* GetBatchEntry( HttpEntryScribe* scribe, const HttpRequestBatch* batch) { return GetEntryHelper(scribe, &batch->http_request(), batch); } static void ReceiveResponseForRequest( HttpEntryScribe* scribe, const HttpRequest* request) { HttpEntryScribe::Entry* entry = scribe->GetEntry(request); entry->set_received_request(true); entry->Received(request); if (!entry->is_batch()) { scribe->DiscardEntry(entry); } } static void ReceiveResponseForRequestBatch( HttpEntryScribe* scribe, const HttpRequestBatch* batch) { HttpEntryScribe::Entry* entry = scribe->GetBatchEntry(batch); entry->set_received_batch(true); entry->ReceivedBatch(batch); scribe->DiscardEntry(entry); } static void RequestFailedWithTransportError( HttpEntryScribe* scribe, const HttpRequest* request, const googleapis::util::Status& status) { HttpEntryScribe::Entry* entry = scribe->GetEntry(request); entry->set_received_request(true); entry->Failed(request, status); if (!entry->is_batch()) { scribe->DiscardEntry(entry); } } static void RequestBatchFailedWithTransportError( HttpEntryScribe* scribe, const HttpRequestBatch* batch, const googleapis::util::Status& status) { HttpEntryScribe::Entry* entry = scribe->GetBatchEntry(batch); entry->set_received_batch(true); entry->FailedBatch(batch, status); scribe->DiscardEntry(entry); } }; void HttpEntryScribe::ReceivedResponseForRequest(const HttpRequest* request) { Internal::ReceiveResponseForRequest(this, request); } void HttpEntryScribe::ReceivedResponseForRequestBatch( const HttpRequestBatch* batch) { Internal::ReceiveResponseForRequestBatch(this, batch); } void HttpEntryScribe::RequestFailedWithTransportError( const HttpRequest* request, const googleapis::util::Status& status) { Internal::RequestFailedWithTransportError(this, request, status); } void HttpEntryScribe::RequestBatchFailedWithTransportError( const HttpRequestBatch* batch, const googleapis::util::Status& status) { Internal::RequestBatchFailedWithTransportError(this, batch, status); } void HttpEntryScribe::DiscardQueue() { MutexLock l(&mutex_); if (!queue_.empty()) { LOG(WARNING) << "Discarding scribe's queue with " << queue_.size() << " entries still outstanding."; while (!queue_.empty()) { UnsafeDiscardEntry(queue_.front()); } } } HttpEntryScribe::Entry* HttpEntryScribe::GetEntry( const HttpRequest* request) { return Internal::GetEntry(this, request); } HttpEntryScribe::Entry* HttpEntryScribe::GetBatchEntry( const HttpRequestBatch* batch) { return Internal::GetBatchEntry(this, batch); } void HttpEntryScribe::DiscardEntry(HttpEntryScribe::Entry* entry) { MutexLock l(&mutex_); VLOG(1) << "Discard " << entry; UnsafeDiscardEntry(entry); } void HttpEntryScribe::UnsafeDiscardEntry( HttpEntryScribe::Entry* entry) { VLOG(1) << "Removing " << entry; EntryMap::iterator found = map_.find(entry->request()); if (VLOG_IS_ON(1) && found == map_.end()) { for (EntryMap::const_iterator it = map_.begin(); it != map_.end(); ++it) { VLOG(1) << " map has " << it->second; } } CHECK(found != map_.end()); bool front = entry == queue_.front(); if (front) { queue_.pop_front(); } else { VLOG(1) << "Still waiting on " << queue_.front(); for (EntryQueue::iterator it = queue_.begin(); it != queue_.end(); ++it) { if (*it == entry) { queue_.erase(it); break; } } } map_.erase(found); entry->FlushAndDestroy(); } } // namespace client } // namespace googleapis
29.795009
79
0.670176
[ "render", "vector" ]
be5ed7a4d161f216051226342df9c645be7f18fd
510
cpp
C++
mission150/[Greedy]45. Jump Game II.cpp
alchemz/mission-peace
59a44b1e7a8fdfdf1f6743c0e6965b49e5291326
[ "MIT" ]
null
null
null
mission150/[Greedy]45. Jump Game II.cpp
alchemz/mission-peace
59a44b1e7a8fdfdf1f6743c0e6965b49e5291326
[ "MIT" ]
null
null
null
mission150/[Greedy]45. Jump Game II.cpp
alchemz/mission-peace
59a44b1e7a8fdfdf1f6743c0e6965b49e5291326
[ "MIT" ]
null
null
null
/* Jump Game II 贪心 Each element in the array represents your maximum jump length at that position. Input: [2,3,1,1,4] Output: 2 Explanation: The minimum number of jumps to reach the last index is 2. Jump 1 step from index 0 to 1, then 3 steps to the last index. */ int jump(vector<int> &nums){ //两个变量cur和pre分别来保存当前的能到达的最远位置和之前能到达的最远位置 int res=0, n=nums.size(), i=0, cur=0; while(cur < n-1){ res++; int pre=cur; for(; i<=pre; i++){ cur = max(cur, i+nums[i]);//当前的能到达的最远位置 } } return res; }
22.173913
79
0.670588
[ "vector" ]
be5f9815d6808953f827b2a6c174201b552be9cc
676
cpp
C++
C08/CountingSort_Inplace.cpp
charlienzw/CLRS-notes
8d8cca4d8170aff1b100ac27ea0430144ce3f6b1
[ "MIT" ]
null
null
null
C08/CountingSort_Inplace.cpp
charlienzw/CLRS-notes
8d8cca4d8170aff1b100ac27ea0430144ce3f6b1
[ "MIT" ]
null
null
null
C08/CountingSort_Inplace.cpp
charlienzw/CLRS-notes
8d8cca4d8170aff1b100ac27ea0430144ce3f6b1
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void CountingSort_Inplace(vector<int> &A) { int maxvalue = 0; for (int j = 0; j < A.size(); j++) { if (A[j] > maxvalue) maxvalue = A[j]; } vector<int> C(maxvalue + 1, 0); int tmp; for (int j = 0; j < A.size(); j++) C[A[j]] = C[A[j]] + 1; int k = 0; for (int i = 0; i < C.size(); i++) { for (int j = 0; j < C[i]; j++) { A[k] = i; k = k + 1; } } } int main() { int N; while (scanf("%d", &N) != EOF) { vector<int> A(N); for (int i = 0; i<A.size(); i++) scanf("%d", &A[i]); CountingSort_Inplace(A); for (int i = 0; i<A.size(); i++) printf("%d ", A[i]); printf("\n"); } return 0; }
16.095238
41
0.474852
[ "vector" ]
be61468ed670a44dae002c4c889798dd15af998b
1,433
cpp
C++
FootCommander.cpp
Itaysim7/cpp4Task
34c41100b7a53d51020d8c912713ffa258b9d11a
[ "MIT" ]
null
null
null
FootCommander.cpp
Itaysim7/cpp4Task
34c41100b7a53d51020d8c912713ffa258b9d11a
[ "MIT" ]
null
null
null
FootCommander.cpp
Itaysim7/cpp4Task
34c41100b7a53d51020d8c912713ffa258b9d11a
[ "MIT" ]
null
null
null
#include <iostream> #include "Board.hpp" #include "FootCommander.hpp" #include "FootSoldier.hpp" #include <limits> #include <string> void FootCommander::attack(vector<vector<Soldier*>> &b, pair<int,int> place) { int row=b.size(); int col=b[0].size(); pair<pair<int,int>,Soldier*> ans=make_pair(make_pair(0,0),nullptr); //how the commander attack double dis=std::numeric_limits<int>::max(); for(int i= 0; i< b.size(); ++i) { for(int j=0; j< b[i].size(); ++j) { Soldier* tempSol=b[i][j]; if(tempSol!=nullptr) { if(tempSol->getPlayerNumber()!=this->playerNumber) //if ememy { double tempDis=distance(place.first,place.second,i,j); if(tempDis<=dis) { dis=tempDis; ans.first.first=i;ans.first.second=j; ans.second=tempSol; } } else { FootSoldier *fs=dynamic_cast<FootSoldier*>(tempSol); //if from my team and footSoldier if(fs) fs->attack(b,{i,j}); } } } } ans.second->setHealth(ans.second->getHealth()+damage); if(ans.second->getHealth()<=0) b[ans.first.first][ans.first.second]=nullptr; }
32.568182
107
0.483601
[ "vector" ]
4158ea908d2ce9e5e9d5f629d8b74efe7b164f10
5,406
cpp
C++
chromium/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
chromium/third_party/WebKit/Source/core/html/canvas/CanvasAsyncBlobCreator.cpp
wedataintelligence/vivaldi-source
22a46f2c969f6a0b7ca239a05575d1ea2738768c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 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 "CanvasAsyncBlobCreator.h" #include "core/fileapi/File.h" #include "platform/Task.h" #include "platform/ThreadSafeFunctional.h" #include "platform/graphics/ImageBuffer.h" #include "platform/image-encoders/skia/PNGImageEncoder.h" #include "public/platform/Platform.h" #include "public/platform/WebScheduler.h" #include "public/platform/WebTaskRunner.h" #include "public/platform/WebThread.h" #include "public/platform/WebTraceLocation.h" #include "wtf/Functional.h" namespace blink { namespace { const double SlackBeforeDeadline = 0.001; // a small slack period between deadline and current time for safety const int NumChannelsPng = 4; bool isDeadlineNearOrPassed(double deadlineSeconds) { return (deadlineSeconds - SlackBeforeDeadline - Platform::current()->monotonicallyIncreasingTimeSeconds() <= 0); } } // anonymous namespace PassRefPtr<CanvasAsyncBlobCreator> CanvasAsyncBlobCreator::create(PassRefPtr<DOMUint8ClampedArray> unpremultipliedRGBAImageData, const String& mimeType, const IntSize& size, FileCallback* callback) { return adoptRef(new CanvasAsyncBlobCreator(unpremultipliedRGBAImageData, mimeType, size, callback)); } CanvasAsyncBlobCreator::CanvasAsyncBlobCreator(PassRefPtr<DOMUint8ClampedArray> data, const String& mimeType, const IntSize& size, FileCallback* callback) : m_data(data) , m_size(size) , m_mimeType(mimeType) , m_callback(callback) { ASSERT(m_data->length() == (unsigned) (size.height() * size.width() * 4)); m_encodedImage = adoptPtr(new Vector<unsigned char>()); m_pixelRowStride = size.width() * NumChannelsPng; m_numRowsCompleted = 0; } CanvasAsyncBlobCreator::~CanvasAsyncBlobCreator() { } void CanvasAsyncBlobCreator::scheduleAsyncBlobCreation(bool canUseIdlePeriodScheduling, double quality) { // TODO: async blob creation should be supported in worker_pool threads as well. but right now blink does not have that ASSERT(isMainThread()); // Make self-reference to keep this object alive until the final task completes m_selfRef = this; if (canUseIdlePeriodScheduling) { ASSERT(m_mimeType == "image/png"); Platform::current()->mainThread()->scheduler()->postIdleTask(BLINK_FROM_HERE, WTF::bind<double>(&CanvasAsyncBlobCreator::initiatePngEncoding, this)); } else { getToBlobThreadInstance()->taskRunner()->postTask(BLINK_FROM_HERE, new Task(threadSafeBind(&CanvasAsyncBlobCreator::encodeImageOnAsyncThread, AllowCrossThreadAccess(this), quality))); } } void CanvasAsyncBlobCreator::initiatePngEncoding(double deadlineSeconds) { m_encoderState = PNGImageEncoderState::create(m_size, m_encodedImage.get()); if (!m_encoderState) { Platform::current()->mainThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&FileCallback::handleEvent, m_callback, nullptr)); m_selfRef.clear(); return; } CanvasAsyncBlobCreator::idleEncodeRowsPng(deadlineSeconds); } void CanvasAsyncBlobCreator::scheduleIdleEncodeRowsPng() { Platform::current()->currentThread()->scheduler()->postIdleTask(BLINK_FROM_HERE, WTF::bind<double>(&CanvasAsyncBlobCreator::idleEncodeRowsPng, this)); } void CanvasAsyncBlobCreator::idleEncodeRowsPng(double deadlineSeconds) { unsigned char* inputPixels = m_data->data() + m_pixelRowStride * m_numRowsCompleted; for (int y = m_numRowsCompleted; y < m_size.height(); ++y) { if (isDeadlineNearOrPassed(deadlineSeconds)) { m_numRowsCompleted = y; CanvasAsyncBlobCreator::scheduleIdleEncodeRowsPng(); return; } PNGImageEncoder::writeOneRowToPng(inputPixels, m_encoderState.get()); inputPixels += m_pixelRowStride; } m_numRowsCompleted = m_size.height(); PNGImageEncoder::finalizePng(m_encoderState.get()); if (isDeadlineNearOrPassed(deadlineSeconds)) { Platform::current()->mainThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&CanvasAsyncBlobCreator::createBlobAndCall, this)); } else { this->createBlobAndCall(); } } void CanvasAsyncBlobCreator::createBlobAndCall() { File* resultBlob = File::create(m_encodedImage->data(), m_encodedImage->size(), m_mimeType); Platform::current()->mainThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&FileCallback::handleEvent, m_callback, resultBlob)); m_selfRef.clear(); // self-destruct once job is done. } void CanvasAsyncBlobCreator::encodeImageOnAsyncThread(double quality) { ASSERT(!isMainThread()); if (!ImageDataBuffer(m_size, m_data->data()).encodeImage(m_mimeType, quality, m_encodedImage.get())) { Platform::current()->mainThread()->taskRunner()->postTask(BLINK_FROM_HERE, bind(&FileCallback::handleEvent, m_callback, nullptr)); } else { Platform::current()->mainThread()->taskRunner()->postTask(BLINK_FROM_HERE, threadSafeBind(&CanvasAsyncBlobCreator::createBlobAndCall, AllowCrossThreadAccess(this))); } } WebThread* CanvasAsyncBlobCreator::getToBlobThreadInstance() { DEFINE_STATIC_LOCAL(OwnPtr<WebThread>, s_toBlobThread, ()); if (!s_toBlobThread) { s_toBlobThread = adoptPtr(Platform::current()->createThread("Async toBlob")); } return s_toBlobThread.get(); } } // namespace blink
40.044444
197
0.744728
[ "object", "vector" ]
415a12e9409aeade7ec55f4a6a26d8abd8da7e5a
374
hpp
C++
overlay/constants.hpp
greggomann/dcos-mesos-modules
26d11daee118055ab0975b0eaa0a25b6cf1a35c3
[ "Apache-2.0" ]
null
null
null
overlay/constants.hpp
greggomann/dcos-mesos-modules
26d11daee118055ab0975b0eaa0a25b6cf1a35c3
[ "Apache-2.0" ]
null
null
null
overlay/constants.hpp
greggomann/dcos-mesos-modules
26d11daee118055ab0975b0eaa0a25b6cf1a35c3
[ "Apache-2.0" ]
null
null
null
#ifndef __OVERLAY_CONSTANTS_HPP__ #define __OVERLAY_CONSTANTS_HPP__ #include <vector> #include <process/future.hpp> namespace mesos { namespace modules { namespace overlay { namespace agent { constexpr char IPSET_OVERLAY[] = "overlay"; } // namespace agent { } // namespace overlay { } // namespace modules { } // namespace mesos { #endif // __OVERLAY_CONSTANTS_HPP__
17.809524
43
0.751337
[ "vector" ]
4161f6d5ec27aadc7dd4ab8df10b55204311f3c4
4,417
cpp
C++
Source/Core/Visualization/Renderer/LineRenderer.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Renderer/LineRenderer.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
Source/Core/Visualization/Renderer/LineRenderer.cpp
CCSEPBVR/KVS
f6153b3f52aa38904cc96d38d5cd609c5dccfc59
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************/ /** * @file LineRenderer.cpp * @author Naohisa Sakamoto */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: LineRenderer.cpp 1634 2013-09-06 08:55:47Z naohisa.sakamoto@gmail.com $ */ /****************************************************************************/ #include "LineRenderer.h" #include "LineRenderingFunction.h" #include <kvs/OpenGL> #include <kvs/Camera> #include <kvs/Light> #include <kvs/ObjectBase> #include <kvs/LineObject> #include <kvs/IgnoreUnusedVariable> namespace kvs { /*==========================================================================*/ /** * @brief Contructs a new LineRenderer class. */ /*==========================================================================*/ LineRenderer::LineRenderer(): m_enable_anti_aliasing( false ), m_enable_multisample_anti_aliasing( false ) { // Disable shading since the line object don't have the normal vectors. this->disableShading(); } /*==========================================================================*/ /** * @brief Destructs the LineRenderer class. */ /*==========================================================================*/ LineRenderer::~LineRenderer() { } /*==========================================================================*/ /** * @brief Executes the rendering process. * @param object [in] pointer to the object * @param camera [in] pointer to the camera * @param light [in] pointer to the light */ /*==========================================================================*/ void LineRenderer::exec( kvs::ObjectBase* object, kvs::Camera* camera, kvs::Light* light ) { kvs::IgnoreUnusedVariable( light ); kvs::IgnoreUnusedVariable( camera ); kvs::LineObject* line = kvs::LineObject::DownCast( object ); BaseClass::startTimer(); kvs::OpenGL::WithPushedAttrib p( GL_CURRENT_BIT | GL_ENABLE_BIT ); this->initialize(); kvs::OpenGL::Enable( GL_DEPTH_TEST ); ::LineRenderingFunction( line, camera->devicePixelRatio() ); BaseClass::stopTimer(); } /*===========================================================================*/ /** * @brief Enables anti-aliasing. */ /*===========================================================================*/ void LineRenderer::enableAntiAliasing( const bool multisample ) const { m_enable_anti_aliasing = true; m_enable_multisample_anti_aliasing = multisample; } /*===========================================================================*/ /** * @brief Disables anti-aliasing. */ /*===========================================================================*/ void LineRenderer::disableAntiAliasing() const { m_enable_anti_aliasing = false; m_enable_multisample_anti_aliasing = false; } /*===========================================================================*/ /** * @brief Initializes the OpenGL properties. */ /*===========================================================================*/ void LineRenderer::initialize() { kvs::OpenGL::SetColorMaterial( GL_FRONT, GL_AMBIENT_AND_DIFFUSE ); kvs::OpenGL::Enable( GL_COLOR_MATERIAL ); // Polygon offset. kvs::OpenGL::SetPolygonOffset( 1.0, 0.0 ); kvs::OpenGL::Enable( GL_POLYGON_OFFSET_FILL ); // Lighting. if ( !BaseClass::isEnabledShading() ) kvs::OpenGL::Disable( GL_LIGHTING ); else kvs::OpenGL::Enable( GL_LIGHTING ); // Anti-aliasing. if ( m_enable_anti_aliasing ) { #if defined ( GL_MULTISAMPLE ) if ( m_enable_multisample_anti_aliasing ) { GLint buffers = 0; GLint samples = 0; kvs::OpenGL::GetIntegerv( GL_SAMPLE_BUFFERS, &buffers ); kvs::OpenGL::GetIntegerv( GL_SAMPLES, &samples ); if ( buffers > 0 && samples > 1 ) kvs::OpenGL::Enable( GL_MULTISAMPLE ); } else #endif { kvs::OpenGL::Enable( GL_LINE_SMOOTH ); kvs::OpenGL::Enable( GL_BLEND ); kvs::OpenGL::SetBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); kvs::OpenGL::Hint( GL_LINE_SMOOTH_HINT, GL_NICEST ); } } } } // end of namespace kvs
31.326241
90
0.48585
[ "object" ]
416922836be5973d960a5b058d5d105a43ed9064
323
hpp
C++
src/robot/i_message-interpreter.hpp
JasonThomasData/marsRoverKata
4707852dfb721635cd5426fbf446a12ee0763658
[ "MIT" ]
null
null
null
src/robot/i_message-interpreter.hpp
JasonThomasData/marsRoverKata
4707852dfb721635cd5426fbf446a12ee0763658
[ "MIT" ]
null
null
null
src/robot/i_message-interpreter.hpp
JasonThomasData/marsRoverKata
4707852dfb721635cd5426fbf446a12ee0763658
[ "MIT" ]
null
null
null
#include <vector> #include <map> #include "movements.hpp" #ifndef IMessageInterpreter_h #define IMessageInterpreter_h class IMessageInterpreter { public: virtual ~IMessageInterpreter() {}; virtual std::vector<Movement> interpretInstructions(const std::string& instructionsToMovements) =0; }; #endif
20.1875
107
0.743034
[ "vector" ]
416a952bdb84f237b6105012db9d65d50540083a
8,225
cc
C++
src/k2/connector/pggate/pg_select.cc
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
3
2021-07-05T09:00:18.000Z
2022-03-18T20:08:33.000Z
src/k2/connector/pggate/pg_select.cc
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
11
2021-09-24T16:52:30.000Z
2022-03-15T23:12:37.000Z
src/k2/connector/pggate/pg_select.cc
futurewei-cloud/chogori-sql
29b1ffd6610616c8571b96aa2366bccc3685e9c0
[ "Apache-2.0" ]
1
2021-07-05T09:01:58.000Z
2021-07-05T09:01:58.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. // // The following only applies to changes made to this file as part of YugaByte development. // // Portions Copyright (c) YugaByte, 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. // // Copyright(c) 2020 Futurewei Cloud // // Permission is hereby granted, // free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : // // The above copyright notice and this permission notice shall be included in all copies // or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", // WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include "pggate/pg_select.h" namespace k2pg { namespace gate { using std::make_shared; PgSelect::PgSelect(std::shared_ptr<PgSession> pg_session, const PgObjectId& table_object_id, const PgObjectId& index_object_id, const PgPrepareParameters *prepare_params) : PgDmlRead(pg_session, table_object_id, index_object_id, prepare_params) { K2LOG_D(log::pg, "Created PgSelect id: {} for {} : {}, {}", stmt_id_, table_object_id.GetDatabaseOid(), table_object_id.GetObjectOid(), index_object_id.GetObjectOid()); } PgSelect::~PgSelect() { } Status PgSelect::Prepare() { // Prepare target and bind descriptors. if (!prepare_params_.use_secondary_index) { target_desc_ = bind_desc_ = VERIFY_RESULT(pg_session_->LoadTable(table_object_id_)); } else { target_desc_ = VERIFY_RESULT(pg_session_->LoadTable(table_object_id_)); bind_desc_ = nullptr; // Create secondary index query. secondary_index_query_ = std::make_shared<PgSelectIndex>(pg_session_, table_object_id_, index_object_id_, &prepare_params_); K2LOG_D(log::pg, "new secondary_index_query_ created."); } // Allocate READ requests to send to storage layer. auto read_op = target_desc_->NewPgsqlSelect(client_id_, stmt_id_); read_req_ = read_op->request(); auto sql_op = make_shared<PgReadOp>(pg_session_, target_desc_, std::move(read_op)); // Prepare the index selection if this operation is using the index. RETURN_NOT_OK(PrepareSecondaryIndex()); // Prepare binds for the request. PrepareBinds(); // Preparation complete. sql_op_ = sql_op; return Status::OK(); } Status PgSelect::PrepareSecondaryIndex() { if (!secondary_index_query_) { // This DML statement is not using secondary index. return Status::OK(); } K2LOG_D(log::pg, "secondary_index_query_ preparing as subquery."); // Prepare subquery. When index_req is not null, it is part of 'this' SELECT request. When it // is nullptr, the subquery will create its own sql_op_ to run a separate read request. return secondary_index_query_->PrepareSubquery(nullptr); } PgSelectIndex::PgSelectIndex(std::shared_ptr<PgSession> pg_session, const PgObjectId& table_object_id, const PgObjectId& index_object_id, const PgPrepareParameters *prepare_params) : PgDmlRead(pg_session, table_object_id, index_object_id, prepare_params) { } PgSelectIndex::~PgSelectIndex() { } Status PgSelectIndex::Prepare() { // We get here only if this is an IndexOnly scan. CHECK(prepare_params_.index_only_scan) << "Unexpected IndexOnly scan type"; K2LOG_D(log::pg, "PgSelectIndex preparing as indexOnly scan."); return PrepareQuery(nullptr); } Status PgSelectIndex::PrepareSubquery(std::shared_ptr<SqlOpReadRequest> read_req) { // We get here if this is an SecondaryIndex scan. CHECK(prepare_params_.use_secondary_index && !prepare_params_.index_only_scan) << "Unexpected Index scan type"; K2LOG_D(log::pg, "PgSelectIndex preparing as secondary index subquery."); return PrepareQuery(read_req); } Status PgSelectIndex::PrepareQuery(std::shared_ptr<SqlOpReadRequest> read_req) { // Setup target and bind descriptor. target_desc_ = bind_desc_ = VERIFY_RESULT(pg_session_->LoadTable(index_object_id_)); // Allocate READ requests to send to K2 SKV. if (read_req) { // For (system and user) colocated tables, SelectIndex is a part of Select and being sent // together with the SELECT request. A read sql_op_ and request is not needed in this // case. DSCHECK(prepare_params_.querying_colocated_table, InvalidArgument, "Read request invalid"); read_req_ = read_req; read_req_->table_id = index_object_id_.GetTableId(); sql_op_ = nullptr; K2LOG_D(log::pg, "PgSelectIndex prepared as secondary index subquery for {}. sql_op_ is null. read_req pagestate is null 1 or 0? {}", read_req_->table_id, (!(read_req_->paging_state) ? 1:0 )); } else { auto read_op = target_desc_->NewPgsqlSelect(client_id_, stmt_id_); read_req_ = read_op->request(); sql_op_ = make_shared<PgReadOp>(pg_session_, target_desc_, std::move(read_op)); } // Prepare index key columns. PrepareBinds(); return Status::OK(); } // From a index table resut set, get the corresponding base table k2pgctids (RowIds) Result<bool> PgSelectIndex::FetchBaseRowIdBatch(std::vector<std::string>& baseRowIds) { K2LOG_D(log::pg, "FetchBaseRowIdBatch, next batch size: {}", (rowsets_.empty() ? 0: rowsets_.front().data_.size())); // Keep reading until we get one batch of k2pgctids or EOF. while (!VERIFY_RESULT(HasBaseRowIdBatch())) { K2LOG_D(log::pg, "FetchBaseRowIdBatch has nothing cached, trying FetchDataFromServer"); if (!VERIFY_RESULT(FetchDataFromServer())) { // Server returns no more rows. return false; } } // Got the next batch of baseCtids. DCHECK(!rowsets_.empty() && !rowsets_.front().is_eof()); rowsets_.front().GetBaseRowIdBatch(baseRowIds); // we should consumed all first batch in rowsets, erase it now. DCHECK(rowsets_.front().is_eof()); rowsets_.pop_front(); K2LOG_D(log::pg, "Exiting FetchBaseRowIdBatch, next batch size: {}", (rowsets_.empty() ? 0: rowsets_.front().data_.size())); return true; } Result<bool> PgSelectIndex::HasBaseRowIdBatch() { for (auto rowset_iter = rowsets_.begin(); rowset_iter != rowsets_.end();) { if (rowset_iter->is_eof()) { rowset_iter = rowsets_.erase(rowset_iter); } else { return true; } } return false; } } // namespace gate } // namespace k2pg
41.540404
414
0.730578
[ "vector" ]
416fd3620cad2c00eb4a81ca2c5649e2565b1f17
1,820
cpp
C++
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMaxUnpool.cpp
KsenijaS/onnxruntime
5086e55a35f83e3137bdb34b6d7210c97a512e6a
[ "MIT" ]
2
2021-07-24T01:13:36.000Z
2021-11-17T11:03:52.000Z
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMaxUnpool.cpp
KsenijaS/onnxruntime
5086e55a35f83e3137bdb34b6d7210c97a512e6a
[ "MIT" ]
17
2020-07-21T11:13:27.000Z
2022-03-27T02:37:05.000Z
onnxruntime/core/providers/dml/DmlExecutionProvider/src/Operators/DmlOperatorMaxUnpool.cpp
Surfndez/onnxruntime
9d748afff19e9604a00632d66b97159b917dabb2
[ "MIT" ]
1
2020-07-30T12:50:02.000Z
2020-07-30T12:50:02.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "precomp.h" namespace Dml { class DmlOperatorMaxUnpool : public DmlOperator, public UnpoolingHelper { public: using Self = DmlOperatorMaxUnpool; DmlOperatorMaxUnpool(const MLOperatorKernelCreationContext& kernelCreationContext) : DmlOperator(kernelCreationContext), UnpoolingHelper(kernelCreationContext, kernelCreationContext.GetTensorShapeDescription()) { uint32_t inputCount = kernelCreationContext.GetInputCount(); ML_CHECK_VALID_ARGUMENT(inputCount == 2 || inputCount == 3, "MaxUnpool expects 2 or 3 inputs."); ML_CHECK_VALID_ARGUMENT(kernelCreationContext.GetOutputCount() == 1, "MaxUnpool expects 1 output."); std::vector<std::optional<uint32_t>> inputIndices = { 0, 1 }; // The 3rd tensor ('output_shape') is not bound, just 'X' and 'I' indices. std::vector<std::optional<uint32_t>> outputIndices = { 0 }; DmlOperator::Initialize(kernelCreationContext, inputIndices, outputIndices); std::vector<DML_TENSOR_DESC> inputDescs = GetDmlInputDescs(); std::vector<DML_TENSOR_DESC> outputDescs = GetDmlOutputDescs(); assert(inputDescs.size() == 2); assert(outputDescs.size() == 1); DML_MAX_UNPOOLING_OPERATOR_DESC poolingDesc = {}; poolingDesc.InputTensor = &inputDescs[0]; poolingDesc.IndicesTensor = &inputDescs[1]; poolingDesc.OutputTensor = outputDescs.data(); DML_OPERATOR_DESC operaterDesc = {}; operaterDesc.Type = DML_OPERATOR_MAX_UNPOOLING; operaterDesc.Desc = &poolingDesc; SetDmlOperatorDesc(operaterDesc, kernelCreationContext); } }; DML_OP_DEFINE_CREATION_FUNCTION(MaxUnpool, DmlOperatorMaxUnpool); } // namespace Dml
39.565217
144
0.719231
[ "vector" ]
417522797dfc8835ff6f72833f9f8cfbbe6d18cf
6,330
hpp
C++
src/algo/hits/gap/CompositionHitIterator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
9
2016-09-30T05:44:35.000Z
2020-09-03T19:40:06.000Z
src/algo/hits/gap/CompositionHitIterator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
10
2017-05-05T14:55:16.000Z
2022-01-24T18:21:51.000Z
src/algo/hits/gap/CompositionHitIterator.hpp
nileshpatra/plast-library
7c962282fdb68ac1f48a587e03fbb1a1b70a7a32
[ "Intel", "DOC" ]
1
2020-12-05T21:33:27.000Z
2020-12-05T21:33:27.000Z
/***************************************************************************** * * * PLAST : Parallel Local Alignment Search Tool * * Version 2.3, released November 2015 * * Copyright (c) 2009-2015 Inria-Cnrs-Ens * * * * PLAST is free software; you can redistribute it and/or modify it under * * the Affero GPL ver 3 License, that is compatible with the GNU General * * Public License * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * Affero GPL ver 3 License for more details. * *****************************************************************************/ /** \file CompositionHitIterator.hpp * \brief Implementation of IHitIterator interface for full gap alignments. * \date 07/11/2011 * \author edrezen */ #ifndef _COMPOSITION_HIT_ITERATOR_HPP_ #define _COMPOSITION_HIT_ITERATOR_HPP_ /********************************************************************************/ #include <seed/api/ISeedModel.hpp> #include <algo/core/api/IScoreMatrix.hpp> #include <algo/core/api/IAlgoParameters.hpp> #include <algo/stats/api/IStatistics.hpp> #include <algo/hits/common/AbstractPipeHitIterator.hpp> #include <algo/hits/gap/FullGapHitIterator.hpp> #include <alignment/core/api/IAlignmentContainer.hpp> #include <alignment/tools/api/IAlignmentSplitter.hpp> #include <alignment/core/impl/UngapAlignmentContainer.hpp> #include <set> /********************************************************************************/ namespace algo { namespace hits { /** \brief Implementation of IHitIterator interface for small gap alignments. */ namespace gapped { /********************************************************************************/ /** \brief Implementation of IHitIterator for full gap alignments * * Last step in the PLAST algorithm. This is here where the resulting Alignment * instances are created. * * This implementation relies on some code of the NCBI BLAST (see ALIGN_EX()). */ class CompositionHitIterator : public algo::hits::gapped::FullGapHitIterator { public: /** \copydoc common::FullGapHitIterator::FullGapHitIterator * \param[in] queryInfo : information about query sequences (including cutoffs) * \param[in] globalStats : global statistics * \param[out] alignmentResult : list of gap alignments to be filled during algorithm execution */ CompositionHitIterator ( algo::hits::IHitIterator* sourceIterator, algo::core::IConfiguration* config, seed::ISeedModel* model, algo::core::IScoreMatrix* scoreMatrix, algo::core::IParameters* parameters, alignment::core::IAlignmentContainer* ungapResult, statistics::IQueryInformation* queryInfo, statistics::IGlobalParameters* globalStats, alignment::core::IAlignmentContainer* alignmentResult ); /** Destructor. */ virtual ~CompositionHitIterator (); /** \copydoc common::AbstractPipeHitIterator::getName */ const char* getName () { return "CompositionHitIterator"; } /** \copydoc common::AbstractPipeHitIterator::getProperties */ dp::IProperties* getProperties (); protected: /** \copydoc common::AbstractPipeHitIterator::clone */ virtual CompositionHitIterator* clone (algo::hits::IHitIterator* sourceIterator) { return new CompositionHitIterator (sourceIterator, _config, _model, _scoreMatrix, _parameters, _ungapResult, _queryInfo, _globalStats, _alignmentResult); } /** \copydoc common::AbstractPipeHitIterator::iterateMethod */ void iterateMethod (algo::hits::Hit* hit); }; /********************************************************************************/ /** \brief Null implementation of IHitIterator for full gap alignments */ class CompositionHitIteratorNull : public algo::hits::common::AbstractPipeHitIterator { public: /** \copydoc common::AbstractPipeHitIterator::AbstractPipeHitIterator * \param[in] queryInfo : information about query sequences (including cutoffs) * \param[in] globalStats : global statistics * \param[out] alignmentResult : list of gap alignments to be filled during algorithm execution */ CompositionHitIteratorNull ( algo::hits::IHitIterator* sourceIterator, seed::ISeedModel* model, algo::core::IScoreMatrix* scoreMatrix, algo::core::IParameters* parameters, alignment::core::IAlignmentContainer* ungapResult, statistics::IQueryInformation* queryInfo, statistics::IGlobalParameters* globalStats, alignment::core::IAlignmentContainer* alignmentResult ) : common::AbstractPipeHitIterator (sourceIterator, model, scoreMatrix, parameters, ungapResult) {} /** Destructor. */ virtual ~CompositionHitIteratorNull () {} /** \copydoc common::AbstractPipeHitIterator::getName */ const char* getName () { return "CompositionHitIteratorNull"; } protected: /** \copydoc common::AbstractPipeHitIterator::clone */ virtual AbstractPipeHitIterator* clone (algo::hits::IHitIterator* sourceIterator) { return new CompositionHitIteratorNull (sourceIterator, _model, _scoreMatrix, _parameters, _ungapResult, 0, 0, 0); } /** \copydoc common::AbstractPipeHitIterator::iterateMethod */ void iterateMethod (algo::hits::Hit* hit) {} }; /********************************************************************************/ }}} /* end of namespaces. */ /********************************************************************************/ #endif /* _COMPOSITION_HIT_ITERATOR_HPP_ */
42.77027
161
0.574566
[ "model" ]
41778be0d624d15e1106b5593ca69f0dc420883e
6,585
cpp
C++
PSME/agent/storage/src/tree_stability/storage_tree_stabilizer.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/agent/storage/src/tree_stability/storage_tree_stabilizer.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/agent/storage/src/tree_stability/storage_tree_stabilizer.cpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @brief Provides class for stabilizing storage agent resource tree * * @copyright * Copyright (c) 2015-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file storage_tree_stabilizer.cpp * */ #include "tree_stability/storage_tree_stabilizer.hpp" #include "tree_stability/helpers/update_relations.hpp" #include "agent-framework/logger_ext.hpp" #include "agent-framework/module/storage_components.hpp" #include "agent-framework/module/common_components.hpp" #include <algorithm> #include <string> using namespace agent_framework::module; using namespace agent::storage; using agent_framework::model::attribute::Array; using agent_framework::model::attribute::TargetLun; using agent_framework::model::enums::LogicalDriveMode; /*! Auxiliary namespace to hold prefixes for unique key construction, needed to maintain data integrity */ namespace literals { constexpr const char MODULE_KEY_BASE[] = "Module_"; constexpr const char SERVICE_KEY_BASE[] = "StorageService_"; constexpr const char TARGET_KEY_BASE[] = "Target_"; constexpr const char LOGICAL_DRIVE_KEY_BASE[] = "LogicalDrive_"; constexpr const char PHYSICAL_DRIVE_KEY_BASE[] = "PhysicalDrive_"; } StorageTreeStabilizer::~StorageTreeStabilizer() { } const std::string StorageTreeStabilizer::stabilize_target(const std::string& target_uuid) { auto& target_manager = StorageComponents::get_instance()->get_iscsi_target_manager(); auto target = target_manager.get_entry(target_uuid); if (target.get_target_iqn().has_value()) { const auto target_iqn = target.get_target_iqn().value(); const auto target_persistent_uuid = stabilize_single_resource(target_uuid, target_manager, literals::TARGET_KEY_BASE + target_iqn); helpers::update_target_in_relations(target_uuid, target_persistent_uuid); return target_persistent_uuid; } else { log_key_value_missing(target.get_component().to_string(), target_uuid); return target_uuid; } } const std::string StorageTreeStabilizer::stabilize_logical_drive(const std::string& drive_uuid) { auto& logical_drive_manager = StorageComponents::get_instance()->get_logical_drive_manager(); auto logical_drive = logical_drive_manager.get_entry(drive_uuid); auto device_path = logical_drive.get_device_path(); const auto drive_persistent_uuid = stabilize_single_resource(drive_uuid, logical_drive_manager, literals::LOGICAL_DRIVE_KEY_BASE + device_path); helpers::update_logical_drive_in_relations(drive_uuid, drive_persistent_uuid); return drive_persistent_uuid; } const std::string StorageTreeStabilizer::stabilize_physical_drive(const std::string& drive_uuid) { auto& physical_drive_manager = StorageComponents::get_instance()->get_physical_drive_manager(); auto physical_drive = physical_drive_manager.get_entry(drive_uuid); const auto serial_number = physical_drive.get_fru_info().get_serial_number(); if (serial_number.has_value()) { const std::string& drive_persistent_uuid = stabilize_single_resource(drive_uuid, physical_drive_manager, literals::PHYSICAL_DRIVE_KEY_BASE + serial_number.value()); return drive_persistent_uuid; } else { log_key_value_missing(physical_drive.get_component().to_string(), drive_uuid); return drive_uuid; } } const std::string StorageTreeStabilizer::stabilize_storage_service(const std::string& service_uuid) { auto& service_manager = StorageComponents::get_instance()->get_storage_services_manager(); auto& physical_drive_manager = StorageComponents::get_instance()->get_physical_drive_manager(); auto& logical_drive_manager = StorageComponents::get_instance()->get_logical_drive_manager(); auto& target_manager = StorageComponents::get_instance()->get_iscsi_target_manager(); auto service = service_manager.get_entry(service_uuid); const auto& physical_drives_uuids = physical_drive_manager.get_keys(); const auto& logical_drives_uuids = logical_drive_manager.get_keys(); const auto& targets_uuids = target_manager.get_keys(service_uuid); const auto service_persistent_uuid = stabilize_single_resource(service_uuid, service_manager, literals::SERVICE_KEY_BASE); for (const auto& physical_drive_uuid : physical_drives_uuids) { stabilize_physical_drive(physical_drive_uuid); } for (const auto& logical_drive_uuid : logical_drives_uuids) { stabilize_logical_drive(logical_drive_uuid); } for (const auto& target_uuid : targets_uuids) { target_manager.get_entry_reference(target_uuid)->set_parent_uuid(service_persistent_uuid); stabilize_target(target_uuid); } return service_persistent_uuid; } const std::string StorageTreeStabilizer::stabilize(const std::string& module_uuid) { auto& module_manager = CommonComponents::get_instance()->get_module_manager(); auto& service_manager = StorageComponents::get_instance()->get_storage_services_manager(); const auto& services_keys = service_manager.get_keys(module_uuid); if (services_keys.empty()) { throw std::runtime_error("No Storage Service found for module " + module_uuid); } const auto service = service_manager.get_entry(services_keys.front()); const auto module_persistent_uuid = stabilize_single_resource(module_uuid, module_manager, literals::MODULE_KEY_BASE); service_manager.get_entry_reference(service.get_uuid())->set_parent_uuid(module_persistent_uuid); stabilize_storage_service(service.get_uuid()); return module_persistent_uuid; }
42.211538
114
0.720881
[ "model" ]
4178cfad8401dc3b5fcf912c358ea3c0b28e16e2
3,693
cc
C++
test/perf/linux/verity_randread_benchmark.cc
xyzst/gvisor
58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082
[ "Apache-2.0" ]
12,536
2018-05-02T09:57:54.000Z
2022-03-31T14:25:15.000Z
test/perf/linux/verity_randread_benchmark.cc
xyzst/gvisor
58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082
[ "Apache-2.0" ]
2,478
2018-05-02T14:01:30.000Z
2022-03-31T19:57:47.000Z
test/perf/linux/verity_randread_benchmark.cc
xyzst/gvisor
58b9bdfc21e792c5d529ec9f4ab0b2f2cd1ee082
[ "Apache-2.0" ]
1,163
2018-05-02T10:03:44.000Z
2022-03-29T17:15:01.000Z
// Copyright 2021 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <fcntl.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/stat.h> #include <sys/uio.h> #include <unistd.h> #include "gtest/gtest.h" #include "benchmark/benchmark.h" #include "test/util/logging.h" #include "test/util/temp_path.h" #include "test/util/test_util.h" #include "test/util/verity_util.h" namespace gvisor { namespace testing { namespace { // Create a 1GB file that will be read from at random positions. This should // invalid any performance gains from caching. const uint64_t kFileSize = Megabytes(1024); // How many bytes to write at once to initialize the file used to read from. const uint32_t kWriteSize = 65536; // Largest benchmarked read unit. const uint32_t kMaxRead = Megabytes(64); // Global test state, initialized once per process lifetime. struct GlobalState { explicit GlobalState() { // Mount a tmpfs file system to be wrapped by a verity fs. tmp_dir_ = TempPath::CreateDir().ValueOrDie(); TEST_CHECK(mount("", tmp_dir_.path().c_str(), "tmpfs", 0, "") == 0); file_ = TempPath::CreateFileIn(tmp_dir_.path()).ValueOrDie(); filename_ = std::string(Basename(file_.path())); FileDescriptor fd = Open(file_.path(), O_WRONLY).ValueOrDie(); // Try to minimize syscalls by using maximum size writev() requests. std::vector<char> buffer(kWriteSize); RandomizeBuffer(buffer.data(), buffer.size()); const std::vector<std::vector<struct iovec>> iovecs_list = GenerateIovecs(kFileSize + kMaxRead, buffer.data(), buffer.size()); for (const auto& iovecs : iovecs_list) { TEST_CHECK(writev(fd.get(), iovecs.data(), iovecs.size()) >= 0); } verity_dir_ = MountVerity(tmp_dir_.path(), {EnableTarget(filename_, O_RDONLY)}) .ValueOrDie(); } TempPath tmp_dir_; TempPath file_; std::string verity_dir_; std::string filename_; }; GlobalState& GetGlobalState() { // This gets created only once throughout the lifetime of the process. // Use a dynamically allocated object (that is never deleted) to avoid order // of destruction of static storage variables issues. static GlobalState* const state = // The actual file size is the maximum random seek range (kFileSize) + the // maximum read size so we can read that number of bytes at the end of the // file. new GlobalState(); return *state; } void BM_VerityRandRead(benchmark::State& state) { const int size = state.range(0); GlobalState& global_state = GetGlobalState(); FileDescriptor verity_fd = ASSERT_NO_ERRNO_AND_VALUE(Open( JoinPath(global_state.verity_dir_, global_state.filename_), O_RDONLY)); std::vector<char> buf(size); unsigned int seed = 1; for (auto _ : state) { TEST_CHECK(PreadFd(verity_fd.get(), buf.data(), buf.size(), rand_r(&seed) % kFileSize) == size); } state.SetBytesProcessed(static_cast<int64_t>(size) * static_cast<int64_t>(state.iterations())); } BENCHMARK(BM_VerityRandRead)->Range(1, kMaxRead)->UseRealTime(); } // namespace } // namespace testing } // namespace gvisor
33.880734
80
0.701598
[ "object", "vector" ]
4181361b20cb06e7fe5a9b87b79b76d98d056700
33,257
cpp
C++
ObjectARX 2016/samples/database/ARXDBG/Tests/ArxDbgCmdTests.cpp
huanjka/AutoCADPlugin-HeatSource
ab0865402b41fe45d3b509c01c6f114d128522a8
[ "MIT" ]
1
2020-02-06T14:08:24.000Z
2020-02-06T14:08:24.000Z
ObjectARX 2016/samples/database/ARXDBG/Tests/ArxDbgCmdTests.cpp
huanjka/AutoCADPlugin-HeatSource
ab0865402b41fe45d3b509c01c6f114d128522a8
[ "MIT" ]
null
null
null
ObjectARX 2016/samples/database/ARXDBG/Tests/ArxDbgCmdTests.cpp
huanjka/AutoCADPlugin-HeatSource
ab0865402b41fe45d3b509c01c6f114d128522a8
[ "MIT" ]
2
2020-02-21T00:52:24.000Z
2022-02-10T06:05:35.000Z
// ////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// // #include "StdAfx.h" #if defined(_DEBUG) && !defined(AC_FULL_DEBUG) #error _DEBUG should not be defined except in internal Adesk debug builds #endif #include "ArxDbgCmdTests.h" #include "ArxDbgUiTdmEntities.h" #include "ArxDbgUiTdmEditor.h" #include "ArxDbgUiTdmDatabase.h" #include "ArxDbgUiDlgServiceDict.h" #include "ArxDbgUiDlgSysRegistry.h" #include "ArxDbgKeywordArray.h" #include "ArxDbgUiPrompts.h" #include "ArxDbgSelSet.h" #include "ArxDbgApp.h" #include "ArxDbgUtils.h" #include "ArxDbgUiDlgObjState.h" #include "XformTest.h" #include "EntMakeTest.h" #include "TblMakeTest.h" #include "ArxDbgUiDlgXdata.h" #include "ArxDbgUiDlgColor.h" #include "ArxDbgUiDlgTestCurves.h" #include "ArxDbgUiDlgWorldDraw.h" #include "ArxDbgUiDlgFilerTest.h" #include "ArxDbgUiDlgSelSet.h" #include "ArxDbgDwgFiler.h" #include "ArxDbgUtilsGe.h" #include "ArxDbgUiTdmTransDbClones.h" #include "SdSysVar.h" /**************************************************************************** ** ** ArxDbgCmdTests::registerCommandLineFunctions ** ** **jma ** *************************************/ void ArxDbgCmdTests::registerCommandLineFunctions(AcEdCommandStack* cmdStack, LPCTSTR appname) { cmdStack->addCommand(appname, _T("ArxDbgTestState"), _T("TestState"), ACRX_CMD_MODAL, &testState); cmdStack->addCommand(appname, _T("ArxDbgTestXform"), _T("TestXform"), ACRX_CMD_MODAL, &testXform); cmdStack->addCommand(appname, _T("ArxDbgTestEntMake"), _T("TestEntMake"), ACRX_CMD_MODAL, &testEntMake); cmdStack->addCommand(appname, _T("ArxDbgTestTblMake"), _T("TestTblMake"), ACRX_CMD_MODAL, &testTblMake); cmdStack->addCommand(appname, _T("ArxDbgTestExtents"), _T("TestExtents"), ACRX_CMD_MODAL, &testExtents); cmdStack->addCommand(appname, _T("ArxDbgTestIntersect"), _T("TestIntersect"), ACRX_CMD_MODAL, &testIntersect); cmdStack->addCommand(appname, _T("ArxDbgTestGetGripPoints"), _T("TestGetGripPoints"), ACRX_CMD_MODAL, &testGetGripPoints); cmdStack->addCommand(appname, _T("ArxDbgTestGetStretchPoints"), _T("TestGetStretchPoints"), ACRX_CMD_MODAL, &testGetStretchPoints); cmdStack->addCommand(appname, _T("ArxDbgTestGetOsnapPoints"), _T("TestGetOsnapPoints"), ACRX_CMD_MODAL, &testGetOsnapPoints); cmdStack->addCommand(appname, _T("ArxDbgTestExtDictAdd"), _T("TestExtDictAdd"), ACRX_CMD_MODAL, &testExtDictAdd); cmdStack->addCommand(appname, _T("ArxDbgTestExtDictRemove"), _T("TextExtDictRemove"), ACRX_CMD_MODAL, &testExtDictRemove); cmdStack->addCommand(appname, _T("ArxDbgTestTransDbClones"), _T("TestTransDbClones"), ACRX_CMD_MODAL, &testTransDatabaseClones); cmdStack->addCommand(appname, _T("ArxDbgTestXdata"), _T("TestXdata"), ACRX_CMD_MODAL, &testXdata); cmdStack->addCommand(appname, _T("ArxDbgTestColor"), _T("TestColor"), ACRX_CMD_MODAL, &testColor); cmdStack->addCommand(appname, _T("ArxDbgTestCurve"), _T("TestCurve"), ACRX_CMD_MODAL, &testCurve); cmdStack->addCommand(appname, _T("ArxDbgTestPruge"), _T("TestPurge"), ACRX_CMD_MODAL, &testPurge); cmdStack->addCommand(appname, _T("ArxDbgTestCountHardRefs"), _T("TestCountHardRefs"), ACRX_CMD_MODAL, &testCountReferences); cmdStack->addCommand(appname, _T("ArxDbgTestWblockCloneObjects"), _T("TestWblockCloneObjects"), ACRX_CMD_MODAL, &testWblockCloneObjects); cmdStack->addCommand(appname, _T("ArxDbgTestWorldDraw"), _T("TestWorldDraw"), ACRX_CMD_MODAL, &testWorldDraw); cmdStack->addCommand(appname, _T("ArxDbgTestDwgFiler"), _T("TestDwgFiler"), ACRX_CMD_MODAL, &testDwgFiler); cmdStack->addCommand(appname, _T("ArxDbgTestSelSet"), _T("TestSelSet"), (ACRX_CMD_MODAL | ACRX_CMD_USEPICKSET), &testSelSet); } /**************************************************************************** ** ** ArxDbgCmdTests::testState ** display the information available for a given entity. ** ** **jma ** *************************************/ void ArxDbgCmdTests::testState() { AcDbObjectId objId; if (!ArxDbgUtils::selectEntity(_T("\nSelect an entity: "), objId)) return; ArxDbgUiDlgObjState dbox(acedGetAcadDwgView(), objId); dbox.DoModal(); } /**************************************************************************** ** ** ArxDbgCmdTests::testXform ** display the information available for a given entity (but possibly nested ** within a block or xref). ** ** **jma ** *************************************/ void ArxDbgCmdTests::testXform() { XformDbox dbox(acedGetAcadDwgView()); dbox.DoModal(); } /**************************************************************************** ** ** ArxDbgCmdTests::testEntMake ** ** **jma ** *************************************/ void ArxDbgCmdTests::testEntMake() { EntMakeDbox dbox(acedGetAcadDwgView()); dbox.DoModal(); } /**************************************************************************** ** ** ArxDbgCmdTests::testTblMake ** ** **jma ** *************************************/ void ArxDbgCmdTests::testTblMake() { TblMakeDbox dbox(acedGetAcadDwgView()); dbox.DoModal(); } /************************************************************************ ** ** ArxDbgCmdTests::makePointEnt ** make a point entity so you can debug where stuff is ** ** **jma ** ***********************************/ void ArxDbgCmdTests::makePointEnt(const AcGePoint3d& pt, int colorIndex) { int mode = 0; getSysVar(_T("pdmode"), mode); if (mode == 0) setSysVar(_T("pdmode"), 99); AcDbPoint* tmpPt = new AcDbPoint(pt); tmpPt->setColorIndex(colorIndex); ArxDbgUtils::addToCurrentSpaceAndClose(tmpPt); } /**************************************************************************** ** ** ArxDbgCmdTests::extMakeAFace ** Used by testExtents to assist in making a AcDbFace entity. ** ** **jma ** *************************************/ void ArxDbgCmdTests::extMakeAFace(AcDbBlockTableRecord* blkRec, const AcGePoint3d& pt1, const AcGePoint3d& pt2, const AcGePoint3d& pt3, const AcGePoint3d& pt4) { AcDbFace* face = new AcDbFace; face->setVertexAt(0, pt1); face->setVertexAt(1, pt2); face->setVertexAt(2, pt3); face->setVertexAt(3, pt4); Acad::ErrorStatus es = blkRec->appendAcDbEntity(face); if (es != Acad::eOk) ArxDbgUtils::rxErrorAlert(es); face->close(); } /**************************************************************************** ** ** ArxDbgCmdTests::testExtents ** ** **jma ** *************************************/ void ArxDbgCmdTests::testExtents() { AcDbEntity* obj; AcGePoint3d p1, p2, p3, p4, p5, p6, p7, p8; Acad::ErrorStatus es; CString str; double deltaX, deltaY, deltaZ; AcGePoint3d centerPt; AcDbBlockTableRecord* newBlkRec; AcDbBlockReference* blkRef; AcGeVector3d offset; AcDbObjectId newBlockId; while (1) { if ((obj = ArxDbgUtils::selectEntity(nullptr, AcDb::kForRead)) == nullptr) return; AcDbExtents* extents = new AcDbExtents; // have to allocate fresh each time or it just grows! if ((es = obj->getGeomExtents(*extents)) != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); obj->close(); delete extents; continue; } acutPrintf(_T("\nEXTMIN: %s"), ArxDbgUtils::ptToStr(extents->minPoint(), str)); acutPrintf(_T("\nEXTMAX: %s"), ArxDbgUtils::ptToStr(extents->maxPoint(), str)); centerPt = ArxDbgUtilsGe::midpoint(extents->minPoint(), extents->maxPoint()); acutPrintf(_T("\nCENTER PT: %s"), ArxDbgUtils::ptToStr(centerPt, str)); deltaX = fabs(extents->maxPoint().x - extents->minPoint().x); deltaY = fabs(extents->maxPoint().y - extents->minPoint().y); deltaZ = fabs(extents->maxPoint().z - extents->minPoint().z); p1 = extents->minPoint(); p7 = extents->maxPoint(); delete extents; // make bottom face p2.set(p1.x + deltaX, p1.y, p1.z); p3.set(p2.x, p2.y + deltaY, p2.z); p4.set(p1.x, p1.y + deltaY, p1.z); // project up by Z p5.set(p1.x, p1.y, p1.z + deltaZ); p6.set(p2.x, p2.y, p2.z + deltaZ); p8.set(p4.x, p4.y, p4.z + deltaZ); offset = centerPt.asVector(); // move points so that they are centered at WCS origin // for block creation. Express everything in WCS since // that is what AcDbEntity::geomExtents() works in. p1 -= offset; p2 -= offset; p3 -= offset; p4 -= offset; p5 -= offset; p6 -= offset; p7 -= offset; p8 -= offset; // make an anonymous block that envelops the entity if (ArxDbgUtils::defineNewAnonymousBlock(newBlkRec, newBlockId, acdbHostApplicationServices()->workingDatabase()) != Acad::eOk) { obj->close(); return; } extMakeAFace(newBlkRec, p1, p2, p3, p4); // bottom face extMakeAFace(newBlkRec, p5, p6, p7, p8); // top face extMakeAFace(newBlkRec, p1, p2, p6, p5); // front face extMakeAFace(newBlkRec, p2, p3, p7, p6); // right side face extMakeAFace(newBlkRec, p3, p4, p8, p7); // back side face extMakeAFace(newBlkRec, p4, p1, p5, p8); // left side face newBlkRec->close(); // insert the block into the drawing blkRef = new AcDbBlockReference; if (blkRef->setBlockTableRecord(newBlockId) != Acad::eOk) { delete blkRef; obj->close(); return; } blkRef->setPosition(centerPt); blkRef->setDatabaseDefaults(); ArxDbgUtils::addToCurrentSpaceAndClose(blkRef); obj->close(); } } /**************************************************************************** ** ** ArxDbgCmdTests::testIntersect ** ** **jma ** *************************************/ void ArxDbgCmdTests::testIntersect() { AcDbEntity* obj1; AcDbEntity* obj2; AcGePoint3dArray points; int i, len; CString str; Acad::ErrorStatus es; AcGePoint3d pt1, pt2; AcDb::Intersect intType; // get intersection type from user ArxDbgUiPrKeyWord prIntType(_T("Extend objects [None/First/Second/Both]"), _T("None First Second Both")); if (prIntType.go() != ArxDbgUiPrBase::kOk) return; if (prIntType.isKeyWordPicked(_T("None"))) intType = AcDb::kOnBothOperands; else if (prIntType.isKeyWordPicked(_T("First"))) intType = AcDb::kExtendThis; else if (prIntType.isKeyWordPicked(_T("Second"))) intType = AcDb::kExtendArg; else intType = AcDb::kExtendBoth; while (1) { if ((obj1 = ArxDbgUtils::selectEntity(_T("\nSelect first entity: "), AcDb::kForRead)) == nullptr) return; if ((obj2 = ArxDbgUtils::selectEntity(_T("\nSelect intersecting entity: "), AcDb::kForRead)) == nullptr) { obj1->close(); return; } es = obj1->intersectWith(obj2, intType, points); if (es == Acad::eOk) { len = points.length(); if (len == 0) acutPrintf(_T("\nObjects do not intersect!")); else { for (i=0;i<len;i++) { acutPrintf(_T("\nINTERSECT PT: %s"), ArxDbgUtils::ptToStr(points[i], str)); makePointEnt(points[i], 3); } points.setLogicalLength(0); } } else ArxDbgUtils::rxErrorMsg(es); obj1->close(); obj2->close(); } } /**************************************************************************** ** ** ArxDbgCmdTests::testGetGripPoints ** ** **jma ** *************************************/ void ArxDbgCmdTests::testGetGripPoints() { AcDbEntity* obj; AcGePoint3dArray gripPoints; AcDbIntArray osnapModes, geomIds; Acad::ErrorStatus es; CString str; while (1) { if ((obj = ArxDbgUtils::selectEntity(nullptr, AcDb::kForRead)) == nullptr) return; // empty previous loops results gripPoints.setLogicalLength(0); osnapModes.setLogicalLength(0); geomIds.setLogicalLength(0); es = obj->getGripPoints(gripPoints, osnapModes, geomIds); if (es == Acad::eOk) { int i; // print out grip points if (gripPoints.isEmpty()) acutPrintf(_T("\nNo grip points specified!")); for (i=0; i<gripPoints.length(); i++) { acutPrintf(_T("\nGRIP[%d]: %s"), i, ArxDbgUtils::ptToStr(gripPoints[i], str)); makePointEnt(gripPoints[i], 2); } // print out osnap modes if (osnapModes.isEmpty()) acutPrintf(_T("\nNo osnap modes specified!")); for (i=0; i<osnapModes.length(); i++) acutPrintf(_T("\nOSNAP MODE[%d]: %s"), i, ArxDbgUtils::osnapToStr(osnapModes[i], str)); // print out geomIds if (geomIds.isEmpty()) acutPrintf(_T("\nNo geomIds specified!")); for (i=0; i<geomIds.length(); i++) acutPrintf(_T("\nGEOM ID[%d]: %s"), i, ArxDbgUtils::intToStr(geomIds[i], str)); } else ArxDbgUtils::rxErrorMsg(es); obj->close(); } } /**************************************************************************** ** ** ArxDbgCmdTests::testGetStretchPoints ** ** **jma ** *************************************/ void ArxDbgCmdTests::testGetStretchPoints() { AcDbEntity* obj; AcGePoint3dArray stretchPoints; Acad::ErrorStatus es; CString str; while (1) { if ((obj = ArxDbgUtils::selectEntity(nullptr, AcDb::kForRead)) == nullptr) return; stretchPoints.setLogicalLength(0); // empty previous results es = obj->getStretchPoints(stretchPoints); if (es == Acad::eOk) { if (stretchPoints.isEmpty()) acutPrintf(_T("\nNo stretch points specified!")); // print out grip points for (int i=0; i<stretchPoints.length(); i++) { acutPrintf(_T("\nSTRETCH[%d]: %s"), i, ArxDbgUtils::ptToStr(stretchPoints[i], str)); makePointEnt(stretchPoints[i], 1); } } else ArxDbgUtils::rxErrorMsg(es); } } /**************************************************************************** ** ** ArxDbgCmdTests::printSnapPts ** ** **jma ** *************************************/ void ArxDbgCmdTests::printSnapPts(LPCTSTR typeStr, const AcGePoint3dArray& pts, Acad::ErrorStatus es) { CString str; acutPrintf(_T("\nSnap Points for: %s"), typeStr); if (es == Acad::eOk) { if (pts.isEmpty()) acutPrintf(_T("\nNo snap points specified!")); // print out snap points for (int i=0; i<pts.length(); i++) { acutPrintf(_T("\nOSNAP[%d]: %s"), i, ArxDbgUtils::ptToStr(pts[i], str)); makePointEnt(pts[i], 1); } } else ArxDbgUtils::rxErrorMsg(es); } /**************************************************************************** ** ** ArxDbgCmdTests::testGetOsnapPoints ** ** **jma ** *************************************/ void ArxDbgCmdTests::testGetOsnapPoints() { AcDbEntity* obj; AcGePoint3dArray snapPoints; AcDbIntArray geomIds; Acad::ErrorStatus es; ArxDbgUiPrPoint prPickPt(_T("Point picked"), nullptr); AcGePoint3d tmpPt; while (1) { if ((obj = ArxDbgUtils::selectEntity(nullptr, AcDb::kForRead)) == nullptr) return; if (prPickPt.go() != ArxDbgUiPrBase::kOk) { obj->close(); return; } tmpPt = ArxDbgUtils::ucsToWcs(prPickPt.value()); es = obj->getOsnapPoints(AcDb::kOsModeNear, 0, tmpPt, tmpPt, AcGeMatrix3d::kIdentity, snapPoints, geomIds); printSnapPts(_T("END"), snapPoints, es); snapPoints.setLogicalLength(0); // empty previous results geomIds.setLogicalLength(0); es = obj->getOsnapPoints(AcDb::kOsModeCen, 0, tmpPt, tmpPt, AcGeMatrix3d::kIdentity, snapPoints, geomIds); printSnapPts(_T("CEN"), snapPoints, es); snapPoints.setLogicalLength(0); // empty previous results geomIds.setLogicalLength(0); obj->close(); } } /**************************************************************************** ** ** ArxDbgCmdTests::testExtDictAdd ** ** **jma ** *************************************/ void ArxDbgCmdTests::testExtDictAdd() { AcDbObjectId objId; AcDbObject* obj; CString str; if (!ArxDbgUtils::selectEntityOrObject(objId)) return; ArxDbgUiPrString prKey(_T("Key to store under"), false); ArxDbgUiPrString prTestStr(_T("Test string to store"), false); if ((prKey.go() != ArxDbgUiPrBase::kOk) || (prTestStr.go() != ArxDbgUiPrBase::kOk)) return; Acad::ErrorStatus es = acdbOpenAcDbObject(obj, objId, AcDb::kForWrite); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); return; } AcDbDictionary* extDict = ArxDbgUtils::openExtDictForWrite(obj, true); if (extDict) { if (extDict->has(prKey.value())) { acutPrintf(_T("\n\"%s\" is already in the extension dictionary."), static_cast<LPCTSTR>(prKey.value())); } else { // make an Xrecord to stick into the dictionary AcDbXrecord* xRec = new AcDbXrecord; resbuf* rb = acutBuildList(2, static_cast<LPCTSTR>(prTestStr.value()), 0); xRec->setFromRbChain(*rb); AcDbObjectId newObjId; es = extDict->setAt(static_cast<LPCTSTR>(prKey.value()), xRec, newObjId); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); delete xRec; } else { acutPrintf(_T("\nAdded it to the dictionary!")); xRec->close(); } } extDict->close(); } else acutPrintf(_T("\nERROR: couldn't get extension dictionary")); obj->close(); } /**************************************************************************** ** ** ArxDbgCmdTests::testExtDictRemove ** remove an extension dictionary on an entity. ** ** **jma ** *************************************/ void ArxDbgCmdTests::testExtDictRemove() { AcDbObject* obj; AcDbObjectId objId; if (!ArxDbgUtils::selectEntityOrObject(objId)) return; Acad::ErrorStatus es = acdbOpenAcDbObject(obj, objId, AcDb::kForWrite); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); return; } AcDbObjectId extDictId = obj->extensionDictionary(); if (extDictId == AcDbObjectId::kNull) { acutPrintf(_T("\nThere was no extension dictionary attaced to this object!")); } else { AcDbDictionary* extDict; Acad::ErrorStatus es; es = acdbOpenObject(extDict, extDictId, AcDb::kForRead); if (es == Acad::eOk) { int numEntries = extDict->numEntries(); extDict->close(); if (numEntries != 0) acutPrintf(_T("\nExtension dict not empty, cannot be removed.")); else { es = obj->releaseExtensionDictionary(); if (es == Acad::eOk) acutPrintf(_T("\nRemoved extension dictionary!")); else ArxDbgUtils::rxErrorMsg(es); } } else ArxDbgUtils::rxErrorMsg(es); } obj->close(); } /**************************************************************************** ** ** ArxDbgCmdTests::testTransDatabaseClones ** ** **jma ** *************************************/ void ArxDbgCmdTests::testTransDatabaseClones() { ArxDbgUiTdmTransDbClones dbox(acedGetAcadDwgView()); dbox.DoModal(); } // used for following Xdata test #define XDT_AGE 20000 #define XDT_RANK 20001 #define XDT_BIRTHDAY 20002 #define XDT_FAVORITE_ANIMALS 20003 #define XDT_MISC 20004 /**************************************************************************** ** ** ArxDbgCmdTests::testGetXdata ** ** **jma ** *************************************/ void ArxDbgCmdTests::testGetXdata(ArxDbgAppXdata& xdata1, ArxDbgAppXdata& xdata2) { CString str; int intVal; double realVal; // get the birthday field if (xdata1.getString(XDT_BIRTHDAY, str)) acutPrintf(_T("\nBirthday is: %s"), str); else ArxDbgUtils::stopAlertBox(_T("Couldn't get birthday")); // try getting a bogus value if (xdata1.getInteger(99999, intVal)) acutPrintf(_T("\nBOGUS VAL: %d"), intVal); else acutPrintf(_T("\nCouldn't get bogus tag 99999")); // get uniform Animal list, and walk it ArxDbgXdataList list1; xdata1.getList(XDT_FAVORITE_ANIMALS, list1); ArxDbgXdataListIterator iter1(list1); while (iter1.getString(str)) acutPrintf(_T("\nANIMAL: %s"), str); // get non-uniform list and retrieve values // expecting string/int/real in order ArxDbgXdataList list2; xdata2.getList(XDT_MISC, list2); ArxDbgXdataListIterator iter2(list2); if ((iter2.getString(str)) && (iter2.getInteger(intVal)) && (iter2.getReal(realVal))) acutPrintf(_T("\nVALUES: %s, %d, %lf"), str, intVal, realVal); else acutPrintf(_T("\nERROR: values not in expected format!")); } /**************************************************************************** ** ** ArxDbgCmdTests::testXdata ** ** **jma ** *************************************/ void ArxDbgCmdTests::testXdata() { AcDbObjectId objId; AcDbObject* obj; if (!ArxDbgUtils::selectEntityOrObject(objId)) return; Acad::ErrorStatus es = acdbOpenAcDbObject(obj, objId, AcDb::kForWrite); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); return; } // add xdata for first app ArxDbgUtils::infoAlertBox(_T("add Xdata for Son #1")); ArxDbgAppXdata connor(_T("CONNOR"), obj->database()); connor.setDistance(XDT_AGE, 6.0); connor.setInteger(XDT_RANK, 1); connor.setString(XDT_BIRTHDAY, _T("January 14, 1993")); // add in a uniform list ArxDbgXdataList list1; list1.appendString(_T("Tiger")); list1.appendString(_T("Lion")); list1.appendString(_T("Wolf")); connor.setList(XDT_FAVORITE_ANIMALS, list1); connor.setXdata(obj); ArxDbgUiDlgXdata dbox1(acedGetAcadDwgView(), obj); dbox1.DoModal(); // add xdata for second app ArxDbgUtils::infoAlertBox(_T("add Xdata for Son #2")); ArxDbgAppXdata mason(_T("MASON"), obj->database()); mason.setDistance(XDT_AGE, 4.2); mason.setInteger(XDT_RANK, 2); mason.setString(XDT_BIRTHDAY, _T("November 22, 1994")); // add in a non-uniform list ArxDbgXdataList list2; list2.appendString(_T("String 1")); list2.appendInteger(44); list2.appendReal(33.33); mason.setList(XDT_MISC, list2); mason.setXdata(obj); ArxDbgUiDlgXdata dbox2(acedGetAcadDwgView(), obj); dbox2.DoModal(); // try retrieving some values ArxDbgUtils::infoAlertBox(_T("Retrieve Xdata values")); connor.getXdata(obj); // no real reason to get again, but what the hell mason.getXdata(obj); // no real reason to get again, but what the hell testGetXdata(connor, mason); // try editing some values ArxDbgUtils::infoAlertBox(_T("Remove Birthday and change age.")); connor.getXdata(obj); // no real reason to get again, but what the hell connor.remove(XDT_BIRTHDAY); connor.setDistance(XDT_AGE, 30.11); // change to my age connor.setXdata(obj); ArxDbgUiDlgXdata dbox3(acedGetAcadDwgView(), obj); dbox3.DoModal(); obj->close(); } /**************************************************************************** ** ** ArxDbgCmdTests::testColor ** ** **jma ** *************************************/ void ArxDbgCmdTests::testColor() { ArxDbgUiDlgColor dbox(acedGetAcadDwgView()); dbox.DoModal(); } /**************************************************************************** ** ** ArxDbgCmdTests::testCurve ** ** **jma ** *************************************/ void ArxDbgCmdTests::testCurve() { ArxDbgUiDlgTestCurve dbox(acedGetAcadDwgView()); dbox.DoModal(); } /**************************************************************************** ** ** ArxDbgCmdTests::testPurge ** ** **jma ** *************************************/ void ArxDbgCmdTests::testPurge() { AcDbObjectIdArray objIds; AcDbObjectId objId; acutPrintf(_T("\nSelect items to purge: ")); while (ArxDbgUtils::getEntityOrObject(objId)) { if (objIds.contains(objId) == Adesk::kFalse) objIds.append(objId); } if (objIds.isEmpty()) { acutPrintf(_T("\nNothing selected!")); return; } AcDbObjectIdArray purgableIds(objIds); Acad::ErrorStatus es = acdbHostApplicationServices()->workingDatabase()->purge(purgableIds); if (es != Acad::eOk) { acutPrintf(_T("\nPurge operation failed: %s"), ArxDbgUtils::rxErrorStr(es)); return; } CString str; AcDbObject* obj; for (AcDbObjectId id : objIds) { es = acdbOpenObject(obj, id, AcDb::kForRead, Adesk::kTrue); if (es == Acad::eOk) { ASSERT(obj->database() == acdbHostApplicationServices()->workingDatabase()); // made an assumption above that user stayed in same database acutPrintf(_T("\n<CLASS: %-20s HANDLE: %-4s>"), ArxDbgUtils::objToClassStr(obj), ArxDbgUtils::objToHandleStr(obj, str)); if (purgableIds.contains(id)) acutPrintf(_T(" (Purgable)")); else acutPrintf(_T(" (UnPurgable)")); obj->close(); } else ArxDbgUtils::rxErrorMsg(es); } } /**************************************************************************** ** ** ArxDbgCmdTests::testCountReferences ** ** **jma ** *************************************/ void ArxDbgCmdTests::testCountReferences() { AcDbObjectIdArray objIds; AcDbObjectId objId; acutPrintf(_T("\nSelect items to count references: ")); while (ArxDbgUtils::getEntityOrObject(objId)) { if (objIds.contains(objId) == Adesk::kFalse) objIds.append(objId); } int len = objIds.length(); if (len == 0) { acutPrintf(_T("\nNothing selected!")); return; } Adesk::UInt32* countArray = new Adesk::UInt32[len]; int i; for (i=0; i<len; i++) countArray[i] = 0; // init count values; Acad::ErrorStatus es = acdbHostApplicationServices()->workingDatabase()->countHardReferences(objIds, countArray); if (es != Acad::eOk) { ArxDbgUtils::rxErrorMsg(es); delete [] countArray; return; } CString str; AcDbObject* obj; len = objIds.length(); for (i=0; i<len; i++) { es = acdbOpenAcDbObject(obj, objIds[i], AcDb::kForRead); if (es == Acad::eOk) { ASSERT(obj->database() == acdbHostApplicationServices()->workingDatabase()); // made an assumption above that user stayed in same database acutPrintf(_T("\n<CLASS: %-20s HANDLE: %-4s>"), ArxDbgUtils::objToClassStr(obj), ArxDbgUtils::objToHandleStr(obj, str)); acutPrintf(_T(" (Count = %d)"), countArray[i]); obj->close(); } else { ArxDbgUtils::rxErrorMsg(es); } } delete [] countArray; } /**************************************************************************** ** ** ArxDbgCmdTests::testWblockCloneObjects ** ** **jma ** *************************************/ void ArxDbgCmdTests::testWblockCloneObjects() { ArxDbgSelSet ss; if (ss.userSelect() != ArxDbgSelSet::kSelected) return; acutPrintf(_T("\nDuplicate Record Options:")); acutPrintf(_T("\n 0 = kDrcNotApplicable")); acutPrintf(_T("\n 1 = kDrcIgnore")); acutPrintf(_T("\n 2 = kDrcReplace")); acutPrintf(_T("\n 3 = kDrcXrefMangleName")); acutPrintf(_T("\n 4 = kDrcMangleName")); acutPrintf(_T("\n 5 = kDrcUnmangleName")); ArxDbgUiPrIntDef prDrc(_T("Duplicate record type"), nullptr, ArxDbgUiPrInt::kRange, AcDb::kDrcIgnore); prDrc.setRange(AcDb::kDrcNotApplicable, AcDb::kDrcUnmangleName); if (prDrc.go() != ArxDbgUiPrBase::kOk) return; AcDbObjectIdArray cloneSet; ss.asArray(cloneSet); Acad::ErrorStatus es; AcDbObjectId destBlkId; AcApDocumentIterator* iter = acDocManager->newAcApDocumentIterator(); AcApDocument* curDoc = acDocManager->curDocument(); AcDbDatabase* fromDb = curDoc->database(); if (iter) { AcApDocument* tmpDoc; for (; !iter->done(); iter->step()) { tmpDoc = iter->document(); if (tmpDoc) { if (tmpDoc != curDoc) { es = acDocManager->setCurDocument(tmpDoc, AcAp::kWrite); if (es == Acad::eOk) { AcDbIdMapping idMap; idMap.setDestDb(tmpDoc->database()); destBlkId = tmpDoc->database()->currentSpaceId(); es = fromDb->wblockCloneObjects(cloneSet, destBlkId, idMap, static_cast<AcDb::DuplicateRecordCloning>(prDrc.value())); acDocManager->unlockDocument(tmpDoc); // Unlock the doc when done... ArxDbgUtils::rxErrorMsg(es); } else { ArxDbgUtils::rxErrorMsg(es); } } } else { ASSERT(0); } } delete iter; } acDocManager->setCurDocument(curDoc); } /**************************************************************************** ** ** ArxDbgCmdTests::testWorldDraw ** ** **jma ** *************************************/ void ArxDbgCmdTests::testWorldDraw() { ArxDbgGiWorldDraw wd; ArxDbgUiDlgWorldDraw dbox(wd, acedGetAcadDwgView()); if (dbox.DoModal() != IDOK) return; AcDbEntity* ent; Adesk::Boolean didWorldDraw; while (1) { ent = ArxDbgUtils::selectEntity(_T("\nSelect entity to test worldDraw(): "), AcDb::kForRead); if (ent) { // set up initial properties to draw with wd.setInitialProps(ent); didWorldDraw = ent->worldDraw(&wd); if (!didWorldDraw) acutPrintf(_T("\nDo viewportDraw()...")); ent->close(); acutPrintf(_T("\n\n********************************************************\n")); } else break; } } /**************************************************************************** ** ** ArxDbgCmdTests::testDwgFiler ** ** **jma ** *************************************/ void ArxDbgCmdTests::testDwgFiler() { ArxDbgUiDlgFilerTest dbox(acedGetAcadDwgView()); if (dbox.DoModal() != IDOK) return; AcDbObjectId objId; AcDbObject* obj; Acad::ErrorStatus es; AcDb::FilerType fType = dbox.indexToFilerType(dbox.m_puFilerTypeIndex); // skirt around bug in R14... and now Tahoe if (fType == AcDb::kFileFiler) { ArxDbgUtils::alertBox(_T("ERROR: FileFiler currently crashes AutoCAD due to blind casting... Setting to CopyFiler instead.")); fType = AcDb::kCopyFiler; } CString str; ArxDbgDwgFiler dwgFiler; dwgFiler.setFilerType(fType); while (ArxDbgUtils::selectEntityOrObject(objId)) { acutPrintf(_T("\n\n*******************************************************\n")); if (acdbOpenAcDbObject(obj, objId, AcDb::kForRead) == Acad::eOk) { acutPrintf(_T("\nFiler for: %s\n"), ArxDbgUtils::objToClassAndHandleStr(obj, str)); es = obj->dwgOut(&dwgFiler); if (es != Acad::eOk) ArxDbgUtils::rxErrorAlert(es); obj->close(); } dwgFiler.resetFilerStatus(); acutPrintf(_T("\n\n*******************************************************\n")); } } /**************************************************************************** ** ** ArxDbgCmdTests::testSelSet ** ** **jma ** *************************************/ void ArxDbgCmdTests::testSelSet() { ArxDbgUiDlgSelSet dbox(acedGetAcadDwgView()); dbox.DoModal(); }
29.961261
154
0.547013
[ "object" ]
41839f35c72dd00da931220ae9afe2a2a34e0895
440
cpp
C++
HackerRank/Algorithms/Implementation/bigger_is_greater.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
HackerRank/Algorithms/Implementation/bigger_is_greater.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
HackerRank/Algorithms/Implementation/bigger_is_greater.cpp
nsudhanva/Competetive
d9e93fdeefaa4e422a2101db41a7ab0a5676e9da
[ "Unlicense" ]
null
null
null
#include <cmath> #include <cstdio> #include <cstring> #include <vector> #include <iostream> #include <algorithm> #define MAX 1000000 using namespace std; int main() { int n; char s[MAX]; cin >> n; while(n--) { cin >> s; int len; len = strlen(s); if(next_permutation(s, s+len)) cout << s << endl; else cout << "no answer" << endl; } return 0; }
15.172414
40
0.509091
[ "vector" ]
4187709c7e9578dc6a782984d8082e7b0eefcaab
5,367
cpp
C++
src/Components/AnimationComponent.cpp
scawful/project-awful
ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6
[ "MIT" ]
4
2021-05-12T15:02:40.000Z
2021-06-04T23:01:16.000Z
src/Components/AnimationComponent.cpp
scawful/project-awful
ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6
[ "MIT" ]
null
null
null
src/Components/AnimationComponent.cpp
scawful/project-awful
ebf5908b4a9e9fc0b12bf24cb8c7e21983d88ba6
[ "MIT" ]
9
2021-05-13T21:54:52.000Z
2021-12-11T01:55:55.000Z
#include "AnimationComponent.hpp" /** * @brief Construct a new Animation Component:: Animation Component object * @author @scawful * * @param sprite * @param texture_sheet */ AnimationComponent::AnimationComponent(sf::Sprite& sprite, sf::Texture& texture_sheet) : sprite(sprite), textureSheet(texture_sheet), lastAnimation(NULL), priorityAnimation(NULL) { } /** * @brief Destroy the Animation Component:: Animation Component object * @author @scawful * */ AnimationComponent::~AnimationComponent() { for ( auto &i : this->animations ) { delete i.second; } } // Accessors /** * @brief Report if the animation for the parameter is finished executing * @author @scawful * * @param key * @return true * @return false */ const bool & AnimationComponent::isDone(const std::string key) { return this->animations[key]->isDone(); } /** * @brief Add a new animation with the given parameters to the component * @author @scawful * * @param key * @param animation_timer * @param start_frame_x * @param start_frame_y * @param frames_x * @param frames_y * @param width * @param height */ void AnimationComponent::addAnimation( const std::string key, float animation_timer, int start_frame_x, int start_frame_y, int frames_x, int frames_y, int width, int height ) { this->animations[key] = new Animation( this->sprite, this->textureSheet, animation_timer, start_frame_x, start_frame_y, frames_x, frames_y, width, height ); } /** * @brief Play an animation based on the requested key and if applicable priority status * @author @scawful * * @param key * @param dt * @param priority * @return true * @return false */ const bool& AnimationComponent::play(const std::string key, const float & dt, const bool priority) { if ( priority ) { this->priorityAnimation = this->animations[key]; } // priority animations play on top of any existing animations // they are discarded upon completion if ( this->priorityAnimation ) { if ( this->priorityAnimation == this->animations[key] ) { if ( this->lastAnimation != this->animations[key] ) { if ( this->lastAnimation == NULL ) { this->lastAnimation = this->animations[key]; } else { this->lastAnimation->reset(); this->lastAnimation = this->animations[key]; } } // if priority animation is done, remove it if (this->animations[key]->play(dt)) { this->priorityAnimation = NULL; } } } else { if ( priority ) { this->priorityAnimation = this->animations[key]; } if ( this->lastAnimation != this->animations[key] ) { if ( this->lastAnimation == NULL ) { this->lastAnimation = this->animations[key]; } else { this->lastAnimation->reset(); this->lastAnimation = this->animations[key]; } } this->animations[key]->play(dt); } return this->animations[key]->isDone(); } /** * @brief Overloaded play with added modifier for speed * @author @scawful * * @param key * @param dt * @param modifier * @param modifier_max * @param priority * @return true * @return false */ const bool& AnimationComponent::play(const std::string key, const float& dt, const float& modifier, const float& modifier_max, const bool priority) { if (priority) { this->priorityAnimation = this->animations[key]; } if ( this->priorityAnimation ) { if ( this->priorityAnimation == this->animations[key] ) { if ( this->lastAnimation != this->animations[key] ) { if ( this->lastAnimation == NULL ) { this->lastAnimation = this->animations[key]; } else { this->lastAnimation->reset(); this->lastAnimation = this->animations[key]; } } // if priority animation is done, remove it if ( this->animations[key]->play(dt) ) { this->priorityAnimation = NULL; } } } else { if ( priority ) { this->priorityAnimation = this->animations[key]; } if ( this->lastAnimation != this->animations[key] ) { if ( this->lastAnimation == NULL ) { this->lastAnimation = this->animations[key]; } else { this->lastAnimation->reset(); this->lastAnimation = this->animations[key]; } } this->animations[key]->play(dt, abs(modifier / modifier_max)); } return this->animations[key]->isDone(); }
27.953125
148
0.526737
[ "object" ]
418c87799c12195cf139ebfc2be149b586ddd8c0
4,082
cpp
C++
Engine/Templates/DynamicStackArray.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
Engine/Templates/DynamicStackArray.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
Engine/Templates/DynamicStackArray.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
#ifndef SE_INCL_DYNAMICSTACKARRAY_CPP #define SE_INCL_DYNAMICSTACKARRAY_CPP #ifdef PRAGMA_ONCE #pragma once #endif #include <Engine/Templates/DynamicStackArray.h> #include <Engine/Templates/DynamicArray.cpp> /* * Default constructor. */ template<class Type> inline CDynamicStackArray<Type>::CDynamicStackArray(void) : CDynamicArray<Type>() { da_ctUsed=0; da_ctAllocationStep = 16; // lock the array on construction CDynamicArray<Type>::Lock(); } /* * Destructor. */ template<class Type> inline CDynamicStackArray<Type>::~CDynamicStackArray(void) { // lock the array on destruction CDynamicArray<Type>::Unlock(); }; /* Destroy all objects, and reset the array to initial (empty) state. */ template<class Type> inline void CDynamicStackArray<Type>::Clear(void) { CDynamicArray<Type>::Clear(); da_ctUsed = 0; } /* * Set how many elements to allocate when stack overflows. */ template<class Type> inline void CDynamicStackArray<Type>::SetAllocationStep(INDEX ctStep) { ASSERT(ctStep>0); da_ctAllocationStep = ctStep; }; /* * Add new object(s) on top of stack. */ template<class Type> inline Type &CDynamicStackArray<Type>::Push(void) { // if there are no free elements in the array if (CDynamicArray<Type>::Count()-da_ctUsed<1) { // alocate a new block CDynamicArray<Type>::New(da_ctAllocationStep); } // get the new element da_ctUsed++; ASSERT(da_ctUsed <= CDynamicArray<Type>::Count()); return CDynamicArray<Type>::operator[](da_ctUsed-1); } template<class Type> inline Type *CDynamicStackArray<Type>::Push(INDEX ct) { // if there are no free elements in the array while(CDynamicArray<Type>::Count()-da_ctUsed<ct) { // alocate a new block CDynamicArray<Type>::New(da_ctAllocationStep); } // get new elements da_ctUsed+=ct; ASSERT(da_ctUsed <= CDynamicArray<Type>::Count()); return &CDynamicArray<Type>::operator[](da_ctUsed-ct); } /* * Remove all objects from stack, but keep stack space. */ template<class Type> inline void CDynamicStackArray<Type>::PopAll(void) { // if there is only one block allocated if ( da_BlocksList.IsEmpty() || &da_BlocksList.Head()==&da_BlocksList.Tail()) { // just clear the counter da_ctUsed = 0; // if there is more than one block allocated } else { // remember how much was allocated, rounded up to allocation step INDEX ctUsedBefore = CDynamicArray<Type>::Count(); // free all memory CDynamicArray<Type>::Clear(); // allocate one big block //CDynamicArray<Type>::New(ctUsedBefore); da_ctUsed = 0; } } /* * Random access operator. */ template<class Type> inline Type &CDynamicStackArray<Type>::operator[](INDEX i) { ASSERT(this!=NULL); ASSERT(i<da_ctUsed); // check bounds return CDynamicArray<Type>::operator[](i); } template<class Type> inline const Type &CDynamicStackArray<Type>::operator[](INDEX i) const { ASSERT(this!=NULL); ASSERT(i<da_ctUsed); // check bounds return CDynamicArray<Type>::operator[](i); } /* * Get number of elements in array. */ template<class Type> INDEX CDynamicStackArray<Type>::Count(void) const { ASSERT(this!=NULL); return da_ctUsed; } /* * Get index of a member from it's pointer */ template<class Type> INDEX CDynamicStackArray<Type>::Index(Type *ptMember) { ASSERT(this!=NULL); INDEX i = CDynamicArray<Type>::Index(ptMember); ASSERTMSG(i<da_ctUsed, "CDynamicStackArray<>::Index(): Not a member of this array!"); return i; } /* * Get array of pointers to elements (used for sorting elements by sorting pointers). */ template<class Type> Type **CDynamicStackArray<Type>::GetArrayOfPointers(void) { return da_Pointers; } /* * Assignment operator. */ template<class Type> CDynamicStackArray<Type> &CDynamicStackArray<Type>::operator=(CDynamicStackArray<Type> &arOriginal) { ASSERT(this!=NULL); ASSERT(&arOriginal!=NULL); ASSERT(this!=&arOriginal); // copy stack arrays CDynamicArray<Type>::operator=(arOriginal); // copy used count da_ctUsed = arOriginal.da_ctUsed; return *this; } #endif /* include-once check. */
25.042945
99
0.709701
[ "object" ]
41906c33c063e8213c9653b136d275d21ae1780c
5,531
cpp
C++
src/libraries/turbulenceModels/mixture/VLES/VLESModel/mxVLESModel.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/turbulenceModels/mixture/VLES/VLESModel/mxVLESModel.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/turbulenceModels/mixture/VLES/VLESModel/mxVLESModel.cpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2015-2019 Applied CCM ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "mxVLESModel.hpp" #include "addToRunTimeSelectionTable.hpp" #ifdef windows extern "C" void mxVLESModelsLoad() {} #endif namespace CML { namespace mixture { defineTypeNameAndDebug(VLESModel, 0); defineRunTimeSelectionTable(VLESModel, dictionary); addToRunTimeSelectionTable(turbulenceModel, VLESModel, turbulenceModel); void VLESModel::printCoeffs() { if (printCoeffs_) { Info<< type() << "Coeffs" << coeffDict_ << endl; } } VLESModel::VLESModel ( const word& type, const volScalarField& rho, const volVectorField& U, const surfaceScalarField& phi, const twoPhaseMixture& transport, const word& turbulenceModelName ) : turbulenceModel(rho, U, phi, transport, turbulenceModelName), IOdictionary ( IOobject ( "VLESProperties", U.time().constant(), U.db(), IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE ) ), turbulence_(lookup("turbulence")), printCoeffs_(lookupOrDefault<Switch>("printCoeffs", false)), coeffDict_(subOrEmptyDict(type + "Coeffs")), kMin_("kMin", sqr(dimVelocity), SMALL), epsilonMin_("epsilonMin", kMin_.dimensions()/dimTime, SMALL), omegaMin_("omegaMin", dimless/dimTime, SMALL) { kMin_.readIfPresent(*this); epsilonMin_.readIfPresent(*this); omegaMin_.readIfPresent(*this); mesh_.deltaCoeffs(); } autoPtr<VLESModel> VLESModel::New ( const volScalarField& rho, const volVectorField& U, const surfaceScalarField& phi, const twoPhaseMixture& transport, const word& turbulenceModelName ) { // get model name, but do not register the dictionary // otherwise it is registered in the database twice const word modelType ( IOdictionary ( IOobject ( "VLESProperties", U.time().constant(), U.db(), IOobject::MUST_READ_IF_MODIFIED, IOobject::NO_WRITE, false ) ).lookup("VLESModel") ); Info<< "Selecting VLES turbulence model " << modelType << endl; dictionaryConstructorTable::iterator cstrIter = dictionaryConstructorTablePtr_->find(modelType); if (cstrIter == dictionaryConstructorTablePtr_->end()) { FatalErrorInFunction << "Unknown VLESModel type " << modelType << nl << nl << "Valid VLESModel types:" << endl << dictionaryConstructorTablePtr_->sortedToc() << exit(FatalError); } return autoPtr<VLESModel> ( cstrIter()(rho, U, phi, transport, turbulenceModelName) ); } tmp<volSymmTensorField> VLESModel::R() const { return tmp<volSymmTensorField> ( new volSymmTensorField ( IOobject ( "R", runTime_.timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), ((2.0/3.0)*I)*k() - mut()*twoSymm(fvc::grad(U_)), k()().boundaryField().types() ) )*Fr(); } tmp<volSymmTensorField> VLESModel::devRhoReff() const { const volScalarField muEff(mu() + mut()*Fr()); return tmp<volSymmTensorField> ( new volSymmTensorField ( IOobject ( "devRhoReff", runTime_.timeName(), mesh_, IOobject::NO_READ, IOobject::NO_WRITE ), -muEff*dev(twoSymm(fvc::grad(U_))) ) ); } tmp<fvVectorMatrix> VLESModel::divDevRhoReff(volVectorField& U) const { return ( - fvm::laplacian(mu(), U) - fvc::div(mu()*dev2(T(fvc::grad(U)))) - Fr()*(fvm::laplacian(mut(), U) + fvc::div(mut()*dev2(T(fvc::grad(U))))) ); } void VLESModel::correct() { turbulenceModel::correct(); } bool VLESModel::read() { bool ok = IOdictionary::readData ( IOdictionary::readStream ( IOdictionary::type() ) ); IOdictionary::close(); if (ok) { lookup("turbulence") >> turbulence_; if (dictionary const* dictPtr = subDictPtr(type() + "Coeffs")) { coeffDict_ <<= *dictPtr; } kMin_.readIfPresent(*this); epsilonMin_.readIfPresent(*this); omegaMin_.readIfPresent(*this); return true; } else { return false; } } } // End namespace mixture } // End namespace CML
24.152838
79
0.566444
[ "model" ]
4191a8d09198cfcdd7e83e94185a7a775eb349b5
20,765
cpp
C++
tests/src/system/test.cpp
hyperglitch/OpenDeck
f78cb720c678f0a675eb620b053c7bf84a041ebc
[ "Apache-2.0" ]
null
null
null
tests/src/system/test.cpp
hyperglitch/OpenDeck
f78cb720c678f0a675eb620b053c7bf84a041ebc
[ "Apache-2.0" ]
null
null
null
tests/src/system/test.cpp
hyperglitch/OpenDeck
f78cb720c678f0a675eb620b053c7bf84a041ebc
[ "Apache-2.0" ]
null
null
null
#ifndef USB_LINK_MCU #include "unity/Framework.h" #include "io/buttons/Buttons.h" #include "io/encoders/Encoders.h" #include "io/analog/Analog.h" #include "io/leds/LEDs.h" #include "io/touchscreen/Touchscreen.h" #include "io/common/CInfo.h" #include "system/System.h" #include "database/Database.h" #include "midi/src/MIDI.h" #include "core/src/general/Timing.h" #include "core/src/general/Helpers.h" #include "stubs/database/DB_ReadWrite.h" #include "helpers/MIDI.h" namespace { typedef struct { uint8_t channel; ///< MIDI channel on which the message was received (1-16) MIDI::messageType_t type; ///< The type of the message uint8_t data1; ///< First data byte (0-127) uint8_t data2; ///< Second data byte (0-127, 0 if message length is 2 bytes) } channelMIDImessage_t; std::vector<channelMIDImessage_t> channelMIDImessages; class SystemHWA : public System::HWA { public: SystemHWA() = default; bool init() override { return true; } void reset() { dinMIDIenabled = false; loopbackEnabled = false; } void reboot(FwSelector::fwType_t type) override { } void enableDINMIDI(bool loopback) override { dinMIDIenabled = true; loopbackEnabled = loopback; } void disableDINMIDI() override { dinMIDIenabled = false; loopbackEnabled = false; } void registerOnUSBconnectionHandler(System::usbConnectionHandler_t usbConnectionHandler) override { } bool dinMIDIenabled = false; bool loopbackEnabled = false; } hwaSystem; class HWAMIDI : public MIDI::HWA { public: HWAMIDI() = default; bool init() override { clear(); return true; } bool dinRead(uint8_t& data) override { if (!dinPacketToBoard.size()) return false; data = dinPacketToBoard.at(0); dinPacketToBoard.erase(dinPacketToBoard.begin()); return true; } bool dinWrite(uint8_t data) override { dinPacketFromBoard.push_back(data); return true; } bool usbRead(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { if (!usbPacketFromBoard.size()) return false; USBMIDIpacket = usbPacketFromBoard.at(0); usbPacketFromBoard.erase(usbPacketFromBoard.begin()); return true; } bool usbWrite(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { usbPacketToBoard.push_back(USBMIDIpacket); return true; } void clear() { usbPacketFromBoard.clear(); usbPacketToBoard.clear(); dinPacketToBoard.clear(); dinPacketFromBoard.clear(); } std::vector<MIDI::USBMIDIpacket_t> usbPacketFromBoard = {}; std::vector<MIDI::USBMIDIpacket_t> usbPacketToBoard = {}; std::vector<uint8_t> dinPacketToBoard = {}; std::vector<uint8_t> dinPacketFromBoard = {}; } hwaMIDI; class HWALEDs : public IO::LEDs::HWA { public: HWALEDs() {} void setState(size_t index, IO::LEDs::brightness_t brightness) override { } size_t rgbSignalIndex(size_t rgbIndex, IO::LEDs::rgbIndex_t rgbComponent) override { return 0; } size_t rgbIndex(size_t singleLEDindex) override { return 0; } } hwaLEDs; class HWAAnalog : public IO::Analog::HWA { public: HWAAnalog() {} bool value(size_t index, uint16_t& value) override { value = adcReturnValue; return true; } uint32_t adcReturnValue; } hwaAnalog; class HWAU8X8 : public IO::U8X8::HWAI2C { public: HWAU8X8() {} bool init() override { return true; } bool deInit() override { return true; } bool write(uint8_t address, uint8_t* data, size_t size) override { return true; } } hwaU8X8; class AnalogFilterStub : public IO::Analog::Filter { public: AnalogFilterStub() {} IO::Analog::adcType_t adcType() override { #ifdef ADC_12_BIT return IO::Analog::adcType_t::adc12bit; #else return IO::Analog::adcType_t::adc10bit; #endif } bool isFiltered(size_t index, IO::Analog::type_t type, uint16_t value, uint16_t& filteredValue) override { filteredValue = value; return true; } void reset(size_t index) override { } } analogFilter; class HWAButtons : public IO::Buttons::HWA { public: HWAButtons() {} bool state(size_t index, uint8_t& numberOfReadings, uint32_t& states) override { return false; } } hwaButtons; class ButtonsFilter : public IO::Buttons::Filter { public: bool isFiltered(size_t index, uint8_t& numberOfReadings, uint32_t& states) override { return true; } } buttonsFilter; class HWAEncoders : public IO::Encoders::HWA { public: HWAEncoders() {} bool state(size_t index, uint8_t& numberOfReadings, uint32_t& states) override { return false; } } hwaEncoders; class EncodersFilter : public IO::Encoders::Filter { public: bool isFiltered(size_t index, IO::Encoders::position_t position, IO::Encoders::position_t& filteredPosition, uint32_t sampleTakenTime) override { return true; } void reset(size_t index) override { } uint32_t lastMovementTime(size_t index) override { return 0; } } encodersFilter; DBstorageMock dbStorageMock; Database database(dbStorageMock, true); MIDI midi(hwaMIDI); ComponentInfo cInfo; IO::LEDs leds(hwaLEDs, database); IO::U8X8 u8x8(hwaU8X8); IO::Display display(u8x8, database); IO::Analog analog(hwaAnalog, analogFilter, database, midi, leds, display, cInfo); IO::Buttons buttons(hwaButtons, buttonsFilter, database, midi, leds, display, cInfo); IO::Encoders encoders(hwaEncoders, encodersFilter, 1, database, midi, display, cInfo); IO::Touchscreen touchscreen(database, cInfo); System systemStub(hwaSystem, cInfo, database, midi, buttons, encoders, analog, leds, display, touchscreen); void sendSysExRequest(const std::vector<uint8_t> request, std::vector<MIDI::USBMIDIpacket_t>& buffer) { class HWAFillMIDI : public MIDI::HWA { public: HWAFillMIDI(std::vector<MIDI::USBMIDIpacket_t>& buffer) : _buffer(buffer) {} bool init() override { return true; } bool dinRead(uint8_t& data) override { return false; } bool dinWrite(uint8_t data) override { return false; } bool usbRead(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { return false; } bool usbWrite(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { _buffer.push_back(USBMIDIpacket); return true; } std::vector<MIDI::USBMIDIpacket_t>& _buffer; } hwaFillMIDI(buffer); //create temp midi object which will fill internal hwaMIDI buffer of the real midi object when send is called //calling the real midi read will then result in parsing those filled bytes by the temp object MIDI fillMIDI(hwaFillMIDI); fillMIDI.enableUSBMIDI(); fillMIDI.sendSysEx(request.size(), &request[0], true); //store this in a variable since every midi.read call will decrement the size of buffer size_t packetSize = hwaFillMIDI._buffer.size(); //now just call system which will call midi.read which in turn will read the filled packets for (size_t i = 0; i < packetSize; i++) systemStub.run(); }; void verifyResponse(const std::vector<uint8_t> response, std::vector<MIDI::USBMIDIpacket_t>& buffer) { class HWAParseMIDI : public MIDI::HWA { public: HWAParseMIDI(std::vector<MIDI::USBMIDIpacket_t>& buffer) : _buffer(buffer) {} bool init() override { return true; } bool dinRead(uint8_t& data) override { return false; } bool dinWrite(uint8_t data) override { _parsed.push_back(data); return true; } bool usbRead(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { if (!_buffer.size()) return false; USBMIDIpacket = _buffer.at(0); _buffer.erase(_buffer.begin()); return true; } bool usbWrite(MIDI::USBMIDIpacket_t& USBMIDIpacket) override { return true; } std::vector<MIDI::USBMIDIpacket_t>& _buffer; std::vector<uint8_t> _parsed; } hwaParseMIDI(buffer); MIDI parseMIDI(hwaParseMIDI); parseMIDI.enableUSBMIDI(); parseMIDI.enableDINMIDI(); parseMIDI.setInputChannel(MIDI_CHANNEL_OMNI); //create temp midi object which will read written usb packets and pass them back as DIN MIDI array //for easier parsing size_t packetSize = hwaParseMIDI._buffer.size(); size_t sysExResponseIndexStart = 0; for (size_t i = 0; i < packetSize; i++) { if (parseMIDI.read(MIDI::interface_t::usb, MIDI::filterMode_t::fullDIN)) { auto messageType = parseMIDI.getType(MIDI::interface_t::usb); uint8_t data1 = parseMIDI.getData1(MIDI::interface_t::usb); uint8_t data2 = parseMIDI.getData2(MIDI::interface_t::usb); uint8_t channel = parseMIDI.getChannel(MIDI::interface_t::usb); bool chMessage = false; switch (messageType) { case MIDI::messageType_t::noteOn: case MIDI::messageType_t::noteOff: case MIDI::messageType_t::controlChange: case MIDI::messageType_t::programChange: chMessage = true; break; default: break; } if (chMessage) { channelMIDImessages.push_back({ channel, messageType, data1, data2, }); } } } for (sysExResponseIndexStart = 0; sysExResponseIndexStart < hwaParseMIDI._parsed.size(); sysExResponseIndexStart++) { if (hwaParseMIDI._parsed.at(sysExResponseIndexStart) != response.at(0)) continue; for (size_t i = 0; i < hwaParseMIDI._parsed.size() - sysExResponseIndexStart; i++) TEST_ASSERT_EQUAL_UINT32(response.at(i), hwaParseMIDI._parsed.at(i + sysExResponseIndexStart)); break; } }; } // namespace TEST_SETUP() { hwaSystem.reset(); midi.init(); midi.enableUSBMIDI(); midi.disableDINMIDI(); } TEST_CASE(SystemInit) { //on init, factory reset is performed so everything is in its default state TEST_ASSERT(systemStub.init() == true); //verify that din midi is disabled TEST_ASSERT(hwaSystem.dinMIDIenabled == false); TEST_ASSERT(hwaSystem.loopbackEnabled == false); //now enable din midi via write in database TEST_ASSERT(database.update(Database::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::dinEnabled), 1) == true); //init system again and verify that din midi is enabled TEST_ASSERT(systemStub.init() == true); #ifdef DIN_MIDI_SUPPORTED TEST_ASSERT(hwaSystem.dinMIDIenabled == true); TEST_ASSERT(hwaSystem.loopbackEnabled == false); #else //nothing should change TEST_ASSERT(hwaSystem.dinMIDIenabled == false); TEST_ASSERT(hwaSystem.loopbackEnabled == false); #endif //now enable din to din merge, init system again and verify that both din midi and loopback are enabled TEST_ASSERT(database.update(Database::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::mergeEnabled), 1) == true); TEST_ASSERT(database.update(Database::Section::global_t::midiMerge, static_cast<size_t>(System::midiMerge_t::mergeType), static_cast<int32_t>(System::midiMergeType_t::DINtoDIN)) == true); TEST_ASSERT(systemStub.init() == true); #ifdef DIN_MIDI_SUPPORTED TEST_ASSERT(hwaSystem.dinMIDIenabled == true); TEST_ASSERT(hwaSystem.loopbackEnabled == true); #else //nothing should change TEST_ASSERT(hwaSystem.dinMIDIenabled == false); TEST_ASSERT(hwaSystem.loopbackEnabled == false); #endif } TEST_CASE(Requests) { database.factoryReset(); //send fake usb midi message containing the handshake //verify that the response is valid hwaMIDI.usbPacketToBoard.clear(); //handshake sendSysExRequest({ 0xF0, 0x00, 0x53, 0x43, 0x00, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketFromBoard); verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x01, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketToBoard); hwaMIDI.usbPacketFromBoard.clear(); //verify that din midi is disabled TEST_ASSERT(hwaSystem.dinMIDIenabled == false); TEST_ASSERT(database.read(Database::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::dinEnabled)) == false); midi.sendNoteOn(127, 127, 1); TEST_ASSERT_EQUAL_UINT32(0, hwaMIDI.dinPacketFromBoard.size()); std::vector<uint8_t> generatedSysExReq; MIDIHelper::generateSysExSetReq(System::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::dinEnabled), 1, generatedSysExReq); hwaMIDI.clear(); sendSysExRequest(generatedSysExReq, hwaMIDI.usbPacketFromBoard); #ifdef DIN_MIDI_SUPPORTED verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x01, 0x00, 0x01, //set 0x00, //single 0x00, //global block 0x00, //midi features 0x00, 0x03, //din midi 0x00, 0x01, //enable 0xF7 }, hwaMIDI.usbPacketToBoard); #else verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x0D, //not supported error 0x00, 0x01, //set 0x00, //single 0x00, //global block 0x00, //midi features 0x00, 0x03, //din midi 0x00, 0x01, //enable 0xF7 }, hwaMIDI.usbPacketToBoard); #endif #ifdef DIN_MIDI_SUPPORTED TEST_ASSERT(hwaSystem.dinMIDIenabled == true); TEST_ASSERT(database.read(Database::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::dinEnabled)) == true); #else TEST_ASSERT(hwaSystem.dinMIDIenabled == false); TEST_ASSERT(database.read(Database::Section::global_t::midiFeatures, static_cast<size_t>(System::midiFeature_t::dinEnabled)) == false); #endif //test din by sending a midi message //verify that it is received via din midi midi.sendNoteOn(127, 127, 1); #ifdef DIN_MIDI_SUPPORTED TEST_ASSERT_EQUAL_UINT32(3, hwaMIDI.dinPacketFromBoard.size()); #else TEST_ASSERT_EQUAL_UINT32(0, hwaMIDI.dinPacketFromBoard.size()); #endif hwaMIDI.usbPacketToBoard.clear(); hwaMIDI.usbPacketFromBoard.clear(); hwaMIDI.dinPacketFromBoard.clear(); hwaMIDI.dinPacketToBoard.clear(); //send handshake again and verify that the response isn't sent to din midi sendSysExRequest({ 0xF0, 0x00, 0x53, 0x43, 0x00, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketFromBoard); verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x01, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketToBoard); TEST_ASSERT_EQUAL_UINT32(0, hwaMIDI.dinPacketFromBoard.size()); } TEST_CASE(ForcedResendOnPresetChange) { database.factoryReset(); TEST_ASSERT(systemStub.init() == true); //enable first analog component in first two presets TEST_ASSERT(database.setPreset(1) == true); TEST_ASSERT(database.update(Database::Section::analog_t::enable, 0, 1) == true); TEST_ASSERT(database.setPreset(0) == true); TEST_ASSERT(database.update(Database::Section::analog_t::enable, 0, 1) == true); hwaMIDI.clear(); hwaAnalog.adcReturnValue = 127; analog.update(); TEST_ASSERT_EQUAL_UINT32(1, hwaMIDI.usbPacketToBoard.size()); TEST_ASSERT_EQUAL_UINT32(MIDI::messageType_t::controlChange, hwaMIDI.usbPacketToBoard.at(0).Event << 4); TEST_ASSERT_EQUAL_UINT32(MIDI::messageType_t::controlChange, hwaMIDI.usbPacketToBoard.at(0).Data1); TEST_ASSERT_EQUAL_UINT32(0, hwaMIDI.usbPacketToBoard.at(0).Data2); TEST_ASSERT_EQUAL_UINT32(127, hwaMIDI.usbPacketToBoard.at(0).Data3); //now change preset and verify that the same midi message is repeated hwaMIDI.clear(); //handshake sendSysExRequest({ 0xF0, 0x00, 0x53, 0x43, 0x00, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketFromBoard); verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x01, 0x00, 0x01, 0xF7 }, hwaMIDI.usbPacketToBoard); hwaMIDI.clear(); channelMIDImessages.clear(); std::vector<uint8_t> generatedSysExReq; MIDIHelper::generateSysExSetReq(System::Section::global_t::presets, static_cast<size_t>(System::presetSetting_t::activePreset), 1, generatedSysExReq); sendSysExRequest(generatedSysExReq, hwaMIDI.usbPacketFromBoard); verifyResponse({ 0xF0, 0x00, 0x53, 0x43, 0x01, 0x00, 0x01, //set 0x00, //single 0x00, //block 0 (global) 0x02, //section 2 (presets) 0x00, //active preset 0x00, 0x00, //preset 1 0x01, 0xF7 }, hwaMIDI.usbPacketToBoard); //since the preset has been changed, all buttons should resend their state and all enabled analog components (only 1 in this case) TEST_ASSERT(channelMIDImessages.size() == MAX_NUMBER_OF_BUTTONS + 1); } #endif
30.137881
191
0.549579
[ "object", "vector" ]
4192a8f19bded8ace1fcec6a7dda35c583b23b67
364,822
cpp
C++
AirCombat/Executables/iOS/AirCombat/Classes/Native/GenericMethods1.cpp
rsaenzi/AirCombatDemoBelatrix
ec5a922eb0dd00356909deadb8ee3df64f6d8ccd
[ "MIT" ]
null
null
null
AirCombat/Executables/iOS/AirCombat/Classes/Native/GenericMethods1.cpp
rsaenzi/AirCombatDemoBelatrix
ec5a922eb0dd00356909deadb8ee3df64f6d8ccd
[ "MIT" ]
null
null
null
AirCombat/Executables/iOS/AirCombat/Classes/Native/GenericMethods1.cpp
rsaenzi/AirCombatDemoBelatrix
ec5a922eb0dd00356909deadb8ee3df64f6d8ccd
[ "MIT" ]
null
null
null
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "il2cpp-class-internals.h" #include "codegen/il2cpp-codegen.h" #include "il2cpp-object-internals.h" template <typename R> struct VirtFuncInvoker0 { typedef R (*Func)(void*, const RuntimeMethod*); static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); return ((Func)invokeData.methodPtr)(obj, invokeData.method); } }; template <typename R, typename T1> struct VirtFuncInvoker1 { typedef R (*Func)(void*, T1, const RuntimeMethod*); static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); return ((Func)invokeData.methodPtr)(obj, p1, invokeData.method); } }; template <typename R, typename T1, typename T2> struct VirtFuncInvoker2 { typedef R (*Func)(void*, T1, T2, const RuntimeMethod*); static inline R Invoke (Il2CppMethodSlot slot, RuntimeObject* obj, T1 p1, T2 p2) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_virtual_invoke_data(slot, obj); return ((Func)invokeData.methodPtr)(obj, p1, p2, invokeData.method); } }; template <typename R> struct InterfaceFuncInvoker0 { typedef R (*Func)(void*, const RuntimeMethod*); static inline R Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface); return ((Func)invokeData.methodPtr)(obj, invokeData.method); } }; struct InterfaceActionInvoker0 { typedef void (*Action)(void*, const RuntimeMethod*); static inline void Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj) { const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface); ((Action)invokeData.methodPtr)(obj, invokeData.method); } }; // System.ArgumentException struct ArgumentException_t132251570; // System.ArgumentNullException struct ArgumentNullException_t1615371798; // System.ArgumentOutOfRangeException struct ArgumentOutOfRangeException_t777629997; // System.AsyncCallback struct AsyncCallback_t3962456242; // System.Boolean[] struct BooleanU5BU5D_t2897418192; // System.Byte struct Byte_t1134296376; // System.Byte[] struct ByteU5BU5D_t4116647657; // System.Char[] struct CharU5BU5D_t3528271667; // System.Collections.DictionaryEntry[] struct DictionaryEntryU5BU5D_t4217117203; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Int32,System.Collections.DictionaryEntry> struct Transform_1_t1750446691; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Int32,System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>> struct Transform_1_t1027527961; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Int32,System.Object> struct Transform_1_t1706577217; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Collections.DictionaryEntry> struct Transform_1_t4209139644; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>> struct Transform_1_t3615381325; // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Object> struct Transform_1_t4165270170; // System.Collections.Generic.Dictionary`2<System.Object,System.Int32> struct Dictionary_2_t3384741; // System.Collections.Generic.Dictionary`2<System.Object,System.Object> struct Dictionary_2_t132545152; // System.Collections.Generic.IEnumerable`1<System.Object> struct IEnumerable_1_t2059959053; // System.Collections.Generic.IEqualityComparer`1<System.Object> struct IEqualityComparer_1_t892470886; // System.Collections.Generic.IList`1<System.Reflection.CustomAttributeNamedArgument> struct IList_1_t2103185493; // System.Collections.Generic.IList`1<System.Reflection.CustomAttributeTypedArgument> struct IList_1_t243502644; // System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>[] struct KeyValuePair_2U5BU5D_t1954543557; // System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>[] struct KeyValuePair_2U5BU5D_t118269214; // System.Collections.Generic.Link[] struct LinkU5BU5D_t964245573; // System.Collections.IDictionary struct IDictionary_t1363984059; // System.Converter`2<System.Object,System.Object> struct Converter_2_t2442480487; // System.DelegateData struct DelegateData_t1677132599; // System.Double struct Double_t594665363; // System.Exception struct Exception_t; // System.Func`2<System.Object,System.Boolean> struct Func_2_t3759279471; // System.IAsyncResult struct IAsyncResult_t767004451; // System.IO.Stream struct Stream_t1273022909; // System.Int32[] struct Int32U5BU5D_t385246372; // System.IntPtr[] struct IntPtrU5BU5D_t4013366056; // System.InvalidOperationException struct InvalidOperationException_t56020091; // System.Object[] struct ObjectU5BU5D_t2843939325; // System.Predicate`1<System.Object> struct Predicate_1_t3905400288; // System.Reflection.ConstructorInfo struct ConstructorInfo_t5769829; // System.Reflection.CustomAttributeNamedArgument[] struct CustomAttributeNamedArgumentU5BU5D_t3710464795; // System.Reflection.CustomAttributeTypedArgument[] struct CustomAttributeTypedArgumentU5BU5D_t1465843424; // System.Reflection.MemberFilter struct MemberFilter_t426314064; // System.Reflection.MemberInfo struct MemberInfo_t; // System.Reflection.MethodInfo struct MethodInfo_t; // System.Runtime.Serialization.SerializationInfo struct SerializationInfo_t950877179; // System.String struct String_t; // System.String[] struct StringU5BU5D_t1281789340; // System.Threading.ManualResetEvent struct ManualResetEvent_t451242010; // System.Threading.SendOrPostCallback struct SendOrPostCallback_t2750080073; // System.Type struct Type_t; // System.Type[] struct TypeU5BU5D_t3940880105; // System.UInt16 struct UInt16_t2177724958; // System.Void struct Void_t1185182177; // UnityEngine.Camera struct Camera_t4157153871; // UnityEngine.Component struct Component_t1923634451; // UnityEngine.DisallowMultipleComponent[] struct DisallowMultipleComponentU5BU5D_t3936143868; // UnityEngine.Events.UnityAction struct UnityAction_t3245792599; // UnityEngine.ExecuteInEditMode[] struct ExecuteInEditModeU5BU5D_t3239458680; // UnityEngine.Experimental.LowLevel.PlayerLoopSystem/UpdateFunction struct UpdateFunction_t377278577; // UnityEngine.Experimental.LowLevel.PlayerLoopSystem[] struct PlayerLoopSystemU5BU5D_t1150299252; // UnityEngine.GameObject struct GameObject_t1113636619; // UnityEngine.Object struct Object_t631007953; // UnityEngine.Playables.PlayableBinding/CreateOutputMethod struct CreateOutputMethod_t2301811773; // UnityEngine.Playables.PlayableBinding[] struct PlayableBindingU5BU5D_t829358056; // UnityEngine.RequireComponent[] struct RequireComponentU5BU5D_t2245623724; // UnityEngine.ScriptableObject struct ScriptableObject_t2528358522; extern RuntimeClass* ArgumentException_t132251570_il2cpp_TypeInfo_var; extern RuntimeClass* ArgumentNullException_t1615371798_il2cpp_TypeInfo_var; extern RuntimeClass* ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var; extern RuntimeClass* Exception_t_il2cpp_TypeInfo_var; extern RuntimeClass* IDisposable_t3640265483_il2cpp_TypeInfo_var; extern RuntimeClass* IEnumerator_t1853284238_il2cpp_TypeInfo_var; extern RuntimeClass* InvalidOperationException_t56020091_il2cpp_TypeInfo_var; extern RuntimeClass* ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var; extern RuntimeClass* Type_t_il2cpp_TypeInfo_var; extern String_t* _stringLiteral1492106003; extern String_t* _stringLiteral273595399; extern String_t* _stringLiteral4007973390; extern String_t* _stringLiteral461028519; extern String_t* _stringLiteral797640427; extern String_t* _stringLiteral879148213; extern const RuntimeMethod* Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_RuntimeMethod_var; extern const RuntimeMethod* Array_FindAll_TisRuntimeObject_m3566631088_RuntimeMethod_var; extern const RuntimeMethod* Array_FindLast_TisRuntimeObject_m1088586648_RuntimeMethod_var; extern const RuntimeMethod* Array_Find_TisRuntimeObject_m2705709394_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisBoolean_t97287965_m1407010309_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisByte_t1134296376_m3566214066_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisChar_t3634460470_m324132692_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisClientCertificateType_t1004704908_m2297379651_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisContactPoint_t3758755253_m2489897608_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisCustomAttributeNamedArgument_t287865710_m2282658220_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisCustomAttributeTypedArgument_t2723150157_m2639399822_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisDateTime_t3738529785_m623181444_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisDecimal_t2948259380_m3511003792_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisDictionaryEntry_t3123975638_m479537688_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisDouble_t594665363_m850827605_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisGcAchievementData_t675222246_m2680268485_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisGcScoreData_t2125309831_m174676143_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisHitInfo_t3229609740_m2260995172_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisILTokenInfo_t2325775114_m3110830457_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisInt16_t2552820387_m76930473_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisInt32_t2950945753_m714868479_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisInt64_t3736567304_m3562990826_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisIntPtr_t_m784054003_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisKeyValuePair_2_t2401056908_m3647027688_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisKeyValuePair_2_t2530217319_m2886833132_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisKeyValuePair_2_t3842366416_m3937535230_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisKeyframe_t4206410242_m27698365_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisLabelData_t360167391_m1054702781_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisLabelFixup_t858502054_m3276643490_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisLink_t544317964_m1669566993_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisMark_t3471605523_m3397473850_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisMonoResource_t4103430009_m2937222811_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisMonoWin32Resource_t1904229483_m513901999_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisOrderBlock_t1585977831_m2406385050_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisParameterModifier_t1461694466_m29553316_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisPlayableBinding_t354260709_m3837494573_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisPlayerLoopSystem_t105772105_m3446275388_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisRaycastHit_t1056001966_m3352067444_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisRefEmitPermissionSet_t484390987_m1505876205_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisResourceCacheItem_t51292791_m1306056717_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisResourceInfo_t2872965302_m3865610257_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisRuntimeObject_m3347010206_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisSByte_t1669577662_m2349608172_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisSingle_t1397266774_m1672589487_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisSlot_t384495010_m2861978404_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisSlot_t3975888750_m905303097_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisTableRange_t3332867892_m1483480711_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisTimeSpan_t881159249_m1885583191_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisTypeTag_t3541821701_m4208350471_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisUInt16_t2177724958_m3601205466_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisUInt32_t2560061978_m1955195035_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisUInt64_t4134040092_m129291315_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisUriScheme_t722425697_m2816273040_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisWorkRequest_t1354518612_m2694410850_RuntimeMethod_var; extern const RuntimeMethod* Array_InternalArray__get_Item_TisX509ChainStatus_t133602714_m2237651489_RuntimeMethod_var; extern const RuntimeMethod* BaseInvokableCall_ThrowOnInvalidArg_TisBoolean_t97287965_m3019671566_RuntimeMethod_var; extern const RuntimeMethod* BaseInvokableCall_ThrowOnInvalidArg_TisInt32_t2950945753_m635860201_RuntimeMethod_var; extern const RuntimeMethod* BaseInvokableCall_ThrowOnInvalidArg_TisRuntimeObject_m2266633109_RuntimeMethod_var; extern const RuntimeMethod* BaseInvokableCall_ThrowOnInvalidArg_TisSingle_t1397266774_m3110598205_RuntimeMethod_var; extern const RuntimeMethod* Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_RuntimeMethod_var; extern const RuntimeMethod* Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_RuntimeMethod_var; extern const RuntimeMethod* Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_RuntimeMethod_var; extern const RuntimeMethod* Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_RuntimeMethod_var; extern const RuntimeMethod* Enumerable_Single_TisRuntimeObject_m1146889774_RuntimeMethod_var; extern const uint32_t Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_MetadataUsageId; extern const uint32_t Array_FindAll_TisRuntimeObject_m3566631088_MetadataUsageId; extern const uint32_t Array_FindLast_TisRuntimeObject_m1088586648_MetadataUsageId; extern const uint32_t Array_Find_TisRuntimeObject_m2705709394_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisBoolean_t97287965_m1407010309_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisByte_t1134296376_m3566214066_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisChar_t3634460470_m324132692_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisClientCertificateType_t1004704908_m2297379651_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisContactPoint_t3758755253_m2489897608_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisCustomAttributeNamedArgument_t287865710_m2282658220_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisCustomAttributeTypedArgument_t2723150157_m2639399822_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisDateTime_t3738529785_m623181444_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisDecimal_t2948259380_m3511003792_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisDictionaryEntry_t3123975638_m479537688_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisDouble_t594665363_m850827605_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisGcAchievementData_t675222246_m2680268485_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisGcScoreData_t2125309831_m174676143_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisHitInfo_t3229609740_m2260995172_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisILTokenInfo_t2325775114_m3110830457_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisInt16_t2552820387_m76930473_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisInt32_t2950945753_m714868479_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisInt64_t3736567304_m3562990826_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisIntPtr_t_m784054003_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisKeyValuePair_2_t2401056908_m3647027688_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisKeyValuePair_2_t2530217319_m2886833132_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisKeyValuePair_2_t3842366416_m3937535230_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisKeyframe_t4206410242_m27698365_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisLabelData_t360167391_m1054702781_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisLabelFixup_t858502054_m3276643490_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisLink_t544317964_m1669566993_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisMark_t3471605523_m3397473850_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisMonoResource_t4103430009_m2937222811_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisMonoWin32Resource_t1904229483_m513901999_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisOrderBlock_t1585977831_m2406385050_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisParameterModifier_t1461694466_m29553316_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisPlayableBinding_t354260709_m3837494573_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisPlayerLoopSystem_t105772105_m3446275388_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisRaycastHit_t1056001966_m3352067444_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisRefEmitPermissionSet_t484390987_m1505876205_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisResourceCacheItem_t51292791_m1306056717_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisResourceInfo_t2872965302_m3865610257_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisRuntimeObject_m3347010206_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisSByte_t1669577662_m2349608172_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisSingle_t1397266774_m1672589487_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisSlot_t384495010_m2861978404_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisSlot_t3975888750_m905303097_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisTableRange_t3332867892_m1483480711_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisTimeSpan_t881159249_m1885583191_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisTypeTag_t3541821701_m4208350471_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisUInt16_t2177724958_m3601205466_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisUInt32_t2560061978_m1955195035_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisUInt64_t4134040092_m129291315_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisUriScheme_t722425697_m2816273040_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisWorkRequest_t1354518612_m2694410850_MetadataUsageId; extern const uint32_t Array_InternalArray__get_Item_TisX509ChainStatus_t133602714_m2237651489_MetadataUsageId; extern const uint32_t AttributeHelperEngine_GetCustomAttributeOfType_TisRuntimeObject_m429013101_MetadataUsageId; extern const uint32_t BaseInvokableCall_ThrowOnInvalidArg_TisBoolean_t97287965_m3019671566_MetadataUsageId; extern const uint32_t BaseInvokableCall_ThrowOnInvalidArg_TisInt32_t2950945753_m635860201_MetadataUsageId; extern const uint32_t BaseInvokableCall_ThrowOnInvalidArg_TisRuntimeObject_m2266633109_MetadataUsageId; extern const uint32_t BaseInvokableCall_ThrowOnInvalidArg_TisSingle_t1397266774_m3110598205_MetadataUsageId; extern const uint32_t Component_GetComponent_TisRuntimeObject_m2906321015_MetadataUsageId; extern const uint32_t Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_MetadataUsageId; extern const uint32_t Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_MetadataUsageId; extern const uint32_t Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_MetadataUsageId; extern const uint32_t Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_MetadataUsageId; extern const uint32_t Enumerable_Single_TisRuntimeObject_m1146889774_MetadataUsageId; extern const uint32_t ScriptableObject_CreateInstance_TisRuntimeObject_m1552711675_MetadataUsageId; struct Object_t631007953_marshaled_com; struct PlayerLoopSystem_t105772105_marshaled_com; struct PlayerLoopSystem_t105772105_marshaled_pinvoke; struct DictionaryEntryU5BU5D_t4217117203; struct KeyValuePair_2U5BU5D_t1954543557; struct KeyValuePair_2U5BU5D_t118269214; struct LinkU5BU5D_t964245573; struct Int32U5BU5D_t385246372; struct ObjectU5BU5D_t2843939325; struct CustomAttributeNamedArgumentU5BU5D_t3710464795; struct CustomAttributeTypedArgumentU5BU5D_t1465843424; #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef DICTIONARY_2_T3384741_H #define DICTIONARY_2_T3384741_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2<System.Object,System.Int32> struct Dictionary_2_t3384741 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::table Int32U5BU5D_t385246372* ___table_4; // System.Collections.Generic.Link[] System.Collections.Generic.Dictionary`2::linkSlots LinkU5BU5D_t964245573* ___linkSlots_5; // TKey[] System.Collections.Generic.Dictionary`2::keySlots ObjectU5BU5D_t2843939325* ___keySlots_6; // TValue[] System.Collections.Generic.Dictionary`2::valueSlots Int32U5BU5D_t385246372* ___valueSlots_7; // System.Int32 System.Collections.Generic.Dictionary`2::touchedSlots int32_t ___touchedSlots_8; // System.Int32 System.Collections.Generic.Dictionary`2::emptySlot int32_t ___emptySlot_9; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_10; // System.Int32 System.Collections.Generic.Dictionary`2::threshold int32_t ___threshold_11; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::hcp RuntimeObject* ___hcp_12; // System.Runtime.Serialization.SerializationInfo System.Collections.Generic.Dictionary`2::serialization_info SerializationInfo_t950877179 * ___serialization_info_13; // System.Int32 System.Collections.Generic.Dictionary`2::generation int32_t ___generation_14; public: inline static int32_t get_offset_of_table_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___table_4)); } inline Int32U5BU5D_t385246372* get_table_4() const { return ___table_4; } inline Int32U5BU5D_t385246372** get_address_of_table_4() { return &___table_4; } inline void set_table_4(Int32U5BU5D_t385246372* value) { ___table_4 = value; Il2CppCodeGenWriteBarrier((&___table_4), value); } inline static int32_t get_offset_of_linkSlots_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___linkSlots_5)); } inline LinkU5BU5D_t964245573* get_linkSlots_5() const { return ___linkSlots_5; } inline LinkU5BU5D_t964245573** get_address_of_linkSlots_5() { return &___linkSlots_5; } inline void set_linkSlots_5(LinkU5BU5D_t964245573* value) { ___linkSlots_5 = value; Il2CppCodeGenWriteBarrier((&___linkSlots_5), value); } inline static int32_t get_offset_of_keySlots_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___keySlots_6)); } inline ObjectU5BU5D_t2843939325* get_keySlots_6() const { return ___keySlots_6; } inline ObjectU5BU5D_t2843939325** get_address_of_keySlots_6() { return &___keySlots_6; } inline void set_keySlots_6(ObjectU5BU5D_t2843939325* value) { ___keySlots_6 = value; Il2CppCodeGenWriteBarrier((&___keySlots_6), value); } inline static int32_t get_offset_of_valueSlots_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___valueSlots_7)); } inline Int32U5BU5D_t385246372* get_valueSlots_7() const { return ___valueSlots_7; } inline Int32U5BU5D_t385246372** get_address_of_valueSlots_7() { return &___valueSlots_7; } inline void set_valueSlots_7(Int32U5BU5D_t385246372* value) { ___valueSlots_7 = value; Il2CppCodeGenWriteBarrier((&___valueSlots_7), value); } inline static int32_t get_offset_of_touchedSlots_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___touchedSlots_8)); } inline int32_t get_touchedSlots_8() const { return ___touchedSlots_8; } inline int32_t* get_address_of_touchedSlots_8() { return &___touchedSlots_8; } inline void set_touchedSlots_8(int32_t value) { ___touchedSlots_8 = value; } inline static int32_t get_offset_of_emptySlot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___emptySlot_9)); } inline int32_t get_emptySlot_9() const { return ___emptySlot_9; } inline int32_t* get_address_of_emptySlot_9() { return &___emptySlot_9; } inline void set_emptySlot_9(int32_t value) { ___emptySlot_9 = value; } inline static int32_t get_offset_of_count_10() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___count_10)); } inline int32_t get_count_10() const { return ___count_10; } inline int32_t* get_address_of_count_10() { return &___count_10; } inline void set_count_10(int32_t value) { ___count_10 = value; } inline static int32_t get_offset_of_threshold_11() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___threshold_11)); } inline int32_t get_threshold_11() const { return ___threshold_11; } inline int32_t* get_address_of_threshold_11() { return &___threshold_11; } inline void set_threshold_11(int32_t value) { ___threshold_11 = value; } inline static int32_t get_offset_of_hcp_12() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___hcp_12)); } inline RuntimeObject* get_hcp_12() const { return ___hcp_12; } inline RuntimeObject** get_address_of_hcp_12() { return &___hcp_12; } inline void set_hcp_12(RuntimeObject* value) { ___hcp_12 = value; Il2CppCodeGenWriteBarrier((&___hcp_12), value); } inline static int32_t get_offset_of_serialization_info_13() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___serialization_info_13)); } inline SerializationInfo_t950877179 * get_serialization_info_13() const { return ___serialization_info_13; } inline SerializationInfo_t950877179 ** get_address_of_serialization_info_13() { return &___serialization_info_13; } inline void set_serialization_info_13(SerializationInfo_t950877179 * value) { ___serialization_info_13 = value; Il2CppCodeGenWriteBarrier((&___serialization_info_13), value); } inline static int32_t get_offset_of_generation_14() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741, ___generation_14)); } inline int32_t get_generation_14() const { return ___generation_14; } inline int32_t* get_address_of_generation_14() { return &___generation_14; } inline void set_generation_14(int32_t value) { ___generation_14 = value; } }; struct Dictionary_2_t3384741_StaticFields { public: // System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,System.Collections.DictionaryEntry> System.Collections.Generic.Dictionary`2::<>f__am$cacheB Transform_1_t1750446691 * ___U3CU3Ef__amU24cacheB_15; public: inline static int32_t get_offset_of_U3CU3Ef__amU24cacheB_15() { return static_cast<int32_t>(offsetof(Dictionary_2_t3384741_StaticFields, ___U3CU3Ef__amU24cacheB_15)); } inline Transform_1_t1750446691 * get_U3CU3Ef__amU24cacheB_15() const { return ___U3CU3Ef__amU24cacheB_15; } inline Transform_1_t1750446691 ** get_address_of_U3CU3Ef__amU24cacheB_15() { return &___U3CU3Ef__amU24cacheB_15; } inline void set_U3CU3Ef__amU24cacheB_15(Transform_1_t1750446691 * value) { ___U3CU3Ef__amU24cacheB_15 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cacheB_15), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DICTIONARY_2_T3384741_H #ifndef DICTIONARY_2_T132545152_H #define DICTIONARY_2_T132545152_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2<System.Object,System.Object> struct Dictionary_2_t132545152 : public RuntimeObject { public: // System.Int32[] System.Collections.Generic.Dictionary`2::table Int32U5BU5D_t385246372* ___table_4; // System.Collections.Generic.Link[] System.Collections.Generic.Dictionary`2::linkSlots LinkU5BU5D_t964245573* ___linkSlots_5; // TKey[] System.Collections.Generic.Dictionary`2::keySlots ObjectU5BU5D_t2843939325* ___keySlots_6; // TValue[] System.Collections.Generic.Dictionary`2::valueSlots ObjectU5BU5D_t2843939325* ___valueSlots_7; // System.Int32 System.Collections.Generic.Dictionary`2::touchedSlots int32_t ___touchedSlots_8; // System.Int32 System.Collections.Generic.Dictionary`2::emptySlot int32_t ___emptySlot_9; // System.Int32 System.Collections.Generic.Dictionary`2::count int32_t ___count_10; // System.Int32 System.Collections.Generic.Dictionary`2::threshold int32_t ___threshold_11; // System.Collections.Generic.IEqualityComparer`1<TKey> System.Collections.Generic.Dictionary`2::hcp RuntimeObject* ___hcp_12; // System.Runtime.Serialization.SerializationInfo System.Collections.Generic.Dictionary`2::serialization_info SerializationInfo_t950877179 * ___serialization_info_13; // System.Int32 System.Collections.Generic.Dictionary`2::generation int32_t ___generation_14; public: inline static int32_t get_offset_of_table_4() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___table_4)); } inline Int32U5BU5D_t385246372* get_table_4() const { return ___table_4; } inline Int32U5BU5D_t385246372** get_address_of_table_4() { return &___table_4; } inline void set_table_4(Int32U5BU5D_t385246372* value) { ___table_4 = value; Il2CppCodeGenWriteBarrier((&___table_4), value); } inline static int32_t get_offset_of_linkSlots_5() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___linkSlots_5)); } inline LinkU5BU5D_t964245573* get_linkSlots_5() const { return ___linkSlots_5; } inline LinkU5BU5D_t964245573** get_address_of_linkSlots_5() { return &___linkSlots_5; } inline void set_linkSlots_5(LinkU5BU5D_t964245573* value) { ___linkSlots_5 = value; Il2CppCodeGenWriteBarrier((&___linkSlots_5), value); } inline static int32_t get_offset_of_keySlots_6() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___keySlots_6)); } inline ObjectU5BU5D_t2843939325* get_keySlots_6() const { return ___keySlots_6; } inline ObjectU5BU5D_t2843939325** get_address_of_keySlots_6() { return &___keySlots_6; } inline void set_keySlots_6(ObjectU5BU5D_t2843939325* value) { ___keySlots_6 = value; Il2CppCodeGenWriteBarrier((&___keySlots_6), value); } inline static int32_t get_offset_of_valueSlots_7() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___valueSlots_7)); } inline ObjectU5BU5D_t2843939325* get_valueSlots_7() const { return ___valueSlots_7; } inline ObjectU5BU5D_t2843939325** get_address_of_valueSlots_7() { return &___valueSlots_7; } inline void set_valueSlots_7(ObjectU5BU5D_t2843939325* value) { ___valueSlots_7 = value; Il2CppCodeGenWriteBarrier((&___valueSlots_7), value); } inline static int32_t get_offset_of_touchedSlots_8() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___touchedSlots_8)); } inline int32_t get_touchedSlots_8() const { return ___touchedSlots_8; } inline int32_t* get_address_of_touchedSlots_8() { return &___touchedSlots_8; } inline void set_touchedSlots_8(int32_t value) { ___touchedSlots_8 = value; } inline static int32_t get_offset_of_emptySlot_9() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___emptySlot_9)); } inline int32_t get_emptySlot_9() const { return ___emptySlot_9; } inline int32_t* get_address_of_emptySlot_9() { return &___emptySlot_9; } inline void set_emptySlot_9(int32_t value) { ___emptySlot_9 = value; } inline static int32_t get_offset_of_count_10() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___count_10)); } inline int32_t get_count_10() const { return ___count_10; } inline int32_t* get_address_of_count_10() { return &___count_10; } inline void set_count_10(int32_t value) { ___count_10 = value; } inline static int32_t get_offset_of_threshold_11() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___threshold_11)); } inline int32_t get_threshold_11() const { return ___threshold_11; } inline int32_t* get_address_of_threshold_11() { return &___threshold_11; } inline void set_threshold_11(int32_t value) { ___threshold_11 = value; } inline static int32_t get_offset_of_hcp_12() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___hcp_12)); } inline RuntimeObject* get_hcp_12() const { return ___hcp_12; } inline RuntimeObject** get_address_of_hcp_12() { return &___hcp_12; } inline void set_hcp_12(RuntimeObject* value) { ___hcp_12 = value; Il2CppCodeGenWriteBarrier((&___hcp_12), value); } inline static int32_t get_offset_of_serialization_info_13() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___serialization_info_13)); } inline SerializationInfo_t950877179 * get_serialization_info_13() const { return ___serialization_info_13; } inline SerializationInfo_t950877179 ** get_address_of_serialization_info_13() { return &___serialization_info_13; } inline void set_serialization_info_13(SerializationInfo_t950877179 * value) { ___serialization_info_13 = value; Il2CppCodeGenWriteBarrier((&___serialization_info_13), value); } inline static int32_t get_offset_of_generation_14() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152, ___generation_14)); } inline int32_t get_generation_14() const { return ___generation_14; } inline int32_t* get_address_of_generation_14() { return &___generation_14; } inline void set_generation_14(int32_t value) { ___generation_14 = value; } }; struct Dictionary_2_t132545152_StaticFields { public: // System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,System.Collections.DictionaryEntry> System.Collections.Generic.Dictionary`2::<>f__am$cacheB Transform_1_t4209139644 * ___U3CU3Ef__amU24cacheB_15; public: inline static int32_t get_offset_of_U3CU3Ef__amU24cacheB_15() { return static_cast<int32_t>(offsetof(Dictionary_2_t132545152_StaticFields, ___U3CU3Ef__amU24cacheB_15)); } inline Transform_1_t4209139644 * get_U3CU3Ef__amU24cacheB_15() const { return ___U3CU3Ef__amU24cacheB_15; } inline Transform_1_t4209139644 ** get_address_of_U3CU3Ef__amU24cacheB_15() { return &___U3CU3Ef__amU24cacheB_15; } inline void set_U3CU3Ef__amU24cacheB_15(Transform_1_t4209139644 * value) { ___U3CU3Ef__amU24cacheB_15 = value; Il2CppCodeGenWriteBarrier((&___U3CU3Ef__amU24cacheB_15), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DICTIONARY_2_T132545152_H #ifndef EXCEPTION_T_H #define EXCEPTION_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Exception struct Exception_t : public RuntimeObject { public: // System.IntPtr[] System.Exception::trace_ips IntPtrU5BU5D_t4013366056* ___trace_ips_0; // System.Exception System.Exception::inner_exception Exception_t * ___inner_exception_1; // System.String System.Exception::message String_t* ___message_2; // System.String System.Exception::help_link String_t* ___help_link_3; // System.String System.Exception::class_name String_t* ___class_name_4; // System.String System.Exception::stack_trace String_t* ___stack_trace_5; // System.String System.Exception::_remoteStackTraceString String_t* ____remoteStackTraceString_6; // System.Int32 System.Exception::remote_stack_index int32_t ___remote_stack_index_7; // System.Int32 System.Exception::hresult int32_t ___hresult_8; // System.String System.Exception::source String_t* ___source_9; // System.Collections.IDictionary System.Exception::_data RuntimeObject* ____data_10; public: inline static int32_t get_offset_of_trace_ips_0() { return static_cast<int32_t>(offsetof(Exception_t, ___trace_ips_0)); } inline IntPtrU5BU5D_t4013366056* get_trace_ips_0() const { return ___trace_ips_0; } inline IntPtrU5BU5D_t4013366056** get_address_of_trace_ips_0() { return &___trace_ips_0; } inline void set_trace_ips_0(IntPtrU5BU5D_t4013366056* value) { ___trace_ips_0 = value; Il2CppCodeGenWriteBarrier((&___trace_ips_0), value); } inline static int32_t get_offset_of_inner_exception_1() { return static_cast<int32_t>(offsetof(Exception_t, ___inner_exception_1)); } inline Exception_t * get_inner_exception_1() const { return ___inner_exception_1; } inline Exception_t ** get_address_of_inner_exception_1() { return &___inner_exception_1; } inline void set_inner_exception_1(Exception_t * value) { ___inner_exception_1 = value; Il2CppCodeGenWriteBarrier((&___inner_exception_1), value); } inline static int32_t get_offset_of_message_2() { return static_cast<int32_t>(offsetof(Exception_t, ___message_2)); } inline String_t* get_message_2() const { return ___message_2; } inline String_t** get_address_of_message_2() { return &___message_2; } inline void set_message_2(String_t* value) { ___message_2 = value; Il2CppCodeGenWriteBarrier((&___message_2), value); } inline static int32_t get_offset_of_help_link_3() { return static_cast<int32_t>(offsetof(Exception_t, ___help_link_3)); } inline String_t* get_help_link_3() const { return ___help_link_3; } inline String_t** get_address_of_help_link_3() { return &___help_link_3; } inline void set_help_link_3(String_t* value) { ___help_link_3 = value; Il2CppCodeGenWriteBarrier((&___help_link_3), value); } inline static int32_t get_offset_of_class_name_4() { return static_cast<int32_t>(offsetof(Exception_t, ___class_name_4)); } inline String_t* get_class_name_4() const { return ___class_name_4; } inline String_t** get_address_of_class_name_4() { return &___class_name_4; } inline void set_class_name_4(String_t* value) { ___class_name_4 = value; Il2CppCodeGenWriteBarrier((&___class_name_4), value); } inline static int32_t get_offset_of_stack_trace_5() { return static_cast<int32_t>(offsetof(Exception_t, ___stack_trace_5)); } inline String_t* get_stack_trace_5() const { return ___stack_trace_5; } inline String_t** get_address_of_stack_trace_5() { return &___stack_trace_5; } inline void set_stack_trace_5(String_t* value) { ___stack_trace_5 = value; Il2CppCodeGenWriteBarrier((&___stack_trace_5), value); } inline static int32_t get_offset_of__remoteStackTraceString_6() { return static_cast<int32_t>(offsetof(Exception_t, ____remoteStackTraceString_6)); } inline String_t* get__remoteStackTraceString_6() const { return ____remoteStackTraceString_6; } inline String_t** get_address_of__remoteStackTraceString_6() { return &____remoteStackTraceString_6; } inline void set__remoteStackTraceString_6(String_t* value) { ____remoteStackTraceString_6 = value; Il2CppCodeGenWriteBarrier((&____remoteStackTraceString_6), value); } inline static int32_t get_offset_of_remote_stack_index_7() { return static_cast<int32_t>(offsetof(Exception_t, ___remote_stack_index_7)); } inline int32_t get_remote_stack_index_7() const { return ___remote_stack_index_7; } inline int32_t* get_address_of_remote_stack_index_7() { return &___remote_stack_index_7; } inline void set_remote_stack_index_7(int32_t value) { ___remote_stack_index_7 = value; } inline static int32_t get_offset_of_hresult_8() { return static_cast<int32_t>(offsetof(Exception_t, ___hresult_8)); } inline int32_t get_hresult_8() const { return ___hresult_8; } inline int32_t* get_address_of_hresult_8() { return &___hresult_8; } inline void set_hresult_8(int32_t value) { ___hresult_8 = value; } inline static int32_t get_offset_of_source_9() { return static_cast<int32_t>(offsetof(Exception_t, ___source_9)); } inline String_t* get_source_9() const { return ___source_9; } inline String_t** get_address_of_source_9() { return &___source_9; } inline void set_source_9(String_t* value) { ___source_9 = value; Il2CppCodeGenWriteBarrier((&___source_9), value); } inline static int32_t get_offset_of__data_10() { return static_cast<int32_t>(offsetof(Exception_t, ____data_10)); } inline RuntimeObject* get__data_10() const { return ____data_10; } inline RuntimeObject** get_address_of__data_10() { return &____data_10; } inline void set__data_10(RuntimeObject* value) { ____data_10 = value; Il2CppCodeGenWriteBarrier((&____data_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // EXCEPTION_T_H #ifndef ENUMERABLE_T538148348_H #define ENUMERABLE_T538148348_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Linq.Enumerable struct Enumerable_t538148348 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ENUMERABLE_T538148348_H #ifndef CUSTOMATTRIBUTEDATA_T1084486650_H #define CUSTOMATTRIBUTEDATA_T1084486650_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.CustomAttributeData struct CustomAttributeData_t1084486650 : public RuntimeObject { public: // System.Reflection.ConstructorInfo System.Reflection.CustomAttributeData::ctorInfo ConstructorInfo_t5769829 * ___ctorInfo_0; // System.Collections.Generic.IList`1<System.Reflection.CustomAttributeTypedArgument> System.Reflection.CustomAttributeData::ctorArgs RuntimeObject* ___ctorArgs_1; // System.Collections.Generic.IList`1<System.Reflection.CustomAttributeNamedArgument> System.Reflection.CustomAttributeData::namedArgs RuntimeObject* ___namedArgs_2; public: inline static int32_t get_offset_of_ctorInfo_0() { return static_cast<int32_t>(offsetof(CustomAttributeData_t1084486650, ___ctorInfo_0)); } inline ConstructorInfo_t5769829 * get_ctorInfo_0() const { return ___ctorInfo_0; } inline ConstructorInfo_t5769829 ** get_address_of_ctorInfo_0() { return &___ctorInfo_0; } inline void set_ctorInfo_0(ConstructorInfo_t5769829 * value) { ___ctorInfo_0 = value; Il2CppCodeGenWriteBarrier((&___ctorInfo_0), value); } inline static int32_t get_offset_of_ctorArgs_1() { return static_cast<int32_t>(offsetof(CustomAttributeData_t1084486650, ___ctorArgs_1)); } inline RuntimeObject* get_ctorArgs_1() const { return ___ctorArgs_1; } inline RuntimeObject** get_address_of_ctorArgs_1() { return &___ctorArgs_1; } inline void set_ctorArgs_1(RuntimeObject* value) { ___ctorArgs_1 = value; Il2CppCodeGenWriteBarrier((&___ctorArgs_1), value); } inline static int32_t get_offset_of_namedArgs_2() { return static_cast<int32_t>(offsetof(CustomAttributeData_t1084486650, ___namedArgs_2)); } inline RuntimeObject* get_namedArgs_2() const { return ___namedArgs_2; } inline RuntimeObject** get_address_of_namedArgs_2() { return &___namedArgs_2; } inline void set_namedArgs_2(RuntimeObject* value) { ___namedArgs_2 = value; Il2CppCodeGenWriteBarrier((&___namedArgs_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CUSTOMATTRIBUTEDATA_T1084486650_H #ifndef MEMBERINFO_T_H #define MEMBERINFO_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.MemberInfo struct MemberInfo_t : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MEMBERINFO_T_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::length int32_t ___length_0; // System.Char System.String::start_char Il2CppChar ___start_char_1; public: inline static int32_t get_offset_of_length_0() { return static_cast<int32_t>(offsetof(String_t, ___length_0)); } inline int32_t get_length_0() const { return ___length_0; } inline int32_t* get_address_of_length_0() { return &___length_0; } inline void set_length_0(int32_t value) { ___length_0 = value; } inline static int32_t get_offset_of_start_char_1() { return static_cast<int32_t>(offsetof(String_t, ___start_char_1)); } inline Il2CppChar get_start_char_1() const { return ___start_char_1; } inline Il2CppChar* get_address_of_start_char_1() { return &___start_char_1; } inline void set_start_char_1(Il2CppChar value) { ___start_char_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_2; // System.Char[] System.String::WhiteChars CharU5BU5D_t3528271667* ___WhiteChars_3; public: inline static int32_t get_offset_of_Empty_2() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_2)); } inline String_t* get_Empty_2() const { return ___Empty_2; } inline String_t** get_address_of_Empty_2() { return &___Empty_2; } inline void set_Empty_2(String_t* value) { ___Empty_2 = value; Il2CppCodeGenWriteBarrier((&___Empty_2), value); } inline static int32_t get_offset_of_WhiteChars_3() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___WhiteChars_3)); } inline CharU5BU5D_t3528271667* get_WhiteChars_3() const { return ___WhiteChars_3; } inline CharU5BU5D_t3528271667** get_address_of_WhiteChars_3() { return &___WhiteChars_3; } inline void set_WhiteChars_3(CharU5BU5D_t3528271667* value) { ___WhiteChars_3 = value; Il2CppCodeGenWriteBarrier((&___WhiteChars_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H #ifndef INTERLOCKED_T2273387594_H #define INTERLOCKED_T2273387594_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Threading.Interlocked struct Interlocked_t2273387594 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTERLOCKED_T2273387594_H #ifndef VALUETYPE_T3640485471_H #define VALUETYPE_T3640485471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3640485471 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3640485471_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3640485471_marshaled_com { }; #endif // VALUETYPE_T3640485471_H #ifndef ATTRIBUTEHELPERENGINE_T2735742303_H #define ATTRIBUTEHELPERENGINE_T2735742303_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.AttributeHelperEngine struct AttributeHelperEngine_t2735742303 : public RuntimeObject { public: public: }; struct AttributeHelperEngine_t2735742303_StaticFields { public: // UnityEngine.DisallowMultipleComponent[] UnityEngine.AttributeHelperEngine::_disallowMultipleComponentArray DisallowMultipleComponentU5BU5D_t3936143868* ____disallowMultipleComponentArray_0; // UnityEngine.ExecuteInEditMode[] UnityEngine.AttributeHelperEngine::_executeInEditModeArray ExecuteInEditModeU5BU5D_t3239458680* ____executeInEditModeArray_1; // UnityEngine.RequireComponent[] UnityEngine.AttributeHelperEngine::_requireComponentArray RequireComponentU5BU5D_t2245623724* ____requireComponentArray_2; public: inline static int32_t get_offset_of__disallowMultipleComponentArray_0() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____disallowMultipleComponentArray_0)); } inline DisallowMultipleComponentU5BU5D_t3936143868* get__disallowMultipleComponentArray_0() const { return ____disallowMultipleComponentArray_0; } inline DisallowMultipleComponentU5BU5D_t3936143868** get_address_of__disallowMultipleComponentArray_0() { return &____disallowMultipleComponentArray_0; } inline void set__disallowMultipleComponentArray_0(DisallowMultipleComponentU5BU5D_t3936143868* value) { ____disallowMultipleComponentArray_0 = value; Il2CppCodeGenWriteBarrier((&____disallowMultipleComponentArray_0), value); } inline static int32_t get_offset_of__executeInEditModeArray_1() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____executeInEditModeArray_1)); } inline ExecuteInEditModeU5BU5D_t3239458680* get__executeInEditModeArray_1() const { return ____executeInEditModeArray_1; } inline ExecuteInEditModeU5BU5D_t3239458680** get_address_of__executeInEditModeArray_1() { return &____executeInEditModeArray_1; } inline void set__executeInEditModeArray_1(ExecuteInEditModeU5BU5D_t3239458680* value) { ____executeInEditModeArray_1 = value; Il2CppCodeGenWriteBarrier((&____executeInEditModeArray_1), value); } inline static int32_t get_offset_of__requireComponentArray_2() { return static_cast<int32_t>(offsetof(AttributeHelperEngine_t2735742303_StaticFields, ____requireComponentArray_2)); } inline RequireComponentU5BU5D_t2245623724* get__requireComponentArray_2() const { return ____requireComponentArray_2; } inline RequireComponentU5BU5D_t2245623724** get_address_of__requireComponentArray_2() { return &____requireComponentArray_2; } inline void set__requireComponentArray_2(RequireComponentU5BU5D_t2245623724* value) { ____requireComponentArray_2 = value; Il2CppCodeGenWriteBarrier((&____requireComponentArray_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ATTRIBUTEHELPERENGINE_T2735742303_H #ifndef BASEINVOKABLECALL_T2703961024_H #define BASEINVOKABLECALL_T2703961024_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Events.BaseInvokableCall struct BaseInvokableCall_t2703961024 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BASEINVOKABLECALL_T2703961024_H #ifndef TABLERANGE_T3332867892_H #define TABLERANGE_T3332867892_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Globalization.Unicode.CodePointIndexer/TableRange struct TableRange_t3332867892 { public: // System.Int32 Mono.Globalization.Unicode.CodePointIndexer/TableRange::Start int32_t ___Start_0; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer/TableRange::End int32_t ___End_1; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer/TableRange::Count int32_t ___Count_2; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer/TableRange::IndexStart int32_t ___IndexStart_3; // System.Int32 Mono.Globalization.Unicode.CodePointIndexer/TableRange::IndexEnd int32_t ___IndexEnd_4; public: inline static int32_t get_offset_of_Start_0() { return static_cast<int32_t>(offsetof(TableRange_t3332867892, ___Start_0)); } inline int32_t get_Start_0() const { return ___Start_0; } inline int32_t* get_address_of_Start_0() { return &___Start_0; } inline void set_Start_0(int32_t value) { ___Start_0 = value; } inline static int32_t get_offset_of_End_1() { return static_cast<int32_t>(offsetof(TableRange_t3332867892, ___End_1)); } inline int32_t get_End_1() const { return ___End_1; } inline int32_t* get_address_of_End_1() { return &___End_1; } inline void set_End_1(int32_t value) { ___End_1 = value; } inline static int32_t get_offset_of_Count_2() { return static_cast<int32_t>(offsetof(TableRange_t3332867892, ___Count_2)); } inline int32_t get_Count_2() const { return ___Count_2; } inline int32_t* get_address_of_Count_2() { return &___Count_2; } inline void set_Count_2(int32_t value) { ___Count_2 = value; } inline static int32_t get_offset_of_IndexStart_3() { return static_cast<int32_t>(offsetof(TableRange_t3332867892, ___IndexStart_3)); } inline int32_t get_IndexStart_3() const { return ___IndexStart_3; } inline int32_t* get_address_of_IndexStart_3() { return &___IndexStart_3; } inline void set_IndexStart_3(int32_t value) { ___IndexStart_3 = value; } inline static int32_t get_offset_of_IndexEnd_4() { return static_cast<int32_t>(offsetof(TableRange_t3332867892, ___IndexEnd_4)); } inline int32_t get_IndexEnd_4() const { return ___IndexEnd_4; } inline int32_t* get_address_of_IndexEnd_4() { return &___IndexEnd_4; } inline void set_IndexEnd_4(int32_t value) { ___IndexEnd_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TABLERANGE_T3332867892_H #ifndef BOOLEAN_T97287965_H #define BOOLEAN_T97287965_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_t97287965 { public: // System.Boolean System.Boolean::m_value bool ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Boolean_t97287965, ___m_value_2)); } inline bool get_m_value_2() const { return ___m_value_2; } inline bool* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(bool value) { ___m_value_2 = value; } }; struct Boolean_t97287965_StaticFields { public: // System.String System.Boolean::FalseString String_t* ___FalseString_0; // System.String System.Boolean::TrueString String_t* ___TrueString_1; public: inline static int32_t get_offset_of_FalseString_0() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___FalseString_0)); } inline String_t* get_FalseString_0() const { return ___FalseString_0; } inline String_t** get_address_of_FalseString_0() { return &___FalseString_0; } inline void set_FalseString_0(String_t* value) { ___FalseString_0 = value; Il2CppCodeGenWriteBarrier((&___FalseString_0), value); } inline static int32_t get_offset_of_TrueString_1() { return static_cast<int32_t>(offsetof(Boolean_t97287965_StaticFields, ___TrueString_1)); } inline String_t* get_TrueString_1() const { return ___TrueString_1; } inline String_t** get_address_of_TrueString_1() { return &___TrueString_1; } inline void set_TrueString_1(String_t* value) { ___TrueString_1 = value; Il2CppCodeGenWriteBarrier((&___TrueString_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T97287965_H #ifndef BYTE_T1134296376_H #define BYTE_T1134296376_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Byte struct Byte_t1134296376 { public: // System.Byte System.Byte::m_value uint8_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Byte_t1134296376, ___m_value_2)); } inline uint8_t get_m_value_2() const { return ___m_value_2; } inline uint8_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint8_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BYTE_T1134296376_H #ifndef CHAR_T3634460470_H #define CHAR_T3634460470_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Char struct Char_t3634460470 { public: // System.Char System.Char::m_value Il2CppChar ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Char_t3634460470, ___m_value_2)); } inline Il2CppChar get_m_value_2() const { return ___m_value_2; } inline Il2CppChar* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(Il2CppChar value) { ___m_value_2 = value; } }; struct Char_t3634460470_StaticFields { public: // System.Byte* System.Char::category_data uint8_t* ___category_data_3; // System.Byte* System.Char::numeric_data uint8_t* ___numeric_data_4; // System.Double* System.Char::numeric_data_values double* ___numeric_data_values_5; // System.UInt16* System.Char::to_lower_data_low uint16_t* ___to_lower_data_low_6; // System.UInt16* System.Char::to_lower_data_high uint16_t* ___to_lower_data_high_7; // System.UInt16* System.Char::to_upper_data_low uint16_t* ___to_upper_data_low_8; // System.UInt16* System.Char::to_upper_data_high uint16_t* ___to_upper_data_high_9; public: inline static int32_t get_offset_of_category_data_3() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___category_data_3)); } inline uint8_t* get_category_data_3() const { return ___category_data_3; } inline uint8_t** get_address_of_category_data_3() { return &___category_data_3; } inline void set_category_data_3(uint8_t* value) { ___category_data_3 = value; } inline static int32_t get_offset_of_numeric_data_4() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___numeric_data_4)); } inline uint8_t* get_numeric_data_4() const { return ___numeric_data_4; } inline uint8_t** get_address_of_numeric_data_4() { return &___numeric_data_4; } inline void set_numeric_data_4(uint8_t* value) { ___numeric_data_4 = value; } inline static int32_t get_offset_of_numeric_data_values_5() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___numeric_data_values_5)); } inline double* get_numeric_data_values_5() const { return ___numeric_data_values_5; } inline double** get_address_of_numeric_data_values_5() { return &___numeric_data_values_5; } inline void set_numeric_data_values_5(double* value) { ___numeric_data_values_5 = value; } inline static int32_t get_offset_of_to_lower_data_low_6() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___to_lower_data_low_6)); } inline uint16_t* get_to_lower_data_low_6() const { return ___to_lower_data_low_6; } inline uint16_t** get_address_of_to_lower_data_low_6() { return &___to_lower_data_low_6; } inline void set_to_lower_data_low_6(uint16_t* value) { ___to_lower_data_low_6 = value; } inline static int32_t get_offset_of_to_lower_data_high_7() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___to_lower_data_high_7)); } inline uint16_t* get_to_lower_data_high_7() const { return ___to_lower_data_high_7; } inline uint16_t** get_address_of_to_lower_data_high_7() { return &___to_lower_data_high_7; } inline void set_to_lower_data_high_7(uint16_t* value) { ___to_lower_data_high_7 = value; } inline static int32_t get_offset_of_to_upper_data_low_8() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___to_upper_data_low_8)); } inline uint16_t* get_to_upper_data_low_8() const { return ___to_upper_data_low_8; } inline uint16_t** get_address_of_to_upper_data_low_8() { return &___to_upper_data_low_8; } inline void set_to_upper_data_low_8(uint16_t* value) { ___to_upper_data_low_8 = value; } inline static int32_t get_offset_of_to_upper_data_high_9() { return static_cast<int32_t>(offsetof(Char_t3634460470_StaticFields, ___to_upper_data_high_9)); } inline uint16_t* get_to_upper_data_high_9() const { return ___to_upper_data_high_9; } inline uint16_t** get_address_of_to_upper_data_high_9() { return &___to_upper_data_high_9; } inline void set_to_upper_data_high_9(uint16_t* value) { ___to_upper_data_high_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CHAR_T3634460470_H #ifndef DICTIONARYENTRY_T3123975638_H #define DICTIONARYENTRY_T3123975638_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.DictionaryEntry struct DictionaryEntry_t3123975638 { public: // System.Object System.Collections.DictionaryEntry::_key RuntimeObject * ____key_0; // System.Object System.Collections.DictionaryEntry::_value RuntimeObject * ____value_1; public: inline static int32_t get_offset_of__key_0() { return static_cast<int32_t>(offsetof(DictionaryEntry_t3123975638, ____key_0)); } inline RuntimeObject * get__key_0() const { return ____key_0; } inline RuntimeObject ** get_address_of__key_0() { return &____key_0; } inline void set__key_0(RuntimeObject * value) { ____key_0 = value; Il2CppCodeGenWriteBarrier((&____key_0), value); } inline static int32_t get_offset_of__value_1() { return static_cast<int32_t>(offsetof(DictionaryEntry_t3123975638, ____value_1)); } inline RuntimeObject * get__value_1() const { return ____value_1; } inline RuntimeObject ** get_address_of__value_1() { return &____value_1; } inline void set__value_1(RuntimeObject * value) { ____value_1 = value; Il2CppCodeGenWriteBarrier((&____value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Collections.DictionaryEntry struct DictionaryEntry_t3123975638_marshaled_pinvoke { Il2CppIUnknown* ____key_0; Il2CppIUnknown* ____value_1; }; // Native definition for COM marshalling of System.Collections.DictionaryEntry struct DictionaryEntry_t3123975638_marshaled_com { Il2CppIUnknown* ____key_0; Il2CppIUnknown* ____value_1; }; #endif // DICTIONARYENTRY_T3123975638_H #ifndef KEYVALUEPAIR_2_T3842366416_H #define KEYVALUEPAIR_2_T3842366416_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.KeyValuePair`2<System.Object,System.Boolean> struct KeyValuePair_2_t3842366416 { public: // TKey System.Collections.Generic.KeyValuePair`2::key RuntimeObject * ___key_0; // TValue System.Collections.Generic.KeyValuePair`2::value bool ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t3842366416, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t3842366416, ___value_1)); } inline bool get_value_1() const { return ___value_1; } inline bool* get_address_of_value_1() { return &___value_1; } inline void set_value_1(bool value) { ___value_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYVALUEPAIR_2_T3842366416_H #ifndef KEYVALUEPAIR_2_T2401056908_H #define KEYVALUEPAIR_2_T2401056908_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32> struct KeyValuePair_2_t2401056908 { public: // TKey System.Collections.Generic.KeyValuePair`2::key RuntimeObject * ___key_0; // TValue System.Collections.Generic.KeyValuePair`2::value int32_t ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2401056908, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2401056908, ___value_1)); } inline int32_t get_value_1() const { return ___value_1; } inline int32_t* get_address_of_value_1() { return &___value_1; } inline void set_value_1(int32_t value) { ___value_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYVALUEPAIR_2_T2401056908_H #ifndef KEYVALUEPAIR_2_T2530217319_H #define KEYVALUEPAIR_2_T2530217319_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.KeyValuePair`2<System.Object,System.Object> struct KeyValuePair_2_t2530217319 { public: // TKey System.Collections.Generic.KeyValuePair`2::key RuntimeObject * ___key_0; // TValue System.Collections.Generic.KeyValuePair`2::value RuntimeObject * ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2530217319, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2530217319, ___value_1)); } inline RuntimeObject * get_value_1() const { return ___value_1; } inline RuntimeObject ** get_address_of_value_1() { return &___value_1; } inline void set_value_1(RuntimeObject * value) { ___value_1 = value; Il2CppCodeGenWriteBarrier((&___value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYVALUEPAIR_2_T2530217319_H #ifndef LINK_T544317964_H #define LINK_T544317964_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Link struct Link_t544317964 { public: // System.Int32 System.Collections.Generic.Link::HashCode int32_t ___HashCode_0; // System.Int32 System.Collections.Generic.Link::Next int32_t ___Next_1; public: inline static int32_t get_offset_of_HashCode_0() { return static_cast<int32_t>(offsetof(Link_t544317964, ___HashCode_0)); } inline int32_t get_HashCode_0() const { return ___HashCode_0; } inline int32_t* get_address_of_HashCode_0() { return &___HashCode_0; } inline void set_HashCode_0(int32_t value) { ___HashCode_0 = value; } inline static int32_t get_offset_of_Next_1() { return static_cast<int32_t>(offsetof(Link_t544317964, ___Next_1)); } inline int32_t get_Next_1() const { return ___Next_1; } inline int32_t* get_address_of_Next_1() { return &___Next_1; } inline void set_Next_1(int32_t value) { ___Next_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LINK_T544317964_H #ifndef SLOT_T3975888750_H #define SLOT_T3975888750_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Hashtable/Slot struct Slot_t3975888750 { public: // System.Object System.Collections.Hashtable/Slot::key RuntimeObject * ___key_0; // System.Object System.Collections.Hashtable/Slot::value RuntimeObject * ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(Slot_t3975888750, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(Slot_t3975888750, ___value_1)); } inline RuntimeObject * get_value_1() const { return ___value_1; } inline RuntimeObject ** get_address_of_value_1() { return &___value_1; } inline void set_value_1(RuntimeObject * value) { ___value_1 = value; Il2CppCodeGenWriteBarrier((&___value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Collections.Hashtable/Slot struct Slot_t3975888750_marshaled_pinvoke { Il2CppIUnknown* ___key_0; Il2CppIUnknown* ___value_1; }; // Native definition for COM marshalling of System.Collections.Hashtable/Slot struct Slot_t3975888750_marshaled_com { Il2CppIUnknown* ___key_0; Il2CppIUnknown* ___value_1; }; #endif // SLOT_T3975888750_H #ifndef SLOT_T384495010_H #define SLOT_T384495010_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.SortedList/Slot struct Slot_t384495010 { public: // System.Object System.Collections.SortedList/Slot::key RuntimeObject * ___key_0; // System.Object System.Collections.SortedList/Slot::value RuntimeObject * ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(Slot_t384495010, ___key_0)); } inline RuntimeObject * get_key_0() const { return ___key_0; } inline RuntimeObject ** get_address_of_key_0() { return &___key_0; } inline void set_key_0(RuntimeObject * value) { ___key_0 = value; Il2CppCodeGenWriteBarrier((&___key_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(Slot_t384495010, ___value_1)); } inline RuntimeObject * get_value_1() const { return ___value_1; } inline RuntimeObject ** get_address_of_value_1() { return &___value_1; } inline void set_value_1(RuntimeObject * value) { ___value_1 = value; Il2CppCodeGenWriteBarrier((&___value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Collections.SortedList/Slot struct Slot_t384495010_marshaled_pinvoke { Il2CppIUnknown* ___key_0; Il2CppIUnknown* ___value_1; }; // Native definition for COM marshalling of System.Collections.SortedList/Slot struct Slot_t384495010_marshaled_com { Il2CppIUnknown* ___key_0; Il2CppIUnknown* ___value_1; }; #endif // SLOT_T384495010_H #ifndef DECIMAL_T2948259380_H #define DECIMAL_T2948259380_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Decimal struct Decimal_t2948259380 { public: // System.UInt32 System.Decimal::flags uint32_t ___flags_5; // System.UInt32 System.Decimal::hi uint32_t ___hi_6; // System.UInt32 System.Decimal::lo uint32_t ___lo_7; // System.UInt32 System.Decimal::mid uint32_t ___mid_8; public: inline static int32_t get_offset_of_flags_5() { return static_cast<int32_t>(offsetof(Decimal_t2948259380, ___flags_5)); } inline uint32_t get_flags_5() const { return ___flags_5; } inline uint32_t* get_address_of_flags_5() { return &___flags_5; } inline void set_flags_5(uint32_t value) { ___flags_5 = value; } inline static int32_t get_offset_of_hi_6() { return static_cast<int32_t>(offsetof(Decimal_t2948259380, ___hi_6)); } inline uint32_t get_hi_6() const { return ___hi_6; } inline uint32_t* get_address_of_hi_6() { return &___hi_6; } inline void set_hi_6(uint32_t value) { ___hi_6 = value; } inline static int32_t get_offset_of_lo_7() { return static_cast<int32_t>(offsetof(Decimal_t2948259380, ___lo_7)); } inline uint32_t get_lo_7() const { return ___lo_7; } inline uint32_t* get_address_of_lo_7() { return &___lo_7; } inline void set_lo_7(uint32_t value) { ___lo_7 = value; } inline static int32_t get_offset_of_mid_8() { return static_cast<int32_t>(offsetof(Decimal_t2948259380, ___mid_8)); } inline uint32_t get_mid_8() const { return ___mid_8; } inline uint32_t* get_address_of_mid_8() { return &___mid_8; } inline void set_mid_8(uint32_t value) { ___mid_8 = value; } }; struct Decimal_t2948259380_StaticFields { public: // System.Decimal System.Decimal::MinValue Decimal_t2948259380 ___MinValue_0; // System.Decimal System.Decimal::MaxValue Decimal_t2948259380 ___MaxValue_1; // System.Decimal System.Decimal::MinusOne Decimal_t2948259380 ___MinusOne_2; // System.Decimal System.Decimal::One Decimal_t2948259380 ___One_3; // System.Decimal System.Decimal::MaxValueDiv10 Decimal_t2948259380 ___MaxValueDiv10_4; public: inline static int32_t get_offset_of_MinValue_0() { return static_cast<int32_t>(offsetof(Decimal_t2948259380_StaticFields, ___MinValue_0)); } inline Decimal_t2948259380 get_MinValue_0() const { return ___MinValue_0; } inline Decimal_t2948259380 * get_address_of_MinValue_0() { return &___MinValue_0; } inline void set_MinValue_0(Decimal_t2948259380 value) { ___MinValue_0 = value; } inline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(Decimal_t2948259380_StaticFields, ___MaxValue_1)); } inline Decimal_t2948259380 get_MaxValue_1() const { return ___MaxValue_1; } inline Decimal_t2948259380 * get_address_of_MaxValue_1() { return &___MaxValue_1; } inline void set_MaxValue_1(Decimal_t2948259380 value) { ___MaxValue_1 = value; } inline static int32_t get_offset_of_MinusOne_2() { return static_cast<int32_t>(offsetof(Decimal_t2948259380_StaticFields, ___MinusOne_2)); } inline Decimal_t2948259380 get_MinusOne_2() const { return ___MinusOne_2; } inline Decimal_t2948259380 * get_address_of_MinusOne_2() { return &___MinusOne_2; } inline void set_MinusOne_2(Decimal_t2948259380 value) { ___MinusOne_2 = value; } inline static int32_t get_offset_of_One_3() { return static_cast<int32_t>(offsetof(Decimal_t2948259380_StaticFields, ___One_3)); } inline Decimal_t2948259380 get_One_3() const { return ___One_3; } inline Decimal_t2948259380 * get_address_of_One_3() { return &___One_3; } inline void set_One_3(Decimal_t2948259380 value) { ___One_3 = value; } inline static int32_t get_offset_of_MaxValueDiv10_4() { return static_cast<int32_t>(offsetof(Decimal_t2948259380_StaticFields, ___MaxValueDiv10_4)); } inline Decimal_t2948259380 get_MaxValueDiv10_4() const { return ___MaxValueDiv10_4; } inline Decimal_t2948259380 * get_address_of_MaxValueDiv10_4() { return &___MaxValueDiv10_4; } inline void set_MaxValueDiv10_4(Decimal_t2948259380 value) { ___MaxValueDiv10_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DECIMAL_T2948259380_H #ifndef DOUBLE_T594665363_H #define DOUBLE_T594665363_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Double struct Double_t594665363 { public: // System.Double System.Double::m_value double ___m_value_13; public: inline static int32_t get_offset_of_m_value_13() { return static_cast<int32_t>(offsetof(Double_t594665363, ___m_value_13)); } inline double get_m_value_13() const { return ___m_value_13; } inline double* get_address_of_m_value_13() { return &___m_value_13; } inline void set_m_value_13(double value) { ___m_value_13 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DOUBLE_T594665363_H #ifndef ENUM_T4135868527_H #define ENUM_T4135868527_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t4135868527 : public ValueType_t3640485471 { public: public: }; struct Enum_t4135868527_StaticFields { public: // System.Char[] System.Enum::split_char CharU5BU5D_t3528271667* ___split_char_0; public: inline static int32_t get_offset_of_split_char_0() { return static_cast<int32_t>(offsetof(Enum_t4135868527_StaticFields, ___split_char_0)); } inline CharU5BU5D_t3528271667* get_split_char_0() const { return ___split_char_0; } inline CharU5BU5D_t3528271667** get_address_of_split_char_0() { return &___split_char_0; } inline void set_split_char_0(CharU5BU5D_t3528271667* value) { ___split_char_0 = value; Il2CppCodeGenWriteBarrier((&___split_char_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t4135868527_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t4135868527_marshaled_com { }; #endif // ENUM_T4135868527_H #ifndef INT16_T2552820387_H #define INT16_T2552820387_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int16 struct Int16_t2552820387 { public: // System.Int16 System.Int16::m_value int16_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int16_t2552820387, ___m_value_0)); } inline int16_t get_m_value_0() const { return ___m_value_0; } inline int16_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int16_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT16_T2552820387_H #ifndef INT32_T2950945753_H #define INT32_T2950945753_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t2950945753 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(Int32_t2950945753, ___m_value_2)); } inline int32_t get_m_value_2() const { return ___m_value_2; } inline int32_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(int32_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2950945753_H #ifndef INT64_T3736567304_H #define INT64_T3736567304_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int64 struct Int64_t3736567304 { public: // System.Int64 System.Int64::m_value int64_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int64_t3736567304, ___m_value_0)); } inline int64_t get_m_value_0() const { return ___m_value_0; } inline int64_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int64_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT64_T3736567304_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef CUSTOMATTRIBUTETYPEDARGUMENT_T2723150157_H #define CUSTOMATTRIBUTETYPEDARGUMENT_T2723150157_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.CustomAttributeTypedArgument struct CustomAttributeTypedArgument_t2723150157 { public: // System.Type System.Reflection.CustomAttributeTypedArgument::argumentType Type_t * ___argumentType_0; // System.Object System.Reflection.CustomAttributeTypedArgument::value RuntimeObject * ___value_1; public: inline static int32_t get_offset_of_argumentType_0() { return static_cast<int32_t>(offsetof(CustomAttributeTypedArgument_t2723150157, ___argumentType_0)); } inline Type_t * get_argumentType_0() const { return ___argumentType_0; } inline Type_t ** get_address_of_argumentType_0() { return &___argumentType_0; } inline void set_argumentType_0(Type_t * value) { ___argumentType_0 = value; Il2CppCodeGenWriteBarrier((&___argumentType_0), value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(CustomAttributeTypedArgument_t2723150157, ___value_1)); } inline RuntimeObject * get_value_1() const { return ___value_1; } inline RuntimeObject ** get_address_of_value_1() { return &___value_1; } inline void set_value_1(RuntimeObject * value) { ___value_1 = value; Il2CppCodeGenWriteBarrier((&___value_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.CustomAttributeTypedArgument struct CustomAttributeTypedArgument_t2723150157_marshaled_pinvoke { Type_t * ___argumentType_0; Il2CppIUnknown* ___value_1; }; // Native definition for COM marshalling of System.Reflection.CustomAttributeTypedArgument struct CustomAttributeTypedArgument_t2723150157_marshaled_com { Type_t * ___argumentType_0; Il2CppIUnknown* ___value_1; }; #endif // CUSTOMATTRIBUTETYPEDARGUMENT_T2723150157_H #ifndef LABELDATA_T360167391_H #define LABELDATA_T360167391_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.ILGenerator/LabelData struct LabelData_t360167391 { public: // System.Int32 System.Reflection.Emit.ILGenerator/LabelData::addr int32_t ___addr_0; // System.Int32 System.Reflection.Emit.ILGenerator/LabelData::maxStack int32_t ___maxStack_1; public: inline static int32_t get_offset_of_addr_0() { return static_cast<int32_t>(offsetof(LabelData_t360167391, ___addr_0)); } inline int32_t get_addr_0() const { return ___addr_0; } inline int32_t* get_address_of_addr_0() { return &___addr_0; } inline void set_addr_0(int32_t value) { ___addr_0 = value; } inline static int32_t get_offset_of_maxStack_1() { return static_cast<int32_t>(offsetof(LabelData_t360167391, ___maxStack_1)); } inline int32_t get_maxStack_1() const { return ___maxStack_1; } inline int32_t* get_address_of_maxStack_1() { return &___maxStack_1; } inline void set_maxStack_1(int32_t value) { ___maxStack_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LABELDATA_T360167391_H #ifndef LABELFIXUP_T858502054_H #define LABELFIXUP_T858502054_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.ILGenerator/LabelFixup struct LabelFixup_t858502054 { public: // System.Int32 System.Reflection.Emit.ILGenerator/LabelFixup::offset int32_t ___offset_0; // System.Int32 System.Reflection.Emit.ILGenerator/LabelFixup::pos int32_t ___pos_1; // System.Int32 System.Reflection.Emit.ILGenerator/LabelFixup::label_idx int32_t ___label_idx_2; public: inline static int32_t get_offset_of_offset_0() { return static_cast<int32_t>(offsetof(LabelFixup_t858502054, ___offset_0)); } inline int32_t get_offset_0() const { return ___offset_0; } inline int32_t* get_address_of_offset_0() { return &___offset_0; } inline void set_offset_0(int32_t value) { ___offset_0 = value; } inline static int32_t get_offset_of_pos_1() { return static_cast<int32_t>(offsetof(LabelFixup_t858502054, ___pos_1)); } inline int32_t get_pos_1() const { return ___pos_1; } inline int32_t* get_address_of_pos_1() { return &___pos_1; } inline void set_pos_1(int32_t value) { ___pos_1 = value; } inline static int32_t get_offset_of_label_idx_2() { return static_cast<int32_t>(offsetof(LabelFixup_t858502054, ___label_idx_2)); } inline int32_t get_label_idx_2() const { return ___label_idx_2; } inline int32_t* get_address_of_label_idx_2() { return &___label_idx_2; } inline void set_label_idx_2(int32_t value) { ___label_idx_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // LABELFIXUP_T858502054_H #ifndef ILTOKENINFO_T2325775114_H #define ILTOKENINFO_T2325775114_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.ILTokenInfo struct ILTokenInfo_t2325775114 { public: // System.Reflection.MemberInfo System.Reflection.Emit.ILTokenInfo::member MemberInfo_t * ___member_0; // System.Int32 System.Reflection.Emit.ILTokenInfo::code_pos int32_t ___code_pos_1; public: inline static int32_t get_offset_of_member_0() { return static_cast<int32_t>(offsetof(ILTokenInfo_t2325775114, ___member_0)); } inline MemberInfo_t * get_member_0() const { return ___member_0; } inline MemberInfo_t ** get_address_of_member_0() { return &___member_0; } inline void set_member_0(MemberInfo_t * value) { ___member_0 = value; Il2CppCodeGenWriteBarrier((&___member_0), value); } inline static int32_t get_offset_of_code_pos_1() { return static_cast<int32_t>(offsetof(ILTokenInfo_t2325775114, ___code_pos_1)); } inline int32_t get_code_pos_1() const { return ___code_pos_1; } inline int32_t* get_address_of_code_pos_1() { return &___code_pos_1; } inline void set_code_pos_1(int32_t value) { ___code_pos_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.Emit.ILTokenInfo struct ILTokenInfo_t2325775114_marshaled_pinvoke { MemberInfo_t * ___member_0; int32_t ___code_pos_1; }; // Native definition for COM marshalling of System.Reflection.Emit.ILTokenInfo struct ILTokenInfo_t2325775114_marshaled_com { MemberInfo_t * ___member_0; int32_t ___code_pos_1; }; #endif // ILTOKENINFO_T2325775114_H #ifndef MONOWIN32RESOURCE_T1904229483_H #define MONOWIN32RESOURCE_T1904229483_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.MonoWin32Resource struct MonoWin32Resource_t1904229483 { public: // System.Int32 System.Reflection.Emit.MonoWin32Resource::res_type int32_t ___res_type_0; // System.Int32 System.Reflection.Emit.MonoWin32Resource::res_id int32_t ___res_id_1; // System.Int32 System.Reflection.Emit.MonoWin32Resource::lang_id int32_t ___lang_id_2; // System.Byte[] System.Reflection.Emit.MonoWin32Resource::data ByteU5BU5D_t4116647657* ___data_3; public: inline static int32_t get_offset_of_res_type_0() { return static_cast<int32_t>(offsetof(MonoWin32Resource_t1904229483, ___res_type_0)); } inline int32_t get_res_type_0() const { return ___res_type_0; } inline int32_t* get_address_of_res_type_0() { return &___res_type_0; } inline void set_res_type_0(int32_t value) { ___res_type_0 = value; } inline static int32_t get_offset_of_res_id_1() { return static_cast<int32_t>(offsetof(MonoWin32Resource_t1904229483, ___res_id_1)); } inline int32_t get_res_id_1() const { return ___res_id_1; } inline int32_t* get_address_of_res_id_1() { return &___res_id_1; } inline void set_res_id_1(int32_t value) { ___res_id_1 = value; } inline static int32_t get_offset_of_lang_id_2() { return static_cast<int32_t>(offsetof(MonoWin32Resource_t1904229483, ___lang_id_2)); } inline int32_t get_lang_id_2() const { return ___lang_id_2; } inline int32_t* get_address_of_lang_id_2() { return &___lang_id_2; } inline void set_lang_id_2(int32_t value) { ___lang_id_2 = value; } inline static int32_t get_offset_of_data_3() { return static_cast<int32_t>(offsetof(MonoWin32Resource_t1904229483, ___data_3)); } inline ByteU5BU5D_t4116647657* get_data_3() const { return ___data_3; } inline ByteU5BU5D_t4116647657** get_address_of_data_3() { return &___data_3; } inline void set_data_3(ByteU5BU5D_t4116647657* value) { ___data_3 = value; Il2CppCodeGenWriteBarrier((&___data_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.Emit.MonoWin32Resource struct MonoWin32Resource_t1904229483_marshaled_pinvoke { int32_t ___res_type_0; int32_t ___res_id_1; int32_t ___lang_id_2; uint8_t* ___data_3; }; // Native definition for COM marshalling of System.Reflection.Emit.MonoWin32Resource struct MonoWin32Resource_t1904229483_marshaled_com { int32_t ___res_type_0; int32_t ___res_id_1; int32_t ___lang_id_2; uint8_t* ___data_3; }; #endif // MONOWIN32RESOURCE_T1904229483_H #ifndef PARAMETERMODIFIER_T1461694466_H #define PARAMETERMODIFIER_T1461694466_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.ParameterModifier struct ParameterModifier_t1461694466 { public: // System.Boolean[] System.Reflection.ParameterModifier::_byref BooleanU5BU5D_t2897418192* ____byref_0; public: inline static int32_t get_offset_of__byref_0() { return static_cast<int32_t>(offsetof(ParameterModifier_t1461694466, ____byref_0)); } inline BooleanU5BU5D_t2897418192* get__byref_0() const { return ____byref_0; } inline BooleanU5BU5D_t2897418192** get_address_of__byref_0() { return &____byref_0; } inline void set__byref_0(BooleanU5BU5D_t2897418192* value) { ____byref_0 = value; Il2CppCodeGenWriteBarrier((&____byref_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.ParameterModifier struct ParameterModifier_t1461694466_marshaled_pinvoke { int32_t* ____byref_0; }; // Native definition for COM marshalling of System.Reflection.ParameterModifier struct ParameterModifier_t1461694466_marshaled_com { int32_t* ____byref_0; }; #endif // PARAMETERMODIFIER_T1461694466_H #ifndef RESOURCECACHEITEM_T51292791_H #define RESOURCECACHEITEM_T51292791_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Resources.ResourceReader/ResourceCacheItem struct ResourceCacheItem_t51292791 { public: // System.String System.Resources.ResourceReader/ResourceCacheItem::ResourceName String_t* ___ResourceName_0; // System.Object System.Resources.ResourceReader/ResourceCacheItem::ResourceValue RuntimeObject * ___ResourceValue_1; public: inline static int32_t get_offset_of_ResourceName_0() { return static_cast<int32_t>(offsetof(ResourceCacheItem_t51292791, ___ResourceName_0)); } inline String_t* get_ResourceName_0() const { return ___ResourceName_0; } inline String_t** get_address_of_ResourceName_0() { return &___ResourceName_0; } inline void set_ResourceName_0(String_t* value) { ___ResourceName_0 = value; Il2CppCodeGenWriteBarrier((&___ResourceName_0), value); } inline static int32_t get_offset_of_ResourceValue_1() { return static_cast<int32_t>(offsetof(ResourceCacheItem_t51292791, ___ResourceValue_1)); } inline RuntimeObject * get_ResourceValue_1() const { return ___ResourceValue_1; } inline RuntimeObject ** get_address_of_ResourceValue_1() { return &___ResourceValue_1; } inline void set_ResourceValue_1(RuntimeObject * value) { ___ResourceValue_1 = value; Il2CppCodeGenWriteBarrier((&___ResourceValue_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Resources.ResourceReader/ResourceCacheItem struct ResourceCacheItem_t51292791_marshaled_pinvoke { char* ___ResourceName_0; Il2CppIUnknown* ___ResourceValue_1; }; // Native definition for COM marshalling of System.Resources.ResourceReader/ResourceCacheItem struct ResourceCacheItem_t51292791_marshaled_com { Il2CppChar* ___ResourceName_0; Il2CppIUnknown* ___ResourceValue_1; }; #endif // RESOURCECACHEITEM_T51292791_H #ifndef RESOURCEINFO_T2872965302_H #define RESOURCEINFO_T2872965302_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Resources.ResourceReader/ResourceInfo struct ResourceInfo_t2872965302 { public: // System.Int64 System.Resources.ResourceReader/ResourceInfo::ValuePosition int64_t ___ValuePosition_0; // System.String System.Resources.ResourceReader/ResourceInfo::ResourceName String_t* ___ResourceName_1; // System.Int32 System.Resources.ResourceReader/ResourceInfo::TypeIndex int32_t ___TypeIndex_2; public: inline static int32_t get_offset_of_ValuePosition_0() { return static_cast<int32_t>(offsetof(ResourceInfo_t2872965302, ___ValuePosition_0)); } inline int64_t get_ValuePosition_0() const { return ___ValuePosition_0; } inline int64_t* get_address_of_ValuePosition_0() { return &___ValuePosition_0; } inline void set_ValuePosition_0(int64_t value) { ___ValuePosition_0 = value; } inline static int32_t get_offset_of_ResourceName_1() { return static_cast<int32_t>(offsetof(ResourceInfo_t2872965302, ___ResourceName_1)); } inline String_t* get_ResourceName_1() const { return ___ResourceName_1; } inline String_t** get_address_of_ResourceName_1() { return &___ResourceName_1; } inline void set_ResourceName_1(String_t* value) { ___ResourceName_1 = value; Il2CppCodeGenWriteBarrier((&___ResourceName_1), value); } inline static int32_t get_offset_of_TypeIndex_2() { return static_cast<int32_t>(offsetof(ResourceInfo_t2872965302, ___TypeIndex_2)); } inline int32_t get_TypeIndex_2() const { return ___TypeIndex_2; } inline int32_t* get_address_of_TypeIndex_2() { return &___TypeIndex_2; } inline void set_TypeIndex_2(int32_t value) { ___TypeIndex_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Resources.ResourceReader/ResourceInfo struct ResourceInfo_t2872965302_marshaled_pinvoke { int64_t ___ValuePosition_0; char* ___ResourceName_1; int32_t ___TypeIndex_2; }; // Native definition for COM marshalling of System.Resources.ResourceReader/ResourceInfo struct ResourceInfo_t2872965302_marshaled_com { int64_t ___ValuePosition_0; Il2CppChar* ___ResourceName_1; int32_t ___TypeIndex_2; }; #endif // RESOURCEINFO_T2872965302_H #ifndef SBYTE_T1669577662_H #define SBYTE_T1669577662_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SByte struct SByte_t1669577662 { public: // System.SByte System.SByte::m_value int8_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(SByte_t1669577662, ___m_value_0)); } inline int8_t get_m_value_0() const { return ___m_value_0; } inline int8_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int8_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SBYTE_T1669577662_H #ifndef SINGLE_T1397266774_H #define SINGLE_T1397266774_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Single struct Single_t1397266774 { public: // System.Single System.Single::m_value float ___m_value_7; public: inline static int32_t get_offset_of_m_value_7() { return static_cast<int32_t>(offsetof(Single_t1397266774, ___m_value_7)); } inline float get_m_value_7() const { return ___m_value_7; } inline float* get_address_of_m_value_7() { return &___m_value_7; } inline void set_m_value_7(float value) { ___m_value_7 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SINGLE_T1397266774_H #ifndef SYSTEMEXCEPTION_T176217640_H #define SYSTEMEXCEPTION_T176217640_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.SystemException struct SystemException_t176217640 : public Exception_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SYSTEMEXCEPTION_T176217640_H #ifndef MARK_T3471605523_H #define MARK_T3471605523_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Mark struct Mark_t3471605523 { public: // System.Int32 System.Text.RegularExpressions.Mark::Start int32_t ___Start_0; // System.Int32 System.Text.RegularExpressions.Mark::End int32_t ___End_1; // System.Int32 System.Text.RegularExpressions.Mark::Previous int32_t ___Previous_2; public: inline static int32_t get_offset_of_Start_0() { return static_cast<int32_t>(offsetof(Mark_t3471605523, ___Start_0)); } inline int32_t get_Start_0() const { return ___Start_0; } inline int32_t* get_address_of_Start_0() { return &___Start_0; } inline void set_Start_0(int32_t value) { ___Start_0 = value; } inline static int32_t get_offset_of_End_1() { return static_cast<int32_t>(offsetof(Mark_t3471605523, ___End_1)); } inline int32_t get_End_1() const { return ___End_1; } inline int32_t* get_address_of_End_1() { return &___End_1; } inline void set_End_1(int32_t value) { ___End_1 = value; } inline static int32_t get_offset_of_Previous_2() { return static_cast<int32_t>(offsetof(Mark_t3471605523, ___Previous_2)); } inline int32_t get_Previous_2() const { return ___Previous_2; } inline int32_t* get_address_of_Previous_2() { return &___Previous_2; } inline void set_Previous_2(int32_t value) { ___Previous_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MARK_T3471605523_H #ifndef TIMESPAN_T881159249_H #define TIMESPAN_T881159249_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TimeSpan struct TimeSpan_t881159249 { public: // System.Int64 System.TimeSpan::_ticks int64_t ____ticks_3; public: inline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249, ____ticks_3)); } inline int64_t get__ticks_3() const { return ____ticks_3; } inline int64_t* get_address_of__ticks_3() { return &____ticks_3; } inline void set__ticks_3(int64_t value) { ____ticks_3 = value; } }; struct TimeSpan_t881159249_StaticFields { public: // System.TimeSpan System.TimeSpan::MaxValue TimeSpan_t881159249 ___MaxValue_0; // System.TimeSpan System.TimeSpan::MinValue TimeSpan_t881159249 ___MinValue_1; // System.TimeSpan System.TimeSpan::Zero TimeSpan_t881159249 ___Zero_2; public: inline static int32_t get_offset_of_MaxValue_0() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___MaxValue_0)); } inline TimeSpan_t881159249 get_MaxValue_0() const { return ___MaxValue_0; } inline TimeSpan_t881159249 * get_address_of_MaxValue_0() { return &___MaxValue_0; } inline void set_MaxValue_0(TimeSpan_t881159249 value) { ___MaxValue_0 = value; } inline static int32_t get_offset_of_MinValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___MinValue_1)); } inline TimeSpan_t881159249 get_MinValue_1() const { return ___MinValue_1; } inline TimeSpan_t881159249 * get_address_of_MinValue_1() { return &___MinValue_1; } inline void set_MinValue_1(TimeSpan_t881159249 value) { ___MinValue_1 = value; } inline static int32_t get_offset_of_Zero_2() { return static_cast<int32_t>(offsetof(TimeSpan_t881159249_StaticFields, ___Zero_2)); } inline TimeSpan_t881159249 get_Zero_2() const { return ___Zero_2; } inline TimeSpan_t881159249 * get_address_of_Zero_2() { return &___Zero_2; } inline void set_Zero_2(TimeSpan_t881159249 value) { ___Zero_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESPAN_T881159249_H #ifndef UINT16_T2177724958_H #define UINT16_T2177724958_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt16 struct UInt16_t2177724958 { public: // System.UInt16 System.UInt16::m_value uint16_t ___m_value_2; public: inline static int32_t get_offset_of_m_value_2() { return static_cast<int32_t>(offsetof(UInt16_t2177724958, ___m_value_2)); } inline uint16_t get_m_value_2() const { return ___m_value_2; } inline uint16_t* get_address_of_m_value_2() { return &___m_value_2; } inline void set_m_value_2(uint16_t value) { ___m_value_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT16_T2177724958_H #ifndef UINT32_T2560061978_H #define UINT32_T2560061978_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt32 struct UInt32_t2560061978 { public: // System.UInt32 System.UInt32::m_value uint32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt32_t2560061978, ___m_value_0)); } inline uint32_t get_m_value_0() const { return ___m_value_0; } inline uint32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(uint32_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT32_T2560061978_H #ifndef UINT64_T4134040092_H #define UINT64_T4134040092_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UInt64 struct UInt64_t4134040092 { public: // System.UInt64 System.UInt64::m_value uint64_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(UInt64_t4134040092, ___m_value_0)); } inline uint64_t get_m_value_0() const { return ___m_value_0; } inline uint64_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(uint64_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // UINT64_T4134040092_H #ifndef URISCHEME_T722425697_H #define URISCHEME_T722425697_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Uri/UriScheme struct UriScheme_t722425697 { public: // System.String System.Uri/UriScheme::scheme String_t* ___scheme_0; // System.String System.Uri/UriScheme::delimiter String_t* ___delimiter_1; // System.Int32 System.Uri/UriScheme::defaultPort int32_t ___defaultPort_2; public: inline static int32_t get_offset_of_scheme_0() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___scheme_0)); } inline String_t* get_scheme_0() const { return ___scheme_0; } inline String_t** get_address_of_scheme_0() { return &___scheme_0; } inline void set_scheme_0(String_t* value) { ___scheme_0 = value; Il2CppCodeGenWriteBarrier((&___scheme_0), value); } inline static int32_t get_offset_of_delimiter_1() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___delimiter_1)); } inline String_t* get_delimiter_1() const { return ___delimiter_1; } inline String_t** get_address_of_delimiter_1() { return &___delimiter_1; } inline void set_delimiter_1(String_t* value) { ___delimiter_1 = value; Il2CppCodeGenWriteBarrier((&___delimiter_1), value); } inline static int32_t get_offset_of_defaultPort_2() { return static_cast<int32_t>(offsetof(UriScheme_t722425697, ___defaultPort_2)); } inline int32_t get_defaultPort_2() const { return ___defaultPort_2; } inline int32_t* get_address_of_defaultPort_2() { return &___defaultPort_2; } inline void set_defaultPort_2(int32_t value) { ___defaultPort_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Uri/UriScheme struct UriScheme_t722425697_marshaled_pinvoke { char* ___scheme_0; char* ___delimiter_1; int32_t ___defaultPort_2; }; // Native definition for COM marshalling of System.Uri/UriScheme struct UriScheme_t722425697_marshaled_com { Il2CppChar* ___scheme_0; Il2CppChar* ___delimiter_1; int32_t ___defaultPort_2; }; #endif // URISCHEME_T722425697_H #ifndef VOID_T1185182177_H #define VOID_T1185182177_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1185182177 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1185182177_H #ifndef ORDERBLOCK_T1585977831_H #define ORDERBLOCK_T1585977831_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831 { public: // System.Int32 UnityEngine.BeforeRenderHelper/OrderBlock::order int32_t ___order_0; // UnityEngine.Events.UnityAction UnityEngine.BeforeRenderHelper/OrderBlock::callback UnityAction_t3245792599 * ___callback_1; public: inline static int32_t get_offset_of_order_0() { return static_cast<int32_t>(offsetof(OrderBlock_t1585977831, ___order_0)); } inline int32_t get_order_0() const { return ___order_0; } inline int32_t* get_address_of_order_0() { return &___order_0; } inline void set_order_0(int32_t value) { ___order_0 = value; } inline static int32_t get_offset_of_callback_1() { return static_cast<int32_t>(offsetof(OrderBlock_t1585977831, ___callback_1)); } inline UnityAction_t3245792599 * get_callback_1() const { return ___callback_1; } inline UnityAction_t3245792599 ** get_address_of_callback_1() { return &___callback_1; } inline void set_callback_1(UnityAction_t3245792599 * value) { ___callback_1 = value; Il2CppCodeGenWriteBarrier((&___callback_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831_marshaled_pinvoke { int32_t ___order_0; Il2CppMethodPointer ___callback_1; }; // Native definition for COM marshalling of UnityEngine.BeforeRenderHelper/OrderBlock struct OrderBlock_t1585977831_marshaled_com { int32_t ___order_0; Il2CppMethodPointer ___callback_1; }; #endif // ORDERBLOCK_T1585977831_H #ifndef KEYFRAME_T4206410242_H #define KEYFRAME_T4206410242_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Keyframe struct Keyframe_t4206410242 { public: // System.Single UnityEngine.Keyframe::m_Time float ___m_Time_0; // System.Single UnityEngine.Keyframe::m_Value float ___m_Value_1; // System.Single UnityEngine.Keyframe::m_InTangent float ___m_InTangent_2; // System.Single UnityEngine.Keyframe::m_OutTangent float ___m_OutTangent_3; // System.Int32 UnityEngine.Keyframe::m_WeightedMode int32_t ___m_WeightedMode_4; // System.Single UnityEngine.Keyframe::m_InWeight float ___m_InWeight_5; // System.Single UnityEngine.Keyframe::m_OutWeight float ___m_OutWeight_6; public: inline static int32_t get_offset_of_m_Time_0() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_Time_0)); } inline float get_m_Time_0() const { return ___m_Time_0; } inline float* get_address_of_m_Time_0() { return &___m_Time_0; } inline void set_m_Time_0(float value) { ___m_Time_0 = value; } inline static int32_t get_offset_of_m_Value_1() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_Value_1)); } inline float get_m_Value_1() const { return ___m_Value_1; } inline float* get_address_of_m_Value_1() { return &___m_Value_1; } inline void set_m_Value_1(float value) { ___m_Value_1 = value; } inline static int32_t get_offset_of_m_InTangent_2() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_InTangent_2)); } inline float get_m_InTangent_2() const { return ___m_InTangent_2; } inline float* get_address_of_m_InTangent_2() { return &___m_InTangent_2; } inline void set_m_InTangent_2(float value) { ___m_InTangent_2 = value; } inline static int32_t get_offset_of_m_OutTangent_3() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_OutTangent_3)); } inline float get_m_OutTangent_3() const { return ___m_OutTangent_3; } inline float* get_address_of_m_OutTangent_3() { return &___m_OutTangent_3; } inline void set_m_OutTangent_3(float value) { ___m_OutTangent_3 = value; } inline static int32_t get_offset_of_m_WeightedMode_4() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_WeightedMode_4)); } inline int32_t get_m_WeightedMode_4() const { return ___m_WeightedMode_4; } inline int32_t* get_address_of_m_WeightedMode_4() { return &___m_WeightedMode_4; } inline void set_m_WeightedMode_4(int32_t value) { ___m_WeightedMode_4 = value; } inline static int32_t get_offset_of_m_InWeight_5() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_InWeight_5)); } inline float get_m_InWeight_5() const { return ___m_InWeight_5; } inline float* get_address_of_m_InWeight_5() { return &___m_InWeight_5; } inline void set_m_InWeight_5(float value) { ___m_InWeight_5 = value; } inline static int32_t get_offset_of_m_OutWeight_6() { return static_cast<int32_t>(offsetof(Keyframe_t4206410242, ___m_OutWeight_6)); } inline float get_m_OutWeight_6() const { return ___m_OutWeight_6; } inline float* get_address_of_m_OutWeight_6() { return &___m_OutWeight_6; } inline void set_m_OutWeight_6(float value) { ___m_OutWeight_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // KEYFRAME_T4206410242_H #ifndef HITINFO_T3229609740_H #define HITINFO_T3229609740_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t3229609740 { public: // UnityEngine.GameObject UnityEngine.SendMouseEvents/HitInfo::target GameObject_t1113636619 * ___target_0; // UnityEngine.Camera UnityEngine.SendMouseEvents/HitInfo::camera Camera_t4157153871 * ___camera_1; public: inline static int32_t get_offset_of_target_0() { return static_cast<int32_t>(offsetof(HitInfo_t3229609740, ___target_0)); } inline GameObject_t1113636619 * get_target_0() const { return ___target_0; } inline GameObject_t1113636619 ** get_address_of_target_0() { return &___target_0; } inline void set_target_0(GameObject_t1113636619 * value) { ___target_0 = value; Il2CppCodeGenWriteBarrier((&___target_0), value); } inline static int32_t get_offset_of_camera_1() { return static_cast<int32_t>(offsetof(HitInfo_t3229609740, ___camera_1)); } inline Camera_t4157153871 * get_camera_1() const { return ___camera_1; } inline Camera_t4157153871 ** get_address_of_camera_1() { return &___camera_1; } inline void set_camera_1(Camera_t4157153871 * value) { ___camera_1 = value; Il2CppCodeGenWriteBarrier((&___camera_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t3229609740_marshaled_pinvoke { GameObject_t1113636619 * ___target_0; Camera_t4157153871 * ___camera_1; }; // Native definition for COM marshalling of UnityEngine.SendMouseEvents/HitInfo struct HitInfo_t3229609740_marshaled_com { GameObject_t1113636619 * ___target_0; Camera_t4157153871 * ___camera_1; }; #endif // HITINFO_T3229609740_H #ifndef GCACHIEVEMENTDATA_T675222246_H #define GCACHIEVEMENTDATA_T675222246_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t675222246 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Identifier String_t* ___m_Identifier_0; // System.Double UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_PercentCompleted double ___m_PercentCompleted_1; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Completed int32_t ___m_Completed_2; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_Hidden int32_t ___m_Hidden_3; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcAchievementData::m_LastReportedDate int32_t ___m_LastReportedDate_4; public: inline static int32_t get_offset_of_m_Identifier_0() { return static_cast<int32_t>(offsetof(GcAchievementData_t675222246, ___m_Identifier_0)); } inline String_t* get_m_Identifier_0() const { return ___m_Identifier_0; } inline String_t** get_address_of_m_Identifier_0() { return &___m_Identifier_0; } inline void set_m_Identifier_0(String_t* value) { ___m_Identifier_0 = value; Il2CppCodeGenWriteBarrier((&___m_Identifier_0), value); } inline static int32_t get_offset_of_m_PercentCompleted_1() { return static_cast<int32_t>(offsetof(GcAchievementData_t675222246, ___m_PercentCompleted_1)); } inline double get_m_PercentCompleted_1() const { return ___m_PercentCompleted_1; } inline double* get_address_of_m_PercentCompleted_1() { return &___m_PercentCompleted_1; } inline void set_m_PercentCompleted_1(double value) { ___m_PercentCompleted_1 = value; } inline static int32_t get_offset_of_m_Completed_2() { return static_cast<int32_t>(offsetof(GcAchievementData_t675222246, ___m_Completed_2)); } inline int32_t get_m_Completed_2() const { return ___m_Completed_2; } inline int32_t* get_address_of_m_Completed_2() { return &___m_Completed_2; } inline void set_m_Completed_2(int32_t value) { ___m_Completed_2 = value; } inline static int32_t get_offset_of_m_Hidden_3() { return static_cast<int32_t>(offsetof(GcAchievementData_t675222246, ___m_Hidden_3)); } inline int32_t get_m_Hidden_3() const { return ___m_Hidden_3; } inline int32_t* get_address_of_m_Hidden_3() { return &___m_Hidden_3; } inline void set_m_Hidden_3(int32_t value) { ___m_Hidden_3 = value; } inline static int32_t get_offset_of_m_LastReportedDate_4() { return static_cast<int32_t>(offsetof(GcAchievementData_t675222246, ___m_LastReportedDate_4)); } inline int32_t get_m_LastReportedDate_4() const { return ___m_LastReportedDate_4; } inline int32_t* get_address_of_m_LastReportedDate_4() { return &___m_LastReportedDate_4; } inline void set_m_LastReportedDate_4(int32_t value) { ___m_LastReportedDate_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t675222246_marshaled_pinvoke { char* ___m_Identifier_0; double ___m_PercentCompleted_1; int32_t ___m_Completed_2; int32_t ___m_Hidden_3; int32_t ___m_LastReportedDate_4; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcAchievementData struct GcAchievementData_t675222246_marshaled_com { Il2CppChar* ___m_Identifier_0; double ___m_PercentCompleted_1; int32_t ___m_Completed_2; int32_t ___m_Hidden_3; int32_t ___m_LastReportedDate_4; }; #endif // GCACHIEVEMENTDATA_T675222246_H #ifndef GCSCOREDATA_T2125309831_H #define GCSCOREDATA_T2125309831_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t2125309831 { public: // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Category String_t* ___m_Category_0; // System.UInt32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_ValueLow uint32_t ___m_ValueLow_1; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_ValueHigh int32_t ___m_ValueHigh_2; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Date int32_t ___m_Date_3; // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_FormattedValue String_t* ___m_FormattedValue_4; // System.String UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_PlayerID String_t* ___m_PlayerID_5; // System.Int32 UnityEngine.SocialPlatforms.GameCenter.GcScoreData::m_Rank int32_t ___m_Rank_6; public: inline static int32_t get_offset_of_m_Category_0() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_Category_0)); } inline String_t* get_m_Category_0() const { return ___m_Category_0; } inline String_t** get_address_of_m_Category_0() { return &___m_Category_0; } inline void set_m_Category_0(String_t* value) { ___m_Category_0 = value; Il2CppCodeGenWriteBarrier((&___m_Category_0), value); } inline static int32_t get_offset_of_m_ValueLow_1() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_ValueLow_1)); } inline uint32_t get_m_ValueLow_1() const { return ___m_ValueLow_1; } inline uint32_t* get_address_of_m_ValueLow_1() { return &___m_ValueLow_1; } inline void set_m_ValueLow_1(uint32_t value) { ___m_ValueLow_1 = value; } inline static int32_t get_offset_of_m_ValueHigh_2() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_ValueHigh_2)); } inline int32_t get_m_ValueHigh_2() const { return ___m_ValueHigh_2; } inline int32_t* get_address_of_m_ValueHigh_2() { return &___m_ValueHigh_2; } inline void set_m_ValueHigh_2(int32_t value) { ___m_ValueHigh_2 = value; } inline static int32_t get_offset_of_m_Date_3() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_Date_3)); } inline int32_t get_m_Date_3() const { return ___m_Date_3; } inline int32_t* get_address_of_m_Date_3() { return &___m_Date_3; } inline void set_m_Date_3(int32_t value) { ___m_Date_3 = value; } inline static int32_t get_offset_of_m_FormattedValue_4() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_FormattedValue_4)); } inline String_t* get_m_FormattedValue_4() const { return ___m_FormattedValue_4; } inline String_t** get_address_of_m_FormattedValue_4() { return &___m_FormattedValue_4; } inline void set_m_FormattedValue_4(String_t* value) { ___m_FormattedValue_4 = value; Il2CppCodeGenWriteBarrier((&___m_FormattedValue_4), value); } inline static int32_t get_offset_of_m_PlayerID_5() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_PlayerID_5)); } inline String_t* get_m_PlayerID_5() const { return ___m_PlayerID_5; } inline String_t** get_address_of_m_PlayerID_5() { return &___m_PlayerID_5; } inline void set_m_PlayerID_5(String_t* value) { ___m_PlayerID_5 = value; Il2CppCodeGenWriteBarrier((&___m_PlayerID_5), value); } inline static int32_t get_offset_of_m_Rank_6() { return static_cast<int32_t>(offsetof(GcScoreData_t2125309831, ___m_Rank_6)); } inline int32_t get_m_Rank_6() const { return ___m_Rank_6; } inline int32_t* get_address_of_m_Rank_6() { return &___m_Rank_6; } inline void set_m_Rank_6(int32_t value) { ___m_Rank_6 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t2125309831_marshaled_pinvoke { char* ___m_Category_0; uint32_t ___m_ValueLow_1; int32_t ___m_ValueHigh_2; int32_t ___m_Date_3; char* ___m_FormattedValue_4; char* ___m_PlayerID_5; int32_t ___m_Rank_6; }; // Native definition for COM marshalling of UnityEngine.SocialPlatforms.GameCenter.GcScoreData struct GcScoreData_t2125309831_marshaled_com { Il2CppChar* ___m_Category_0; uint32_t ___m_ValueLow_1; int32_t ___m_ValueHigh_2; int32_t ___m_Date_3; Il2CppChar* ___m_FormattedValue_4; Il2CppChar* ___m_PlayerID_5; int32_t ___m_Rank_6; }; #endif // GCSCOREDATA_T2125309831_H #ifndef WORKREQUEST_T1354518612_H #define WORKREQUEST_T1354518612_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.UnitySynchronizationContext/WorkRequest struct WorkRequest_t1354518612 { public: // System.Threading.SendOrPostCallback UnityEngine.UnitySynchronizationContext/WorkRequest::m_DelagateCallback SendOrPostCallback_t2750080073 * ___m_DelagateCallback_0; // System.Object UnityEngine.UnitySynchronizationContext/WorkRequest::m_DelagateState RuntimeObject * ___m_DelagateState_1; // System.Threading.ManualResetEvent UnityEngine.UnitySynchronizationContext/WorkRequest::m_WaitHandle ManualResetEvent_t451242010 * ___m_WaitHandle_2; public: inline static int32_t get_offset_of_m_DelagateCallback_0() { return static_cast<int32_t>(offsetof(WorkRequest_t1354518612, ___m_DelagateCallback_0)); } inline SendOrPostCallback_t2750080073 * get_m_DelagateCallback_0() const { return ___m_DelagateCallback_0; } inline SendOrPostCallback_t2750080073 ** get_address_of_m_DelagateCallback_0() { return &___m_DelagateCallback_0; } inline void set_m_DelagateCallback_0(SendOrPostCallback_t2750080073 * value) { ___m_DelagateCallback_0 = value; Il2CppCodeGenWriteBarrier((&___m_DelagateCallback_0), value); } inline static int32_t get_offset_of_m_DelagateState_1() { return static_cast<int32_t>(offsetof(WorkRequest_t1354518612, ___m_DelagateState_1)); } inline RuntimeObject * get_m_DelagateState_1() const { return ___m_DelagateState_1; } inline RuntimeObject ** get_address_of_m_DelagateState_1() { return &___m_DelagateState_1; } inline void set_m_DelagateState_1(RuntimeObject * value) { ___m_DelagateState_1 = value; Il2CppCodeGenWriteBarrier((&___m_DelagateState_1), value); } inline static int32_t get_offset_of_m_WaitHandle_2() { return static_cast<int32_t>(offsetof(WorkRequest_t1354518612, ___m_WaitHandle_2)); } inline ManualResetEvent_t451242010 * get_m_WaitHandle_2() const { return ___m_WaitHandle_2; } inline ManualResetEvent_t451242010 ** get_address_of_m_WaitHandle_2() { return &___m_WaitHandle_2; } inline void set_m_WaitHandle_2(ManualResetEvent_t451242010 * value) { ___m_WaitHandle_2 = value; Il2CppCodeGenWriteBarrier((&___m_WaitHandle_2), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.UnitySynchronizationContext/WorkRequest struct WorkRequest_t1354518612_marshaled_pinvoke { Il2CppMethodPointer ___m_DelagateCallback_0; Il2CppIUnknown* ___m_DelagateState_1; ManualResetEvent_t451242010 * ___m_WaitHandle_2; }; // Native definition for COM marshalling of UnityEngine.UnitySynchronizationContext/WorkRequest struct WorkRequest_t1354518612_marshaled_com { Il2CppMethodPointer ___m_DelagateCallback_0; Il2CppIUnknown* ___m_DelagateState_1; ManualResetEvent_t451242010 * ___m_WaitHandle_2; }; #endif // WORKREQUEST_T1354518612_H #ifndef VECTOR2_T2156229523_H #define VECTOR2_T2156229523_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector2 struct Vector2_t2156229523 { public: // System.Single UnityEngine.Vector2::x float ___x_0; // System.Single UnityEngine.Vector2::y float ___y_1; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Vector2_t2156229523, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } }; struct Vector2_t2156229523_StaticFields { public: // UnityEngine.Vector2 UnityEngine.Vector2::zeroVector Vector2_t2156229523 ___zeroVector_2; // UnityEngine.Vector2 UnityEngine.Vector2::oneVector Vector2_t2156229523 ___oneVector_3; // UnityEngine.Vector2 UnityEngine.Vector2::upVector Vector2_t2156229523 ___upVector_4; // UnityEngine.Vector2 UnityEngine.Vector2::downVector Vector2_t2156229523 ___downVector_5; // UnityEngine.Vector2 UnityEngine.Vector2::leftVector Vector2_t2156229523 ___leftVector_6; // UnityEngine.Vector2 UnityEngine.Vector2::rightVector Vector2_t2156229523 ___rightVector_7; // UnityEngine.Vector2 UnityEngine.Vector2::positiveInfinityVector Vector2_t2156229523 ___positiveInfinityVector_8; // UnityEngine.Vector2 UnityEngine.Vector2::negativeInfinityVector Vector2_t2156229523 ___negativeInfinityVector_9; public: inline static int32_t get_offset_of_zeroVector_2() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___zeroVector_2)); } inline Vector2_t2156229523 get_zeroVector_2() const { return ___zeroVector_2; } inline Vector2_t2156229523 * get_address_of_zeroVector_2() { return &___zeroVector_2; } inline void set_zeroVector_2(Vector2_t2156229523 value) { ___zeroVector_2 = value; } inline static int32_t get_offset_of_oneVector_3() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___oneVector_3)); } inline Vector2_t2156229523 get_oneVector_3() const { return ___oneVector_3; } inline Vector2_t2156229523 * get_address_of_oneVector_3() { return &___oneVector_3; } inline void set_oneVector_3(Vector2_t2156229523 value) { ___oneVector_3 = value; } inline static int32_t get_offset_of_upVector_4() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___upVector_4)); } inline Vector2_t2156229523 get_upVector_4() const { return ___upVector_4; } inline Vector2_t2156229523 * get_address_of_upVector_4() { return &___upVector_4; } inline void set_upVector_4(Vector2_t2156229523 value) { ___upVector_4 = value; } inline static int32_t get_offset_of_downVector_5() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___downVector_5)); } inline Vector2_t2156229523 get_downVector_5() const { return ___downVector_5; } inline Vector2_t2156229523 * get_address_of_downVector_5() { return &___downVector_5; } inline void set_downVector_5(Vector2_t2156229523 value) { ___downVector_5 = value; } inline static int32_t get_offset_of_leftVector_6() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___leftVector_6)); } inline Vector2_t2156229523 get_leftVector_6() const { return ___leftVector_6; } inline Vector2_t2156229523 * get_address_of_leftVector_6() { return &___leftVector_6; } inline void set_leftVector_6(Vector2_t2156229523 value) { ___leftVector_6 = value; } inline static int32_t get_offset_of_rightVector_7() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___rightVector_7)); } inline Vector2_t2156229523 get_rightVector_7() const { return ___rightVector_7; } inline Vector2_t2156229523 * get_address_of_rightVector_7() { return &___rightVector_7; } inline void set_rightVector_7(Vector2_t2156229523 value) { ___rightVector_7 = value; } inline static int32_t get_offset_of_positiveInfinityVector_8() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___positiveInfinityVector_8)); } inline Vector2_t2156229523 get_positiveInfinityVector_8() const { return ___positiveInfinityVector_8; } inline Vector2_t2156229523 * get_address_of_positiveInfinityVector_8() { return &___positiveInfinityVector_8; } inline void set_positiveInfinityVector_8(Vector2_t2156229523 value) { ___positiveInfinityVector_8 = value; } inline static int32_t get_offset_of_negativeInfinityVector_9() { return static_cast<int32_t>(offsetof(Vector2_t2156229523_StaticFields, ___negativeInfinityVector_9)); } inline Vector2_t2156229523 get_negativeInfinityVector_9() const { return ___negativeInfinityVector_9; } inline Vector2_t2156229523 * get_address_of_negativeInfinityVector_9() { return &___negativeInfinityVector_9; } inline void set_negativeInfinityVector_9(Vector2_t2156229523 value) { ___negativeInfinityVector_9 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR2_T2156229523_H #ifndef VECTOR3_T3722313464_H #define VECTOR3_T3722313464_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Vector3 struct Vector3_t3722313464 { public: // System.Single UnityEngine.Vector3::x float ___x_0; // System.Single UnityEngine.Vector3::y float ___y_1; // System.Single UnityEngine.Vector3::z float ___z_2; public: inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___x_0)); } inline float get_x_0() const { return ___x_0; } inline float* get_address_of_x_0() { return &___x_0; } inline void set_x_0(float value) { ___x_0 = value; } inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___y_1)); } inline float get_y_1() const { return ___y_1; } inline float* get_address_of_y_1() { return &___y_1; } inline void set_y_1(float value) { ___y_1 = value; } inline static int32_t get_offset_of_z_2() { return static_cast<int32_t>(offsetof(Vector3_t3722313464, ___z_2)); } inline float get_z_2() const { return ___z_2; } inline float* get_address_of_z_2() { return &___z_2; } inline void set_z_2(float value) { ___z_2 = value; } }; struct Vector3_t3722313464_StaticFields { public: // UnityEngine.Vector3 UnityEngine.Vector3::zeroVector Vector3_t3722313464 ___zeroVector_3; // UnityEngine.Vector3 UnityEngine.Vector3::oneVector Vector3_t3722313464 ___oneVector_4; // UnityEngine.Vector3 UnityEngine.Vector3::upVector Vector3_t3722313464 ___upVector_5; // UnityEngine.Vector3 UnityEngine.Vector3::downVector Vector3_t3722313464 ___downVector_6; // UnityEngine.Vector3 UnityEngine.Vector3::leftVector Vector3_t3722313464 ___leftVector_7; // UnityEngine.Vector3 UnityEngine.Vector3::rightVector Vector3_t3722313464 ___rightVector_8; // UnityEngine.Vector3 UnityEngine.Vector3::forwardVector Vector3_t3722313464 ___forwardVector_9; // UnityEngine.Vector3 UnityEngine.Vector3::backVector Vector3_t3722313464 ___backVector_10; // UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector Vector3_t3722313464 ___positiveInfinityVector_11; // UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector Vector3_t3722313464 ___negativeInfinityVector_12; public: inline static int32_t get_offset_of_zeroVector_3() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___zeroVector_3)); } inline Vector3_t3722313464 get_zeroVector_3() const { return ___zeroVector_3; } inline Vector3_t3722313464 * get_address_of_zeroVector_3() { return &___zeroVector_3; } inline void set_zeroVector_3(Vector3_t3722313464 value) { ___zeroVector_3 = value; } inline static int32_t get_offset_of_oneVector_4() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___oneVector_4)); } inline Vector3_t3722313464 get_oneVector_4() const { return ___oneVector_4; } inline Vector3_t3722313464 * get_address_of_oneVector_4() { return &___oneVector_4; } inline void set_oneVector_4(Vector3_t3722313464 value) { ___oneVector_4 = value; } inline static int32_t get_offset_of_upVector_5() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___upVector_5)); } inline Vector3_t3722313464 get_upVector_5() const { return ___upVector_5; } inline Vector3_t3722313464 * get_address_of_upVector_5() { return &___upVector_5; } inline void set_upVector_5(Vector3_t3722313464 value) { ___upVector_5 = value; } inline static int32_t get_offset_of_downVector_6() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___downVector_6)); } inline Vector3_t3722313464 get_downVector_6() const { return ___downVector_6; } inline Vector3_t3722313464 * get_address_of_downVector_6() { return &___downVector_6; } inline void set_downVector_6(Vector3_t3722313464 value) { ___downVector_6 = value; } inline static int32_t get_offset_of_leftVector_7() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___leftVector_7)); } inline Vector3_t3722313464 get_leftVector_7() const { return ___leftVector_7; } inline Vector3_t3722313464 * get_address_of_leftVector_7() { return &___leftVector_7; } inline void set_leftVector_7(Vector3_t3722313464 value) { ___leftVector_7 = value; } inline static int32_t get_offset_of_rightVector_8() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___rightVector_8)); } inline Vector3_t3722313464 get_rightVector_8() const { return ___rightVector_8; } inline Vector3_t3722313464 * get_address_of_rightVector_8() { return &___rightVector_8; } inline void set_rightVector_8(Vector3_t3722313464 value) { ___rightVector_8 = value; } inline static int32_t get_offset_of_forwardVector_9() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___forwardVector_9)); } inline Vector3_t3722313464 get_forwardVector_9() const { return ___forwardVector_9; } inline Vector3_t3722313464 * get_address_of_forwardVector_9() { return &___forwardVector_9; } inline void set_forwardVector_9(Vector3_t3722313464 value) { ___forwardVector_9 = value; } inline static int32_t get_offset_of_backVector_10() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___backVector_10)); } inline Vector3_t3722313464 get_backVector_10() const { return ___backVector_10; } inline Vector3_t3722313464 * get_address_of_backVector_10() { return &___backVector_10; } inline void set_backVector_10(Vector3_t3722313464 value) { ___backVector_10 = value; } inline static int32_t get_offset_of_positiveInfinityVector_11() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___positiveInfinityVector_11)); } inline Vector3_t3722313464 get_positiveInfinityVector_11() const { return ___positiveInfinityVector_11; } inline Vector3_t3722313464 * get_address_of_positiveInfinityVector_11() { return &___positiveInfinityVector_11; } inline void set_positiveInfinityVector_11(Vector3_t3722313464 value) { ___positiveInfinityVector_11 = value; } inline static int32_t get_offset_of_negativeInfinityVector_12() { return static_cast<int32_t>(offsetof(Vector3_t3722313464_StaticFields, ___negativeInfinityVector_12)); } inline Vector3_t3722313464 get_negativeInfinityVector_12() const { return ___negativeInfinityVector_12; } inline Vector3_t3722313464 * get_address_of_negativeInfinityVector_12() { return &___negativeInfinityVector_12; } inline void set_negativeInfinityVector_12(Vector3_t3722313464 value) { ___negativeInfinityVector_12 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VECTOR3_T3722313464_H #ifndef CLIENTCERTIFICATETYPE_T1004704908_H #define CLIENTCERTIFICATETYPE_T1004704908_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Mono.Security.Protocol.Tls.Handshake.ClientCertificateType struct ClientCertificateType_t1004704908 { public: // System.Int32 Mono.Security.Protocol.Tls.Handshake.ClientCertificateType::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ClientCertificateType_t1004704908, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CLIENTCERTIFICATETYPE_T1004704908_H #ifndef ARGUMENTEXCEPTION_T132251570_H #define ARGUMENTEXCEPTION_T132251570_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ArgumentException struct ArgumentException_t132251570 : public SystemException_t176217640 { public: // System.String System.ArgumentException::param_name String_t* ___param_name_12; public: inline static int32_t get_offset_of_param_name_12() { return static_cast<int32_t>(offsetof(ArgumentException_t132251570, ___param_name_12)); } inline String_t* get_param_name_12() const { return ___param_name_12; } inline String_t** get_address_of_param_name_12() { return &___param_name_12; } inline void set_param_name_12(String_t* value) { ___param_name_12 = value; Il2CppCodeGenWriteBarrier((&___param_name_12), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARGUMENTEXCEPTION_T132251570_H #ifndef DATETIMEKIND_T3468814247_H #define DATETIMEKIND_T3468814247_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.DateTimeKind struct DateTimeKind_t3468814247 { public: // System.Int32 System.DateTimeKind::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(DateTimeKind_t3468814247, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DATETIMEKIND_T3468814247_H #ifndef DELEGATE_T1188392813_H #define DELEGATE_T1188392813_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Delegate struct Delegate_t1188392813 : public RuntimeObject { public: // System.IntPtr System.Delegate::method_ptr Il2CppMethodPointer ___method_ptr_0; // System.IntPtr System.Delegate::invoke_impl intptr_t ___invoke_impl_1; // System.Object System.Delegate::m_target RuntimeObject * ___m_target_2; // System.IntPtr System.Delegate::method intptr_t ___method_3; // System.IntPtr System.Delegate::delegate_trampoline intptr_t ___delegate_trampoline_4; // System.IntPtr System.Delegate::method_code intptr_t ___method_code_5; // System.Reflection.MethodInfo System.Delegate::method_info MethodInfo_t * ___method_info_6; // System.Reflection.MethodInfo System.Delegate::original_method_info MethodInfo_t * ___original_method_info_7; // System.DelegateData System.Delegate::data DelegateData_t1677132599 * ___data_8; public: inline static int32_t get_offset_of_method_ptr_0() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_ptr_0)); } inline Il2CppMethodPointer get_method_ptr_0() const { return ___method_ptr_0; } inline Il2CppMethodPointer* get_address_of_method_ptr_0() { return &___method_ptr_0; } inline void set_method_ptr_0(Il2CppMethodPointer value) { ___method_ptr_0 = value; } inline static int32_t get_offset_of_invoke_impl_1() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___invoke_impl_1)); } inline intptr_t get_invoke_impl_1() const { return ___invoke_impl_1; } inline intptr_t* get_address_of_invoke_impl_1() { return &___invoke_impl_1; } inline void set_invoke_impl_1(intptr_t value) { ___invoke_impl_1 = value; } inline static int32_t get_offset_of_m_target_2() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___m_target_2)); } inline RuntimeObject * get_m_target_2() const { return ___m_target_2; } inline RuntimeObject ** get_address_of_m_target_2() { return &___m_target_2; } inline void set_m_target_2(RuntimeObject * value) { ___m_target_2 = value; Il2CppCodeGenWriteBarrier((&___m_target_2), value); } inline static int32_t get_offset_of_method_3() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_3)); } inline intptr_t get_method_3() const { return ___method_3; } inline intptr_t* get_address_of_method_3() { return &___method_3; } inline void set_method_3(intptr_t value) { ___method_3 = value; } inline static int32_t get_offset_of_delegate_trampoline_4() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___delegate_trampoline_4)); } inline intptr_t get_delegate_trampoline_4() const { return ___delegate_trampoline_4; } inline intptr_t* get_address_of_delegate_trampoline_4() { return &___delegate_trampoline_4; } inline void set_delegate_trampoline_4(intptr_t value) { ___delegate_trampoline_4 = value; } inline static int32_t get_offset_of_method_code_5() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_code_5)); } inline intptr_t get_method_code_5() const { return ___method_code_5; } inline intptr_t* get_address_of_method_code_5() { return &___method_code_5; } inline void set_method_code_5(intptr_t value) { ___method_code_5 = value; } inline static int32_t get_offset_of_method_info_6() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___method_info_6)); } inline MethodInfo_t * get_method_info_6() const { return ___method_info_6; } inline MethodInfo_t ** get_address_of_method_info_6() { return &___method_info_6; } inline void set_method_info_6(MethodInfo_t * value) { ___method_info_6 = value; Il2CppCodeGenWriteBarrier((&___method_info_6), value); } inline static int32_t get_offset_of_original_method_info_7() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___original_method_info_7)); } inline MethodInfo_t * get_original_method_info_7() const { return ___original_method_info_7; } inline MethodInfo_t ** get_address_of_original_method_info_7() { return &___original_method_info_7; } inline void set_original_method_info_7(MethodInfo_t * value) { ___original_method_info_7 = value; Il2CppCodeGenWriteBarrier((&___original_method_info_7), value); } inline static int32_t get_offset_of_data_8() { return static_cast<int32_t>(offsetof(Delegate_t1188392813, ___data_8)); } inline DelegateData_t1677132599 * get_data_8() const { return ___data_8; } inline DelegateData_t1677132599 ** get_address_of_data_8() { return &___data_8; } inline void set_data_8(DelegateData_t1677132599 * value) { ___data_8 = value; Il2CppCodeGenWriteBarrier((&___data_8), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DELEGATE_T1188392813_H #ifndef INVALIDOPERATIONEXCEPTION_T56020091_H #define INVALIDOPERATIONEXCEPTION_T56020091_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.InvalidOperationException struct InvalidOperationException_t56020091 : public SystemException_t176217640 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INVALIDOPERATIONEXCEPTION_T56020091_H #ifndef FALLBACK_T3495999270_H #define FALLBACK_T3495999270_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Linq.Enumerable/Fallback struct Fallback_t3495999270 { public: // System.Int32 System.Linq.Enumerable/Fallback::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(Fallback_t3495999270, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FALLBACK_T3495999270_H #ifndef BINDINGFLAGS_T2721792723_H #define BINDINGFLAGS_T2721792723_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.BindingFlags struct BindingFlags_t2721792723 { public: // System.Int32 System.Reflection.BindingFlags::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(BindingFlags_t2721792723, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BINDINGFLAGS_T2721792723_H #ifndef CUSTOMATTRIBUTENAMEDARGUMENT_T287865710_H #define CUSTOMATTRIBUTENAMEDARGUMENT_T287865710_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.CustomAttributeNamedArgument struct CustomAttributeNamedArgument_t287865710 { public: // System.Reflection.CustomAttributeTypedArgument System.Reflection.CustomAttributeNamedArgument::typedArgument CustomAttributeTypedArgument_t2723150157 ___typedArgument_0; // System.Reflection.MemberInfo System.Reflection.CustomAttributeNamedArgument::memberInfo MemberInfo_t * ___memberInfo_1; public: inline static int32_t get_offset_of_typedArgument_0() { return static_cast<int32_t>(offsetof(CustomAttributeNamedArgument_t287865710, ___typedArgument_0)); } inline CustomAttributeTypedArgument_t2723150157 get_typedArgument_0() const { return ___typedArgument_0; } inline CustomAttributeTypedArgument_t2723150157 * get_address_of_typedArgument_0() { return &___typedArgument_0; } inline void set_typedArgument_0(CustomAttributeTypedArgument_t2723150157 value) { ___typedArgument_0 = value; } inline static int32_t get_offset_of_memberInfo_1() { return static_cast<int32_t>(offsetof(CustomAttributeNamedArgument_t287865710, ___memberInfo_1)); } inline MemberInfo_t * get_memberInfo_1() const { return ___memberInfo_1; } inline MemberInfo_t ** get_address_of_memberInfo_1() { return &___memberInfo_1; } inline void set_memberInfo_1(MemberInfo_t * value) { ___memberInfo_1 = value; Il2CppCodeGenWriteBarrier((&___memberInfo_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.CustomAttributeNamedArgument struct CustomAttributeNamedArgument_t287865710_marshaled_pinvoke { CustomAttributeTypedArgument_t2723150157_marshaled_pinvoke ___typedArgument_0; MemberInfo_t * ___memberInfo_1; }; // Native definition for COM marshalling of System.Reflection.CustomAttributeNamedArgument struct CustomAttributeNamedArgument_t287865710_marshaled_com { CustomAttributeTypedArgument_t2723150157_marshaled_com ___typedArgument_0; MemberInfo_t * ___memberInfo_1; }; #endif // CUSTOMATTRIBUTENAMEDARGUMENT_T287865710_H #ifndef RESOURCEATTRIBUTES_T3997964906_H #define RESOURCEATTRIBUTES_T3997964906_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.ResourceAttributes struct ResourceAttributes_t3997964906 { public: // System.Int32 System.Reflection.ResourceAttributes::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ResourceAttributes_t3997964906, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RESOURCEATTRIBUTES_T3997964906_H #ifndef TYPETAG_T3541821701_H #define TYPETAG_T3541821701_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Runtime.Serialization.Formatters.Binary.TypeTag struct TypeTag_t3541821701 { public: // System.Byte System.Runtime.Serialization.Formatters.Binary.TypeTag::value__ uint8_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(TypeTag_t3541821701, ___value___1)); } inline uint8_t get_value___1() const { return ___value___1; } inline uint8_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(uint8_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPETAG_T3541821701_H #ifndef RUNTIMETYPEHANDLE_T3027515415_H #define RUNTIMETYPEHANDLE_T3027515415_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.RuntimeTypeHandle struct RuntimeTypeHandle_t3027515415 { public: // System.IntPtr System.RuntimeTypeHandle::value intptr_t ___value_0; public: inline static int32_t get_offset_of_value_0() { return static_cast<int32_t>(offsetof(RuntimeTypeHandle_t3027515415, ___value_0)); } inline intptr_t get_value_0() const { return ___value_0; } inline intptr_t* get_address_of_value_0() { return &___value_0; } inline void set_value_0(intptr_t value) { ___value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMETYPEHANDLE_T3027515415_H #ifndef X509CHAINSTATUSFLAGS_T1026973125_H #define X509CHAINSTATUSFLAGS_T1026973125_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509ChainStatusFlags struct X509ChainStatusFlags_t1026973125 { public: // System.Int32 System.Security.Cryptography.X509Certificates.X509ChainStatusFlags::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(X509ChainStatusFlags_t1026973125, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // X509CHAINSTATUSFLAGS_T1026973125_H #ifndef SECURITYACTION_T569814076_H #define SECURITYACTION_T569814076_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Permissions.SecurityAction struct SecurityAction_t569814076 { public: // System.Int32 System.Security.Permissions.SecurityAction::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(SecurityAction_t569814076, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // SECURITYACTION_T569814076_H #ifndef CASTHELPER_1_T2613165452_H #define CASTHELPER_1_T2613165452_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.CastHelper`1<System.Object> struct CastHelper_1_t2613165452 { public: // T UnityEngine.CastHelper`1::t RuntimeObject * ___t_0; // System.IntPtr UnityEngine.CastHelper`1::onePointerFurtherThanT intptr_t ___onePointerFurtherThanT_1; public: inline static int32_t get_offset_of_t_0() { return static_cast<int32_t>(offsetof(CastHelper_1_t2613165452, ___t_0)); } inline RuntimeObject * get_t_0() const { return ___t_0; } inline RuntimeObject ** get_address_of_t_0() { return &___t_0; } inline void set_t_0(RuntimeObject * value) { ___t_0 = value; Il2CppCodeGenWriteBarrier((&___t_0), value); } inline static int32_t get_offset_of_onePointerFurtherThanT_1() { return static_cast<int32_t>(offsetof(CastHelper_1_t2613165452, ___onePointerFurtherThanT_1)); } inline intptr_t get_onePointerFurtherThanT_1() const { return ___onePointerFurtherThanT_1; } inline intptr_t* get_address_of_onePointerFurtherThanT_1() { return &___onePointerFurtherThanT_1; } inline void set_onePointerFurtherThanT_1(intptr_t value) { ___onePointerFurtherThanT_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CASTHELPER_1_T2613165452_H #ifndef CONTACTPOINT_T3758755253_H #define CONTACTPOINT_T3758755253_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ContactPoint struct ContactPoint_t3758755253 { public: // UnityEngine.Vector3 UnityEngine.ContactPoint::m_Point Vector3_t3722313464 ___m_Point_0; // UnityEngine.Vector3 UnityEngine.ContactPoint::m_Normal Vector3_t3722313464 ___m_Normal_1; // System.Int32 UnityEngine.ContactPoint::m_ThisColliderInstanceID int32_t ___m_ThisColliderInstanceID_2; // System.Int32 UnityEngine.ContactPoint::m_OtherColliderInstanceID int32_t ___m_OtherColliderInstanceID_3; // System.Single UnityEngine.ContactPoint::m_Separation float ___m_Separation_4; public: inline static int32_t get_offset_of_m_Point_0() { return static_cast<int32_t>(offsetof(ContactPoint_t3758755253, ___m_Point_0)); } inline Vector3_t3722313464 get_m_Point_0() const { return ___m_Point_0; } inline Vector3_t3722313464 * get_address_of_m_Point_0() { return &___m_Point_0; } inline void set_m_Point_0(Vector3_t3722313464 value) { ___m_Point_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast<int32_t>(offsetof(ContactPoint_t3758755253, ___m_Normal_1)); } inline Vector3_t3722313464 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_t3722313464 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_t3722313464 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_ThisColliderInstanceID_2() { return static_cast<int32_t>(offsetof(ContactPoint_t3758755253, ___m_ThisColliderInstanceID_2)); } inline int32_t get_m_ThisColliderInstanceID_2() const { return ___m_ThisColliderInstanceID_2; } inline int32_t* get_address_of_m_ThisColliderInstanceID_2() { return &___m_ThisColliderInstanceID_2; } inline void set_m_ThisColliderInstanceID_2(int32_t value) { ___m_ThisColliderInstanceID_2 = value; } inline static int32_t get_offset_of_m_OtherColliderInstanceID_3() { return static_cast<int32_t>(offsetof(ContactPoint_t3758755253, ___m_OtherColliderInstanceID_3)); } inline int32_t get_m_OtherColliderInstanceID_3() const { return ___m_OtherColliderInstanceID_3; } inline int32_t* get_address_of_m_OtherColliderInstanceID_3() { return &___m_OtherColliderInstanceID_3; } inline void set_m_OtherColliderInstanceID_3(int32_t value) { ___m_OtherColliderInstanceID_3 = value; } inline static int32_t get_offset_of_m_Separation_4() { return static_cast<int32_t>(offsetof(ContactPoint_t3758755253, ___m_Separation_4)); } inline float get_m_Separation_4() const { return ___m_Separation_4; } inline float* get_address_of_m_Separation_4() { return &___m_Separation_4; } inline void set_m_Separation_4(float value) { ___m_Separation_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONTACTPOINT_T3758755253_H #ifndef PLAYERLOOPSYSTEM_T105772105_H #define PLAYERLOOPSYSTEM_T105772105_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Experimental.LowLevel.PlayerLoopSystem struct PlayerLoopSystem_t105772105 { public: // System.Type UnityEngine.Experimental.LowLevel.PlayerLoopSystem::type Type_t * ___type_0; // UnityEngine.Experimental.LowLevel.PlayerLoopSystem[] UnityEngine.Experimental.LowLevel.PlayerLoopSystem::subSystemList PlayerLoopSystemU5BU5D_t1150299252* ___subSystemList_1; // UnityEngine.Experimental.LowLevel.PlayerLoopSystem/UpdateFunction UnityEngine.Experimental.LowLevel.PlayerLoopSystem::updateDelegate UpdateFunction_t377278577 * ___updateDelegate_2; // System.IntPtr UnityEngine.Experimental.LowLevel.PlayerLoopSystem::updateFunction intptr_t ___updateFunction_3; // System.IntPtr UnityEngine.Experimental.LowLevel.PlayerLoopSystem::loopConditionFunction intptr_t ___loopConditionFunction_4; public: inline static int32_t get_offset_of_type_0() { return static_cast<int32_t>(offsetof(PlayerLoopSystem_t105772105, ___type_0)); } inline Type_t * get_type_0() const { return ___type_0; } inline Type_t ** get_address_of_type_0() { return &___type_0; } inline void set_type_0(Type_t * value) { ___type_0 = value; Il2CppCodeGenWriteBarrier((&___type_0), value); } inline static int32_t get_offset_of_subSystemList_1() { return static_cast<int32_t>(offsetof(PlayerLoopSystem_t105772105, ___subSystemList_1)); } inline PlayerLoopSystemU5BU5D_t1150299252* get_subSystemList_1() const { return ___subSystemList_1; } inline PlayerLoopSystemU5BU5D_t1150299252** get_address_of_subSystemList_1() { return &___subSystemList_1; } inline void set_subSystemList_1(PlayerLoopSystemU5BU5D_t1150299252* value) { ___subSystemList_1 = value; Il2CppCodeGenWriteBarrier((&___subSystemList_1), value); } inline static int32_t get_offset_of_updateDelegate_2() { return static_cast<int32_t>(offsetof(PlayerLoopSystem_t105772105, ___updateDelegate_2)); } inline UpdateFunction_t377278577 * get_updateDelegate_2() const { return ___updateDelegate_2; } inline UpdateFunction_t377278577 ** get_address_of_updateDelegate_2() { return &___updateDelegate_2; } inline void set_updateDelegate_2(UpdateFunction_t377278577 * value) { ___updateDelegate_2 = value; Il2CppCodeGenWriteBarrier((&___updateDelegate_2), value); } inline static int32_t get_offset_of_updateFunction_3() { return static_cast<int32_t>(offsetof(PlayerLoopSystem_t105772105, ___updateFunction_3)); } inline intptr_t get_updateFunction_3() const { return ___updateFunction_3; } inline intptr_t* get_address_of_updateFunction_3() { return &___updateFunction_3; } inline void set_updateFunction_3(intptr_t value) { ___updateFunction_3 = value; } inline static int32_t get_offset_of_loopConditionFunction_4() { return static_cast<int32_t>(offsetof(PlayerLoopSystem_t105772105, ___loopConditionFunction_4)); } inline intptr_t get_loopConditionFunction_4() const { return ___loopConditionFunction_4; } inline intptr_t* get_address_of_loopConditionFunction_4() { return &___loopConditionFunction_4; } inline void set_loopConditionFunction_4(intptr_t value) { ___loopConditionFunction_4 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Experimental.LowLevel.PlayerLoopSystem struct PlayerLoopSystem_t105772105_marshaled_pinvoke { Type_t * ___type_0; PlayerLoopSystem_t105772105_marshaled_pinvoke* ___subSystemList_1; Il2CppMethodPointer ___updateDelegate_2; intptr_t ___updateFunction_3; intptr_t ___loopConditionFunction_4; }; // Native definition for COM marshalling of UnityEngine.Experimental.LowLevel.PlayerLoopSystem struct PlayerLoopSystem_t105772105_marshaled_com { Type_t * ___type_0; PlayerLoopSystem_t105772105_marshaled_com* ___subSystemList_1; Il2CppMethodPointer ___updateDelegate_2; intptr_t ___updateFunction_3; intptr_t ___loopConditionFunction_4; }; #endif // PLAYERLOOPSYSTEM_T105772105_H #ifndef OBJECT_T631007953_H #define OBJECT_T631007953_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Object struct Object_t631007953 : public RuntimeObject { public: // System.IntPtr UnityEngine.Object::m_CachedPtr intptr_t ___m_CachedPtr_0; public: inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_t631007953, ___m_CachedPtr_0)); } inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; } inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; } inline void set_m_CachedPtr_0(intptr_t value) { ___m_CachedPtr_0 = value; } }; struct Object_t631007953_StaticFields { public: // System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1; public: inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_t631007953_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); } inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; } inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; } inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value) { ___OffsetOfInstanceIDInCPlusPlusObject_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Object struct Object_t631007953_marshaled_pinvoke { intptr_t ___m_CachedPtr_0; }; // Native definition for COM marshalling of UnityEngine.Object struct Object_t631007953_marshaled_com { intptr_t ___m_CachedPtr_0; }; #endif // OBJECT_T631007953_H #ifndef RAYCASTHIT_T1056001966_H #define RAYCASTHIT_T1056001966_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.RaycastHit struct RaycastHit_t1056001966 { public: // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Point Vector3_t3722313464 ___m_Point_0; // UnityEngine.Vector3 UnityEngine.RaycastHit::m_Normal Vector3_t3722313464 ___m_Normal_1; // System.UInt32 UnityEngine.RaycastHit::m_FaceID uint32_t ___m_FaceID_2; // System.Single UnityEngine.RaycastHit::m_Distance float ___m_Distance_3; // UnityEngine.Vector2 UnityEngine.RaycastHit::m_UV Vector2_t2156229523 ___m_UV_4; // System.Int32 UnityEngine.RaycastHit::m_Collider int32_t ___m_Collider_5; public: inline static int32_t get_offset_of_m_Point_0() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_Point_0)); } inline Vector3_t3722313464 get_m_Point_0() const { return ___m_Point_0; } inline Vector3_t3722313464 * get_address_of_m_Point_0() { return &___m_Point_0; } inline void set_m_Point_0(Vector3_t3722313464 value) { ___m_Point_0 = value; } inline static int32_t get_offset_of_m_Normal_1() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_Normal_1)); } inline Vector3_t3722313464 get_m_Normal_1() const { return ___m_Normal_1; } inline Vector3_t3722313464 * get_address_of_m_Normal_1() { return &___m_Normal_1; } inline void set_m_Normal_1(Vector3_t3722313464 value) { ___m_Normal_1 = value; } inline static int32_t get_offset_of_m_FaceID_2() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_FaceID_2)); } inline uint32_t get_m_FaceID_2() const { return ___m_FaceID_2; } inline uint32_t* get_address_of_m_FaceID_2() { return &___m_FaceID_2; } inline void set_m_FaceID_2(uint32_t value) { ___m_FaceID_2 = value; } inline static int32_t get_offset_of_m_Distance_3() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_Distance_3)); } inline float get_m_Distance_3() const { return ___m_Distance_3; } inline float* get_address_of_m_Distance_3() { return &___m_Distance_3; } inline void set_m_Distance_3(float value) { ___m_Distance_3 = value; } inline static int32_t get_offset_of_m_UV_4() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_UV_4)); } inline Vector2_t2156229523 get_m_UV_4() const { return ___m_UV_4; } inline Vector2_t2156229523 * get_address_of_m_UV_4() { return &___m_UV_4; } inline void set_m_UV_4(Vector2_t2156229523 value) { ___m_UV_4 = value; } inline static int32_t get_offset_of_m_Collider_5() { return static_cast<int32_t>(offsetof(RaycastHit_t1056001966, ___m_Collider_5)); } inline int32_t get_m_Collider_5() const { return ___m_Collider_5; } inline int32_t* get_address_of_m_Collider_5() { return &___m_Collider_5; } inline void set_m_Collider_5(int32_t value) { ___m_Collider_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RAYCASTHIT_T1056001966_H #ifndef ARGUMENTNULLEXCEPTION_T1615371798_H #define ARGUMENTNULLEXCEPTION_T1615371798_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ArgumentNullException struct ArgumentNullException_t1615371798 : public ArgumentException_t132251570 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARGUMENTNULLEXCEPTION_T1615371798_H #ifndef ARGUMENTOUTOFRANGEEXCEPTION_T777629997_H #define ARGUMENTOUTOFRANGEEXCEPTION_T777629997_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ArgumentOutOfRangeException struct ArgumentOutOfRangeException_t777629997 : public ArgumentException_t132251570 { public: // System.Object System.ArgumentOutOfRangeException::actual_value RuntimeObject * ___actual_value_13; public: inline static int32_t get_offset_of_actual_value_13() { return static_cast<int32_t>(offsetof(ArgumentOutOfRangeException_t777629997, ___actual_value_13)); } inline RuntimeObject * get_actual_value_13() const { return ___actual_value_13; } inline RuntimeObject ** get_address_of_actual_value_13() { return &___actual_value_13; } inline void set_actual_value_13(RuntimeObject * value) { ___actual_value_13 = value; Il2CppCodeGenWriteBarrier((&___actual_value_13), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // ARGUMENTOUTOFRANGEEXCEPTION_T777629997_H #ifndef DATETIME_T3738529785_H #define DATETIME_T3738529785_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.DateTime struct DateTime_t3738529785 { public: // System.TimeSpan System.DateTime::ticks TimeSpan_t881159249 ___ticks_0; // System.DateTimeKind System.DateTime::kind int32_t ___kind_1; public: inline static int32_t get_offset_of_ticks_0() { return static_cast<int32_t>(offsetof(DateTime_t3738529785, ___ticks_0)); } inline TimeSpan_t881159249 get_ticks_0() const { return ___ticks_0; } inline TimeSpan_t881159249 * get_address_of_ticks_0() { return &___ticks_0; } inline void set_ticks_0(TimeSpan_t881159249 value) { ___ticks_0 = value; } inline static int32_t get_offset_of_kind_1() { return static_cast<int32_t>(offsetof(DateTime_t3738529785, ___kind_1)); } inline int32_t get_kind_1() const { return ___kind_1; } inline int32_t* get_address_of_kind_1() { return &___kind_1; } inline void set_kind_1(int32_t value) { ___kind_1 = value; } }; struct DateTime_t3738529785_StaticFields { public: // System.DateTime System.DateTime::MaxValue DateTime_t3738529785 ___MaxValue_2; // System.DateTime System.DateTime::MinValue DateTime_t3738529785 ___MinValue_3; // System.String[] System.DateTime::ParseTimeFormats StringU5BU5D_t1281789340* ___ParseTimeFormats_4; // System.String[] System.DateTime::ParseYearDayMonthFormats StringU5BU5D_t1281789340* ___ParseYearDayMonthFormats_5; // System.String[] System.DateTime::ParseYearMonthDayFormats StringU5BU5D_t1281789340* ___ParseYearMonthDayFormats_6; // System.String[] System.DateTime::ParseDayMonthYearFormats StringU5BU5D_t1281789340* ___ParseDayMonthYearFormats_7; // System.String[] System.DateTime::ParseMonthDayYearFormats StringU5BU5D_t1281789340* ___ParseMonthDayYearFormats_8; // System.String[] System.DateTime::MonthDayShortFormats StringU5BU5D_t1281789340* ___MonthDayShortFormats_9; // System.String[] System.DateTime::DayMonthShortFormats StringU5BU5D_t1281789340* ___DayMonthShortFormats_10; // System.Int32[] System.DateTime::daysmonth Int32U5BU5D_t385246372* ___daysmonth_11; // System.Int32[] System.DateTime::daysmonthleap Int32U5BU5D_t385246372* ___daysmonthleap_12; // System.Object System.DateTime::to_local_time_span_object RuntimeObject * ___to_local_time_span_object_13; // System.Int64 System.DateTime::last_now int64_t ___last_now_14; public: inline static int32_t get_offset_of_MaxValue_2() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MaxValue_2)); } inline DateTime_t3738529785 get_MaxValue_2() const { return ___MaxValue_2; } inline DateTime_t3738529785 * get_address_of_MaxValue_2() { return &___MaxValue_2; } inline void set_MaxValue_2(DateTime_t3738529785 value) { ___MaxValue_2 = value; } inline static int32_t get_offset_of_MinValue_3() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MinValue_3)); } inline DateTime_t3738529785 get_MinValue_3() const { return ___MinValue_3; } inline DateTime_t3738529785 * get_address_of_MinValue_3() { return &___MinValue_3; } inline void set_MinValue_3(DateTime_t3738529785 value) { ___MinValue_3 = value; } inline static int32_t get_offset_of_ParseTimeFormats_4() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseTimeFormats_4)); } inline StringU5BU5D_t1281789340* get_ParseTimeFormats_4() const { return ___ParseTimeFormats_4; } inline StringU5BU5D_t1281789340** get_address_of_ParseTimeFormats_4() { return &___ParseTimeFormats_4; } inline void set_ParseTimeFormats_4(StringU5BU5D_t1281789340* value) { ___ParseTimeFormats_4 = value; Il2CppCodeGenWriteBarrier((&___ParseTimeFormats_4), value); } inline static int32_t get_offset_of_ParseYearDayMonthFormats_5() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseYearDayMonthFormats_5)); } inline StringU5BU5D_t1281789340* get_ParseYearDayMonthFormats_5() const { return ___ParseYearDayMonthFormats_5; } inline StringU5BU5D_t1281789340** get_address_of_ParseYearDayMonthFormats_5() { return &___ParseYearDayMonthFormats_5; } inline void set_ParseYearDayMonthFormats_5(StringU5BU5D_t1281789340* value) { ___ParseYearDayMonthFormats_5 = value; Il2CppCodeGenWriteBarrier((&___ParseYearDayMonthFormats_5), value); } inline static int32_t get_offset_of_ParseYearMonthDayFormats_6() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseYearMonthDayFormats_6)); } inline StringU5BU5D_t1281789340* get_ParseYearMonthDayFormats_6() const { return ___ParseYearMonthDayFormats_6; } inline StringU5BU5D_t1281789340** get_address_of_ParseYearMonthDayFormats_6() { return &___ParseYearMonthDayFormats_6; } inline void set_ParseYearMonthDayFormats_6(StringU5BU5D_t1281789340* value) { ___ParseYearMonthDayFormats_6 = value; Il2CppCodeGenWriteBarrier((&___ParseYearMonthDayFormats_6), value); } inline static int32_t get_offset_of_ParseDayMonthYearFormats_7() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseDayMonthYearFormats_7)); } inline StringU5BU5D_t1281789340* get_ParseDayMonthYearFormats_7() const { return ___ParseDayMonthYearFormats_7; } inline StringU5BU5D_t1281789340** get_address_of_ParseDayMonthYearFormats_7() { return &___ParseDayMonthYearFormats_7; } inline void set_ParseDayMonthYearFormats_7(StringU5BU5D_t1281789340* value) { ___ParseDayMonthYearFormats_7 = value; Il2CppCodeGenWriteBarrier((&___ParseDayMonthYearFormats_7), value); } inline static int32_t get_offset_of_ParseMonthDayYearFormats_8() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___ParseMonthDayYearFormats_8)); } inline StringU5BU5D_t1281789340* get_ParseMonthDayYearFormats_8() const { return ___ParseMonthDayYearFormats_8; } inline StringU5BU5D_t1281789340** get_address_of_ParseMonthDayYearFormats_8() { return &___ParseMonthDayYearFormats_8; } inline void set_ParseMonthDayYearFormats_8(StringU5BU5D_t1281789340* value) { ___ParseMonthDayYearFormats_8 = value; Il2CppCodeGenWriteBarrier((&___ParseMonthDayYearFormats_8), value); } inline static int32_t get_offset_of_MonthDayShortFormats_9() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___MonthDayShortFormats_9)); } inline StringU5BU5D_t1281789340* get_MonthDayShortFormats_9() const { return ___MonthDayShortFormats_9; } inline StringU5BU5D_t1281789340** get_address_of_MonthDayShortFormats_9() { return &___MonthDayShortFormats_9; } inline void set_MonthDayShortFormats_9(StringU5BU5D_t1281789340* value) { ___MonthDayShortFormats_9 = value; Il2CppCodeGenWriteBarrier((&___MonthDayShortFormats_9), value); } inline static int32_t get_offset_of_DayMonthShortFormats_10() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___DayMonthShortFormats_10)); } inline StringU5BU5D_t1281789340* get_DayMonthShortFormats_10() const { return ___DayMonthShortFormats_10; } inline StringU5BU5D_t1281789340** get_address_of_DayMonthShortFormats_10() { return &___DayMonthShortFormats_10; } inline void set_DayMonthShortFormats_10(StringU5BU5D_t1281789340* value) { ___DayMonthShortFormats_10 = value; Il2CppCodeGenWriteBarrier((&___DayMonthShortFormats_10), value); } inline static int32_t get_offset_of_daysmonth_11() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___daysmonth_11)); } inline Int32U5BU5D_t385246372* get_daysmonth_11() const { return ___daysmonth_11; } inline Int32U5BU5D_t385246372** get_address_of_daysmonth_11() { return &___daysmonth_11; } inline void set_daysmonth_11(Int32U5BU5D_t385246372* value) { ___daysmonth_11 = value; Il2CppCodeGenWriteBarrier((&___daysmonth_11), value); } inline static int32_t get_offset_of_daysmonthleap_12() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___daysmonthleap_12)); } inline Int32U5BU5D_t385246372* get_daysmonthleap_12() const { return ___daysmonthleap_12; } inline Int32U5BU5D_t385246372** get_address_of_daysmonthleap_12() { return &___daysmonthleap_12; } inline void set_daysmonthleap_12(Int32U5BU5D_t385246372* value) { ___daysmonthleap_12 = value; Il2CppCodeGenWriteBarrier((&___daysmonthleap_12), value); } inline static int32_t get_offset_of_to_local_time_span_object_13() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___to_local_time_span_object_13)); } inline RuntimeObject * get_to_local_time_span_object_13() const { return ___to_local_time_span_object_13; } inline RuntimeObject ** get_address_of_to_local_time_span_object_13() { return &___to_local_time_span_object_13; } inline void set_to_local_time_span_object_13(RuntimeObject * value) { ___to_local_time_span_object_13 = value; Il2CppCodeGenWriteBarrier((&___to_local_time_span_object_13), value); } inline static int32_t get_offset_of_last_now_14() { return static_cast<int32_t>(offsetof(DateTime_t3738529785_StaticFields, ___last_now_14)); } inline int64_t get_last_now_14() const { return ___last_now_14; } inline int64_t* get_address_of_last_now_14() { return &___last_now_14; } inline void set_last_now_14(int64_t value) { ___last_now_14 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // DATETIME_T3738529785_H #ifndef MULTICASTDELEGATE_T_H #define MULTICASTDELEGATE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.MulticastDelegate struct MulticastDelegate_t : public Delegate_t1188392813 { public: // System.MulticastDelegate System.MulticastDelegate::prev MulticastDelegate_t * ___prev_9; // System.MulticastDelegate System.MulticastDelegate::kpm_next MulticastDelegate_t * ___kpm_next_10; public: inline static int32_t get_offset_of_prev_9() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___prev_9)); } inline MulticastDelegate_t * get_prev_9() const { return ___prev_9; } inline MulticastDelegate_t ** get_address_of_prev_9() { return &___prev_9; } inline void set_prev_9(MulticastDelegate_t * value) { ___prev_9 = value; Il2CppCodeGenWriteBarrier((&___prev_9), value); } inline static int32_t get_offset_of_kpm_next_10() { return static_cast<int32_t>(offsetof(MulticastDelegate_t, ___kpm_next_10)); } inline MulticastDelegate_t * get_kpm_next_10() const { return ___kpm_next_10; } inline MulticastDelegate_t ** get_address_of_kpm_next_10() { return &___kpm_next_10; } inline void set_kpm_next_10(MulticastDelegate_t * value) { ___kpm_next_10 = value; Il2CppCodeGenWriteBarrier((&___kpm_next_10), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // MULTICASTDELEGATE_T_H #ifndef MONORESOURCE_T4103430009_H #define MONORESOURCE_T4103430009_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.MonoResource struct MonoResource_t4103430009 { public: // System.Byte[] System.Reflection.Emit.MonoResource::data ByteU5BU5D_t4116647657* ___data_0; // System.String System.Reflection.Emit.MonoResource::name String_t* ___name_1; // System.String System.Reflection.Emit.MonoResource::filename String_t* ___filename_2; // System.Reflection.ResourceAttributes System.Reflection.Emit.MonoResource::attrs int32_t ___attrs_3; // System.Int32 System.Reflection.Emit.MonoResource::offset int32_t ___offset_4; // System.IO.Stream System.Reflection.Emit.MonoResource::stream Stream_t1273022909 * ___stream_5; public: inline static int32_t get_offset_of_data_0() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___data_0)); } inline ByteU5BU5D_t4116647657* get_data_0() const { return ___data_0; } inline ByteU5BU5D_t4116647657** get_address_of_data_0() { return &___data_0; } inline void set_data_0(ByteU5BU5D_t4116647657* value) { ___data_0 = value; Il2CppCodeGenWriteBarrier((&___data_0), value); } inline static int32_t get_offset_of_name_1() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___name_1)); } inline String_t* get_name_1() const { return ___name_1; } inline String_t** get_address_of_name_1() { return &___name_1; } inline void set_name_1(String_t* value) { ___name_1 = value; Il2CppCodeGenWriteBarrier((&___name_1), value); } inline static int32_t get_offset_of_filename_2() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___filename_2)); } inline String_t* get_filename_2() const { return ___filename_2; } inline String_t** get_address_of_filename_2() { return &___filename_2; } inline void set_filename_2(String_t* value) { ___filename_2 = value; Il2CppCodeGenWriteBarrier((&___filename_2), value); } inline static int32_t get_offset_of_attrs_3() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___attrs_3)); } inline int32_t get_attrs_3() const { return ___attrs_3; } inline int32_t* get_address_of_attrs_3() { return &___attrs_3; } inline void set_attrs_3(int32_t value) { ___attrs_3 = value; } inline static int32_t get_offset_of_offset_4() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___offset_4)); } inline int32_t get_offset_4() const { return ___offset_4; } inline int32_t* get_address_of_offset_4() { return &___offset_4; } inline void set_offset_4(int32_t value) { ___offset_4 = value; } inline static int32_t get_offset_of_stream_5() { return static_cast<int32_t>(offsetof(MonoResource_t4103430009, ___stream_5)); } inline Stream_t1273022909 * get_stream_5() const { return ___stream_5; } inline Stream_t1273022909 ** get_address_of_stream_5() { return &___stream_5; } inline void set_stream_5(Stream_t1273022909 * value) { ___stream_5 = value; Il2CppCodeGenWriteBarrier((&___stream_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.Emit.MonoResource struct MonoResource_t4103430009_marshaled_pinvoke { uint8_t* ___data_0; char* ___name_1; char* ___filename_2; int32_t ___attrs_3; int32_t ___offset_4; Stream_t1273022909 * ___stream_5; }; // Native definition for COM marshalling of System.Reflection.Emit.MonoResource struct MonoResource_t4103430009_marshaled_com { uint8_t* ___data_0; Il2CppChar* ___name_1; Il2CppChar* ___filename_2; int32_t ___attrs_3; int32_t ___offset_4; Stream_t1273022909 * ___stream_5; }; #endif // MONORESOURCE_T4103430009_H #ifndef REFEMITPERMISSIONSET_T484390987_H #define REFEMITPERMISSIONSET_T484390987_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Reflection.Emit.RefEmitPermissionSet struct RefEmitPermissionSet_t484390987 { public: // System.Security.Permissions.SecurityAction System.Reflection.Emit.RefEmitPermissionSet::action int32_t ___action_0; // System.String System.Reflection.Emit.RefEmitPermissionSet::pset String_t* ___pset_1; public: inline static int32_t get_offset_of_action_0() { return static_cast<int32_t>(offsetof(RefEmitPermissionSet_t484390987, ___action_0)); } inline int32_t get_action_0() const { return ___action_0; } inline int32_t* get_address_of_action_0() { return &___action_0; } inline void set_action_0(int32_t value) { ___action_0 = value; } inline static int32_t get_offset_of_pset_1() { return static_cast<int32_t>(offsetof(RefEmitPermissionSet_t484390987, ___pset_1)); } inline String_t* get_pset_1() const { return ___pset_1; } inline String_t** get_address_of_pset_1() { return &___pset_1; } inline void set_pset_1(String_t* value) { ___pset_1 = value; Il2CppCodeGenWriteBarrier((&___pset_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Reflection.Emit.RefEmitPermissionSet struct RefEmitPermissionSet_t484390987_marshaled_pinvoke { int32_t ___action_0; char* ___pset_1; }; // Native definition for COM marshalling of System.Reflection.Emit.RefEmitPermissionSet struct RefEmitPermissionSet_t484390987_marshaled_com { int32_t ___action_0; Il2CppChar* ___pset_1; }; #endif // REFEMITPERMISSIONSET_T484390987_H #ifndef X509CHAINSTATUS_T133602714_H #define X509CHAINSTATUS_T133602714_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.X509Certificates.X509ChainStatus struct X509ChainStatus_t133602714 { public: // System.Security.Cryptography.X509Certificates.X509ChainStatusFlags System.Security.Cryptography.X509Certificates.X509ChainStatus::status int32_t ___status_0; // System.String System.Security.Cryptography.X509Certificates.X509ChainStatus::info String_t* ___info_1; public: inline static int32_t get_offset_of_status_0() { return static_cast<int32_t>(offsetof(X509ChainStatus_t133602714, ___status_0)); } inline int32_t get_status_0() const { return ___status_0; } inline int32_t* get_address_of_status_0() { return &___status_0; } inline void set_status_0(int32_t value) { ___status_0 = value; } inline static int32_t get_offset_of_info_1() { return static_cast<int32_t>(offsetof(X509ChainStatus_t133602714, ___info_1)); } inline String_t* get_info_1() const { return ___info_1; } inline String_t** get_address_of_info_1() { return &___info_1; } inline void set_info_1(String_t* value) { ___info_1 = value; Il2CppCodeGenWriteBarrier((&___info_1), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Security.Cryptography.X509Certificates.X509ChainStatus struct X509ChainStatus_t133602714_marshaled_pinvoke { int32_t ___status_0; char* ___info_1; }; // Native definition for COM marshalling of System.Security.Cryptography.X509Certificates.X509ChainStatus struct X509ChainStatus_t133602714_marshaled_com { int32_t ___status_0; Il2CppChar* ___info_1; }; #endif // X509CHAINSTATUS_T133602714_H #ifndef TYPE_T_H #define TYPE_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Type struct Type_t : public MemberInfo_t { public: // System.RuntimeTypeHandle System.Type::_impl RuntimeTypeHandle_t3027515415 ____impl_1; public: inline static int32_t get_offset_of__impl_1() { return static_cast<int32_t>(offsetof(Type_t, ____impl_1)); } inline RuntimeTypeHandle_t3027515415 get__impl_1() const { return ____impl_1; } inline RuntimeTypeHandle_t3027515415 * get_address_of__impl_1() { return &____impl_1; } inline void set__impl_1(RuntimeTypeHandle_t3027515415 value) { ____impl_1 = value; } }; struct Type_t_StaticFields { public: // System.Char System.Type::Delimiter Il2CppChar ___Delimiter_2; // System.Type[] System.Type::EmptyTypes TypeU5BU5D_t3940880105* ___EmptyTypes_3; // System.Reflection.MemberFilter System.Type::FilterAttribute MemberFilter_t426314064 * ___FilterAttribute_4; // System.Reflection.MemberFilter System.Type::FilterName MemberFilter_t426314064 * ___FilterName_5; // System.Reflection.MemberFilter System.Type::FilterNameIgnoreCase MemberFilter_t426314064 * ___FilterNameIgnoreCase_6; // System.Object System.Type::Missing RuntimeObject * ___Missing_7; public: inline static int32_t get_offset_of_Delimiter_2() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Delimiter_2)); } inline Il2CppChar get_Delimiter_2() const { return ___Delimiter_2; } inline Il2CppChar* get_address_of_Delimiter_2() { return &___Delimiter_2; } inline void set_Delimiter_2(Il2CppChar value) { ___Delimiter_2 = value; } inline static int32_t get_offset_of_EmptyTypes_3() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___EmptyTypes_3)); } inline TypeU5BU5D_t3940880105* get_EmptyTypes_3() const { return ___EmptyTypes_3; } inline TypeU5BU5D_t3940880105** get_address_of_EmptyTypes_3() { return &___EmptyTypes_3; } inline void set_EmptyTypes_3(TypeU5BU5D_t3940880105* value) { ___EmptyTypes_3 = value; Il2CppCodeGenWriteBarrier((&___EmptyTypes_3), value); } inline static int32_t get_offset_of_FilterAttribute_4() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterAttribute_4)); } inline MemberFilter_t426314064 * get_FilterAttribute_4() const { return ___FilterAttribute_4; } inline MemberFilter_t426314064 ** get_address_of_FilterAttribute_4() { return &___FilterAttribute_4; } inline void set_FilterAttribute_4(MemberFilter_t426314064 * value) { ___FilterAttribute_4 = value; Il2CppCodeGenWriteBarrier((&___FilterAttribute_4), value); } inline static int32_t get_offset_of_FilterName_5() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterName_5)); } inline MemberFilter_t426314064 * get_FilterName_5() const { return ___FilterName_5; } inline MemberFilter_t426314064 ** get_address_of_FilterName_5() { return &___FilterName_5; } inline void set_FilterName_5(MemberFilter_t426314064 * value) { ___FilterName_5 = value; Il2CppCodeGenWriteBarrier((&___FilterName_5), value); } inline static int32_t get_offset_of_FilterNameIgnoreCase_6() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___FilterNameIgnoreCase_6)); } inline MemberFilter_t426314064 * get_FilterNameIgnoreCase_6() const { return ___FilterNameIgnoreCase_6; } inline MemberFilter_t426314064 ** get_address_of_FilterNameIgnoreCase_6() { return &___FilterNameIgnoreCase_6; } inline void set_FilterNameIgnoreCase_6(MemberFilter_t426314064 * value) { ___FilterNameIgnoreCase_6 = value; Il2CppCodeGenWriteBarrier((&___FilterNameIgnoreCase_6), value); } inline static int32_t get_offset_of_Missing_7() { return static_cast<int32_t>(offsetof(Type_t_StaticFields, ___Missing_7)); } inline RuntimeObject * get_Missing_7() const { return ___Missing_7; } inline RuntimeObject ** get_address_of_Missing_7() { return &___Missing_7; } inline void set_Missing_7(RuntimeObject * value) { ___Missing_7 = value; Il2CppCodeGenWriteBarrier((&___Missing_7), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TYPE_T_H #ifndef COMPONENT_T1923634451_H #define COMPONENT_T1923634451_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Component struct Component_t1923634451 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // COMPONENT_T1923634451_H #ifndef PLAYABLEBINDING_T354260709_H #define PLAYABLEBINDING_T354260709_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Playables.PlayableBinding struct PlayableBinding_t354260709 { public: // System.String UnityEngine.Playables.PlayableBinding::m_StreamName String_t* ___m_StreamName_0; // UnityEngine.Object UnityEngine.Playables.PlayableBinding::m_SourceObject Object_t631007953 * ___m_SourceObject_1; // System.Type UnityEngine.Playables.PlayableBinding::m_SourceBindingType Type_t * ___m_SourceBindingType_2; // UnityEngine.Playables.PlayableBinding/CreateOutputMethod UnityEngine.Playables.PlayableBinding::m_CreateOutputMethod CreateOutputMethod_t2301811773 * ___m_CreateOutputMethod_3; public: inline static int32_t get_offset_of_m_StreamName_0() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709, ___m_StreamName_0)); } inline String_t* get_m_StreamName_0() const { return ___m_StreamName_0; } inline String_t** get_address_of_m_StreamName_0() { return &___m_StreamName_0; } inline void set_m_StreamName_0(String_t* value) { ___m_StreamName_0 = value; Il2CppCodeGenWriteBarrier((&___m_StreamName_0), value); } inline static int32_t get_offset_of_m_SourceObject_1() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709, ___m_SourceObject_1)); } inline Object_t631007953 * get_m_SourceObject_1() const { return ___m_SourceObject_1; } inline Object_t631007953 ** get_address_of_m_SourceObject_1() { return &___m_SourceObject_1; } inline void set_m_SourceObject_1(Object_t631007953 * value) { ___m_SourceObject_1 = value; Il2CppCodeGenWriteBarrier((&___m_SourceObject_1), value); } inline static int32_t get_offset_of_m_SourceBindingType_2() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709, ___m_SourceBindingType_2)); } inline Type_t * get_m_SourceBindingType_2() const { return ___m_SourceBindingType_2; } inline Type_t ** get_address_of_m_SourceBindingType_2() { return &___m_SourceBindingType_2; } inline void set_m_SourceBindingType_2(Type_t * value) { ___m_SourceBindingType_2 = value; Il2CppCodeGenWriteBarrier((&___m_SourceBindingType_2), value); } inline static int32_t get_offset_of_m_CreateOutputMethod_3() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709, ___m_CreateOutputMethod_3)); } inline CreateOutputMethod_t2301811773 * get_m_CreateOutputMethod_3() const { return ___m_CreateOutputMethod_3; } inline CreateOutputMethod_t2301811773 ** get_address_of_m_CreateOutputMethod_3() { return &___m_CreateOutputMethod_3; } inline void set_m_CreateOutputMethod_3(CreateOutputMethod_t2301811773 * value) { ___m_CreateOutputMethod_3 = value; Il2CppCodeGenWriteBarrier((&___m_CreateOutputMethod_3), value); } }; struct PlayableBinding_t354260709_StaticFields { public: // UnityEngine.Playables.PlayableBinding[] UnityEngine.Playables.PlayableBinding::None PlayableBindingU5BU5D_t829358056* ___None_4; // System.Double UnityEngine.Playables.PlayableBinding::DefaultDuration double ___DefaultDuration_5; public: inline static int32_t get_offset_of_None_4() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709_StaticFields, ___None_4)); } inline PlayableBindingU5BU5D_t829358056* get_None_4() const { return ___None_4; } inline PlayableBindingU5BU5D_t829358056** get_address_of_None_4() { return &___None_4; } inline void set_None_4(PlayableBindingU5BU5D_t829358056* value) { ___None_4 = value; Il2CppCodeGenWriteBarrier((&___None_4), value); } inline static int32_t get_offset_of_DefaultDuration_5() { return static_cast<int32_t>(offsetof(PlayableBinding_t354260709_StaticFields, ___DefaultDuration_5)); } inline double get_DefaultDuration_5() const { return ___DefaultDuration_5; } inline double* get_address_of_DefaultDuration_5() { return &___DefaultDuration_5; } inline void set_DefaultDuration_5(double value) { ___DefaultDuration_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Playables.PlayableBinding struct PlayableBinding_t354260709_marshaled_pinvoke { char* ___m_StreamName_0; Object_t631007953_marshaled_pinvoke ___m_SourceObject_1; Type_t * ___m_SourceBindingType_2; Il2CppMethodPointer ___m_CreateOutputMethod_3; }; // Native definition for COM marshalling of UnityEngine.Playables.PlayableBinding struct PlayableBinding_t354260709_marshaled_com { Il2CppChar* ___m_StreamName_0; Object_t631007953_marshaled_com* ___m_SourceObject_1; Type_t * ___m_SourceBindingType_2; Il2CppMethodPointer ___m_CreateOutputMethod_3; }; #endif // PLAYABLEBINDING_T354260709_H #ifndef SCRIPTABLEOBJECT_T2528358522_H #define SCRIPTABLEOBJECT_T2528358522_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.ScriptableObject struct ScriptableObject_t2528358522 : public Object_t631007953 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t2528358522_marshaled_pinvoke : public Object_t631007953_marshaled_pinvoke { }; // Native definition for COM marshalling of UnityEngine.ScriptableObject struct ScriptableObject_t2528358522_marshaled_com : public Object_t631007953_marshaled_com { }; #endif // SCRIPTABLEOBJECT_T2528358522_H #ifndef TRANSFORM_1_T1027527961_H #define TRANSFORM_1_T1027527961_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Int32,System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>> struct Transform_1_t1027527961 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_1_T1027527961_H #ifndef TRANSFORM_1_T1706577217_H #define TRANSFORM_1_T1706577217_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Int32,System.Object> struct Transform_1_t1706577217 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_1_T1706577217_H #ifndef TRANSFORM_1_T4209139644_H #define TRANSFORM_1_T4209139644_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Collections.DictionaryEntry> struct Transform_1_t4209139644 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_1_T4209139644_H #ifndef TRANSFORM_1_T3615381325_H #define TRANSFORM_1_T3615381325_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>> struct Transform_1_t3615381325 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_1_T3615381325_H #ifndef TRANSFORM_1_T4165270170_H #define TRANSFORM_1_T4165270170_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.Object,System.Object,System.Object> struct Transform_1_t4165270170 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TRANSFORM_1_T4165270170_H #ifndef CONVERTER_2_T2442480487_H #define CONVERTER_2_T2442480487_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Converter`2<System.Object,System.Object> struct Converter_2_t2442480487 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CONVERTER_2_T2442480487_H #ifndef FUNC_2_T3759279471_H #define FUNC_2_T3759279471_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Func`2<System.Object,System.Boolean> struct Func_2_t3759279471 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FUNC_2_T3759279471_H #ifndef PREDICATE_1_T3905400288_H #define PREDICATE_1_T3905400288_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Predicate`1<System.Object> struct Predicate_1_t3905400288 : public MulticastDelegate_t { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // PREDICATE_1_T3905400288_H // System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>[] struct KeyValuePair_2U5BU5D_t1954543557 : public RuntimeArray { public: ALIGN_FIELD (8) KeyValuePair_2_t2401056908 m_Items[1]; public: inline KeyValuePair_2_t2401056908 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline KeyValuePair_2_t2401056908 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, KeyValuePair_2_t2401056908 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline KeyValuePair_2_t2401056908 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline KeyValuePair_2_t2401056908 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, KeyValuePair_2_t2401056908 value) { m_Items[index] = value; } }; // System.Collections.Generic.Link[] struct LinkU5BU5D_t964245573 : public RuntimeArray { public: ALIGN_FIELD (8) Link_t544317964 m_Items[1]; public: inline Link_t544317964 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline Link_t544317964 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, Link_t544317964 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline Link_t544317964 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline Link_t544317964 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, Link_t544317964 value) { m_Items[index] = value; } }; // System.Object[] struct ObjectU5BU5D_t2843939325 : public RuntimeArray { public: ALIGN_FIELD (8) RuntimeObject * m_Items[1]; public: inline RuntimeObject * GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline RuntimeObject ** GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, RuntimeObject * value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } inline RuntimeObject * GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline RuntimeObject ** GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, RuntimeObject * value) { m_Items[index] = value; Il2CppCodeGenWriteBarrier(m_Items + index, value); } }; // System.Int32[] struct Int32U5BU5D_t385246372 : public RuntimeArray { public: ALIGN_FIELD (8) int32_t m_Items[1]; public: inline int32_t GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline int32_t* GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, int32_t value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline int32_t GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline int32_t* GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, int32_t value) { m_Items[index] = value; } }; // System.Collections.DictionaryEntry[] struct DictionaryEntryU5BU5D_t4217117203 : public RuntimeArray { public: ALIGN_FIELD (8) DictionaryEntry_t3123975638 m_Items[1]; public: inline DictionaryEntry_t3123975638 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline DictionaryEntry_t3123975638 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, DictionaryEntry_t3123975638 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline DictionaryEntry_t3123975638 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline DictionaryEntry_t3123975638 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, DictionaryEntry_t3123975638 value) { m_Items[index] = value; } }; // System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>[] struct KeyValuePair_2U5BU5D_t118269214 : public RuntimeArray { public: ALIGN_FIELD (8) KeyValuePair_2_t2530217319 m_Items[1]; public: inline KeyValuePair_2_t2530217319 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline KeyValuePair_2_t2530217319 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, KeyValuePair_2_t2530217319 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline KeyValuePair_2_t2530217319 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline KeyValuePair_2_t2530217319 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, KeyValuePair_2_t2530217319 value) { m_Items[index] = value; } }; // System.Reflection.CustomAttributeNamedArgument[] struct CustomAttributeNamedArgumentU5BU5D_t3710464795 : public RuntimeArray { public: ALIGN_FIELD (8) CustomAttributeNamedArgument_t287865710 m_Items[1]; public: inline CustomAttributeNamedArgument_t287865710 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline CustomAttributeNamedArgument_t287865710 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, CustomAttributeNamedArgument_t287865710 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline CustomAttributeNamedArgument_t287865710 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline CustomAttributeNamedArgument_t287865710 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, CustomAttributeNamedArgument_t287865710 value) { m_Items[index] = value; } }; // System.Reflection.CustomAttributeTypedArgument[] struct CustomAttributeTypedArgumentU5BU5D_t1465843424 : public RuntimeArray { public: ALIGN_FIELD (8) CustomAttributeTypedArgument_t2723150157 m_Items[1]; public: inline CustomAttributeTypedArgument_t2723150157 GetAt(il2cpp_array_size_t index) const { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items[index]; } inline CustomAttributeTypedArgument_t2723150157 * GetAddressAt(il2cpp_array_size_t index) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); return m_Items + index; } inline void SetAt(il2cpp_array_size_t index, CustomAttributeTypedArgument_t2723150157 value) { IL2CPP_ARRAY_BOUNDS_CHECK(index, (uint32_t)(this)->max_length); m_Items[index] = value; } inline CustomAttributeTypedArgument_t2723150157 GetAtUnchecked(il2cpp_array_size_t index) const { return m_Items[index]; } inline CustomAttributeTypedArgument_t2723150157 * GetAddressAtUnchecked(il2cpp_array_size_t index) { return m_Items + index; } inline void SetAtUnchecked(il2cpp_array_size_t index, CustomAttributeTypedArgument_t2723150157 value) { m_Items[index] = value; } }; // System.Type System.Type::GetTypeFromHandle(System.RuntimeTypeHandle) extern "C" IL2CPP_METHOD_ATTR Type_t * Type_GetTypeFromHandle_m1620074514 (RuntimeObject * __this /* static, unused */, RuntimeTypeHandle_t3027515415 ___handle0, const RuntimeMethod* method); // System.Type System.Object::GetType() extern "C" IL2CPP_METHOD_ATTR Type_t * Object_GetType_m88164663 (RuntimeObject * __this, const RuntimeMethod* method); // System.Boolean System.Type::get_IsPrimitive() extern "C" IL2CPP_METHOD_ATTR bool Type_get_IsPrimitive_m1114712797 (Type_t * __this, const RuntimeMethod* method); // System.Void System.Exception::.ctor() extern "C" IL2CPP_METHOD_ATTR void Exception__ctor_m213470898 (Exception_t * __this, const RuntimeMethod* method); // System.Void System.ArgumentException::.ctor(System.String,System.String,System.Exception) extern "C" IL2CPP_METHOD_ATTR void ArgumentException__ctor_m3761792013 (ArgumentException_t132251570 * __this, String_t* ___message0, String_t* ___paramName1, Exception_t * ___innerException2, const RuntimeMethod* method); // System.String UnityEngine.UnityString::Format(System.String,System.Object[]) extern "C" IL2CPP_METHOD_ATTR String_t* UnityString_Format_m261690510 (RuntimeObject * __this /* static, unused */, String_t* p0, ObjectU5BU5D_t2843939325* p1, const RuntimeMethod* method); // System.Void System.ArgumentException::.ctor(System.String) extern "C" IL2CPP_METHOD_ATTR void ArgumentException__ctor_m1312628991 (ArgumentException_t132251570 * __this, String_t* p0, const RuntimeMethod* method); // System.Void System.ArgumentNullException::.ctor(System.String) extern "C" IL2CPP_METHOD_ATTR void ArgumentNullException__ctor_m1170824041 (ArgumentNullException_t1615371798 * __this, String_t* ___paramName0, const RuntimeMethod* method); // System.Int32 System.Array::get_Length() extern "C" IL2CPP_METHOD_ATTR int32_t Array_get_Length_m21610649 (RuntimeArray * __this, const RuntimeMethod* method); // System.Void System.ArgumentOutOfRangeException::.ctor(System.String) extern "C" IL2CPP_METHOD_ATTR void ArgumentOutOfRangeException__ctor_m3628145864 (ArgumentOutOfRangeException_t777629997 * __this, String_t* ___paramName0, const RuntimeMethod* method); // System.Void System.IntPtr::.ctor(System.Void*) extern "C" IL2CPP_METHOD_ATTR void IntPtr__ctor_m3384658186 (intptr_t* __this, void* p0, const RuntimeMethod* method); // System.Void UnityEngine.Component::GetComponentFastPath(System.Type,System.IntPtr) extern "C" IL2CPP_METHOD_ATTR void Component_GetComponentFastPath_m1180649031 (Component_t1923634451 * __this, Type_t * ___type0, intptr_t ___oneFurtherThanResultValue1, const RuntimeMethod* method); // UnityEngine.ScriptableObject UnityEngine.ScriptableObject::CreateInstance(System.Type) extern "C" IL2CPP_METHOD_ATTR ScriptableObject_t2528358522 * ScriptableObject_CreateInstance_m2611081756 (RuntimeObject * __this /* static, unused */, Type_t * ___type0, const RuntimeMethod* method); // System.Void System.InvalidOperationException::.ctor() extern "C" IL2CPP_METHOD_ATTR void InvalidOperationException__ctor_m2734335978 (InvalidOperationException_t56020091 * __this, const RuntimeMethod* method); // System.Void System.Linq.Check::SourceAndPredicate(System.Object,System.Object) extern "C" IL2CPP_METHOD_ATTR void Check_SourceAndPredicate_m2332465641 (RuntimeObject * __this /* static, unused */, RuntimeObject * ___source0, RuntimeObject * ___predicate1, const RuntimeMethod* method); // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Int32>::Do_CopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>,System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisKeyValuePair_2_t2401056908_TisKeyValuePair_2_t2401056908_m676905794_gshared (Dictionary_2_t3384741 * __this, KeyValuePair_2U5BU5D_t1954543557* ___array0, int32_t ___index1, Transform_1_t1027527961 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { KeyValuePair_2U5BU5D_t1954543557* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t1027527961 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); Int32U5BU5D_t385246372* L_11 = (Int32U5BU5D_t385246372*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; int32_t L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t1027527961 *)L_6); KeyValuePair_2_t2401056908 L_15 = (( KeyValuePair_2_t2401056908 (*) (Transform_1_t1027527961 *, RuntimeObject *, int32_t, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t1027527961 *)L_6, (RuntimeObject *)L_10, (int32_t)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); KeyValuePair_2_t2401056908 L_16 = L_15; RuntimeObject * L_17 = Box(IL2CPP_RGCTX_DATA(method->rgctx_data, 1), &L_16); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (KeyValuePair_2_t2401056908 )((*(KeyValuePair_2_t2401056908 *)((KeyValuePair_2_t2401056908 *)UnBox(L_17, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))))); } IL_0057: { int32_t L_18 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005b: { int32_t L_19 = V_0; int32_t L_20 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_19) < ((int32_t)L_20))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Int32>::Do_CopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>,System.Object>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisKeyValuePair_2_t2401056908_TisRuntimeObject_m4084399341_gshared (Dictionary_2_t3384741 * __this, ObjectU5BU5D_t2843939325* ___array0, int32_t ___index1, Transform_1_t1027527961 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { ObjectU5BU5D_t2843939325* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t1027527961 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); Int32U5BU5D_t385246372* L_11 = (Int32U5BU5D_t385246372*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; int32_t L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t1027527961 *)L_6); KeyValuePair_2_t2401056908 L_15 = (( KeyValuePair_2_t2401056908 (*) (Transform_1_t1027527961 *, RuntimeObject *, int32_t, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t1027527961 *)L_6, (RuntimeObject *)L_10, (int32_t)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); KeyValuePair_2_t2401056908 L_16 = L_15; RuntimeObject * L_17 = Box(IL2CPP_RGCTX_DATA(method->rgctx_data, 1), &L_16); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_17, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))); } IL_0057: { int32_t L_18 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005b: { int32_t L_19 = V_0; int32_t L_20 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_19) < ((int32_t)L_20))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Int32>::Do_CopyTo<System.Object,System.Object>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisRuntimeObject_TisRuntimeObject_m1607739207_gshared (Dictionary_2_t3384741 * __this, ObjectU5BU5D_t2843939325* ___array0, int32_t ___index1, Transform_1_t1706577217 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { ObjectU5BU5D_t2843939325* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t1706577217 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); Int32U5BU5D_t385246372* L_11 = (Int32U5BU5D_t385246372*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; int32_t L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t1706577217 *)L_6); RuntimeObject * L_15 = (( RuntimeObject * (*) (Transform_1_t1706577217 *, RuntimeObject *, int32_t, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t1706577217 *)L_6, (RuntimeObject *)L_10, (int32_t)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_15, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))); } IL_0057: { int32_t L_16 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_16, (int32_t)1)); } IL_005b: { int32_t L_17 = V_0; int32_t L_18 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_17) < ((int32_t)L_18))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Int32>::Do_ICollectionCopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>>(System.Array,System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_gshared (Dictionary_2_t3384741 * __this, RuntimeArray * ___array0, int32_t ___index1, Transform_1_t1027527961 * ___transform2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_MetadataUsageId); s_Il2CppMethodInitialized = true; } Type_t * V_0 = NULL; Type_t * V_1 = NULL; Exception_t * V_2 = NULL; Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); V_0 = (Type_t *)L_1; RuntimeArray * L_2 = ___array0; NullCheck((RuntimeObject *)L_2); Type_t * L_3 = Object_GetType_m88164663((RuntimeObject *)L_2, /*hidden argument*/NULL); NullCheck((Type_t *)L_3); Type_t * L_4 = VirtFuncInvoker0< Type_t * >::Invoke(44 /* System.Type System.Type::GetElementType() */, (Type_t *)L_3); V_1 = (Type_t *)L_4; } IL_0017: try { // begin try (depth: 1) { Type_t * L_5 = V_0; NullCheck((Type_t *)L_5); bool L_6 = Type_get_IsPrimitive_m1114712797((Type_t *)L_5, /*hidden argument*/NULL); if (L_6) { goto IL_002d; } } IL_0022: { Type_t * L_7 = V_1; NullCheck((Type_t *)L_7); bool L_8 = Type_get_IsPrimitive_m1114712797((Type_t *)L_7, /*hidden argument*/NULL); if (!L_8) { goto IL_003f; } } IL_002d: { Type_t * L_9 = V_1; Type_t * L_10 = V_0; NullCheck((Type_t *)L_9); bool L_11 = VirtFuncInvoker1< bool, Type_t * >::Invoke(41 /* System.Boolean System.Type::IsAssignableFrom(System.Type) */, (Type_t *)L_9, (Type_t *)L_10); if (L_11) { goto IL_003f; } } IL_0039: { Exception_t * L_12 = (Exception_t *)il2cpp_codegen_object_new(Exception_t_il2cpp_TypeInfo_var); Exception__ctor_m213470898(L_12, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_12, NULL, Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_RuntimeMethod_var); } IL_003f: { RuntimeArray * L_13 = ___array0; int32_t L_14 = ___index1; Transform_1_t1027527961 * L_15 = ___transform2; NullCheck((Dictionary_2_t3384741 *)__this); (( void (*) (Dictionary_2_t3384741 *, ObjectU5BU5D_t2843939325*, int32_t, Transform_1_t1027527961 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Dictionary_2_t3384741 *)__this, (ObjectU5BU5D_t2843939325*)((ObjectU5BU5D_t2843939325*)Castclass((RuntimeObject*)L_13, ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var)), (int32_t)L_14, (Transform_1_t1027527961 *)L_15, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); goto IL_0069; } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __exception_local = (Exception_t *)e.ex; if(il2cpp_codegen_class_is_assignable_from (Exception_t_il2cpp_TypeInfo_var, il2cpp_codegen_object_class(e.ex))) goto CATCH_0052; throw e; } CATCH_0052: { // begin catch(System.Exception) { V_2 = (Exception_t *)((Exception_t *)__exception_local); Exception_t * L_16 = V_2; ArgumentException_t132251570 * L_17 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m3761792013(L_17, (String_t*)_stringLiteral1492106003, (String_t*)_stringLiteral4007973390, (Exception_t *)L_16, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_17, NULL, Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2401056908_m1169495264_RuntimeMethod_var); } IL_0064: { goto IL_0069; } } // end catch (depth: 1) IL_0069: { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Int32>::Do_ICollectionCopyTo<System.Object>(System.Array,System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_gshared (Dictionary_2_t3384741 * __this, RuntimeArray * ___array0, int32_t ___index1, Transform_1_t1706577217 * ___transform2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_MetadataUsageId); s_Il2CppMethodInitialized = true; } Type_t * V_0 = NULL; Type_t * V_1 = NULL; Exception_t * V_2 = NULL; Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); V_0 = (Type_t *)L_1; RuntimeArray * L_2 = ___array0; NullCheck((RuntimeObject *)L_2); Type_t * L_3 = Object_GetType_m88164663((RuntimeObject *)L_2, /*hidden argument*/NULL); NullCheck((Type_t *)L_3); Type_t * L_4 = VirtFuncInvoker0< Type_t * >::Invoke(44 /* System.Type System.Type::GetElementType() */, (Type_t *)L_3); V_1 = (Type_t *)L_4; } IL_0017: try { // begin try (depth: 1) { Type_t * L_5 = V_0; NullCheck((Type_t *)L_5); bool L_6 = Type_get_IsPrimitive_m1114712797((Type_t *)L_5, /*hidden argument*/NULL); if (L_6) { goto IL_002d; } } IL_0022: { Type_t * L_7 = V_1; NullCheck((Type_t *)L_7); bool L_8 = Type_get_IsPrimitive_m1114712797((Type_t *)L_7, /*hidden argument*/NULL); if (!L_8) { goto IL_003f; } } IL_002d: { Type_t * L_9 = V_1; Type_t * L_10 = V_0; NullCheck((Type_t *)L_9); bool L_11 = VirtFuncInvoker1< bool, Type_t * >::Invoke(41 /* System.Boolean System.Type::IsAssignableFrom(System.Type) */, (Type_t *)L_9, (Type_t *)L_10); if (L_11) { goto IL_003f; } } IL_0039: { Exception_t * L_12 = (Exception_t *)il2cpp_codegen_object_new(Exception_t_il2cpp_TypeInfo_var); Exception__ctor_m213470898(L_12, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_12, NULL, Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_RuntimeMethod_var); } IL_003f: { RuntimeArray * L_13 = ___array0; int32_t L_14 = ___index1; Transform_1_t1706577217 * L_15 = ___transform2; NullCheck((Dictionary_2_t3384741 *)__this); (( void (*) (Dictionary_2_t3384741 *, ObjectU5BU5D_t2843939325*, int32_t, Transform_1_t1706577217 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Dictionary_2_t3384741 *)__this, (ObjectU5BU5D_t2843939325*)((ObjectU5BU5D_t2843939325*)Castclass((RuntimeObject*)L_13, ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var)), (int32_t)L_14, (Transform_1_t1706577217 *)L_15, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); goto IL_0069; } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __exception_local = (Exception_t *)e.ex; if(il2cpp_codegen_class_is_assignable_from (Exception_t_il2cpp_TypeInfo_var, il2cpp_codegen_object_class(e.ex))) goto CATCH_0052; throw e; } CATCH_0052: { // begin catch(System.Exception) { V_2 = (Exception_t *)((Exception_t *)__exception_local); Exception_t * L_16 = V_2; ArgumentException_t132251570 * L_17 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m3761792013(L_17, (String_t*)_stringLiteral1492106003, (String_t*)_stringLiteral4007973390, (Exception_t *)L_16, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_17, NULL, Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m1362949338_RuntimeMethod_var); } IL_0064: { goto IL_0069; } } // end catch (depth: 1) IL_0069: { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_CopyTo<System.Collections.DictionaryEntry,System.Collections.DictionaryEntry>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisDictionaryEntry_t3123975638_TisDictionaryEntry_t3123975638_m3864993650_gshared (Dictionary_2_t132545152 * __this, DictionaryEntryU5BU5D_t4217117203* ___array0, int32_t ___index1, Transform_1_t4209139644 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { DictionaryEntryU5BU5D_t4217117203* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t4209139644 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); ObjectU5BU5D_t2843939325* L_11 = (ObjectU5BU5D_t2843939325*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; RuntimeObject * L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t4209139644 *)L_6); DictionaryEntry_t3123975638 L_15 = (( DictionaryEntry_t3123975638 (*) (Transform_1_t4209139644 *, RuntimeObject *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t4209139644 *)L_6, (RuntimeObject *)L_10, (RuntimeObject *)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); DictionaryEntry_t3123975638 L_16 = L_15; RuntimeObject * L_17 = Box(IL2CPP_RGCTX_DATA(method->rgctx_data, 1), &L_16); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (DictionaryEntry_t3123975638 )((*(DictionaryEntry_t3123975638 *)((DictionaryEntry_t3123975638 *)UnBox(L_17, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))))); } IL_0057: { int32_t L_18 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005b: { int32_t L_19 = V_0; int32_t L_20 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_19) < ((int32_t)L_20))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_CopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>,System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisKeyValuePair_2_t2530217319_TisKeyValuePair_2_t2530217319_m985448706_gshared (Dictionary_2_t132545152 * __this, KeyValuePair_2U5BU5D_t118269214* ___array0, int32_t ___index1, Transform_1_t3615381325 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { KeyValuePair_2U5BU5D_t118269214* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t3615381325 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); ObjectU5BU5D_t2843939325* L_11 = (ObjectU5BU5D_t2843939325*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; RuntimeObject * L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t3615381325 *)L_6); KeyValuePair_2_t2530217319 L_15 = (( KeyValuePair_2_t2530217319 (*) (Transform_1_t3615381325 *, RuntimeObject *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t3615381325 *)L_6, (RuntimeObject *)L_10, (RuntimeObject *)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); KeyValuePair_2_t2530217319 L_16 = L_15; RuntimeObject * L_17 = Box(IL2CPP_RGCTX_DATA(method->rgctx_data, 1), &L_16); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (KeyValuePair_2_t2530217319 )((*(KeyValuePair_2_t2530217319 *)((KeyValuePair_2_t2530217319 *)UnBox(L_17, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))))); } IL_0057: { int32_t L_18 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005b: { int32_t L_19 = V_0; int32_t L_20 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_19) < ((int32_t)L_20))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_CopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>,System.Object>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisKeyValuePair_2_t2530217319_TisRuntimeObject_m311023789_gshared (Dictionary_2_t132545152 * __this, ObjectU5BU5D_t2843939325* ___array0, int32_t ___index1, Transform_1_t3615381325 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { ObjectU5BU5D_t2843939325* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t3615381325 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); ObjectU5BU5D_t2843939325* L_11 = (ObjectU5BU5D_t2843939325*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; RuntimeObject * L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t3615381325 *)L_6); KeyValuePair_2_t2530217319 L_15 = (( KeyValuePair_2_t2530217319 (*) (Transform_1_t3615381325 *, RuntimeObject *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t3615381325 *)L_6, (RuntimeObject *)L_10, (RuntimeObject *)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); KeyValuePair_2_t2530217319 L_16 = L_15; RuntimeObject * L_17 = Box(IL2CPP_RGCTX_DATA(method->rgctx_data, 1), &L_16); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_17, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))); } IL_0057: { int32_t L_18 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005b: { int32_t L_19 = V_0; int32_t L_20 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_19) < ((int32_t)L_20))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_CopyTo<System.Object,System.Object>(TElem[],System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_CopyTo_TisRuntimeObject_TisRuntimeObject_m976542334_gshared (Dictionary_2_t132545152 * __this, ObjectU5BU5D_t2843939325* ___array0, int32_t ___index1, Transform_1_t4165270170 * ___transform2, const RuntimeMethod* method) { int32_t V_0 = 0; { V_0 = (int32_t)0; goto IL_005b; } IL_0007: { LinkU5BU5D_t964245573* L_0 = (LinkU5BU5D_t964245573*)__this->get_linkSlots_5(); int32_t L_1 = V_0; NullCheck(L_0); int32_t L_2 = (int32_t)((L_0)->GetAddressAt(static_cast<il2cpp_array_size_t>(L_1)))->get_HashCode_0(); if (!((int32_t)((int32_t)L_2&(int32_t)((int32_t)-2147483648LL)))) { goto IL_0057; } } { ObjectU5BU5D_t2843939325* L_3 = ___array0; int32_t L_4 = ___index1; int32_t L_5 = (int32_t)L_4; ___index1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_5, (int32_t)1)); Transform_1_t4165270170 * L_6 = ___transform2; ObjectU5BU5D_t2843939325* L_7 = (ObjectU5BU5D_t2843939325*)__this->get_keySlots_6(); int32_t L_8 = V_0; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); ObjectU5BU5D_t2843939325* L_11 = (ObjectU5BU5D_t2843939325*)__this->get_valueSlots_7(); int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; RuntimeObject * L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); NullCheck((Transform_1_t4165270170 *)L_6); RuntimeObject * L_15 = (( RuntimeObject * (*) (Transform_1_t4165270170 *, RuntimeObject *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Transform_1_t4165270170 *)L_6, (RuntimeObject *)L_10, (RuntimeObject *)L_14, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); NullCheck(L_3); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(L_5), (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_15, IL2CPP_RGCTX_DATA(method->rgctx_data, 2)))); } IL_0057: { int32_t L_16 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_16, (int32_t)1)); } IL_005b: { int32_t L_17 = V_0; int32_t L_18 = (int32_t)__this->get_touchedSlots_8(); if ((((int32_t)L_17) < ((int32_t)L_18))) { goto IL_0007; } } { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_ICollectionCopyTo<System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>>(System.Array,System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_gshared (Dictionary_2_t132545152 * __this, RuntimeArray * ___array0, int32_t ___index1, Transform_1_t3615381325 * ___transform2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_MetadataUsageId); s_Il2CppMethodInitialized = true; } Type_t * V_0 = NULL; Type_t * V_1 = NULL; Exception_t * V_2 = NULL; Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); V_0 = (Type_t *)L_1; RuntimeArray * L_2 = ___array0; NullCheck((RuntimeObject *)L_2); Type_t * L_3 = Object_GetType_m88164663((RuntimeObject *)L_2, /*hidden argument*/NULL); NullCheck((Type_t *)L_3); Type_t * L_4 = VirtFuncInvoker0< Type_t * >::Invoke(44 /* System.Type System.Type::GetElementType() */, (Type_t *)L_3); V_1 = (Type_t *)L_4; } IL_0017: try { // begin try (depth: 1) { Type_t * L_5 = V_0; NullCheck((Type_t *)L_5); bool L_6 = Type_get_IsPrimitive_m1114712797((Type_t *)L_5, /*hidden argument*/NULL); if (L_6) { goto IL_002d; } } IL_0022: { Type_t * L_7 = V_1; NullCheck((Type_t *)L_7); bool L_8 = Type_get_IsPrimitive_m1114712797((Type_t *)L_7, /*hidden argument*/NULL); if (!L_8) { goto IL_003f; } } IL_002d: { Type_t * L_9 = V_1; Type_t * L_10 = V_0; NullCheck((Type_t *)L_9); bool L_11 = VirtFuncInvoker1< bool, Type_t * >::Invoke(41 /* System.Boolean System.Type::IsAssignableFrom(System.Type) */, (Type_t *)L_9, (Type_t *)L_10); if (L_11) { goto IL_003f; } } IL_0039: { Exception_t * L_12 = (Exception_t *)il2cpp_codegen_object_new(Exception_t_il2cpp_TypeInfo_var); Exception__ctor_m213470898(L_12, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_12, NULL, Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_RuntimeMethod_var); } IL_003f: { RuntimeArray * L_13 = ___array0; int32_t L_14 = ___index1; Transform_1_t3615381325 * L_15 = ___transform2; NullCheck((Dictionary_2_t132545152 *)__this); (( void (*) (Dictionary_2_t132545152 *, ObjectU5BU5D_t2843939325*, int32_t, Transform_1_t3615381325 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Dictionary_2_t132545152 *)__this, (ObjectU5BU5D_t2843939325*)((ObjectU5BU5D_t2843939325*)Castclass((RuntimeObject*)L_13, ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var)), (int32_t)L_14, (Transform_1_t3615381325 *)L_15, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); goto IL_0069; } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __exception_local = (Exception_t *)e.ex; if(il2cpp_codegen_class_is_assignable_from (Exception_t_il2cpp_TypeInfo_var, il2cpp_codegen_object_class(e.ex))) goto CATCH_0052; throw e; } CATCH_0052: { // begin catch(System.Exception) { V_2 = (Exception_t *)((Exception_t *)__exception_local); Exception_t * L_16 = V_2; ArgumentException_t132251570 * L_17 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m3761792013(L_17, (String_t*)_stringLiteral1492106003, (String_t*)_stringLiteral4007973390, (Exception_t *)L_16, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_17, NULL, Dictionary_2_Do_ICollectionCopyTo_TisKeyValuePair_2_t2530217319_m1439704807_RuntimeMethod_var); } IL_0064: { goto IL_0069; } } // end catch (depth: 1) IL_0069: { return; } } // System.Void System.Collections.Generic.Dictionary`2<System.Object,System.Object>::Do_ICollectionCopyTo<System.Object>(System.Array,System.Int32,System.Collections.Generic.Dictionary`2/Transform`1<TKey,TValue,TRet>) extern "C" IL2CPP_METHOD_ATTR void Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_gshared (Dictionary_2_t132545152 * __this, RuntimeArray * ___array0, int32_t ___index1, Transform_1_t4165270170 * ___transform2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_MetadataUsageId); s_Il2CppMethodInitialized = true; } Type_t * V_0 = NULL; Type_t * V_1 = NULL; Exception_t * V_2 = NULL; Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); V_0 = (Type_t *)L_1; RuntimeArray * L_2 = ___array0; NullCheck((RuntimeObject *)L_2); Type_t * L_3 = Object_GetType_m88164663((RuntimeObject *)L_2, /*hidden argument*/NULL); NullCheck((Type_t *)L_3); Type_t * L_4 = VirtFuncInvoker0< Type_t * >::Invoke(44 /* System.Type System.Type::GetElementType() */, (Type_t *)L_3); V_1 = (Type_t *)L_4; } IL_0017: try { // begin try (depth: 1) { Type_t * L_5 = V_0; NullCheck((Type_t *)L_5); bool L_6 = Type_get_IsPrimitive_m1114712797((Type_t *)L_5, /*hidden argument*/NULL); if (L_6) { goto IL_002d; } } IL_0022: { Type_t * L_7 = V_1; NullCheck((Type_t *)L_7); bool L_8 = Type_get_IsPrimitive_m1114712797((Type_t *)L_7, /*hidden argument*/NULL); if (!L_8) { goto IL_003f; } } IL_002d: { Type_t * L_9 = V_1; Type_t * L_10 = V_0; NullCheck((Type_t *)L_9); bool L_11 = VirtFuncInvoker1< bool, Type_t * >::Invoke(41 /* System.Boolean System.Type::IsAssignableFrom(System.Type) */, (Type_t *)L_9, (Type_t *)L_10); if (L_11) { goto IL_003f; } } IL_0039: { Exception_t * L_12 = (Exception_t *)il2cpp_codegen_object_new(Exception_t_il2cpp_TypeInfo_var); Exception__ctor_m213470898(L_12, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_12, NULL, Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_RuntimeMethod_var); } IL_003f: { RuntimeArray * L_13 = ___array0; int32_t L_14 = ___index1; Transform_1_t4165270170 * L_15 = ___transform2; NullCheck((Dictionary_2_t132545152 *)__this); (( void (*) (Dictionary_2_t132545152 *, ObjectU5BU5D_t2843939325*, int32_t, Transform_1_t4165270170 *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Dictionary_2_t132545152 *)__this, (ObjectU5BU5D_t2843939325*)((ObjectU5BU5D_t2843939325*)Castclass((RuntimeObject*)L_13, ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var)), (int32_t)L_14, (Transform_1_t4165270170 *)L_15, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); goto IL_0069; } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __exception_local = (Exception_t *)e.ex; if(il2cpp_codegen_class_is_assignable_from (Exception_t_il2cpp_TypeInfo_var, il2cpp_codegen_object_class(e.ex))) goto CATCH_0052; throw e; } CATCH_0052: { // begin catch(System.Exception) { V_2 = (Exception_t *)((Exception_t *)__exception_local); Exception_t * L_16 = V_2; ArgumentException_t132251570 * L_17 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m3761792013(L_17, (String_t*)_stringLiteral1492106003, (String_t*)_stringLiteral4007973390, (Exception_t *)L_16, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_17, NULL, Dictionary_2_Do_ICollectionCopyTo_TisRuntimeObject_m3942192587_RuntimeMethod_var); } IL_0064: { goto IL_0069; } } // end catch (depth: 1) IL_0069: { return; } } // System.Void UnityEngine.Events.BaseInvokableCall::ThrowOnInvalidArg<System.Boolean>(System.Object) extern "C" IL2CPP_METHOD_ATTR void BaseInvokableCall_ThrowOnInvalidArg_TisBoolean_t97287965_m3019671566_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject * ___arg0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (BaseInvokableCall_ThrowOnInvalidArg_TisBoolean_t97287965_m3019671566_MetadataUsageId); s_Il2CppMethodInitialized = true; } { RuntimeObject * L_0 = ___arg0; if (!L_0) { goto IL_003e; } } { RuntimeObject * L_1 = ___arg0; if (((RuntimeObject *)IsInst((RuntimeObject*)L_1, IL2CPP_RGCTX_DATA(method->rgctx_data, 0)))) { goto IL_003e; } } { ObjectU5BU5D_t2843939325* L_2 = (ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)2); ObjectU5BU5D_t2843939325* L_3 = (ObjectU5BU5D_t2843939325*)L_2; RuntimeObject * L_4 = ___arg0; NullCheck((RuntimeObject *)L_4); Type_t * L_5 = Object_GetType_m88164663((RuntimeObject *)L_4, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_5); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_5); ObjectU5BU5D_t2843939325* L_6 = (ObjectU5BU5D_t2843939325*)L_3; RuntimeTypeHandle_t3027515415 L_7 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 1)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_8 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_7, /*hidden argument*/NULL); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_8); (L_6)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_8); String_t* L_9 = UnityString_Format_m261690510(NULL /*static, unused*/, (String_t*)_stringLiteral273595399, (ObjectU5BU5D_t2843939325*)L_6, /*hidden argument*/NULL); ArgumentException_t132251570 * L_10 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m1312628991(L_10, (String_t*)L_9, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_10, NULL, BaseInvokableCall_ThrowOnInvalidArg_TisBoolean_t97287965_m3019671566_RuntimeMethod_var); } IL_003e: { return; } } // System.Void UnityEngine.Events.BaseInvokableCall::ThrowOnInvalidArg<System.Int32>(System.Object) extern "C" IL2CPP_METHOD_ATTR void BaseInvokableCall_ThrowOnInvalidArg_TisInt32_t2950945753_m635860201_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject * ___arg0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (BaseInvokableCall_ThrowOnInvalidArg_TisInt32_t2950945753_m635860201_MetadataUsageId); s_Il2CppMethodInitialized = true; } { RuntimeObject * L_0 = ___arg0; if (!L_0) { goto IL_003e; } } { RuntimeObject * L_1 = ___arg0; if (((RuntimeObject *)IsInst((RuntimeObject*)L_1, IL2CPP_RGCTX_DATA(method->rgctx_data, 0)))) { goto IL_003e; } } { ObjectU5BU5D_t2843939325* L_2 = (ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)2); ObjectU5BU5D_t2843939325* L_3 = (ObjectU5BU5D_t2843939325*)L_2; RuntimeObject * L_4 = ___arg0; NullCheck((RuntimeObject *)L_4); Type_t * L_5 = Object_GetType_m88164663((RuntimeObject *)L_4, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_5); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_5); ObjectU5BU5D_t2843939325* L_6 = (ObjectU5BU5D_t2843939325*)L_3; RuntimeTypeHandle_t3027515415 L_7 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 1)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_8 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_7, /*hidden argument*/NULL); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_8); (L_6)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_8); String_t* L_9 = UnityString_Format_m261690510(NULL /*static, unused*/, (String_t*)_stringLiteral273595399, (ObjectU5BU5D_t2843939325*)L_6, /*hidden argument*/NULL); ArgumentException_t132251570 * L_10 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m1312628991(L_10, (String_t*)L_9, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_10, NULL, BaseInvokableCall_ThrowOnInvalidArg_TisInt32_t2950945753_m635860201_RuntimeMethod_var); } IL_003e: { return; } } // System.Void UnityEngine.Events.BaseInvokableCall::ThrowOnInvalidArg<System.Object>(System.Object) extern "C" IL2CPP_METHOD_ATTR void BaseInvokableCall_ThrowOnInvalidArg_TisRuntimeObject_m2266633109_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject * ___arg0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (BaseInvokableCall_ThrowOnInvalidArg_TisRuntimeObject_m2266633109_MetadataUsageId); s_Il2CppMethodInitialized = true; } { RuntimeObject * L_0 = ___arg0; if (!L_0) { goto IL_003e; } } { RuntimeObject * L_1 = ___arg0; if (((RuntimeObject *)IsInst((RuntimeObject*)L_1, IL2CPP_RGCTX_DATA(method->rgctx_data, 0)))) { goto IL_003e; } } { ObjectU5BU5D_t2843939325* L_2 = (ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)2); ObjectU5BU5D_t2843939325* L_3 = (ObjectU5BU5D_t2843939325*)L_2; RuntimeObject * L_4 = ___arg0; NullCheck((RuntimeObject *)L_4); Type_t * L_5 = Object_GetType_m88164663((RuntimeObject *)L_4, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_5); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_5); ObjectU5BU5D_t2843939325* L_6 = (ObjectU5BU5D_t2843939325*)L_3; RuntimeTypeHandle_t3027515415 L_7 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 1)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_8 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_7, /*hidden argument*/NULL); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_8); (L_6)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_8); String_t* L_9 = UnityString_Format_m261690510(NULL /*static, unused*/, (String_t*)_stringLiteral273595399, (ObjectU5BU5D_t2843939325*)L_6, /*hidden argument*/NULL); ArgumentException_t132251570 * L_10 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m1312628991(L_10, (String_t*)L_9, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_10, NULL, BaseInvokableCall_ThrowOnInvalidArg_TisRuntimeObject_m2266633109_RuntimeMethod_var); } IL_003e: { return; } } // System.Void UnityEngine.Events.BaseInvokableCall::ThrowOnInvalidArg<System.Single>(System.Object) extern "C" IL2CPP_METHOD_ATTR void BaseInvokableCall_ThrowOnInvalidArg_TisSingle_t1397266774_m3110598205_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject * ___arg0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (BaseInvokableCall_ThrowOnInvalidArg_TisSingle_t1397266774_m3110598205_MetadataUsageId); s_Il2CppMethodInitialized = true; } { RuntimeObject * L_0 = ___arg0; if (!L_0) { goto IL_003e; } } { RuntimeObject * L_1 = ___arg0; if (((RuntimeObject *)IsInst((RuntimeObject*)L_1, IL2CPP_RGCTX_DATA(method->rgctx_data, 0)))) { goto IL_003e; } } { ObjectU5BU5D_t2843939325* L_2 = (ObjectU5BU5D_t2843939325*)SZArrayNew(ObjectU5BU5D_t2843939325_il2cpp_TypeInfo_var, (uint32_t)2); ObjectU5BU5D_t2843939325* L_3 = (ObjectU5BU5D_t2843939325*)L_2; RuntimeObject * L_4 = ___arg0; NullCheck((RuntimeObject *)L_4); Type_t * L_5 = Object_GetType_m88164663((RuntimeObject *)L_4, /*hidden argument*/NULL); NullCheck(L_3); ArrayElementTypeCheck (L_3, L_5); (L_3)->SetAt(static_cast<il2cpp_array_size_t>(0), (RuntimeObject *)L_5); ObjectU5BU5D_t2843939325* L_6 = (ObjectU5BU5D_t2843939325*)L_3; RuntimeTypeHandle_t3027515415 L_7 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 1)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_8 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_7, /*hidden argument*/NULL); NullCheck(L_6); ArrayElementTypeCheck (L_6, L_8); (L_6)->SetAt(static_cast<il2cpp_array_size_t>(1), (RuntimeObject *)L_8); String_t* L_9 = UnityString_Format_m261690510(NULL /*static, unused*/, (String_t*)_stringLiteral273595399, (ObjectU5BU5D_t2843939325*)L_6, /*hidden argument*/NULL); ArgumentException_t132251570 * L_10 = (ArgumentException_t132251570 *)il2cpp_codegen_object_new(ArgumentException_t132251570_il2cpp_TypeInfo_var); ArgumentException__ctor_m1312628991(L_10, (String_t*)L_9, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_10, NULL, BaseInvokableCall_ThrowOnInvalidArg_TisSingle_t1397266774_m3110598205_RuntimeMethod_var); } IL_003e: { return; } } // T System.Array::Find<System.Object>(T[],System.Predicate`1<T>) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Array_Find_TisRuntimeObject_m2705709394_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___array0, Predicate_1_t3905400288 * ___match1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_Find_TisRuntimeObject_m2705709394_MetadataUsageId); s_Il2CppMethodInitialized = true; } RuntimeObject * V_0 = NULL; ObjectU5BU5D_t2843939325* V_1 = NULL; int32_t V_2 = 0; RuntimeObject * V_3 = NULL; { ObjectU5BU5D_t2843939325* L_0 = ___array0; if (L_0) { goto IL_0011; } } { ArgumentNullException_t1615371798 * L_1 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_1, (String_t*)_stringLiteral4007973390, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_1, NULL, Array_Find_TisRuntimeObject_m2705709394_RuntimeMethod_var); } IL_0011: { Predicate_1_t3905400288 * L_2 = ___match1; if (L_2) { goto IL_0022; } } { ArgumentNullException_t1615371798 * L_3 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_3, (String_t*)_stringLiteral461028519, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_3, NULL, Array_Find_TisRuntimeObject_m2705709394_RuntimeMethod_var); } IL_0022: { ObjectU5BU5D_t2843939325* L_4 = ___array0; V_1 = (ObjectU5BU5D_t2843939325*)L_4; V_2 = (int32_t)0; goto IL_0045; } IL_002b: { ObjectU5BU5D_t2843939325* L_5 = V_1; int32_t L_6 = V_2; NullCheck(L_5); int32_t L_7 = L_6; RuntimeObject * L_8 = (L_5)->GetAt(static_cast<il2cpp_array_size_t>(L_7)); V_0 = (RuntimeObject *)L_8; Predicate_1_t3905400288 * L_9 = ___match1; RuntimeObject * L_10 = V_0; NullCheck((Predicate_1_t3905400288 *)L_9); bool L_11 = (( bool (*) (Predicate_1_t3905400288 *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Predicate_1_t3905400288 *)L_9, (RuntimeObject *)L_10, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); if (!L_11) { goto IL_0041; } } { RuntimeObject * L_12 = V_0; return L_12; } IL_0041: { int32_t L_13 = V_2; V_2 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_13, (int32_t)1)); } IL_0045: { int32_t L_14 = V_2; ObjectU5BU5D_t2843939325* L_15 = V_1; NullCheck(L_15); if ((((int32_t)L_14) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_15)->max_length))))))) { goto IL_002b; } } { il2cpp_codegen_initobj((&V_3), sizeof(RuntimeObject *)); RuntimeObject * L_16 = V_3; return L_16; } } // T System.Array::FindLast<System.Object>(T[],System.Predicate`1<T>) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Array_FindLast_TisRuntimeObject_m1088586648_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___array0, Predicate_1_t3905400288 * ___match1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_FindLast_TisRuntimeObject_m1088586648_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; RuntimeObject * V_1 = NULL; { ObjectU5BU5D_t2843939325* L_0 = ___array0; if (L_0) { goto IL_0011; } } { ArgumentNullException_t1615371798 * L_1 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_1, (String_t*)_stringLiteral4007973390, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_1, NULL, Array_FindLast_TisRuntimeObject_m1088586648_RuntimeMethod_var); } IL_0011: { Predicate_1_t3905400288 * L_2 = ___match1; if (L_2) { goto IL_0022; } } { ArgumentNullException_t1615371798 * L_3 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_3, (String_t*)_stringLiteral461028519, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_3, NULL, Array_FindLast_TisRuntimeObject_m1088586648_RuntimeMethod_var); } IL_0022: { ObjectU5BU5D_t2843939325* L_4 = ___array0; NullCheck(L_4); V_0 = (int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_4)->max_length)))), (int32_t)1)); goto IL_004b; } IL_002d: { Predicate_1_t3905400288 * L_5 = ___match1; ObjectU5BU5D_t2843939325* L_6 = ___array0; int32_t L_7 = V_0; NullCheck(L_6); int32_t L_8 = L_7; RuntimeObject * L_9 = (L_6)->GetAt(static_cast<il2cpp_array_size_t>(L_8)); NullCheck((Predicate_1_t3905400288 *)L_5); bool L_10 = (( bool (*) (Predicate_1_t3905400288 *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)((Predicate_1_t3905400288 *)L_5, (RuntimeObject *)L_9, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); if (!L_10) { goto IL_0047; } } { ObjectU5BU5D_t2843939325* L_11 = ___array0; int32_t L_12 = V_0; NullCheck(L_11); int32_t L_13 = L_12; RuntimeObject * L_14 = (L_11)->GetAt(static_cast<il2cpp_array_size_t>(L_13)); return L_14; } IL_0047: { int32_t L_15 = V_0; V_0 = (int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_15, (int32_t)1)); } IL_004b: { int32_t L_16 = V_0; if ((((int32_t)L_16) >= ((int32_t)0))) { goto IL_002d; } } { il2cpp_codegen_initobj((&V_1), sizeof(RuntimeObject *)); RuntimeObject * L_17 = V_1; return L_17; } } // T System.Array::InternalArray__get_Item<Mono.Globalization.Unicode.CodePointIndexer/TableRange>(System.Int32) extern "C" IL2CPP_METHOD_ATTR TableRange_t3332867892 Array_InternalArray__get_Item_TisTableRange_t3332867892_m1483480711_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisTableRange_t3332867892_m1483480711_MetadataUsageId); s_Il2CppMethodInitialized = true; } TableRange_t3332867892 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisTableRange_t3332867892_m1483480711_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (TableRange_t3332867892 *)(TableRange_t3332867892 *)(&V_0)); TableRange_t3332867892 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<Mono.Security.Protocol.Tls.Handshake.ClientCertificateType>(System.Int32) extern "C" IL2CPP_METHOD_ATTR int32_t Array_InternalArray__get_Item_TisClientCertificateType_t1004704908_m2297379651_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisClientCertificateType_t1004704908_m2297379651_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisClientCertificateType_t1004704908_m2297379651_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (int32_t*)(int32_t*)(&V_0)); int32_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Boolean>(System.Int32) extern "C" IL2CPP_METHOD_ATTR bool Array_InternalArray__get_Item_TisBoolean_t97287965_m1407010309_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisBoolean_t97287965_m1407010309_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisBoolean_t97287965_m1407010309_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (bool*)(bool*)(&V_0)); bool L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Byte>(System.Int32) extern "C" IL2CPP_METHOD_ATTR uint8_t Array_InternalArray__get_Item_TisByte_t1134296376_m3566214066_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisByte_t1134296376_m3566214066_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint8_t V_0 = 0x0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisByte_t1134296376_m3566214066_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (uint8_t*)(uint8_t*)(&V_0)); uint8_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Char>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Il2CppChar Array_InternalArray__get_Item_TisChar_t3634460470_m324132692_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisChar_t3634460470_m324132692_MetadataUsageId); s_Il2CppMethodInitialized = true; } Il2CppChar V_0 = 0x0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisChar_t3634460470_m324132692_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Il2CppChar*)(Il2CppChar*)(&V_0)); Il2CppChar L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.DictionaryEntry>(System.Int32) extern "C" IL2CPP_METHOD_ATTR DictionaryEntry_t3123975638 Array_InternalArray__get_Item_TisDictionaryEntry_t3123975638_m479537688_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisDictionaryEntry_t3123975638_m479537688_MetadataUsageId); s_Il2CppMethodInitialized = true; } DictionaryEntry_t3123975638 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisDictionaryEntry_t3123975638_m479537688_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (DictionaryEntry_t3123975638 *)(DictionaryEntry_t3123975638 *)(&V_0)); DictionaryEntry_t3123975638 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.Generic.KeyValuePair`2<System.Object,System.Boolean>>(System.Int32) extern "C" IL2CPP_METHOD_ATTR KeyValuePair_2_t3842366416 Array_InternalArray__get_Item_TisKeyValuePair_2_t3842366416_m3937535230_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisKeyValuePair_2_t3842366416_m3937535230_MetadataUsageId); s_Il2CppMethodInitialized = true; } KeyValuePair_2_t3842366416 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisKeyValuePair_2_t3842366416_m3937535230_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (KeyValuePair_2_t3842366416 *)(KeyValuePair_2_t3842366416 *)(&V_0)); KeyValuePair_2_t3842366416 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.Generic.KeyValuePair`2<System.Object,System.Int32>>(System.Int32) extern "C" IL2CPP_METHOD_ATTR KeyValuePair_2_t2401056908 Array_InternalArray__get_Item_TisKeyValuePair_2_t2401056908_m3647027688_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisKeyValuePair_2_t2401056908_m3647027688_MetadataUsageId); s_Il2CppMethodInitialized = true; } KeyValuePair_2_t2401056908 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisKeyValuePair_2_t2401056908_m3647027688_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (KeyValuePair_2_t2401056908 *)(KeyValuePair_2_t2401056908 *)(&V_0)); KeyValuePair_2_t2401056908 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.Generic.KeyValuePair`2<System.Object,System.Object>>(System.Int32) extern "C" IL2CPP_METHOD_ATTR KeyValuePair_2_t2530217319 Array_InternalArray__get_Item_TisKeyValuePair_2_t2530217319_m2886833132_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisKeyValuePair_2_t2530217319_m2886833132_MetadataUsageId); s_Il2CppMethodInitialized = true; } KeyValuePair_2_t2530217319 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisKeyValuePair_2_t2530217319_m2886833132_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (KeyValuePair_2_t2530217319 *)(KeyValuePair_2_t2530217319 *)(&V_0)); KeyValuePair_2_t2530217319 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.Generic.Link>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Link_t544317964 Array_InternalArray__get_Item_TisLink_t544317964_m1669566993_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisLink_t544317964_m1669566993_MetadataUsageId); s_Il2CppMethodInitialized = true; } Link_t544317964 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisLink_t544317964_m1669566993_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Link_t544317964 *)(Link_t544317964 *)(&V_0)); Link_t544317964 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.Hashtable/Slot>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Slot_t3975888750 Array_InternalArray__get_Item_TisSlot_t3975888750_m905303097_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisSlot_t3975888750_m905303097_MetadataUsageId); s_Il2CppMethodInitialized = true; } Slot_t3975888750 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisSlot_t3975888750_m905303097_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Slot_t3975888750 *)(Slot_t3975888750 *)(&V_0)); Slot_t3975888750 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Collections.SortedList/Slot>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Slot_t384495010 Array_InternalArray__get_Item_TisSlot_t384495010_m2861978404_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisSlot_t384495010_m2861978404_MetadataUsageId); s_Il2CppMethodInitialized = true; } Slot_t384495010 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisSlot_t384495010_m2861978404_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Slot_t384495010 *)(Slot_t384495010 *)(&V_0)); Slot_t384495010 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.DateTime>(System.Int32) extern "C" IL2CPP_METHOD_ATTR DateTime_t3738529785 Array_InternalArray__get_Item_TisDateTime_t3738529785_m623181444_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisDateTime_t3738529785_m623181444_MetadataUsageId); s_Il2CppMethodInitialized = true; } DateTime_t3738529785 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisDateTime_t3738529785_m623181444_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (DateTime_t3738529785 *)(DateTime_t3738529785 *)(&V_0)); DateTime_t3738529785 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Decimal>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Decimal_t2948259380 Array_InternalArray__get_Item_TisDecimal_t2948259380_m3511003792_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisDecimal_t2948259380_m3511003792_MetadataUsageId); s_Il2CppMethodInitialized = true; } Decimal_t2948259380 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisDecimal_t2948259380_m3511003792_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Decimal_t2948259380 *)(Decimal_t2948259380 *)(&V_0)); Decimal_t2948259380 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Double>(System.Int32) extern "C" IL2CPP_METHOD_ATTR double Array_InternalArray__get_Item_TisDouble_t594665363_m850827605_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisDouble_t594665363_m850827605_MetadataUsageId); s_Il2CppMethodInitialized = true; } double V_0 = 0.0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisDouble_t594665363_m850827605_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (double*)(double*)(&V_0)); double L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Int16>(System.Int32) extern "C" IL2CPP_METHOD_ATTR int16_t Array_InternalArray__get_Item_TisInt16_t2552820387_m76930473_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisInt16_t2552820387_m76930473_MetadataUsageId); s_Il2CppMethodInitialized = true; } int16_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisInt16_t2552820387_m76930473_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (int16_t*)(int16_t*)(&V_0)); int16_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Int32>(System.Int32) extern "C" IL2CPP_METHOD_ATTR int32_t Array_InternalArray__get_Item_TisInt32_t2950945753_m714868479_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisInt32_t2950945753_m714868479_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisInt32_t2950945753_m714868479_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (int32_t*)(int32_t*)(&V_0)); int32_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Int64>(System.Int32) extern "C" IL2CPP_METHOD_ATTR int64_t Array_InternalArray__get_Item_TisInt64_t3736567304_m3562990826_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisInt64_t3736567304_m3562990826_MetadataUsageId); s_Il2CppMethodInitialized = true; } int64_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisInt64_t3736567304_m3562990826_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (int64_t*)(int64_t*)(&V_0)); int64_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.IntPtr>(System.Int32) extern "C" IL2CPP_METHOD_ATTR intptr_t Array_InternalArray__get_Item_TisIntPtr_t_m784054003_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisIntPtr_t_m784054003_MetadataUsageId); s_Il2CppMethodInitialized = true; } intptr_t V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisIntPtr_t_m784054003_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (intptr_t*)(intptr_t*)(&V_0)); intptr_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Object>(System.Int32) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Array_InternalArray__get_Item_TisRuntimeObject_m3347010206_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisRuntimeObject_m3347010206_MetadataUsageId); s_Il2CppMethodInitialized = true; } RuntimeObject * V_0 = NULL; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisRuntimeObject_m3347010206_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (RuntimeObject **)(RuntimeObject **)(&V_0)); RuntimeObject * L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.CustomAttributeNamedArgument>(System.Int32) extern "C" IL2CPP_METHOD_ATTR CustomAttributeNamedArgument_t287865710 Array_InternalArray__get_Item_TisCustomAttributeNamedArgument_t287865710_m2282658220_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisCustomAttributeNamedArgument_t287865710_m2282658220_MetadataUsageId); s_Il2CppMethodInitialized = true; } CustomAttributeNamedArgument_t287865710 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisCustomAttributeNamedArgument_t287865710_m2282658220_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (CustomAttributeNamedArgument_t287865710 *)(CustomAttributeNamedArgument_t287865710 *)(&V_0)); CustomAttributeNamedArgument_t287865710 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.CustomAttributeTypedArgument>(System.Int32) extern "C" IL2CPP_METHOD_ATTR CustomAttributeTypedArgument_t2723150157 Array_InternalArray__get_Item_TisCustomAttributeTypedArgument_t2723150157_m2639399822_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisCustomAttributeTypedArgument_t2723150157_m2639399822_MetadataUsageId); s_Il2CppMethodInitialized = true; } CustomAttributeTypedArgument_t2723150157 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisCustomAttributeTypedArgument_t2723150157_m2639399822_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (CustomAttributeTypedArgument_t2723150157 *)(CustomAttributeTypedArgument_t2723150157 *)(&V_0)); CustomAttributeTypedArgument_t2723150157 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.ILGenerator/LabelData>(System.Int32) extern "C" IL2CPP_METHOD_ATTR LabelData_t360167391 Array_InternalArray__get_Item_TisLabelData_t360167391_m1054702781_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisLabelData_t360167391_m1054702781_MetadataUsageId); s_Il2CppMethodInitialized = true; } LabelData_t360167391 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisLabelData_t360167391_m1054702781_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (LabelData_t360167391 *)(LabelData_t360167391 *)(&V_0)); LabelData_t360167391 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.ILGenerator/LabelFixup>(System.Int32) extern "C" IL2CPP_METHOD_ATTR LabelFixup_t858502054 Array_InternalArray__get_Item_TisLabelFixup_t858502054_m3276643490_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisLabelFixup_t858502054_m3276643490_MetadataUsageId); s_Il2CppMethodInitialized = true; } LabelFixup_t858502054 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisLabelFixup_t858502054_m3276643490_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (LabelFixup_t858502054 *)(LabelFixup_t858502054 *)(&V_0)); LabelFixup_t858502054 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.ILTokenInfo>(System.Int32) extern "C" IL2CPP_METHOD_ATTR ILTokenInfo_t2325775114 Array_InternalArray__get_Item_TisILTokenInfo_t2325775114_m3110830457_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisILTokenInfo_t2325775114_m3110830457_MetadataUsageId); s_Il2CppMethodInitialized = true; } ILTokenInfo_t2325775114 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisILTokenInfo_t2325775114_m3110830457_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (ILTokenInfo_t2325775114 *)(ILTokenInfo_t2325775114 *)(&V_0)); ILTokenInfo_t2325775114 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.MonoResource>(System.Int32) extern "C" IL2CPP_METHOD_ATTR MonoResource_t4103430009 Array_InternalArray__get_Item_TisMonoResource_t4103430009_m2937222811_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisMonoResource_t4103430009_m2937222811_MetadataUsageId); s_Il2CppMethodInitialized = true; } MonoResource_t4103430009 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisMonoResource_t4103430009_m2937222811_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (MonoResource_t4103430009 *)(MonoResource_t4103430009 *)(&V_0)); MonoResource_t4103430009 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.MonoWin32Resource>(System.Int32) extern "C" IL2CPP_METHOD_ATTR MonoWin32Resource_t1904229483 Array_InternalArray__get_Item_TisMonoWin32Resource_t1904229483_m513901999_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisMonoWin32Resource_t1904229483_m513901999_MetadataUsageId); s_Il2CppMethodInitialized = true; } MonoWin32Resource_t1904229483 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisMonoWin32Resource_t1904229483_m513901999_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (MonoWin32Resource_t1904229483 *)(MonoWin32Resource_t1904229483 *)(&V_0)); MonoWin32Resource_t1904229483 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.Emit.RefEmitPermissionSet>(System.Int32) extern "C" IL2CPP_METHOD_ATTR RefEmitPermissionSet_t484390987 Array_InternalArray__get_Item_TisRefEmitPermissionSet_t484390987_m1505876205_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisRefEmitPermissionSet_t484390987_m1505876205_MetadataUsageId); s_Il2CppMethodInitialized = true; } RefEmitPermissionSet_t484390987 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisRefEmitPermissionSet_t484390987_m1505876205_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (RefEmitPermissionSet_t484390987 *)(RefEmitPermissionSet_t484390987 *)(&V_0)); RefEmitPermissionSet_t484390987 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Reflection.ParameterModifier>(System.Int32) extern "C" IL2CPP_METHOD_ATTR ParameterModifier_t1461694466 Array_InternalArray__get_Item_TisParameterModifier_t1461694466_m29553316_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisParameterModifier_t1461694466_m29553316_MetadataUsageId); s_Il2CppMethodInitialized = true; } ParameterModifier_t1461694466 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisParameterModifier_t1461694466_m29553316_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (ParameterModifier_t1461694466 *)(ParameterModifier_t1461694466 *)(&V_0)); ParameterModifier_t1461694466 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Resources.ResourceReader/ResourceCacheItem>(System.Int32) extern "C" IL2CPP_METHOD_ATTR ResourceCacheItem_t51292791 Array_InternalArray__get_Item_TisResourceCacheItem_t51292791_m1306056717_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisResourceCacheItem_t51292791_m1306056717_MetadataUsageId); s_Il2CppMethodInitialized = true; } ResourceCacheItem_t51292791 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisResourceCacheItem_t51292791_m1306056717_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (ResourceCacheItem_t51292791 *)(ResourceCacheItem_t51292791 *)(&V_0)); ResourceCacheItem_t51292791 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Resources.ResourceReader/ResourceInfo>(System.Int32) extern "C" IL2CPP_METHOD_ATTR ResourceInfo_t2872965302 Array_InternalArray__get_Item_TisResourceInfo_t2872965302_m3865610257_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisResourceInfo_t2872965302_m3865610257_MetadataUsageId); s_Il2CppMethodInitialized = true; } ResourceInfo_t2872965302 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisResourceInfo_t2872965302_m3865610257_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (ResourceInfo_t2872965302 *)(ResourceInfo_t2872965302 *)(&V_0)); ResourceInfo_t2872965302 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Runtime.Serialization.Formatters.Binary.TypeTag>(System.Int32) extern "C" IL2CPP_METHOD_ATTR uint8_t Array_InternalArray__get_Item_TisTypeTag_t3541821701_m4208350471_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisTypeTag_t3541821701_m4208350471_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint8_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisTypeTag_t3541821701_m4208350471_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (uint8_t*)(uint8_t*)(&V_0)); uint8_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.SByte>(System.Int32) extern "C" IL2CPP_METHOD_ATTR int8_t Array_InternalArray__get_Item_TisSByte_t1669577662_m2349608172_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisSByte_t1669577662_m2349608172_MetadataUsageId); s_Il2CppMethodInitialized = true; } int8_t V_0 = 0x0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisSByte_t1669577662_m2349608172_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (int8_t*)(int8_t*)(&V_0)); int8_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Security.Cryptography.X509Certificates.X509ChainStatus>(System.Int32) extern "C" IL2CPP_METHOD_ATTR X509ChainStatus_t133602714 Array_InternalArray__get_Item_TisX509ChainStatus_t133602714_m2237651489_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisX509ChainStatus_t133602714_m2237651489_MetadataUsageId); s_Il2CppMethodInitialized = true; } X509ChainStatus_t133602714 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisX509ChainStatus_t133602714_m2237651489_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (X509ChainStatus_t133602714 *)(X509ChainStatus_t133602714 *)(&V_0)); X509ChainStatus_t133602714 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Single>(System.Int32) extern "C" IL2CPP_METHOD_ATTR float Array_InternalArray__get_Item_TisSingle_t1397266774_m1672589487_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisSingle_t1397266774_m1672589487_MetadataUsageId); s_Il2CppMethodInitialized = true; } float V_0 = 0.0f; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisSingle_t1397266774_m1672589487_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (float*)(float*)(&V_0)); float L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Text.RegularExpressions.Mark>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Mark_t3471605523 Array_InternalArray__get_Item_TisMark_t3471605523_m3397473850_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisMark_t3471605523_m3397473850_MetadataUsageId); s_Il2CppMethodInitialized = true; } Mark_t3471605523 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisMark_t3471605523_m3397473850_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Mark_t3471605523 *)(Mark_t3471605523 *)(&V_0)); Mark_t3471605523 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.TimeSpan>(System.Int32) extern "C" IL2CPP_METHOD_ATTR TimeSpan_t881159249 Array_InternalArray__get_Item_TisTimeSpan_t881159249_m1885583191_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisTimeSpan_t881159249_m1885583191_MetadataUsageId); s_Il2CppMethodInitialized = true; } TimeSpan_t881159249 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisTimeSpan_t881159249_m1885583191_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (TimeSpan_t881159249 *)(TimeSpan_t881159249 *)(&V_0)); TimeSpan_t881159249 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.UInt16>(System.Int32) extern "C" IL2CPP_METHOD_ATTR uint16_t Array_InternalArray__get_Item_TisUInt16_t2177724958_m3601205466_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisUInt16_t2177724958_m3601205466_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint16_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisUInt16_t2177724958_m3601205466_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (uint16_t*)(uint16_t*)(&V_0)); uint16_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.UInt32>(System.Int32) extern "C" IL2CPP_METHOD_ATTR uint32_t Array_InternalArray__get_Item_TisUInt32_t2560061978_m1955195035_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisUInt32_t2560061978_m1955195035_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint32_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisUInt32_t2560061978_m1955195035_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (uint32_t*)(uint32_t*)(&V_0)); uint32_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.UInt64>(System.Int32) extern "C" IL2CPP_METHOD_ATTR uint64_t Array_InternalArray__get_Item_TisUInt64_t4134040092_m129291315_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisUInt64_t4134040092_m129291315_MetadataUsageId); s_Il2CppMethodInitialized = true; } uint64_t V_0 = 0; { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisUInt64_t4134040092_m129291315_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (uint64_t*)(uint64_t*)(&V_0)); uint64_t L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<System.Uri/UriScheme>(System.Int32) extern "C" IL2CPP_METHOD_ATTR UriScheme_t722425697 Array_InternalArray__get_Item_TisUriScheme_t722425697_m2816273040_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisUriScheme_t722425697_m2816273040_MetadataUsageId); s_Il2CppMethodInitialized = true; } UriScheme_t722425697 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisUriScheme_t722425697_m2816273040_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (UriScheme_t722425697 *)(UriScheme_t722425697 *)(&V_0)); UriScheme_t722425697 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.BeforeRenderHelper/OrderBlock>(System.Int32) extern "C" IL2CPP_METHOD_ATTR OrderBlock_t1585977831 Array_InternalArray__get_Item_TisOrderBlock_t1585977831_m2406385050_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisOrderBlock_t1585977831_m2406385050_MetadataUsageId); s_Il2CppMethodInitialized = true; } OrderBlock_t1585977831 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisOrderBlock_t1585977831_m2406385050_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (OrderBlock_t1585977831 *)(OrderBlock_t1585977831 *)(&V_0)); OrderBlock_t1585977831 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.ContactPoint>(System.Int32) extern "C" IL2CPP_METHOD_ATTR ContactPoint_t3758755253 Array_InternalArray__get_Item_TisContactPoint_t3758755253_m2489897608_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisContactPoint_t3758755253_m2489897608_MetadataUsageId); s_Il2CppMethodInitialized = true; } ContactPoint_t3758755253 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisContactPoint_t3758755253_m2489897608_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (ContactPoint_t3758755253 *)(ContactPoint_t3758755253 *)(&V_0)); ContactPoint_t3758755253 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.Experimental.LowLevel.PlayerLoopSystem>(System.Int32) extern "C" IL2CPP_METHOD_ATTR PlayerLoopSystem_t105772105 Array_InternalArray__get_Item_TisPlayerLoopSystem_t105772105_m3446275388_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisPlayerLoopSystem_t105772105_m3446275388_MetadataUsageId); s_Il2CppMethodInitialized = true; } PlayerLoopSystem_t105772105 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisPlayerLoopSystem_t105772105_m3446275388_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (PlayerLoopSystem_t105772105 *)(PlayerLoopSystem_t105772105 *)(&V_0)); PlayerLoopSystem_t105772105 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.Keyframe>(System.Int32) extern "C" IL2CPP_METHOD_ATTR Keyframe_t4206410242 Array_InternalArray__get_Item_TisKeyframe_t4206410242_m27698365_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisKeyframe_t4206410242_m27698365_MetadataUsageId); s_Il2CppMethodInitialized = true; } Keyframe_t4206410242 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisKeyframe_t4206410242_m27698365_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (Keyframe_t4206410242 *)(Keyframe_t4206410242 *)(&V_0)); Keyframe_t4206410242 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.Playables.PlayableBinding>(System.Int32) extern "C" IL2CPP_METHOD_ATTR PlayableBinding_t354260709 Array_InternalArray__get_Item_TisPlayableBinding_t354260709_m3837494573_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisPlayableBinding_t354260709_m3837494573_MetadataUsageId); s_Il2CppMethodInitialized = true; } PlayableBinding_t354260709 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisPlayableBinding_t354260709_m3837494573_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (PlayableBinding_t354260709 *)(PlayableBinding_t354260709 *)(&V_0)); PlayableBinding_t354260709 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.RaycastHit>(System.Int32) extern "C" IL2CPP_METHOD_ATTR RaycastHit_t1056001966 Array_InternalArray__get_Item_TisRaycastHit_t1056001966_m3352067444_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisRaycastHit_t1056001966_m3352067444_MetadataUsageId); s_Il2CppMethodInitialized = true; } RaycastHit_t1056001966 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisRaycastHit_t1056001966_m3352067444_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (RaycastHit_t1056001966 *)(RaycastHit_t1056001966 *)(&V_0)); RaycastHit_t1056001966 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.SendMouseEvents/HitInfo>(System.Int32) extern "C" IL2CPP_METHOD_ATTR HitInfo_t3229609740 Array_InternalArray__get_Item_TisHitInfo_t3229609740_m2260995172_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisHitInfo_t3229609740_m2260995172_MetadataUsageId); s_Il2CppMethodInitialized = true; } HitInfo_t3229609740 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisHitInfo_t3229609740_m2260995172_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (HitInfo_t3229609740 *)(HitInfo_t3229609740 *)(&V_0)); HitInfo_t3229609740 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.SocialPlatforms.GameCenter.GcAchievementData>(System.Int32) extern "C" IL2CPP_METHOD_ATTR GcAchievementData_t675222246 Array_InternalArray__get_Item_TisGcAchievementData_t675222246_m2680268485_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisGcAchievementData_t675222246_m2680268485_MetadataUsageId); s_Il2CppMethodInitialized = true; } GcAchievementData_t675222246 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisGcAchievementData_t675222246_m2680268485_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (GcAchievementData_t675222246 *)(GcAchievementData_t675222246 *)(&V_0)); GcAchievementData_t675222246 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.SocialPlatforms.GameCenter.GcScoreData>(System.Int32) extern "C" IL2CPP_METHOD_ATTR GcScoreData_t2125309831 Array_InternalArray__get_Item_TisGcScoreData_t2125309831_m174676143_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisGcScoreData_t2125309831_m174676143_MetadataUsageId); s_Il2CppMethodInitialized = true; } GcScoreData_t2125309831 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisGcScoreData_t2125309831_m174676143_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (GcScoreData_t2125309831 *)(GcScoreData_t2125309831 *)(&V_0)); GcScoreData_t2125309831 L_4 = V_0; return L_4; } } // T System.Array::InternalArray__get_Item<UnityEngine.UnitySynchronizationContext/WorkRequest>(System.Int32) extern "C" IL2CPP_METHOD_ATTR WorkRequest_t1354518612 Array_InternalArray__get_Item_TisWorkRequest_t1354518612_m2694410850_gshared (RuntimeArray * __this, int32_t ___index0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_InternalArray__get_Item_TisWorkRequest_t1354518612_m2694410850_MetadataUsageId); s_Il2CppMethodInitialized = true; } WorkRequest_t1354518612 V_0; memset(&V_0, 0, sizeof(V_0)); { int32_t L_0 = ___index0; NullCheck((RuntimeArray *)__this); int32_t L_1 = Array_get_Length_m21610649((RuntimeArray *)__this, /*hidden argument*/NULL); if ((!(((uint32_t)L_0) >= ((uint32_t)L_1)))) { goto IL_0017; } } { ArgumentOutOfRangeException_t777629997 * L_2 = (ArgumentOutOfRangeException_t777629997 *)il2cpp_codegen_object_new(ArgumentOutOfRangeException_t777629997_il2cpp_TypeInfo_var); ArgumentOutOfRangeException__ctor_m3628145864(L_2, (String_t*)_stringLiteral797640427, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_2, NULL, Array_InternalArray__get_Item_TisWorkRequest_t1354518612_m2694410850_RuntimeMethod_var); } IL_0017: { int32_t L_3 = ___index0; NullCheck((RuntimeArray *)__this); ArrayGetGenericValueImpl((RuntimeArray *)__this, (int32_t)L_3, (WorkRequest_t1354518612 *)(WorkRequest_t1354518612 *)(&V_0)); WorkRequest_t1354518612 L_4 = V_0; return L_4; } } // T UnityEngine.AttributeHelperEngine::GetCustomAttributeOfType<System.Object>(System.Type) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * AttributeHelperEngine_GetCustomAttributeOfType_TisRuntimeObject_m429013101_gshared (RuntimeObject * __this /* static, unused */, Type_t * ___klass0, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (AttributeHelperEngine_GetCustomAttributeOfType_TisRuntimeObject_m429013101_MetadataUsageId); s_Il2CppMethodInitialized = true; } Type_t * V_0 = NULL; ObjectU5BU5D_t2843939325* V_1 = NULL; RuntimeObject * V_2 = NULL; { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); V_0 = (Type_t *)L_1; Type_t * L_2 = ___klass0; Type_t * L_3 = V_0; NullCheck((MemberInfo_t *)L_2); ObjectU5BU5D_t2843939325* L_4 = VirtFuncInvoker2< ObjectU5BU5D_t2843939325*, Type_t *, bool >::Invoke(13 /* System.Object[] System.Reflection.MemberInfo::GetCustomAttributes(System.Type,System.Boolean) */, (MemberInfo_t *)L_2, (Type_t *)L_3, (bool)1); V_1 = (ObjectU5BU5D_t2843939325*)L_4; ObjectU5BU5D_t2843939325* L_5 = V_1; if (!L_5) { goto IL_0031; } } { ObjectU5BU5D_t2843939325* L_6 = V_1; NullCheck(L_6); if (!(((int32_t)((int32_t)(((RuntimeArray *)L_6)->max_length))))) { goto IL_0031; } } { ObjectU5BU5D_t2843939325* L_7 = V_1; NullCheck(L_7); int32_t L_8 = 0; RuntimeObject * L_9 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_8)); V_2 = (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_9, IL2CPP_RGCTX_DATA(method->rgctx_data, 1))); goto IL_003d; } IL_0031: { V_2 = (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)NULL, IL2CPP_RGCTX_DATA(method->rgctx_data, 1))); goto IL_003d; } IL_003d: { RuntimeObject * L_10 = V_2; return L_10; } } // T UnityEngine.Component::GetComponent<System.Object>() extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Component_GetComponent_TisRuntimeObject_m2906321015_gshared (Component_t1923634451 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Component_GetComponent_TisRuntimeObject_m2906321015_MetadataUsageId); s_Il2CppMethodInitialized = true; } CastHelper_1_t2613165452 V_0; memset(&V_0, 0, sizeof(V_0)); RuntimeObject * V_1 = NULL; { il2cpp_codegen_initobj((&V_0), sizeof(CastHelper_1_t2613165452 )); RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); intptr_t* L_2 = (intptr_t*)(&V_0)->get_address_of_onePointerFurtherThanT_1(); intptr_t L_3; memset(&L_3, 0, sizeof(L_3)); IntPtr__ctor_m3384658186((&L_3), (void*)(void*)L_2, /*hidden argument*/NULL); NullCheck((Component_t1923634451 *)__this); Component_GetComponentFastPath_m1180649031((Component_t1923634451 *)__this, (Type_t *)L_1, (intptr_t)L_3, /*hidden argument*/NULL); RuntimeObject * L_4 = (RuntimeObject *)(&V_0)->get_t_0(); V_1 = (RuntimeObject *)L_4; goto IL_0032; } IL_0032: { RuntimeObject * L_5 = V_1; return L_5; } } // T UnityEngine.ScriptableObject::CreateInstance<System.Object>() extern "C" IL2CPP_METHOD_ATTR RuntimeObject * ScriptableObject_CreateInstance_TisRuntimeObject_m1552711675_gshared (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (ScriptableObject_CreateInstance_TisRuntimeObject_m1552711675_MetadataUsageId); s_Il2CppMethodInitialized = true; } RuntimeObject * V_0 = NULL; { RuntimeTypeHandle_t3027515415 L_0 = { reinterpret_cast<intptr_t> (IL2CPP_RGCTX_TYPE(method->rgctx_data, 0)) }; IL2CPP_RUNTIME_CLASS_INIT(Type_t_il2cpp_TypeInfo_var); Type_t * L_1 = Type_GetTypeFromHandle_m1620074514(NULL /*static, unused*/, (RuntimeTypeHandle_t3027515415 )L_0, /*hidden argument*/NULL); ScriptableObject_t2528358522 * L_2 = ScriptableObject_CreateInstance_m2611081756(NULL /*static, unused*/, (Type_t *)L_1, /*hidden argument*/NULL); V_0 = (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_2, IL2CPP_RGCTX_DATA(method->rgctx_data, 1))); goto IL_001b; } IL_001b: { RuntimeObject * L_3 = V_0; return L_3; } } // TOutput[] System.Array::ConvertAll<System.Object,System.Object>(TInput[],System.Converter`2<TInput,TOutput>) extern "C" IL2CPP_METHOD_ATTR ObjectU5BU5D_t2843939325* Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___array0, Converter_2_t2442480487 * ___converter1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_MetadataUsageId); s_Il2CppMethodInitialized = true; } ObjectU5BU5D_t2843939325* V_0 = NULL; int32_t V_1 = 0; { ObjectU5BU5D_t2843939325* L_0 = ___array0; if (L_0) { goto IL_0011; } } { ArgumentNullException_t1615371798 * L_1 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_1, (String_t*)_stringLiteral4007973390, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_1, NULL, Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_RuntimeMethod_var); } IL_0011: { Converter_2_t2442480487 * L_2 = ___converter1; if (L_2) { goto IL_0022; } } { ArgumentNullException_t1615371798 * L_3 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_3, (String_t*)_stringLiteral879148213, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_3, NULL, Array_ConvertAll_TisRuntimeObject_TisRuntimeObject_m2417852296_RuntimeMethod_var); } IL_0022: { ObjectU5BU5D_t2843939325* L_4 = ___array0; NullCheck(L_4); ObjectU5BU5D_t2843939325* L_5 = (ObjectU5BU5D_t2843939325*)SZArrayNew(IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_4)->max_length))))); V_0 = (ObjectU5BU5D_t2843939325*)L_5; V_1 = (int32_t)0; goto IL_004a; } IL_0032: { ObjectU5BU5D_t2843939325* L_6 = V_0; int32_t L_7 = V_1; Converter_2_t2442480487 * L_8 = ___converter1; ObjectU5BU5D_t2843939325* L_9 = ___array0; int32_t L_10 = V_1; NullCheck(L_9); int32_t L_11 = L_10; RuntimeObject * L_12 = (L_9)->GetAt(static_cast<il2cpp_array_size_t>(L_11)); NullCheck((Converter_2_t2442480487 *)L_8); RuntimeObject * L_13 = (( RuntimeObject * (*) (Converter_2_t2442480487 *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Converter_2_t2442480487 *)L_8, (RuntimeObject *)L_12, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); NullCheck(L_6); (L_6)->SetAt(static_cast<il2cpp_array_size_t>(L_7), (RuntimeObject *)L_13); int32_t L_14 = V_1; V_1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_14, (int32_t)1)); } IL_004a: { int32_t L_15 = V_1; ObjectU5BU5D_t2843939325* L_16 = ___array0; NullCheck(L_16); if ((((int32_t)L_15) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_16)->max_length))))))) { goto IL_0032; } } { ObjectU5BU5D_t2843939325* L_17 = V_0; return L_17; } } // TSource System.Linq.Enumerable::Single<System.Object>(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>,System.Linq.Enumerable/Fallback) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Enumerable_Single_TisRuntimeObject_m1146889774_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject* ___source0, Func_2_t3759279471 * ___predicate1, int32_t ___fallback2, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Enumerable_Single_TisRuntimeObject_m1146889774_MetadataUsageId); s_Il2CppMethodInitialized = true; } bool V_0 = false; RuntimeObject * V_1 = NULL; RuntimeObject * V_2 = NULL; RuntimeObject* V_3 = NULL; RuntimeObject * V_4 = NULL; Exception_t * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = -1; NO_UNUSED_WARNING (__leave_target); { V_0 = (bool)0; il2cpp_codegen_initobj((&V_4), sizeof(RuntimeObject *)); RuntimeObject * L_0 = V_4; V_1 = (RuntimeObject *)L_0; RuntimeObject* L_1 = ___source0; NullCheck((RuntimeObject*)L_1); RuntimeObject* L_2 = InterfaceFuncInvoker0< RuntimeObject* >::Invoke(0 /* System.Collections.Generic.IEnumerator`1<!0> System.Collections.Generic.IEnumerable`1<System.Object>::GetEnumerator() */, IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (RuntimeObject*)L_1); V_3 = (RuntimeObject*)L_2; } IL_0014: try { // begin try (depth: 1) { goto IL_0041; } IL_0019: { RuntimeObject* L_3 = V_3; NullCheck((RuntimeObject*)L_3); RuntimeObject * L_4 = InterfaceFuncInvoker0< RuntimeObject * >::Invoke(0 /* !0 System.Collections.Generic.IEnumerator`1<System.Object>::get_Current() */, IL2CPP_RGCTX_DATA(method->rgctx_data, 1), (RuntimeObject*)L_3); V_2 = (RuntimeObject *)L_4; Func_2_t3759279471 * L_5 = ___predicate1; RuntimeObject * L_6 = V_2; NullCheck((Func_2_t3759279471 *)L_5); bool L_7 = (( bool (*) (Func_2_t3759279471 *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 2)->methodPointer)((Func_2_t3759279471 *)L_5, (RuntimeObject *)L_6, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 2)); if (L_7) { goto IL_0031; } } IL_002c: { goto IL_0041; } IL_0031: { bool L_8 = V_0; if (!L_8) { goto IL_003d; } } IL_0037: { InvalidOperationException_t56020091 * L_9 = (InvalidOperationException_t56020091 *)il2cpp_codegen_object_new(InvalidOperationException_t56020091_il2cpp_TypeInfo_var); InvalidOperationException__ctor_m2734335978(L_9, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_9, NULL, Enumerable_Single_TisRuntimeObject_m1146889774_RuntimeMethod_var); } IL_003d: { V_0 = (bool)1; RuntimeObject * L_10 = V_2; V_1 = (RuntimeObject *)L_10; } IL_0041: { RuntimeObject* L_11 = V_3; NullCheck((RuntimeObject*)L_11); bool L_12 = InterfaceFuncInvoker0< bool >::Invoke(1 /* System.Boolean System.Collections.IEnumerator::MoveNext() */, IEnumerator_t1853284238_il2cpp_TypeInfo_var, (RuntimeObject*)L_11); if (L_12) { goto IL_0019; } } IL_004c: { IL2CPP_LEAVE(0x5C, FINALLY_0051); } } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t *)e.ex; goto FINALLY_0051; } FINALLY_0051: { // begin finally (depth: 1) { RuntimeObject* L_13 = V_3; if (L_13) { goto IL_0055; } } IL_0054: { IL2CPP_END_FINALLY(81) } IL_0055: { RuntimeObject* L_14 = V_3; NullCheck((RuntimeObject*)L_14); InterfaceActionInvoker0::Invoke(0 /* System.Void System.IDisposable::Dispose() */, IDisposable_t3640265483_il2cpp_TypeInfo_var, (RuntimeObject*)L_14); IL2CPP_END_FINALLY(81) } } // end finally (depth: 1) IL2CPP_CLEANUP(81) { IL2CPP_JUMP_TBL(0x5C, IL_005c) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t *) } IL_005c: { bool L_15 = V_0; if (L_15) { goto IL_006f; } } { int32_t L_16 = ___fallback2; if ((!(((uint32_t)L_16) == ((uint32_t)1)))) { goto IL_006f; } } { InvalidOperationException_t56020091 * L_17 = (InvalidOperationException_t56020091 *)il2cpp_codegen_object_new(InvalidOperationException_t56020091_il2cpp_TypeInfo_var); InvalidOperationException__ctor_m2734335978(L_17, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_17, NULL, Enumerable_Single_TisRuntimeObject_m1146889774_RuntimeMethod_var); } IL_006f: { RuntimeObject * L_18 = V_1; return L_18; } } // TSource System.Linq.Enumerable::SingleOrDefault<System.Object>(System.Collections.Generic.IEnumerable`1<TSource>,System.Func`2<TSource,System.Boolean>) extern "C" IL2CPP_METHOD_ATTR RuntimeObject * Enumerable_SingleOrDefault_TisRuntimeObject_m555175825_gshared (RuntimeObject * __this /* static, unused */, RuntimeObject* ___source0, Func_2_t3759279471 * ___predicate1, const RuntimeMethod* method) { { RuntimeObject* L_0 = ___source0; Func_2_t3759279471 * L_1 = ___predicate1; Check_SourceAndPredicate_m2332465641(NULL /*static, unused*/, (RuntimeObject *)L_0, (RuntimeObject *)L_1, /*hidden argument*/NULL); RuntimeObject* L_2 = ___source0; Func_2_t3759279471 * L_3 = ___predicate1; RuntimeObject * L_4 = (( RuntimeObject * (*) (RuntimeObject * /* static, unused */, RuntimeObject*, Func_2_t3759279471 *, int32_t, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)->methodPointer)(NULL /*static, unused*/, (RuntimeObject*)L_2, (Func_2_t3759279471 *)L_3, (int32_t)0, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 0)); return L_4; } } // T[] System.Array::FindAll<System.Object>(T[],System.Predicate`1<T>) extern "C" IL2CPP_METHOD_ATTR ObjectU5BU5D_t2843939325* Array_FindAll_TisRuntimeObject_m3566631088_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___array0, Predicate_1_t3905400288 * ___match1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (Array_FindAll_TisRuntimeObject_m3566631088_MetadataUsageId); s_Il2CppMethodInitialized = true; } int32_t V_0 = 0; ObjectU5BU5D_t2843939325* V_1 = NULL; RuntimeObject * V_2 = NULL; ObjectU5BU5D_t2843939325* V_3 = NULL; int32_t V_4 = 0; { ObjectU5BU5D_t2843939325* L_0 = ___array0; if (L_0) { goto IL_0011; } } { ArgumentNullException_t1615371798 * L_1 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_1, (String_t*)_stringLiteral4007973390, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_1, NULL, Array_FindAll_TisRuntimeObject_m3566631088_RuntimeMethod_var); } IL_0011: { Predicate_1_t3905400288 * L_2 = ___match1; if (L_2) { goto IL_0022; } } { ArgumentNullException_t1615371798 * L_3 = (ArgumentNullException_t1615371798 *)il2cpp_codegen_object_new(ArgumentNullException_t1615371798_il2cpp_TypeInfo_var); ArgumentNullException__ctor_m1170824041(L_3, (String_t*)_stringLiteral461028519, /*hidden argument*/NULL); IL2CPP_RAISE_MANAGED_EXCEPTION(L_3, NULL, Array_FindAll_TisRuntimeObject_m3566631088_RuntimeMethod_var); } IL_0022: { V_0 = (int32_t)0; ObjectU5BU5D_t2843939325* L_4 = ___array0; NullCheck(L_4); ObjectU5BU5D_t2843939325* L_5 = (ObjectU5BU5D_t2843939325*)SZArrayNew(IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_4)->max_length))))); V_1 = (ObjectU5BU5D_t2843939325*)L_5; ObjectU5BU5D_t2843939325* L_6 = ___array0; V_3 = (ObjectU5BU5D_t2843939325*)L_6; V_4 = (int32_t)0; goto IL_005e; } IL_0037: { ObjectU5BU5D_t2843939325* L_7 = V_3; int32_t L_8 = V_4; NullCheck(L_7); int32_t L_9 = L_8; RuntimeObject * L_10 = (L_7)->GetAt(static_cast<il2cpp_array_size_t>(L_9)); V_2 = (RuntimeObject *)L_10; Predicate_1_t3905400288 * L_11 = ___match1; RuntimeObject * L_12 = V_2; NullCheck((Predicate_1_t3905400288 *)L_11); bool L_13 = (( bool (*) (Predicate_1_t3905400288 *, RuntimeObject *, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)->methodPointer)((Predicate_1_t3905400288 *)L_11, (RuntimeObject *)L_12, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 1)); if (!L_13) { goto IL_0058; } } { ObjectU5BU5D_t2843939325* L_14 = V_1; int32_t L_15 = V_0; int32_t L_16 = (int32_t)L_15; V_0 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_16, (int32_t)1)); RuntimeObject * L_17 = V_2; NullCheck(L_14); (L_14)->SetAt(static_cast<il2cpp_array_size_t>(L_16), (RuntimeObject *)L_17); } IL_0058: { int32_t L_18 = V_4; V_4 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_18, (int32_t)1)); } IL_005e: { int32_t L_19 = V_4; ObjectU5BU5D_t2843939325* L_20 = V_3; NullCheck(L_20); if ((((int32_t)L_19) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_20)->max_length))))))) { goto IL_0037; } } { int32_t L_21 = V_0; (( void (*) (RuntimeObject * /* static, unused */, ObjectU5BU5D_t2843939325**, int32_t, const RuntimeMethod*))IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 2)->methodPointer)(NULL /*static, unused*/, (ObjectU5BU5D_t2843939325**)(ObjectU5BU5D_t2843939325**)(&V_1), (int32_t)L_21, /*hidden argument*/IL2CPP_RGCTX_METHOD_INFO(method->rgctx_data, 2)); ObjectU5BU5D_t2843939325* L_22 = V_1; return L_22; } } // T[] System.Reflection.CustomAttributeData::UnboxValues<System.Object>(System.Object[]) extern "C" IL2CPP_METHOD_ATTR ObjectU5BU5D_t2843939325* CustomAttributeData_UnboxValues_TisRuntimeObject_m160061819_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___values0, const RuntimeMethod* method) { ObjectU5BU5D_t2843939325* V_0 = NULL; int32_t V_1 = 0; { ObjectU5BU5D_t2843939325* L_0 = ___values0; NullCheck(L_0); ObjectU5BU5D_t2843939325* L_1 = (ObjectU5BU5D_t2843939325*)SZArrayNew(IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_0)->max_length))))); V_0 = (ObjectU5BU5D_t2843939325*)L_1; V_1 = (int32_t)0; goto IL_0023; } IL_0010: { ObjectU5BU5D_t2843939325* L_2 = V_0; int32_t L_3 = V_1; ObjectU5BU5D_t2843939325* L_4 = ___values0; int32_t L_5 = V_1; NullCheck(L_4); int32_t L_6 = L_5; RuntimeObject * L_7 = (L_4)->GetAt(static_cast<il2cpp_array_size_t>(L_6)); NullCheck(L_2); (L_2)->SetAt(static_cast<il2cpp_array_size_t>(L_3), (RuntimeObject *)((RuntimeObject *)Castclass((RuntimeObject*)L_7, IL2CPP_RGCTX_DATA(method->rgctx_data, 1)))); int32_t L_8 = V_1; V_1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_8, (int32_t)1)); } IL_0023: { int32_t L_9 = V_1; ObjectU5BU5D_t2843939325* L_10 = ___values0; NullCheck(L_10); if ((((int32_t)L_9) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_10)->max_length))))))) { goto IL_0010; } } { ObjectU5BU5D_t2843939325* L_11 = V_0; return L_11; } } // T[] System.Reflection.CustomAttributeData::UnboxValues<System.Reflection.CustomAttributeNamedArgument>(System.Object[]) extern "C" IL2CPP_METHOD_ATTR CustomAttributeNamedArgumentU5BU5D_t3710464795* CustomAttributeData_UnboxValues_TisCustomAttributeNamedArgument_t287865710_m2244692512_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___values0, const RuntimeMethod* method) { CustomAttributeNamedArgumentU5BU5D_t3710464795* V_0 = NULL; int32_t V_1 = 0; { ObjectU5BU5D_t2843939325* L_0 = ___values0; NullCheck(L_0); CustomAttributeNamedArgumentU5BU5D_t3710464795* L_1 = (CustomAttributeNamedArgumentU5BU5D_t3710464795*)SZArrayNew(IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_0)->max_length))))); V_0 = (CustomAttributeNamedArgumentU5BU5D_t3710464795*)L_1; V_1 = (int32_t)0; goto IL_0023; } IL_0010: { CustomAttributeNamedArgumentU5BU5D_t3710464795* L_2 = V_0; int32_t L_3 = V_1; ObjectU5BU5D_t2843939325* L_4 = ___values0; int32_t L_5 = V_1; NullCheck(L_4); int32_t L_6 = L_5; RuntimeObject * L_7 = (L_4)->GetAt(static_cast<il2cpp_array_size_t>(L_6)); NullCheck(L_2); (L_2)->SetAt(static_cast<il2cpp_array_size_t>(L_3), (CustomAttributeNamedArgument_t287865710 )((*(CustomAttributeNamedArgument_t287865710 *)((CustomAttributeNamedArgument_t287865710 *)UnBox(L_7, IL2CPP_RGCTX_DATA(method->rgctx_data, 1)))))); int32_t L_8 = V_1; V_1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_8, (int32_t)1)); } IL_0023: { int32_t L_9 = V_1; ObjectU5BU5D_t2843939325* L_10 = ___values0; NullCheck(L_10); if ((((int32_t)L_9) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_10)->max_length))))))) { goto IL_0010; } } { CustomAttributeNamedArgumentU5BU5D_t3710464795* L_11 = V_0; return L_11; } } // T[] System.Reflection.CustomAttributeData::UnboxValues<System.Reflection.CustomAttributeTypedArgument>(System.Object[]) extern "C" IL2CPP_METHOD_ATTR CustomAttributeTypedArgumentU5BU5D_t1465843424* CustomAttributeData_UnboxValues_TisCustomAttributeTypedArgument_t2723150157_m679789813_gshared (RuntimeObject * __this /* static, unused */, ObjectU5BU5D_t2843939325* ___values0, const RuntimeMethod* method) { CustomAttributeTypedArgumentU5BU5D_t1465843424* V_0 = NULL; int32_t V_1 = 0; { ObjectU5BU5D_t2843939325* L_0 = ___values0; NullCheck(L_0); CustomAttributeTypedArgumentU5BU5D_t1465843424* L_1 = (CustomAttributeTypedArgumentU5BU5D_t1465843424*)SZArrayNew(IL2CPP_RGCTX_DATA(method->rgctx_data, 0), (uint32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_0)->max_length))))); V_0 = (CustomAttributeTypedArgumentU5BU5D_t1465843424*)L_1; V_1 = (int32_t)0; goto IL_0023; } IL_0010: { CustomAttributeTypedArgumentU5BU5D_t1465843424* L_2 = V_0; int32_t L_3 = V_1; ObjectU5BU5D_t2843939325* L_4 = ___values0; int32_t L_5 = V_1; NullCheck(L_4); int32_t L_6 = L_5; RuntimeObject * L_7 = (L_4)->GetAt(static_cast<il2cpp_array_size_t>(L_6)); NullCheck(L_2); (L_2)->SetAt(static_cast<il2cpp_array_size_t>(L_3), (CustomAttributeTypedArgument_t2723150157 )((*(CustomAttributeTypedArgument_t2723150157 *)((CustomAttributeTypedArgument_t2723150157 *)UnBox(L_7, IL2CPP_RGCTX_DATA(method->rgctx_data, 1)))))); int32_t L_8 = V_1; V_1 = (int32_t)((int32_t)il2cpp_codegen_add((int32_t)L_8, (int32_t)1)); } IL_0023: { int32_t L_9 = V_1; ObjectU5BU5D_t2843939325* L_10 = ___values0; NullCheck(L_10); if ((((int32_t)L_9) < ((int32_t)(((int32_t)((int32_t)(((RuntimeArray *)L_10)->max_length))))))) { goto IL_0010; } } { CustomAttributeTypedArgumentU5BU5D_t1465843424* L_11 = V_0; return L_11; } }
39.5471
479
0.80809
[ "object", "transform" ]
419af2257386c34b16d52ad1192ad8014b39f6b1
3,504
hpp
C++
space/src/caches/Complete_Cache.hpp
sirikata/sirikata
3a0d54a8c4778ad6e25ef031d461b2bc3e264860
[ "BSD-3-Clause" ]
31
2015-01-28T17:01:10.000Z
2021-11-04T08:30:37.000Z
space/src/caches/Complete_Cache.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
null
null
null
space/src/caches/Complete_Cache.hpp
pathorn/sirikata
5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa
[ "BSD-3-Clause" ]
9
2015-08-02T18:39:49.000Z
2019-10-11T10:32:30.000Z
/* Sirikata * Complete_Cache.hpp * * Copyright (c) 2010, Behram Mistree * 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 Sirikata 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 <map> #include <functional> #include <vector> #include <list> #include "Cache.hpp" #include "Utility.hpp" #include <string> #include "CacheRecords.hpp" #include <float.h> #ifndef __COMPLETE_CACHE_HPP__ #define __COMPLETE_CACHE_HPP__ namespace Sirikata { typedef double (*CompleteCacheScoreFunc) (const FCacheRecord* a); typedef double (*CompleteCacheScoreFuncPrint) (const FCacheRecord* a,bool toPrint); class Complete_Cache : public Cache { private: typedef std::map<UUID,FCacheRecord*> IDRecordMap; IDRecordMap idRecMap; typedef std::multimap<double,FCacheRecord*> TimeRecordMap; TimeRecordMap timeRecMap; void maintain(); double ewmaPopPar; std::string mName; int mMaxSize; CompleteCacheScoreFunc mScoreFunc; CompleteCacheScoreFuncPrint mScoreFuncPrint; SpaceContext* ctx; CacheTimeMS mPrevTime; float mInsideRadiusInsert; void checkUpdate(); public: OSegEntry mCraqEntry; Complete_Cache(double avgPopPar,std::string complete_name, CompleteCacheScoreFunc ccScorer,CompleteCacheScoreFuncPrint ccScorerPrint, SpaceContext* spctx, float insideRadiusInsert= FLT_MAX); Complete_Cache(double avgPopPar,std::string complete_name,CompleteCacheScoreFunc ccScorer,CompleteCacheScoreFuncPrint ccScorerPrint,SpaceContext* spctx,int complete_size, float insideRadiusInsert = FLT_MAX); virtual ~Complete_Cache(); // void insert(UUID toInsert, ServerID bid, CacheTimeMS tms, double vMag); virtual void insert(const UUID& toInsert, ServerID bid, CacheTimeMS tms, double vMag, double weight, double distance, double radius,double lookupWeight,double scaler); virtual const OSegEntry& lookup (const UUID& lookingFor); ServerID lookup_dynamic(UUID uuid); virtual std::string getCacheName(); virtual void remove(const UUID& oid); void printAll(); }; } #endif
34.693069
211
0.759703
[ "vector" ]
41a6141e2071bd7c38e5e6f05d813500662d9e7a
86,678
cpp
C++
platform/windows/Corona.Simulator/SimulatorView.cpp
joehinkle11/corona
530320beaa518a2b82fa8beb2a92f3be6b56a00e
[ "MIT" ]
1,968
2018-12-30T21:14:22.000Z
2022-03-31T23:48:16.000Z
platform/windows/Corona.Simulator/SimulatorView.cpp
joehinkle11/corona
530320beaa518a2b82fa8beb2a92f3be6b56a00e
[ "MIT" ]
303
2019-01-02T19:36:43.000Z
2022-03-31T23:52:45.000Z
platform/windows/Corona.Simulator/SimulatorView.cpp
joehinkle11/corona
530320beaa518a2b82fa8beb2a92f3be6b56a00e
[ "MIT" ]
254
2019-01-02T19:05:52.000Z
2022-03-30T06:32:28.000Z
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include <shlwapi.h> #include <gdiplus.h> #include <stdlib.h> #include <math.h> #include "Core\Rtt_Build.h" #include "Interop\UI\TaskDialog.h" #include "Interop\MDeviceSimulatorServices.h" #include "Interop\SimulatorRuntimeEnvironment.h" #include "Rtt_LuaContext.h" #include "Rtt_LuaFile.h" #include "Rtt_MPlatform.h" #include "Rtt_PlatformAppPackager.h" #include "Rtt_PlatformPlayer.h" #include "Rtt_PlatformSimulator.h" #include "Rtt_RenderingStream.h" #include "Rtt_Runtime.h" #include "Rtt_SimulatorAnalytics.h" #include "Rtt_WinPlatform.h" #include "Rtt_WinSimulatorServices.h" #include "Simulator.h" #include "MainFrm.h" #include "SimulatorDoc.h" #include "SimulatorView.h" #include "AboutDlg.h" #include "BuildAndroidDlg.h" #include "BuildWebDlg.h" #include "BuildLinuxDlg.h" #include "BuildNxSDlg.h" #include "BuildWin32AppDlg.h" #include "NewProjectDlg.h" #include "SelectSampleProjectDlg.h" #include "RelaunchPrefDlg.h" #include "WinString.h" #include "WinGlobalProperties.h" // WMU_ message IDs #include "PreferencesDlg.h" #include "ProgressWnd.h" // ActivityIndicator #include "MessageDlg.h" // Alert #include "CoronaInterface.h" #include "Rtt_SimulatorRecents.h" #include "CustomDeviceDlg.h" // ---------------------------------------------------------------------------- // Microsoft Visual C++ macro which allows us to easily do bitwise operations on the given enum like in C. DEFINE_ENUM_FLAG_OPERATORS(Rtt::Runtime::LaunchOptions) #define ENABLE_DEBUG_PRINT 0 #if ENABLE_DEBUG_PRINT #define DEBUG_PRINT( ... ) Rtt_LogException( __VA_ARGS__ ); #else #define DEBUG_PRINT( ... ) #endif // ---------------------------------------------------------------------------- // The #includes must go above this line because this macro will override the "new" operator // which will cause compiler errors with header files belonging to other libraries. #ifdef _DEBUG # define new DEBUG_NEW #endif #pragma region Timer IDs static const UINT TIMER_ID_CHECK_APP = 1; static const UINT TIMER_ID_SHAKE_WINDOW = 2; #pragma endregion // Utility function Gdiplus::RotateFlipType DegreesToRFType( int rotation ); #pragma region Message Mappings IMPLEMENT_DYNCREATE(CSimulatorView, CView) BEGIN_MESSAGE_MAP(CSimulatorView, CView) ON_WM_CREATE() ON_WM_CLOSE() ON_WM_DESTROY() ON_WM_ERASEBKGND() ON_WM_SETFOCUS() ON_WM_TIMER() ON_COMMAND(ID_APP_ABOUT, &CSimulatorView::OnAppAbout) ON_COMMAND(ID_HELP, &CSimulatorView::OnHelp) ON_COMMAND(ID_VIEW_HOME_SCREEN, &CSimulatorView::OnViewHomeScreen) ON_COMMAND(ID_VIEW_CONSOLE, &CSimulatorView::OnViewConsole) ON_COMMAND(ID_VIEW_SHAKE, &CSimulatorView::OnViewShake) ON_COMMAND(ID_VIEW_SUSPEND, &CSimulatorView::OnViewSuspend) ON_COMMAND(ID_VIEW_ROTATELEFT, &CSimulatorView::OnViewRotateLeft) ON_COMMAND(ID_VIEW_ROTATERIGHT, &CSimulatorView::OnViewRotateRight) ON_COMMAND(ID_VIEW_NAVIGATE_BACK, &CSimulatorView::OnViewNavigateBack) ON_COMMAND(ID_FILE_MRU_FILE1, &CSimulatorView::OnFileMRU1) ON_COMMAND(ID_FILE_NEW, &CSimulatorView::OnFileNew) ON_COMMAND(ID_FILE_OPEN, &CSimulatorView::OnFileOpen) ON_COMMAND(ID_FILE_OPEN_SAMPLE_PROJECT, &CSimulatorView::OnFileOpenSampleProject) ON_COMMAND(ID_FILE_PREFERENCES, &CSimulatorView::OnPreferences) ON_COMMAND(ID_BUILD_FOR_ANDROID, &CSimulatorView::OnBuildForAndroid) ON_COMMAND(ID_BUILD_FOR_WEB, &CSimulatorView::OnBuildForWeb) ON_COMMAND(ID_BUILD_FOR_LINUX, &CSimulatorView::OnBuildForLinux) ON_COMMAND(ID_BUILD_FOR_NXS, &CSimulatorView::OnBuildForNxS) ON_COMMAND(ID_BUILD_FOR_WIN32, &CSimulatorView::OnBuildForWin32) ON_COMMAND(ID_FILE_OPENINEDITOR, &CSimulatorView::OnFileOpenInEditor) ON_COMMAND(ID_FILE_RELAUNCH, &CSimulatorView::OnFileRelaunch) ON_COMMAND(ID_FILE_CLOSE, &CSimulatorView::OnFileClose) ON_COMMAND(ID_FILE_SHOW_PROJECT_FILES, &CSimulatorView::OnShowProjectFiles) ON_COMMAND(ID_FILE_SHOWPROJECTSANDBOX, &CSimulatorView::OnShowProjectSandbox) ON_COMMAND(ID_FILE_CLEARPROJECTSANDBOX, &CSimulatorView::OnClearProjectSandbox) ON_UPDATE_COMMAND_UI(ID_VIEW_SUSPEND, &CSimulatorView::OnUpdateViewSuspend) ON_COMMAND_RANGE(ID_VIEWAS_BEGIN, ID_VIEWAS_END, &CSimulatorView::OnWindowViewAs) ON_UPDATE_COMMAND_UI_RANGE(ID_VIEWAS_BEGIN, ID_VIEWAS_END, &CSimulatorView::OnUpdateWindowViewAs ) ON_UPDATE_COMMAND_UI(ID_VIEW_VIEWAS, &CSimulatorView::OnUpdateWindowViewAs ) ON_UPDATE_COMMAND_UI(ID_VIEW_NAVIGATE_BACK, &CSimulatorView::OnUpdateViewNavigateBack) ON_UPDATE_COMMAND_UI(ID_FILE_RELAUNCH, &CSimulatorView::OnUpdateFileRelaunch) ON_UPDATE_COMMAND_UI(ID_FILE_CLOSE, &CSimulatorView::OnUpdateFileClose) ON_UPDATE_COMMAND_UI(ID_BUILD_FOR_ANDROID, &CSimulatorView::OnUpdateBuildMenuItem) ON_UPDATE_COMMAND_UI(ID_BUILD_FOR_WEB, &CSimulatorView::OnUpdateBuildMenuItem) ON_UPDATE_COMMAND_UI(ID_BUILD_FOR_LINUX, &CSimulatorView::OnUpdateBuildMenuItem) ON_UPDATE_COMMAND_UI(ID_BUILD_FOR_NXS, &CSimulatorView::OnUpdateBuildMenuItem) ON_UPDATE_COMMAND_UI(ID_BUILD_FOR_WIN32, &CSimulatorView::OnUpdateBuildMenuItem) ON_UPDATE_COMMAND_UI(ID_FILE_OPENINEDITOR, &CSimulatorView::OnUpdateFileOpenInEditor) ON_UPDATE_COMMAND_UI(ID_FILE_SHOW_PROJECT_FILES, &CSimulatorView::OnUpdateShowProjectFiles) ON_UPDATE_COMMAND_UI(ID_FILE_SHOWPROJECTSANDBOX, &CSimulatorView::OnUpdateShowProjectSandbox) ON_MESSAGE(WMU_ACTIVITYINDICATOR, &CSimulatorView::OnActivityIndicator) ON_MESSAGE(WMU_NATIVEALERT, &CSimulatorView::OnNativeAlert) END_MESSAGE_MAP() BEGIN_MESSAGE_MAP(CSimulatorView::CCoronaControlContainer, CStatic) ON_WM_CREATE() ON_WM_CTLCOLOR_REFLECT() ON_WM_SIZE() END_MESSAGE_MAP() #pragma endregion #pragma region Constructor/Destructor /// Creates a new Corona Simulator CView. CSimulatorView::CSimulatorView() : mSimulatorServices(*this), mMessageDlgPointer(nullptr), mProgressDlgPointer(nullptr), mDeviceConfig(*Rtt_AllocatorCreate()), mRuntimeLoadedEventHandler(this, &CSimulatorView::OnRuntimeLoaded) { CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); CoInitialize(nullptr); mRotation = 0; // current rotation mpSkinBitmap = nullptr; mRuntimeEnvironmentPointer = nullptr; mIsShowingInternalScreen = false; mDisplayName = applicationPointer->GetDisplayName(); mAppChangeHandle = nullptr; mShakeAmount = SIM_SHAKE_AMOUNT; mShakeReps = SIM_SHAKE_REPS; mShakeNum = 0; m_nSkinId = Rtt::TargetDevice::kUnknownSkin; mRelaunchCount = 0; } /// Destructor. Destroys owned objects. CSimulatorView::~CSimulatorView() { CStringA relaunchCountStr; relaunchCountStr.Format("%d", mRelaunchCount); GetWinProperties()->GetAnalytics()->Log("relaunch", "count", relaunchCountStr); if (mRuntimeEnvironmentPointer) { Interop::SimulatorRuntimeEnvironment::Destroy(mRuntimeEnvironmentPointer); mRuntimeEnvironmentPointer = nullptr; } if (mAppChangeHandle) { ::FindCloseChangeNotification(mAppChangeHandle); mAppChangeHandle = nullptr; } if (mMessageDlgPointer) { if (mMessageDlgPointer->GetSafeHwnd()) { mMessageDlgPointer->SendMessage(WM_COMMAND, IDCANCEL, 0); } delete mMessageDlgPointer; mMessageDlgPointer = nullptr; } if (mProgressDlgPointer) { delete mProgressDlgPointer; mProgressDlgPointer = nullptr; } } #pragma endregion #pragma region Window Event Handlers /// Called after a new file was selected by the CSimulatorDoc. void CSimulatorView::OnInitialUpdate() { } /// Called after the CSimulatorDoc has been updated with a different file or if the file was closed. /// Starts simulating the selected file or displays the home/welcome screen. /// @param pSender Pointer to the view that requested an update. NULL if update came from the document. /// @param lHint Contains information about the modification made to the document. /// @param pHint Pointer to an object storing information about the modification. /// NULL if not information has been provided. void CSimulatorView::OnUpdate(CView* pSender, LPARAM lHint, CObject *pHint) { // Start simulation with the new or updated file. // If the last file was closed, then this will display the home screen. InitializeSimulation(m_nSkinId); } // OnDestroy - clean up void CSimulatorView::OnDestroy() { StopSimulation(); if (mpSkinBitmap) { delete mpSkinBitmap; mpSkinBitmap = nullptr; } CView::OnDestroy(); } // PreCreateWindow - remove border, set default size BOOL CSimulatorView::PreCreateWindow(CREATESTRUCT& cs) { cs.style &= ~WS_BORDER; // view window doesn't need a border cs.cx = 320; // Note that this doesn't do much, see Simulator.cpp for where the main frame size gets set. cs.cy = 480; return CView::PreCreateWindow(cs); } // OnCreate - init OpenGL int CSimulatorView::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CView::OnCreate(lpCreateStruct) == -1) { return -1; } // Add the Corona container control to the view. // This container control will always be sized to fit the screen within the device skin. RECT bounds; bounds.top = 0; bounds.left = 0; bounds.bottom = lpCreateStruct->cy; bounds.right = lpCreateStruct->cx; mCoronaContainerControl.Create(nullptr, WS_CHILD | WS_VISIBLE, bounds, this); mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_HIDE); // Start the timer that implements the file modification detection feature SetTimer(TIMER_ID_CHECK_APP, 500, NULL); // Get system skin directory (we have to do this manually because the just-in-time // way that the platform is loaded in tandem with the first application means that the information // is not available in the platform when we need it) Rtt_ASSERT(AfxGetApp() != NULL); mSystemSkinsDir = ((CSimulatorApp *)AfxGetApp())->GetResourceDir(); mSystemSkinsDir += _T("\\Skins\\"); // Get user's skins directory if there is one (we have to do this manually because the just-in-time // way that the platform is loaded in tandem with the first application means that the information // is not available in the platform when we need it) TCHAR myDocs[MAX_PATH]; myDocs[0] = 0; HRESULT hr = ::SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, 0, myDocs); _tcscat_s(myDocs, MAX_PATH, _T("\\Corona Labs\\Corona Simulator\\Skins\\")); mUserSkinsDir = myDocs; mCustomSkinFileName = mUserSkinsDir + _T("CustomDevice.lua.tmp"); LoadSkinResources(); // Now that we've loaded the skins, get a valid skin id if (mDisplayName.IsEmpty()) { m_nSkinId = Rtt::TargetDevice::fDefaultSkinID; } else if (mDisplayName == _T("CustomDevice")) { m_nSkinId = Rtt::TargetDevice::kCustomSkin; } else { m_nSkinId = Rtt::TargetDevice::SkinForLabel(CStringA(mDisplayName)); } return 0; } void CSimulatorView::OnSetFocus(CWnd* pOldWnd) { CWnd& coronaControl = mCoronaContainerControl.GetCoronaControl(); if (coronaControl.IsWindowVisible()) { coronaControl.SetFocus(); } } bool CSimulatorView::HasApplicationChanged() { static bool dialogRunning = false; bool result = false; // If we've put up a runtime error or are doing a build, the app will be suspended and // we don't want to restart here so behave as if we're already displaying the dialog. bool isSuspended = IsSimulationSuspended(); if (!dialogRunning && !isSuspended && (GetDocument()->GetPath().GetLength() > 0)) { if (mAppChangeHandle == NULL) { CString projectPath = GetDocument()->GetProject()->GetDir(); if (projectPath.GetLength() < 3 || // path is too short (projectPath[0] == '\\' && projectPath[1] == '\\') || // path starts with "\\" (projectPath[1] == ':' && GetDriveType(projectPath.Left(3)) == DRIVE_REMOTE)) // path's drive is remote { // This a UNC or remote path and filesystem notifications don't work so bail return false; } WinString tstr; tstr.SetTCHAR(projectPath); // fprintf(stderr, "Project: %s\n", tstr.GetUTF8()); mAppChangeHandle = FindFirstChangeNotification(tstr.GetTCHAR(), true, FILE_NOTIFY_CHANGE_LAST_WRITE); } dialogRunning = true; // See if there's been a change DWORD waitResult = 0; waitResult = WaitForSingleObject(mAppChangeHandle, 1); if (waitResult == WAIT_OBJECT_0) { result = true; // Drain the queue (there may be other notifications related to same file system change) while (WaitForSingleObject(mAppChangeHandle, 1) == WAIT_OBJECT_0) FindNextChangeNotification(mAppChangeHandle); // Sign up for future change notifications FindNextChangeNotification(mAppChangeHandle); } CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); if (result && (applicationPointer!= NULL && applicationPointer->GetRelaunchSimStyle() == RELAUNCH_SIM_ASK)) { CRelaunchPrefDlg relaunchPrefDlg; int dlgResult = relaunchPrefDlg.DoModal(); if (dlgResult != IDOK) { result = false; } } dialogRunning = false; } return result; } // OnTimer - redraw window void CSimulatorView::OnTimer(UINT nIDEvent) { CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); // Perform the scheduled operation. switch (nIDEvent) { case TIMER_ID_CHECK_APP: if (applicationPointer!= NULL && applicationPointer->GetRelaunchSimStyle() != RELAUNCH_SIM_NEVER) { if (HasApplicationChanged()) { // fprintf(stderr, "Relaunching the app due to project modification ...\n"); // Restart the currently running project. RestartSimulation(); } } break; case TIMER_ID_SHAKE_WINDOW: if (mShakeNum < mShakeReps) { int offset = ((mShakeNum % 2) == 0) ? mShakeAmount : -(mShakeAmount * 2); AfxGetMainWnd()->MoveWindow(mShakeOriginRect.left + offset, mShakeOriginRect.top, mShakeOriginRect.Width(), mShakeOriginRect.Height(), true); ++mShakeNum; } else { // We're done, make sure the window is back where it should be AfxGetMainWnd()->MoveWindow(mShakeOriginRect, true); KillTimer(TIMER_ID_SHAKE_WINDOW); } break; } } // OnClose- WinPlatformServices::Terminate() sends msg here, forward to Main window // Also used if skin .png files are missing void CSimulatorView::OnClose() { StopSimulation(); AfxGetMainWnd()->SendMessage( WM_CLOSE ); } void CSimulatorView::OnDraw(CDC* pDC) { // Fetch the region to draw in. CRect rect; GetClientRect(&rect); // Fetch the device bitmap to draw if a device was selected. // Ignore the device bitmap if the view is currently showing the home screen. Gdiplus::Bitmap *pBitmap = NULL; COLORREF backgroundColor = RGB(255, 255, 255); if (false == mIsShowingInternalScreen) { pBitmap = GetSkinBitmap(); // TODO: implement background color in skin Lua if (!pBitmap || (GetDisplayName() == "iPad Retina")) { // Use a black background for skinless devices or white devices. backgroundColor = RGB(0, 0, 0); } } // Draw the background. if (pBitmap) { // Draw the device image in the background. CDC dcMemory; CBitmap mfcbitmap; HBITMAP hBmp; dcMemory.CreateCompatibleDC(pDC); pBitmap->GetHBITMAP(backgroundColor, &hBmp); mfcbitmap.Attach(hBmp); dcMemory.SelectObject(&mfcbitmap); pDC->SetStretchBltMode(COLORONCOLOR); // improves skin rendering dramatically pDC->StretchBlt(0, 0, rect.Width(), rect.Height(), &dcMemory, 0, 0, pBitmap->GetWidth(), pBitmap->GetHeight(), SRCCOPY); } else { // Draw a solid background. CBrush brush(backgroundColor); CBrush* pOldBrush = pDC->SelectObject(&brush); CPen pen; pen.CreatePen(PS_SOLID, 3, backgroundColor); CPen* pOldPen = pDC->SelectObject(&pen); pDC->Rectangle(rect); pDC->SelectObject(pOldBrush); pDC->SelectObject(pOldPen); } } // OnEraseBkgnd - do nothing, to minimize flickering BOOL CSimulatorView::OnEraseBkgnd(CDC* pDC) { return TRUE; } #pragma endregion #pragma region Menu Event Handlers /// Displays the About Box window. void CSimulatorView::OnAppAbout() { CAboutDlg aboutDlg; aboutDlg.DoModal(); } /// Displays help documentation on Corona Labs' website via the system's default web browser. void CSimulatorView::OnHelp() { try { const wchar_t kUrl[] = L"https://docs.coronalabs.com/guide"; ::ShellExecuteW(nullptr, L"open", kUrl, nullptr, nullptr, SW_SHOWNORMAL); } catch (...) { } } /// Closes the current project and displays the welcome/home screen. void CSimulatorView::OnViewHomeScreen() { // Do not continue if the machine does not meet the simulator's minimum OpenGL requirements. if (ValidateOpenGL() == false) { return; } // Display the home screen. StopSimulation(); GetParentFrame()->OnUpdateFrameTitle(FALSE); SetRotation(0); RunCoronaProject(((CSimulatorApp*)AfxGetApp())->GetResourceDir() + _T("\\homescreen")); GetWinProperties()->GetAnalytics()->Log("show-welcome", NULL); } /// Closes the current project and displays the welcome/home screen. void CSimulatorView::OnViewConsole() { ((CSimulatorApp*)AfxGetApp())->GetOutputViewerProcessPointer()->RequestShowMainWindow(); GetWinProperties()->GetAnalytics()->Log("show-console", NULL); } // OnViewShake - handle Shake menu item void CSimulatorView::OnViewShake() { if (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()->Shake(); mShakeNum = 0; AfxGetMainWnd()->GetWindowRect(&mShakeOriginRect); SetTimer(TIMER_ID_SHAKE_WINDOW, SIM_SHAKE_PERIOD, NULL); GetWinProperties()->GetAnalytics()->Log("shake", NULL); } } // OnViewSuspend - handle Suspend/Resume menu item void CSimulatorView::OnViewSuspend() { // Suspend/resume the Corona runtime. // Always show the "Suspended" overlay, unless the shift key was held down. bool showSuspendedScreen = !((::GetKeyState(VK_LSHIFT) | ::GetKeyState(VK_RSHIFT)) & 0x80); SuspendResumeSimulationWithOverlay(showSuspendedScreen, true); } // OnUpdateViewSuspend - set to Suspend or Resume as appropriate void CSimulatorView::OnUpdateViewSuspend(CCmdUI *pCmdUI) { bool isSuspended = IsSimulationSuspended(); int id = isSuspended ? IDS_HARDWARE_RESUME : IDS_HARDWARE_SUSPEND; CString sCaption; sCaption.LoadString(id); pCmdUI->SetText( sCaption ); GetWinProperties()->GetAnalytics()->Log("suspend-resume", "type", CStringA(sCaption)); } // OnViewRotateLeft - change rotation value, tell corona core, update skin void CSimulatorView::OnViewRotateLeft() { // Do not rotate the welcome screen. if (mIsShowingInternalScreen) { return; } // Do not continue if the simulated device's screen does not support rotation. if (false == mDeviceConfig.supportsScreenRotation) { return; } // Rotate the simulated device. SetRotation( GetRotation() + 270 ); if (GetSkinBitmap() != NULL) { GetSkinBitmap()->RotateFlip( Gdiplus::Rotate270FlipNone ); } if (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()->RotateCounterClockwise(); } UpdateSimulatorSkin(); GetWinProperties()->GetAnalytics()->Log("rotate", "direction", "left"); } // OnViewRotateRight - change rotation value, tell corona core, update skin void CSimulatorView::OnViewRotateRight() { // Do not rotate the welcome screen. if (mIsShowingInternalScreen) { return; } // Do not continue if the simulated device's screen does not support rotation. if (false == mDeviceConfig.supportsScreenRotation) { return; } // Rotate the simulated device. SetRotation( GetRotation() + 90 ); if (GetSkinBitmap() != NULL) { GetSkinBitmap()->RotateFlip( Gdiplus::Rotate90FlipNone ); } if (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()->RotateClockwise(); } UpdateSimulatorSkin(); GetWinProperties()->GetAnalytics()->Log("rotate", "direction", "right"); } void CSimulatorView::OnViewNavigateBack() { // Do not continue if we're not simulating a device. if (mIsShowingInternalScreen) { return; } if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { return; } // Do not continue if we're currently suspended. if (IsSimulationSuspended()) { return; } // Do not continue if the simulated device does not support back key navigation. if (!mDeviceConfig.supportsKeyEvents || !mDeviceConfig.supportsBackKey) { return; } // Send "back" key down/up messages to the Corona control. // Corona will automatically terminate the runtime if the Lua key listener does not handle them. auto windowPointer = &mCoronaContainerControl.GetCoronaControl(); windowPointer->PostMessage(WM_KEYDOWN, VK_BROWSER_BACK, 0L); windowPointer->PostMessage(WM_KEYUP, VK_BROWSER_BACK, 0x40000000L); GetWinProperties()->GetAnalytics()->Log("back", nullptr); } /// Called when the top most file in the "Most Recent Files" list is clicked on in the menu. /// The application won't update the document when the top most file is selected so we /// we have to update it manually here. void CSimulatorView::OnFileMRU1() { // Fetch the application's MRU list. // Warning: The returned pointer can be NULL if no files were ever loaded. CRecentFileList *recentFileListPointer = ((CSimulatorApp*)AfxGetApp())->GetRecentFileList(); if (NULL == recentFileListPointer) { return; } // Compare the selected file name with what is currently opened. const CString& fileName = (*recentFileListPointer)[0]; if (!mIsShowingInternalScreen && (GetDocument()->GetPath() == fileName)) { // The selected file is already open. Relaunch it in the simulator. ++mRelaunchCount; RestartSimulation(); } else { // Open the selected file for simulation. GetWinProperties()->GetAnalytics()->Log("open-recent", NULL); GetDocument()->GetDocTemplate()->OpenDocumentFile(fileName); } } //Called from the simulator services. This matches the selected recent project with the windows recent //project ID and posts a message to load it, this must be invoked through a message post void CSimulatorView::PostOpenWithPath(CString fileName) { CRecentFileList *recentFileListPointer = ((CSimulatorApp*)AfxGetApp())->GetRecentFileList(); if (recentFileListPointer) { for (int i = 0; i < recentFileListPointer->GetSize(); i++) { const CString& fileName2 = (*recentFileListPointer)[i]; if (fileName == fileName2) { this->GetParent()->PostMessage(WM_COMMAND,ID_FILE_MRU_FIRST+i); return; } } recentFileListPointer->Add(fileName); this->GetParent()->PostMessage(WM_COMMAND, ID_FILE_MRU_FIRST); } } // OnPreferences - show Preferences dialog void CSimulatorView::OnPreferences() { // Display the preferences dialog. CPreferencesDlg dlgPreferences; auto result = dlgPreferences.DoModal(); if (result != IDOK) { // No changes were made. GetWinProperties()->GetAnalytics()->Log("preferences", "result", "not-changed"); return; } GetWinProperties()->GetAnalytics()->Log("preferences", "result", "changed"); // If we're currently running a project, then update its "Show runtime error" setting. CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); if (applicationPointer && mRuntimeEnvironmentPointer) { Rtt::Runtime *runtimePointer = mRuntimeEnvironmentPointer->GetRuntime(); bool bIsShowingRuntimeErrors = applicationPointer->IsShowingRuntimeErrors(); bool showRuntimeErrors = mIsShowingInternalScreen ? false : bIsShowingRuntimeErrors; runtimePointer->SetProperty(Rtt::Runtime::kShowRuntimeErrors, showRuntimeErrors); } } /// Displays a window for creating a new Corona project. void CSimulatorView::OnFileNew() { // Display the "New Project" dialog. CNewProjectDlg dialog; int result = dialog.DoModal(); if ((result != IDOK) || dialog.GetNewProjectPath().IsEmpty()) { return; } // Start simulating the new project. CString projectFilePath = dialog.GetNewProjectPath() + _T("\\main.lua"); GetDocument()->GetDocTemplate()->OpenDocumentFile(projectFilePath); // Show the new project's folder in Windows Explorer. OnShowProjectFiles(); // Show the new project's folder in their editor OnFileOpenInEditor(); } // OnFileOpen - overloaded to check OpenGL and reopen file if already open void CSimulatorView::OnFileOpen() { CString filename; // Do not continue if the machine does not meet the simulator's minimum OpenGL requirements. if (ValidateOpenGL() == false) { return; } // Open the file if the user didn't "Cancel" out of the dialog. if (AfxGetApp()->DoPromptFileName(filename, AFX_IDS_OPENFILE, OFN_HIDEREADONLY | OFN_FILEMUSTEXIST, TRUE, NULL)) { // if the file is already open, relaunch if (!mIsShowingInternalScreen && (GetDocument()->GetPath() == filename)) { ++mRelaunchCount; RestartSimulation(); } else { GetWinProperties()->GetAnalytics()->Log("open-project", NULL); GetDocument()->GetDocTemplate()->OpenDocumentFile(filename); } } } /// Displays an "Open File" dialog which default to the sample projects directory. void CSimulatorView::OnFileOpenSampleProject() { // Do not continue if unable to find the Samples directory. CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); if (applicationPointer->CheckDirExists(applicationPointer->GetSampleDir()) == false) { CString title; CString message; title.LoadString(IDS_WARNING); message.LoadString(IDS_UNABLE_TO_FIND_SAMPLE_PROJECTS_DIRECTORY); MessageBox(message, title, MB_OK | MB_ICONWARNING); return; } // Display the "Select Sample Project" dialog. CSelectSampleProjectDlg dialog; int result = dialog.DoModal(); if (result != IDOK) { return; } // Start simulating the selected project. CString filePath = dialog.GetSelectedProjectPath() + _T("\\main.lua"); if (!mIsShowingInternalScreen && (GetDocument()->GetPath() == filePath)) { RestartSimulation(); } else { GetDocument()->GetDocTemplate()->OpenDocumentFile(filePath); } WinString projectName; projectName.SetTCHAR(GetDocument()->GetTitle()); GetWinProperties()->GetAnalytics()->Log("open-sample", "sample", projectName.GetUTF8()); } /// <summary>Opens a dialog to build the currently selected project for Android.</summary> void CSimulatorView::OnBuildForAndroid() { // Check whether JDK and jarsigner.exe are available first BOOL retval = CSimulatorApp::InitJavaPaths(); if ( ! retval) { return; } // If app is running, suspend it during the build bool buildSuspendedSimulator = false; bool isSuspended = IsSimulationSuspended(); if (false == isSuspended) { buildSuspendedSimulator = true; SuspendResumeSimulationWithOverlay(true, false); } // Display the build window. CBuildAndroidDlg dlg; dlg.SetProject( GetDocument()->GetProject() ); dlg.DoModal(); if (buildSuspendedSimulator) { // Toggle suspend SuspendResumeSimulationWithOverlay(true, false); } } /// <summary>Opens a dialog to build the currently selected project as an HTML5 app.</summary> void CSimulatorView::OnBuildForWeb() { // If app is running, suspend it during the build bool buildSuspendedSimulator = false; bool isSuspended = IsSimulationSuspended(); if (false == isSuspended) { buildSuspendedSimulator = true; SuspendResumeSimulationWithOverlay(true, false); } // Display the build window. CBuildWebDlg dlg; dlg.SetProject( GetDocument()->GetProject() ); dlg.DoModal(); if (buildSuspendedSimulator) { // Toggle suspend SuspendResumeSimulationWithOverlay(true, false); } } /// <summary>Opens a dialog to build the currently selected project as an HTML5 app.</summary> void CSimulatorView::OnBuildForLinux() { // If app is running, suspend it during the build bool buildSuspendedSimulator = false; bool isSuspended = IsSimulationSuspended(); if (false == isSuspended) { buildSuspendedSimulator = true; SuspendResumeSimulationWithOverlay(true, false); } // Display the build window. CBuildLinuxDlg dlg; dlg.SetProject( GetDocument()->GetProject() ); dlg.DoModal(); if (buildSuspendedSimulator) { // Toggle suspend SuspendResumeSimulationWithOverlay(true, false); } } /// <summary>Opens a dialog to build the currently selected project as an NxS Switch app.</summary> void CSimulatorView::OnBuildForNxS() { CSimulatorApp* applicationPointer = (CSimulatorApp*)AfxGetApp(); if (!applicationPointer->ShouldShowNXBuildDlg()) { return; } // If app is running, suspend it during the build bool buildSuspendedSimulator = false; bool isSuspended = IsSimulationSuspended(); if (false == isSuspended) { buildSuspendedSimulator = true; SuspendResumeSimulationWithOverlay(true, false); } // Display the build window. CBuildNxSDlg dlg; dlg.SetProject(GetDocument()->GetProject()); dlg.DoModal(); if (buildSuspendedSimulator) { // Toggle suspend SuspendResumeSimulationWithOverlay(true, false); } } /// <summary>Opens a dialog to build the currently selected project as a Win32 desktop app.</summary> void CSimulatorView::OnBuildForWin32() { // Ask the user to select a Corona project if we're not currently running one. // Note: This should never happen, but check just in case. if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetRuntime()) { OnFileOpen(); if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetRuntime()) { return; } } // Do not contnue if not all plugins have been acquired for the selected project. // We do this because local Win32 app builds require the plugins zips to be downloaded first. if (VerifyAllPluginsAcquired() == false) { return; } // If app is running, suspend it during the build. bool wasAppRunning = false; bool isSuspended = IsSimulationSuspended(); if (false == isSuspended) { wasAppRunning = true; SuspendResumeSimulationWithOverlay(true, false); } // Display the build window. CBuildWin32AppDlg dialog; dialog.SetProject(GetDocument()->GetProject()); dialog.DoModal(); // Resume the project if it was previously running and the user hasn't started running the built app. if (wasAppRunning && !dialog.HasRanBuiltApp()) { SuspendResumeSimulationWithOverlay(true, false); } } /// <summary>Enables/disables the "Build for Android/HTML5/Windows" item in the menu.</summary> void CSimulatorView::OnUpdateBuildMenuItem(CCmdUI *pCmdUI) { pCmdUI->Enable( mRuntimeEnvironmentPointer && ! GetDocument()->GetPath().IsEmpty() ); } // OnFileOpenInEditor - give project name to shell, if associated with an editor // Note TODO item below void CSimulatorView::OnFileOpenInEditor() { const int MAX_PATH_LENGTH = 512; CString applicationFileName; CString fileAssociation; DWORD fileAssociationLength = MAX_PATH_LENGTH; HRESULT result; int length; int index; bool hasValidFileAssociation = false; try { // Fetch this application's file name without the path. length = ::GetModuleFileName(NULL, applicationFileName.GetBuffer(MAX_PATH_LENGTH), MAX_PATH_LENGTH); applicationFileName.ReleaseBuffer(length); if (length > 0) { index = applicationFileName.ReverseFind(_T('\\')); if (index > 0) { applicationFileName.Delete(0, index + 1); } } // Fetch the file association in Windows for all Lua files, if assigned. // ie: This is the default executable used to open a Lua file when double clicked on. result = ::AssocQueryString( ASSOCF_INIT_DEFAULTTOSTAR, ASSOCSTR_EXECUTABLE, _T(".lua"), NULL, fileAssociation.GetBuffer(MAX_PATH_LENGTH), &fileAssociationLength); fileAssociation.ReleaseBuffer(); CString fullAssociationPath(fileAssociation); if (S_OK == result) { index = fileAssociation.ReverseFind(_T('\\')); if (index > 0) { fileAssociation.Delete(0, index + 1); } } // Check if we have a valid file association in Windows to edit the "main.lua" file. // Note: The default association on Windows XP or lower is an empty string. if (fileAssociation.GetLength() > 0) { // A file association has been assigned. // Make sure it is associated with an application that can open the file. // Note: The default association on Windows Vista or higher is "shell32.dll". CString extension = fileAssociation.Right(4); if ((extension.CompareNoCase(_T(".exe")) == 0) || (extension.CompareNoCase(_T(".com")) == 0) || (extension.CompareNoCase(_T(".bat")) == 0)) { // Also, don't allow the applications below since they won't edit the file. if ((fileAssociation.CompareNoCase(applicationFileName) != 0) && (fileAssociation.CompareNoCase(_T("Lightroom.exe")) != 0)) // Adobe Lightroom { // The application associated with the file is valid. hasValidFileAssociation = true; } } } // Open the Lua file for editing using the default application assigned in Windows. // If Windows doesn't have a valid file association, then open it with Notepad. if (hasValidFileAssociation) { if (fileAssociation == _T("sublime_text.exe") || fileAssociation == _T("Code.exe")) { CString fullPath(GetDocument()->GetPath()); index = fullPath.ReverseFind(_T('\\')); if (index > 0) { CString dirPath(fullPath); dirPath.Delete(index, dirPath.GetLength() - index); fullPath.Insert(0, _T('"')); fullPath.Append(_T("\" --add \"")); fullPath.Append(dirPath); fullPath.Append(_T("\"")); } ::ShellExecute(nullptr, nullptr, fullAssociationPath, fullPath, nullptr, SW_SHOWNORMAL); } else { ::ShellExecute(nullptr, _T("open"), GetDocument()->GetPath(), nullptr, nullptr, SW_SHOWNORMAL); } WinString appName; appName.SetTCHAR(fileAssociation); GetWinProperties()->GetAnalytics()->Log( "open-in-editor", "editor", appName.GetUTF8() ); } else { ::ShellExecute(nullptr, nullptr, _T("notepad.exe"), GetDocument()->GetPath(), nullptr, SW_SHOWNORMAL); GetWinProperties()->GetAnalytics()->Log( "open-in-editor", "editor", "notepad" ); } } catch (...) { } } // OnUpdateFileOpenInEditor - enable menu item when project is open void CSimulatorView::OnUpdateFileOpenInEditor(CCmdUI *pCmdUI) { pCmdUI->Enable( mRuntimeEnvironmentPointer && ! GetDocument()->GetPath().IsEmpty() ); } /// Restart simulation of the last selected project. void CSimulatorView::OnFileRelaunch() { if (GetDocument()->GetPath().GetLength() > 0) { // Restart the currently running project. RestartSimulation(); } else { // A project is not currently open. // Attempt to open and run the last ran project in the "recent file list". CRecentFileList *recentFileListPointer = ((CSimulatorApp*)AfxGetApp())->GetRecentFileList(); CString lastFilePathName = (*recentFileListPointer)[0]; if (lastFilePathName.GetString() > 0) { GetDocument()->GetDocTemplate()->OpenDocumentFile(lastFilePathName); } } } /// Enables or disables the "Relaunch" menu item. void CSimulatorView::OnUpdateFileRelaunch(CCmdUI *pCmdUI) { CRecentFileList *recentFileListPointer = ((CSimulatorApp*)AfxGetApp())->GetRecentFileList(); bool hasRecentFile = (recentFileListPointer && ((*recentFileListPointer)[0].GetLength() > 0)); bool isProjectOpen = (GetDocument()->GetPath().GetLength() > 0); pCmdUI->Enable((isProjectOpen || hasRecentFile) ? TRUE : FALSE); } /// Display the currently running Corona project's root folder in Windows Explorer. void CSimulatorView::OnShowProjectFiles() { // Fetch current project. Will be NULL no project is selected. auto projectPointer = GetDocument()->GetProject(); if (!projectPointer) { return; } // Fetch the project's absolute path without the file name. Make sure directory exists. CString projectPath = projectPointer->GetDir(); if (CSimulatorApp::CheckDirExists(projectPath) == false) { return; } // Display the project folder in the default file viewer. Typically "Windows Explorer". try { ::ShellExecute(nullptr, _T("open"), projectPath, nullptr, nullptr, SW_SHOWNORMAL); } catch (...) { } GetWinProperties()->GetAnalytics()->Log("show-project-files", nullptr); } /// Enables or disables the "Show Project Files" menu item. void CSimulatorView::OnUpdateShowProjectFiles(CCmdUI *pCmdUI) { BOOL enabled = (GetDocument()->GetPath().GetLength() > 0) ? TRUE : FALSE; pCmdUI->Enable(enabled); } // OnShowProjectSandbox - Open this app's sandbox in Windows Explorer void CSimulatorView::OnShowProjectSandbox() { // Do not continue if not simulating a project. if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { return; } CStringW utf16DirectoryPath = mRuntimeEnvironmentPointer->GetUtf16PathFor(Rtt::MPlatform::kDocumentsDir); utf16DirectoryPath.Append(L"\\..\\."); if (CSimulatorApp::CheckDirExists(utf16DirectoryPath)) { ::ShellExecuteW(nullptr, L"open", utf16DirectoryPath, nullptr, nullptr, SW_SHOWNORMAL); GetWinProperties()->GetAnalytics()->Log("show-sandbox", nullptr); } } // OnClearProjectSandbox - Open this app's sandbox in Windows Explorer void CSimulatorView::OnClearProjectSandbox() { // Do not continue if not simulating a project. if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { return; } const TCHAR *confPrefKey = _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\DontShowMeThisDialogAgain"); TCHAR sandboxPath[MAX_PATH]; CStringW utf16DirectoryPath = mRuntimeEnvironmentPointer->GetUtf16PathFor(Rtt::MPlatform::kDocumentsDir); // TODO: handle paths longer than MAX_PATH gracefully // We have the Documents directory but we want its parent utf16DirectoryPath.Append(L"\\..\\."); // Resolve the relative part of the sandbox path PathCanonicalize(sandboxPath, utf16DirectoryPath.GetString()); // The trailing part of the sandbox path works as a key for SHMessageBoxCheck() CString confPrefValue = CString("CPS-"); confPrefValue.Append(PathFindFileName(sandboxPath)); // If shift is held down, forget any remembered value for the "don't show dialog again" checkbox bool forgetRememberedSetting = (((::GetKeyState(VK_LSHIFT) | ::GetKeyState(VK_RSHIFT)) & 0x80) != 0); if (forgetRememberedSetting) { HKEY hKey = NULL; DWORD regResult = RegOpenKeyEx(HKEY_CURRENT_USER, confPrefKey, 0L, KEY_SET_VALUE, &hKey); if (regResult == ERROR_SUCCESS) { RegDeleteValue(hKey, confPrefValue); RegCloseKey(hKey); } } WinString clearPrompt; clearPrompt.Format(_T("Are you sure you want to delete the contents of the sandbox for '%s'?\n\nThis will also clear any app preferences and restart the project"), GetDocument()->GetTitle()); // This confirmation dialog includes a "don't show dialog again" checkbox int yesNo = SHMessageBoxCheck(this->GetSafeHwnd(), clearPrompt.GetUTF16(), TEXT("Clear Project Sandbox"), MB_YESNO, IDYES, confPrefValue); if (yesNo == IDYES) { StopSimulation(); // The fine API has a crunchy way of handling multiple paths and it must be // terminated with a double NUL sandboxPath[_tcslen(sandboxPath)+1] = 0; // Send the app's sandbox to the recycle bin. As luck would have it, the prefs database // for the app is in the same location so we have nothing more to do SHFILEOPSTRUCT shFileOp = { NULL, FO_DELETE, sandboxPath, NULL, FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_ALLOWUNDO, FALSE, NULL, NULL }; SHFileOperation(&shFileOp); Rtt_Log("Project sandbox and preferences cleared"); GetWinProperties()->GetAnalytics()->Log("clear-sandbox", nullptr); StartSimulation(); } else { // they choose not to proceed, forget that answer if they checked the box HKEY hKey = NULL; DWORD regResult = RegOpenKeyEx(HKEY_CURRENT_USER, confPrefKey, 0L, KEY_SET_VALUE, &hKey); if (regResult == ERROR_SUCCESS) { RegDeleteValue(hKey, confPrefValue); RegCloseKey(hKey); } } } // OnUpdateShowProjectSandbox - enable menu item when project is open void CSimulatorView::OnUpdateShowProjectSandbox(CCmdUI *pCmdUI) { bool isSimulatingProject = (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()); pCmdUI->Enable(isSimulatingProject ? TRUE : FALSE); } // OnFileClose - close project, show Welcome window again if enabled void CSimulatorView::OnFileClose() { // Stop the currently simulated project, if running. StopSimulation(); // Next part depends if we're running in debug mode or not. CSimulatorApp* pApp = (CSimulatorApp*)::AfxGetApp(); if (pApp) { if (pApp->IsDebugModeEnabled()) { // This application is running in debug mode. Exit out of the application. // This is because the debugger exits when simulation has stopped. // AfxGetMainWnd()->SendMessage(WM_CLOSE); } else { // Display the welcome window, if enabled. GetDocument()->GetDocTemplate()->OpenDocumentFile(NULL); } } } // OnUpdateFileClose - enable menu item if project is open void CSimulatorView::OnUpdateFileClose(CCmdUI *pCmdUI) { bool enable = mRuntimeEnvironmentPointer && !GetDocument()->GetPath().IsEmpty(); pCmdUI->Enable(enable ? TRUE : FALSE); } /// Called when a device skin has been selected from the "View As" menu. /// Displays the selected device skin within the simulator window. /// @param nID The unique ID of the menu item that was clicked on. void CSimulatorView::OnWindowViewAs( UINT nID ) { Rtt::TargetDevice::Skin skinId = Rtt::TargetDevice::kUnknownSkin; if (nID == ID_VIEWAS_CUSTOMDEVICE) { // Display the custom device skin dialog. CustomDeviceDlg cdDlg; int dlgResult = cdDlg.DoModal(); // Do not continue if the user canceled out of the dialog. if (dlgResult != IDOK) { return; } // Fetch the device settings entered into the above dialog. WinString customDeviceTemplateName; WinString customDeviceTemplate; WinString customDeviceWidthStr, customDeviceHeightStr; customDeviceTemplateName.SetTCHAR( mSystemSkinsDir ); customDeviceTemplateName.Append( "CustomDevice.lua.template" ); customDeviceWidthStr.Format( "%d", cdDlg.GetCustomDeviceWidth() ); customDeviceHeightStr.Format( "%d", cdDlg.GetCustomDeviceHeight() ); // Read the custom device skin template. if ( ! customDeviceTemplate.GetFileContents( customDeviceTemplateName ) ) { Rtt_TRACE(("Error reading template from '%s'\n", customDeviceTemplateName)); return; } // Replace the template's parameters with the values entered into the dialog. customDeviceTemplate.Replace( "{customDeviceWidth}", customDeviceWidthStr ); customDeviceTemplate.Replace( "{customDeviceHeight}", customDeviceHeightStr ); customDeviceTemplate.Replace( "{customDeviceIsRotatable}", "true" ); { WinString stringTranscoder(cdDlg.GetCustomDeviceName()); customDeviceTemplate.Replace("{customDeviceName}", stringTranscoder.GetUTF8()); } { WinString stringTranscoder(cdDlg.GetCustomDevicePlatform()); customDeviceTemplate.Replace("{customDevicePlatform}", stringTranscoder.GetUTF8()); } // Save the custom skin's settings to file. WinString customSkinFileNamePath( mCustomSkinFileName ); customDeviceTemplateName.SetTCHAR( mCustomSkinFileName.GetString() ); if ( ! customDeviceTemplate.WriteFileContents( customSkinFileNamePath.GetUTF8() ) ) { Rtt_TRACE(("Error writing custom device template to '%s'\n", customSkinFileNamePath.GetUTF8())); return; } // Select the custom skin to be used by the simulator. skinId = Rtt::TargetDevice::kCustomSkin; } else { // Fetch the selected device skin's unique ID. skinId = SkinIDFromMenuID(nID); } if (skinId == Rtt::TargetDevice::kCustomSkin) { GetWinProperties()->GetAnalytics()->Log("change-skin", "skin", "custom-device" ); } else { CString skinName(Rtt::TargetDevice::LabelForSkin(skinId)); GetWinProperties()->GetAnalytics()->Log("change-skin", "skin", CStringA(skinName) ); } // Display the selected device skin InitializeSimulation(skinId); } // OnUpdateWindowViewAs - check mark for the currently displayed skin // (gets called when "Window" menu is clicked as well as when "View As" menu is shown) void CSimulatorView::OnUpdateWindowViewAs( CCmdUI *pCmdUI ) { int skinID = 0; CMainFrame *pFrameWindowPointer = (CMainFrame*)GetParentFrame(); if (pFrameWindowPointer != NULL) { CMenu *pMainMenu = pFrameWindowPointer->GetMenu(); CMenu *pViewMenu = pMainMenu->GetSubMenu(2); // position of "View" submenu in main menu CMenu *pViewAsMenu = pViewMenu->GetSubMenu(3); // position of "View As" submenu in "View" menu // Create the skins menu if we haven't already if (pViewAsMenu == NULL || pViewAsMenu->GetMenuItemCount() == 1) { CMenu borderlessMenu; borderlessMenu.CreateMenu(); CMenu *pBorderlessMenu = &borderlessMenu; CMenu *pParentMenu = pViewAsMenu; #if _DEBUG Rtt_TRACE(( "CSimulatorView::OnUpdateWindowViewAs: populating View As menu\n" )); #endif // Remove the placeholder which is needed to trigger the population of the otherwise // empty menu (because it's a popup, "View As" can't have an ID and thus can't trigger) pViewAsMenu->RemoveMenu(0, MF_BYPOSITION); const char *skinName = NULL; const char *deviceType = NULL; const char *lastDeviceType = NULL; long skinCount = 0; long itemCount = 0; long viewAsItemCount = 0; while ((skinName = Rtt::TargetDevice::NameForSkin(skinCount)) != NULL) { CString itemTitle; int skinWidth = Rtt::TargetDevice::WidthForSkin(skinCount); int skinHeight = Rtt::TargetDevice::HeightForSkin(skinCount); deviceType = Rtt::TargetDevice::DeviceTypeForSkin(skinCount); // Note that this programmatic conceit depends on "borderless-*" device types being sorted to the end of the list // (see Rtt_TargetDevice.cpp) if (pParentMenu == pViewAsMenu && lastDeviceType != NULL && strncmp(deviceType, "borderless-", 11) == 0) { // Separator pViewAsMenu->InsertMenu(itemCount, MF_BYPOSITION|MFT_SEPARATOR, 0, _T("-")); ++itemCount; pViewAsMenu->InsertMenu(itemCount, MF_BYPOSITION | MF_POPUP, (UINT_PTR)pBorderlessMenu->GetSafeHmenu(), _T("Borderless")); ++itemCount; viewAsItemCount = itemCount + 1; lastDeviceType = deviceType; itemCount = 0; pParentMenu = pBorderlessMenu; } itemTitle.Format(_T("%S\t%dx%d"), skinName, skinWidth, skinHeight); pParentMenu->InsertMenu(itemCount, MF_BYPOSITION, ID_VIEWAS_BEGIN + skinCount, itemTitle); // If the device type changes, insert a separator in the menu if (lastDeviceType != NULL && strcmp(deviceType, lastDeviceType) != 0) { pParentMenu->InsertMenu(itemCount, MF_BYPOSITION|MFT_SEPARATOR, 0, _T("-")); ++itemCount; } lastDeviceType = deviceType; ++skinCount; ++itemCount; } if (pParentMenu == pBorderlessMenu) { borderlessMenu.Detach(); } else { bool uhOh = true; } // Separator pViewAsMenu->InsertMenu(viewAsItemCount, MF_BYPOSITION|MFT_SEPARATOR, 0, _T("-")); ++viewAsItemCount; pViewAsMenu->InsertMenu(viewAsItemCount, MF_BYPOSITION, ID_VIEWAS_CUSTOMDEVICE, _T("Custom Device...")); } } if (pCmdUI->m_nID == ID_VIEWAS_CUSTOMDEVICE) pCmdUI->SetCheck( Rtt::TargetDevice::kCustomSkin == m_nSkinId ); else pCmdUI->SetCheck( SkinIDFromMenuID( pCmdUI->m_nID ) == m_nSkinId ); } void CSimulatorView::OnUpdateViewNavigateBack(CCmdUI *pCmdUI) { bool isEnabled = false; if (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetDeviceSimulatorServices() && !IsSimulationSuspended()) { if (mDeviceConfig.supportsKeyEvents && mDeviceConfig.supportsBackKey) { isEnabled = true; } } pCmdUI->Enable(isEnabled ? TRUE : FALSE); } #pragma endregion void CSimulatorView::GetFilePaths(LPCTSTR pattern, CStringArray& filepaths) { // Object to enumerate files CFileFind finder; // Init the file finding job BOOL working = finder.FindFile( pattern ); // For each file that is found: while ( working ) { // Update finder status with new file working = finder.FindNextFile(); // Skip '.' and '..' if ( finder.IsDots() ) { continue; } // Skip sub-directories if ( finder.IsDirectory() ) { continue; } // Add file path to container filepaths.Add( finder.GetFilePath() ); } // Cleanup file finder finder.Close(); } bool CSimulatorView::LoadSkinResources() { CString msg; CStringArray filePaths; CString systemSkinFilesGlob; systemSkinFilesGlob = mSystemSkinsDir + _T("*.lua"); GetFilePaths(systemSkinFilesGlob, filePaths); // Only "Pro" users get to have custom skins. For business purposes, the ability to // use Daily Builds equates to "Pro and above" #ifdef WE_FIXED_THE_APP_INITIALIZATION_ORDER // TODO: Unfortunately the app initialization process is sufficiently convoluted that we have // a chicken and egg issue here. One day we'll figure it out, until then everyone on // Windows gets user defined skins, not just Pro const Rtt::AuthorizationTicket *ticket = GetWinProperties()->GetTicket(); if ( ticket && ticket->IsDailyBuildAllowed() ) #endif { CString userSkinsGlob; userSkinsGlob = mUserSkinsDir + _T("*.lua"); GetFilePaths(CString(userSkinsGlob), filePaths); } // Put the skins into a data structure we can share with core code char **skinPaths; skinPaths = (char **) calloc(sizeof(char *), filePaths.GetSize()); if (skinPaths == NULL && filePaths.GetSize() > 0) { printf("CSimulatorView::OnUpdateWindowViewAs: Problem processing skin files. Please restart\n"); } else { for ( int i = 0; i < filePaths.GetSize(); i++ ) { skinPaths[i] = (char *) _strdup(CStringA(filePaths[i])); } // Tell the core about the skins Rtt::TargetDevice::Initialize(skinPaths, filePaths.GetSize()); for (int i = 0; i < filePaths.GetSize(); i++) { free(skinPaths[i]); } free(skinPaths); } return TRUE; } #pragma region Corona Event Handlers void CSimulatorView::OnRuntimeLoaded(Interop::RuntimeEnvironment& sender, const Interop::EventArgs& arguments) { // Store a pointer to the newly created/loaded Corona runtime. mRuntimeEnvironmentPointer = (Interop::SimulatorRuntimeEnvironment*)&sender; // Finish configuring the runtime now that it is loaded. Rtt::Runtime *runtimePointer = mRuntimeEnvironmentPointer->GetRuntime(); bool bIsShowingRuntimeErrors = ((CSimulatorApp*)AfxGetApp())->IsShowingRuntimeErrors(); bool showRuntimeErrors = mIsShowingInternalScreen ? false : bIsShowingRuntimeErrors; runtimePointer->SetProperty(Rtt::Runtime::kShowRuntimeErrors, showRuntimeErrors); // If simulating a project, then log its paths. if (mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { Rtt_TRACE_SIM(( "Loading project from: %s\r\n", mRuntimeEnvironmentPointer->GetUtf8PathFor(Rtt::MPlatform::kResourceDir))); Rtt_TRACE_SIM(( "Project sandbox folder: %s\r\n", mRuntimeEnvironmentPointer->GetUtf8PathFor(Rtt::MPlatform::kDocumentsDir))); } // Fetch the loaded app's default rotation/orientation. int launchRotation = 0; if (mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()) { auto orientation = mRuntimeEnvironmentPointer->GetDeviceSimulatorServices()->GetOrientation(); switch (orientation) { case Rtt::DeviceOrientation::kUpright: launchRotation = 0; break; case Rtt::DeviceOrientation::kSidewaysRight: // bottom of device is to the right launchRotation = 270; break; case Rtt::DeviceOrientation::kUpsideDown: // bottom of device is at the top launchRotation = 180; break; case Rtt::DeviceOrientation::kSidewaysLeft: // bottom of device is to the left launchRotation = 90; break; } } // Rotate the device skin's bitmap to match the app's rotation. int diffRotation = launchRotation - GetRotation(); if( diffRotation < 0 ) { diffRotation += 360; } if (NULL != GetSkinBitmap()) { GetSkinBitmap()->RotateFlip( DegreesToRFType( diffRotation ) ); } // Store the rotation value. SetRotation( launchRotation ); // Update the window for the current skin and rotation. UpdateSimulatorSkin(); } // OnActivityIndicator - ActivityIndicator message from lua code // Use CProgressWnd for now, but doesn't look great. TODO: improve appearance // wParam = 0 for hide, 1 for show. Only one window can be active at a time. // lParam = NULL or pointer to string of text shown on window LRESULT CSimulatorView::OnActivityIndicator(WPARAM wParam, LPARAM lParam) { if (wParam) { // Show the progress dialog. if (!mProgressDlgPointer) { mProgressDlgPointer = new CProgressWnd(this); mProgressDlgPointer->Create(CProgressWnd::IDD); } mProgressDlgPointer->ShowWindow(SW_SHOW); } else { // Hide the progress dialog. if (mProgressDlgPointer) { mProgressDlgPointer->ShowWindow(SW_HIDE); } } return 0; } // OnNativeAlert - message from lua code // Use CMessageDlg, configured as indicated by WMU_ALERT_PARAMS in lParam // wParam = 0 for cancel, 1 for show. Only one window can be active at a time. // lParam = NULL (only OK button) or ptr to array of strings for buttons LRESULT CSimulatorView::OnNativeAlert(WPARAM wParam, LPARAM lParam) { int result = 0; WMU_ALERT_PARAMS *pWAP = (WMU_ALERT_PARAMS *)lParam; if (nullptr == pWAP) { return -1; } if (0 == wParam) // Cancel alert -- usually canceled directly { if (0 != pWAP->hwnd) { ::SendMessage((HWND)pWAP->hwnd, WM_COMMAND, IDCANCEL, NULL); } } else // 0 != wParam, show alert { // Clean up previous memory if (mMessageDlgPointer) { if (mMessageDlgPointer->GetSafeHwnd()) { mMessageDlgPointer->SendMessage(WM_COMMAND, IDCANCEL, 0); } delete mMessageDlgPointer; mMessageDlgPointer = nullptr; } // Create a new message box. mMessageDlgPointer = new CMessageDlg(this); // Set up parameters of message window WinString string; string.SetUTF8( pWAP->sTitle ); mMessageDlgPointer->SetTitle(string.GetTCHAR()); string.SetUTF8( pWAP->sMsg ); mMessageDlgPointer->SetText(string.GetTCHAR()); // Custom labels for up to 3 buttons if ( pWAP->nButtonLabels > 0 ) { string.SetUTF8( pWAP->psButtonLabels[0] ); mMessageDlgPointer->SetDefaultText(string.GetTCHAR()); } if ( pWAP->nButtonLabels > 1 ) { string.SetUTF8( pWAP->psButtonLabels[1] ); mMessageDlgPointer->SetAltText(string.GetTCHAR()); } if ( pWAP->nButtonLabels > 2 ) { string.SetUTF8( pWAP->psButtonLabels[2] ); mMessageDlgPointer->SetButton3Text(string.GetTCHAR()); } // When a button is pressed pLuaResource is used to call back into lua code mMessageDlgPointer->SetNativeAlertInfo(pWAP->pLuaResource); // Create the message window (non-zero means success) if (mMessageDlgPointer->Create(CMessageDlg::IDD) == 0) { result = -1; } mMessageDlgPointer->ShowWindow(SW_SHOW); // Return hwnd for future cancel message pWAP->hwnd = mMessageDlgPointer->GetSafeHwnd(); } return result; } #pragma endregion #pragma region Public Functions /// Starts simulating the project file currently held by the CSimulatorDoc. void CSimulatorView::StartSimulation() { // Stop the last running simulation. if (mRuntimeEnvironmentPointer) { StopSimulation(); } Rtt::SimulatorAnalytics *pAnalytics = GetWinProperties()->GetAnalytics(); if (pAnalytics && (GetDocument()->GetPath().GetLength() > 0)) { // Log this project open pAnalytics->Log( "open-project", "skin", Rtt::TargetDevice::LabelForSkin( (Rtt::TargetDevice::Skin)GetAnalyticsSkinId() ) ); } // Run the currently selected Corona project set in this view's document. RunCoronaProject(); } /// Restarts simulation of the project file currently held by the CSimulatorDoc. void CSimulatorView::RestartSimulation() { // If the simulator is not currently running, then do a "Start" instead. if (nullptr == mRuntimeEnvironmentPointer) { StartSimulation(); return; } // Record the "Restart" to the usage feedback to be posted to Corona Labs' server later. Rtt::SimulatorAnalytics *pAnalytics = GetWinProperties()->GetAnalytics(); if (pAnalytics && (GetDocument()->GetPath().GetLength() > 0)) { ++mRelaunchCount; } // Run the currently selected Corona project set in this view's document. RunCoronaProject(); } void CSimulatorView::SuspendResumeSimulationWithOverlay(bool showOverlay, bool sendSystemEvents) { // Do not continue if we're showing an internal screen, such as the Welcome window. if (mIsShowingInternalScreen) { return; } // Do not continue if we're not currently running a project. if (!mRuntimeEnvironmentPointer) { return; } auto runtimePointer = mRuntimeEnvironmentPointer->GetRuntime(); if (!runtimePointer) { return; } // Suspend/resume the Corona runtime. if (runtimePointer->IsSuspended()) { runtimePointer->Resume(sendSystemEvents); } else { runtimePointer->Suspend(sendSystemEvents); } if (runtimePointer->IsSuspended()) { if (showOverlay) { mCoronaContainerControl.SetWindowTextW(L"Suspended"); mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_HIDE); } EnableWindow(FALSE); } else { EnableWindow(TRUE); if (mCoronaContainerControl.GetCoronaControl().IsWindowVisible() == FALSE) { mCoronaContainerControl.SetWindowTextW(L""); mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_SHOW); mCoronaContainerControl.GetCoronaControl().SetFocus(); } } } /// Stops the current simulation and blanks out the screen. void CSimulatorView::StopSimulation() { // Do not continue if already stopped. if (!mRuntimeEnvironmentPointer) { return; } // Terminate the Corona runtime. Interop::SimulatorRuntimeEnvironment::Destroy(mRuntimeEnvironmentPointer); mRuntimeEnvironmentPointer = nullptr; // Hide the Corona control and show its black container without any text. mCoronaContainerControl.SetWindowTextW(L""); mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_HIDE); // Clear the simulator screen. UpdateSimulatorSkin(); } bool CSimulatorView::IsSimulationSuspended() const { if (mRuntimeEnvironmentPointer) { auto runtimePointer = mRuntimeEnvironmentPointer->GetRuntime(); if (runtimePointer) { return runtimePointer->IsSuspended(); } } return false; } // InitializeSimulation - select new skin and update bool CSimulatorView::InitializeSimulation(Rtt::TargetDevice::Skin skinId) { int zoom = (int) AfxGetApp()->GetProfileInt(REGISTRY_SECTION, REGISTRY_ZOOM, REGISTRY_ZOOM_DEFAULT); int rotation = AfxGetApp()->GetProfileInt(REGISTRY_SECTION, REGISTRY_ROTATION, REGISTRY_ROTATION_DEFAULT); // Restore the remembered zoom level and rotation CMainFrame *pMainWnd = (CMainFrame *)GetParentFrame(); ASSERT(pMainWnd); pMainWnd->SetZoom(zoom); SetRotation(rotation); if (skinId == Rtt::TargetDevice::kCustomSkin) { mDisplayName = _T("CustomDevice"); } else { mDisplayName = Rtt::TargetDevice::LabelForSkin(skinId); } ((CSimulatorApp*)AfxGetApp())->PutDisplayName(mDisplayName); bool skinLoaded = InitSkin(skinId); UpdateSimulatorSkin(); // Draw the device skin onscreen. if (skinLoaded) { RestartSimulation(); } return skinLoaded; } // UpdateSimulatorSkin - Update main window size & skin based on display type, // zoom state, rotation state. // CMainFrame handles resizing the window for zoom & rotate void CSimulatorView::UpdateSimulatorSkin() { CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); // Determine what the size of the client area of the window needs to be. UINT clientWidth = 0; UINT clientHeight = 0; Gdiplus::Bitmap *pBitmap = mIsShowingInternalScreen ? nullptr : GetSkinBitmap(); if (pBitmap) { // A simulator skin was loaded by InitSkin(). Use the already rotated bitmap's dimensions. clientWidth = pBitmap->GetWidth(); clientHeight = pBitmap->GetHeight(); } else if (mIsShowingInternalScreen) { // We are not simulating a device. Use the runtime's width and height. if (mRuntimeEnvironmentPointer && mRuntimeEnvironmentPointer->GetRuntime()) { Rtt::Display& display = mRuntimeEnvironmentPointer->GetRuntime()->GetDisplay(); clientWidth = display.ContentWidth(); clientHeight = display.ContentHeight(); } // Apply the system's DPI scale factor to the width and height. // Note: In the future, we should resize the window when the DPI scale factor changes dynamically. auto deviceContextPointer = this->GetDC(); if (deviceContextPointer) { const int kBaseDpi = 96; int dpiValue = deviceContextPointer->GetDeviceCaps(LOGPIXELSX); if ((dpiValue > 0) && (dpiValue != kBaseDpi)) { double dpiScale = (double)dpiValue / (double)kBaseDpi; clientWidth = (int)std::round((double)clientWidth * dpiScale); } dpiValue = deviceContextPointer->GetDeviceCaps(LOGPIXELSY); if ((dpiValue > 0) && (dpiValue != kBaseDpi)) { double dpiScale = (double)dpiValue / (double)kBaseDpi; clientHeight = (int)std::round((double)clientHeight * dpiScale); } } } else { // We're simulating a skinless device such as an Ouya or GameStick. if (mDeviceConfig.supportsScreenRotation) { bool isUpright = ((GetRotation() == 0) || (GetRotation() == 180)); clientWidth = (UINT)(isUpright ? mDeviceConfig.screenWidth : mDeviceConfig.screenHeight); clientHeight = (UINT)(isUpright ? mDeviceConfig.screenHeight : mDeviceConfig.screenWidth); } else { bool isPortrait = mDeviceConfig.isUprightOrientationPortrait; clientWidth = (UINT)(isPortrait ? mDeviceConfig.screenWidth : mDeviceConfig.screenHeight); clientHeight = (UINT)(isPortrait ? mDeviceConfig.screenHeight : mDeviceConfig.screenWidth); } } // Validate width and height. if ((clientWidth <= 0) || (clientHeight <= 0)) { return; } // Fetch the size of the window's client area, which the surface we render to. CMainFrame *pMainWnd = (CMainFrame*)GetParentFrame(); if (!pMainWnd) { return; } CRect clientBounds; pMainWnd->GetClientRect(clientBounds); // Do not update window size if it is currently minimized. if (pMainWnd->IsIconic() || (clientBounds.Width() <= 0) || (clientBounds.Height() <= 0)) { return; } // Calculate a good zoom factor for the window to size itself to. if (mIsShowingInternalScreen) { // We are displaying the Home or Demo screens. // Set the zoom factor to 0, which means do not zoom. pMainWnd->SetZoom(0); } else { // Zoom in/out to fit the device skin. pMainWnd->AdjustZoom(clientWidth, clientHeight); } float zoomFactor = pMainWnd->CalcZoomFactor(); // Set the client window size that will render the device skin and the Corona contents. clientBounds.top = 0; clientBounds.left = 0; clientBounds.right = (int)floor(zoomFactor * clientWidth); clientBounds.bottom = (int)floor(zoomFactor * clientHeight); pMainWnd->SizeToClient(clientBounds); // Calculate the bounds of the Corona control. CRect coronaBounds; if (pBitmap) { // We're displaying a skin. So, set the bounds of the Corona control in the skin's screen region. // Note: The skin's origin is in the bottom-left corner. We need to flip it to the top-left corner for Windows. bool isUpright = ((GetRotation() == 0) || (GetRotation() == 180)); LONG unrotatedBitmapWidth = isUpright ? pBitmap->GetWidth() : pBitmap->GetHeight(); LONG unrotatedBitmapHeight = isUpright ? pBitmap->GetHeight() : pBitmap->GetWidth(); coronaBounds.top = unrotatedBitmapHeight - (LONG)(mDeviceConfig.screenOriginY + mDeviceConfig.screenHeight + 0.5f); coronaBounds.left = (LONG)(mDeviceConfig.screenOriginX + 0.5f); coronaBounds.bottom = unrotatedBitmapHeight - (LONG)(mDeviceConfig.screenOriginY + 0.5f); coronaBounds.right = (LONG)(mDeviceConfig.screenOriginX + mDeviceConfig.screenWidth + 0.5f); // Rotate the Corona control bounds if the skin is rotated. switch (GetRotation()) { case 90: { CRect rotatedBounds; rotatedBounds.left = unrotatedBitmapHeight - coronaBounds.bottom; rotatedBounds.top = coronaBounds.left; rotatedBounds.right = unrotatedBitmapHeight - coronaBounds.top; rotatedBounds.bottom = coronaBounds.right; coronaBounds = rotatedBounds; break; } case 180: { CRect rotatedBounds; rotatedBounds.left = unrotatedBitmapWidth - coronaBounds.right; rotatedBounds.top = unrotatedBitmapHeight - coronaBounds.bottom; rotatedBounds.right = unrotatedBitmapWidth - coronaBounds.left; rotatedBounds.bottom = unrotatedBitmapHeight - coronaBounds.top; coronaBounds = rotatedBounds; break; } case 270: { CRect rotatedBounds; rotatedBounds.left = coronaBounds.top; rotatedBounds.top = unrotatedBitmapWidth - coronaBounds.right; rotatedBounds.right = coronaBounds.bottom; rotatedBounds.bottom = unrotatedBitmapWidth - coronaBounds.left; coronaBounds = rotatedBounds; break; } } // Apple the zoom level scale. ScaleRect(coronaBounds, zoomFactor); } else { // Not showing a skin. Use the same bounds as the window's client area. coronaBounds.CopyRect(&clientBounds); } mCoronaContainerControl.MoveWindow(coronaBounds, FALSE); // Set size, position, and visibility of view window this->MoveWindow(clientBounds, TRUE); this->ShowWindow(SW_SHOW); } bool CSimulatorView::VerifyAllPluginsAcquired() { // Do not continue if we're not currently running a Corona project. if (!mRuntimeEnvironmentPointer || !mRuntimeEnvironmentPointer->GetRuntime()) { return true; } // Verify that all of the Corona project's plugins have been downloaded/acquired. if (mRuntimeEnvironmentPointer->GetRuntime()->RequiresDownloadablePlugins()) { Rtt::String utf8MissingPluginsString; auto runtimePointer = mRuntimeEnvironmentPointer->GetRuntime(); if (Rtt::PlatformAppPackager::AreAllPluginsAvailable(runtimePointer, &utf8MissingPluginsString) == false) { // Display a message box detailing which plugins were not found and how to resolve it. CStringW title; CStringW message; title.LoadStringW(IDS_WARNING); WinString missingPluginsString(L""); if (!utf8MissingPluginsString.IsEmpty()) { missingPluginsString.SetUTF16(L"Corona failed to acquire the following plugins:\n- "); WinString stringBuffer(utf8MissingPluginsString.GetString()); stringBuffer.Replace("\n", "\n- "); missingPluginsString.Append(stringBuffer.GetUTF16()); missingPluginsString.Append(L"\n\n"); } message.Format(IDS_CANNOT_BUILD_WITHOUT_PLUGINS, missingPluginsString.GetUTF16()); Interop::UI::TaskDialog dialog; dialog.GetSettings().SetParentWindowHandle(this->GetSafeHwnd()); dialog.GetSettings().SetTitleText(title); dialog.GetSettings().SetMessageText(message); dialog.GetSettings().GetButtonLabels().push_back(std::wstring(L"&Learn More")); dialog.GetSettings().GetButtonLabels().push_back(std::wstring(L"&Cancel")); dialog.Show(); // Display Corona's documentation about plugin "build.settings" via the default web browser. if (dialog.GetLastPressedButtonIndex() == 0) { try { ::ShellExecuteW( nullptr, L"open", L"https://docs.coronalabs.com/daily/guide/distribution/buildSettings/index.html#plugins", nullptr, nullptr, SW_SHOWNORMAL); } catch (...) {} } // Returning false indicates that we've failed to acquire all plugins. return false; } } // All plugins have been acquired or the project does not require plugins. return true; } #ifdef _DEBUG void CSimulatorView::AssertValid() const { CView::AssertValid(); } void CSimulatorView::Dump(CDumpContext& dc) const { CView::Dump(dc); } CSimulatorDoc* CSimulatorView::GetDocument() const // non-debug version is inline { ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimulatorDoc))); return (CSimulatorDoc*)m_pDocument; } #endif //_DEBUG #pragma endregion #pragma region Private Functions /// Open the document's currently selectd Corona project and starts simulation. /// Shows the home screen if no project was selected and only if enabled in application preferences. void CSimulatorView::RunCoronaProject() { if (ValidateOpenGL() == false) { return; } // Fetch the document's currently selected "main.lua" file. CString filePath = GetDocument()->GetPath(); if (filePath.IsEmpty()) { // A file was not selected. Show the home screen if enabled. // Do not show the home screen if we're running the Corona Debugger. CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); if (applicationPointer->IsHomeScreenEnabled() && (applicationPointer->IsDebugModeEnabled() == false)) { filePath = applicationPointer->GetHomeScreenFilePath(); } else { applicationPointer->LoadZoomFromRegistry(); } } // Run the Corona project. RunCoronaProject(CCoronaProject::RemoveMainLua(filePath)); } /// Opens the given Corona project and starts simulation. /// @param filePath The path to the directory containing the Corona project's "main.lua" file. /// Set this to an empty string to stop simulation and show a blank screen. void CSimulatorView::RunCoronaProject(CString& projectPath) { // Fetch the application object. CSimulatorApp *applicationPointer = ((CSimulatorApp*)AfxGetApp()); if (!applicationPointer) { return; } // Identify if we are loading the home screen Corona project. { CString lowercaseProjectPath = projectPath; lowercaseProjectPath.MakeLower(); CString lowercaseResourceDir = ((CSimulatorApp*)AfxGetApp())->GetResourceDir(); lowercaseResourceDir.MakeLower(); mIsShowingInternalScreen = (lowercaseProjectPath.Find(lowercaseResourceDir) >= 0); } // Set the working directory that the Open File dialog will use to the // parent directory of the currently active project. if (!mIsShowingInternalScreen) { CString sParentDir = projectPath; sParentDir = sParentDir.Left( sParentDir.ReverseFind(_T('\\')) ); CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); applicationPointer->SetWorkingDir( sParentDir ); applicationPointer->LoadZoomFromRegistry(); } // If we're opening the "home screen" project, then show the home menu. // Otherwise, show the device simulator menu. auto frameWindowPointer = (CMainFrame*)GetParentFrame(); if (frameWindowPointer) { // Only replace the menu if it needs changing. If we're already showing the right menu, do nothing. UINT nextMenuId = mIsShowingInternalScreen ? IDR_HOME_MENU : IDR_SIMULATOR_MENU; auto lastMenuPointer = frameWindowPointer->GetMenu(); MENUINFO menuInfo{}; menuInfo.cbSize = sizeof(menuInfo); menuInfo.fMask = MIM_MENUDATA; lastMenuPointer->GetMenuInfo(&menuInfo); if (menuInfo.dwMenuData != nextMenuId) { // Load a new menu from our resource table. CMenu newMenu; newMenu.LoadMenu(mIsShowingInternalScreen ? IDR_HOME_MENU : IDR_SIMULATOR_MENU); // Assign the loaded menu's resource ID to its info struct. // This is an optimization. We don't want to reload the menu everytime we start/stop a Corona project. memset(&menuInfo, 0, sizeof(menuInfo)); menuInfo.cbSize = sizeof(menuInfo); menuInfo.fMask = MIM_MENUDATA; if (newMenu.GetMenuInfo(&menuInfo)) { menuInfo.dwMenuData = nextMenuId; newMenu.SetMenuInfo(&menuInfo); } // Remove items from the "Build" menu that the end-user is not authorized to use. RemoveUnauthorizedMenuItemsFrom(&newMenu); // Replace the window's menu. frameWindowPointer->SetMenu(&newMenu); frameWindowPointer->m_hMenuDefault = newMenu.GetSafeHmenu(); lastMenuPointer->DestroyMenu(); newMenu.Detach(); } } // Do not load the project if the machine does not meet the minimum OpenGL requirements. if ((projectPath.GetLength() > 0) && (ValidateOpenGL() == false)) { projectPath.Empty(); } // Disable logging if showing the Welcome screen, unless our undocumented debug flag is set in the registry. // We do this because the simulator user will only be interested in debugging their own simulated apps. // Note: Debug logging cannot be disabled when running the debug version of the Corona Simulator. if (mIsShowingInternalScreen && !applicationPointer->GetProfileInt(REGISTRY_SECTION, _T("debugWelcomeProcess"), 0)) { Rtt_LogDisable(); } else { Rtt_LogEnable(); } // Terminate the last Corona runtime. Interop::SimulatorRuntimeEnvironment::Destroy(mRuntimeEnvironmentPointer); mRuntimeEnvironmentPointer = nullptr; // Load and run the application. if (projectPath.GetLength() > 0) { // Show the Corona control before creating the runtime. The Corona runtime will render to this control. mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_SHOW); mCoronaContainerControl.GetCoronaControl().SetFocus(); // Set up the Corona runtime launch settings. Interop::SimulatorRuntimeEnvironment::CreationSettings settings; settings.ResourceDirectoryPath = projectPath; settings.MainWindowHandle = nullptr; // <- Do not let the runtime take control of the main window. settings.RenderSurfaceHandle = mCoronaContainerControl.GetCoronaControl().GetSafeHwnd(); settings.LoadedEventHandlerPointer = &mRuntimeLoadedEventHandler; if (mIsShowingInternalScreen) { // Give the Welcome Window access to our "WinSimulatorServices" object's features. settings.CoronaSimulatorServicesPointer = &mSimulatorServices; } else { // Provide the configuration of the device we will be simulating. settings.DeviceConfigPointer = &mDeviceConfig; // Set up the runtime for debug mode, if enabled. if (((CSimulatorApp*)::AfxGetApp())->IsDebugModeEnabled()) { settings.LaunchOptions |= Rtt::Runtime::kConnectToDebugger; } } // Create and startup the Corona runtime. // Note: This class' OnRuntimeLoaded() method will be called before this function returns if successfully loaded. auto result = Interop::SimulatorRuntimeEnvironment::CreateUsing(settings); // Display an error message if we've failed to load the Corona project. if (result.HasFailed() || !mRuntimeEnvironmentPointer) { CStringW title; title.LoadString(IDS_WARNING); auto errorMessage = result.GetMessageW(); if (!errorMessage || (L'\0' == errorMessage[0])) { errorMessage = L"Failed to load Corona project."; } ::MessageBoxW(GetSafeHwnd(), errorMessage, (LPCWSTR)title, MB_OK | MB_ICONWARNING); } } // Update the size of the window to match the project's default orientation and configured skin, if specified. EnableWindow(TRUE); // in case we were suspended if (!mRuntimeEnvironmentPointer) { UpdateSimulatorSkin(); mCoronaContainerControl.SetWindowTextW(L""); mCoronaContainerControl.GetCoronaControl().ShowWindow(SW_HIDE); } // If we're monitoring a project directory, close that handle (we'll open a new one when we need to) if (mAppChangeHandle) { FindCloseChangeNotification(mAppChangeHandle); mAppChangeHandle = nullptr; } } // SkinDisplayNameFromID - translate skin type from resource id Rtt::TargetDevice::Skin CSimulatorView::SkinIDFromMenuID( UINT nMenuID ) { Rtt::TargetDevice::Skin skinID = (Rtt::TargetDevice::Skin) ( nMenuID - ID_VIEWAS_BEGIN ); return skinID; } /// Gets a unique integer ID for the currently selected device skin. /// @return Returns a unique skin ID of type Rtt::TargetDevice for the current skin selection. /// Returns Rtt::TargetDevice::kUnknownSkin if the current skin selction is unknown. int CSimulatorView::GetAnalyticsSkinId() { return m_nSkinId; } // SetRotation - validate rotation value and set member variable void CSimulatorView::SetRotation( int rotation ) { // only 0, 90, 180, 270 are valid rotation = rotation % 360; if (rotation < 90) // neg. numbers are set to 0 rotation = 0; else if( rotation < 180) rotation = 90; else if( rotation < 270) rotation = 180; else if( rotation < 360 ) rotation = 270; // Store the given rotation value. CSimulatorApp *applicationPointer = ((CSimulatorApp*)AfxGetApp()); if (applicationPointer) { applicationPointer->PutRotation(rotation); } mRotation = rotation; } // ScaleRect - Multiply all members of a rect by a scale factor. Modifies rect. void CSimulatorView::ScaleRect( CRect& rect, float scale ) { rect.left = (LONG) floor( rect.left * scale ); rect.top = (LONG) floor( rect.top * scale ); rect.right = (LONG) floor( rect.right * scale ); rect.bottom = (LONG) floor( rect.bottom * scale ); } // InitSkin - Load device bitmap and rotate as needed // Only called from InitializeSimulation() bool CSimulatorView::InitSkin( Rtt::TargetDevice::Skin skinId ) { WinString skinFile; if (skinId == Rtt::TargetDevice::kCustomSkin) { skinFile.SetTCHAR(mCustomSkinFileName); } else { skinFile.SetUTF8( Rtt::TargetDevice::LuaObjectFileFromSkin( skinId ) ); } m_nSkinId = skinId; // Get the skins directory which is wherever the Lua file for the skin is // (things like the skin bitmap and statusbar images will be specified // relative to this) wchar_t skinPathBuf[MAX_PATH]; _tcsncpy_s(skinPathBuf, skinFile.GetTCHAR(), MAX_PATH); PathRemoveFileSpec(skinPathBuf); // Delete the last loaded bitmap. if (mpSkinBitmap != NULL) { delete mpSkinBitmap; mpSkinBitmap = NULL; } // Load the skin's configuration in Lua. Rtt::PlatformSimulator::LoadConfig(skinFile.GetUTF8(), mDeviceConfig); CString sPath( mDeviceConfig.deviceImageFile.GetString() ); // Load skin image file as a bitmap. if (sPath.GetLength() > 0) { PathAppend(skinPathBuf, sPath); mpSkinBitmap = Gdiplus::Bitmap::FromFile(CStringW(skinPathBuf)); if (mpSkinBitmap && (mpSkinBitmap->GetLastStatus() == Gdiplus::Ok)) { // Match bitmap orientation to current window rotation. mpSkinBitmap->RotateFlip( DegreesToRFType( GetRotation() ) ); } else { // Image file not found or failed to load it. // Assume the simulated device is skinless and continue. if (mpSkinBitmap) { delete mpSkinBitmap; mpSkinBitmap = NULL; } } } // Device skin was loaded successfully. It will be drawn within UpdateSimulatorSkin(). return true; } // ValidateOpenGL - // Checks if the current OpenGL context meets Corona's minimum requirements. // This function should be called after calling EnableOpenGL() and before simulating an app. // Displays an error message if the minimum requirements have not been met. // Returns true if the minimum OpenGL requirements for simulation have been met and // it is okay to proceed to simulate an app. bool CSimulatorView::ValidateOpenGL() { // Verify that the control we want to render to meets Corona's minimum requirements. HWND windowHandle = mCoronaContainerControl.GetCoronaControl().GetSafeHwnd(); auto result = Interop::RuntimeEnvironment::ValidateRenderSurface(windowHandle); // Fetch the renderer's version string. WinString rendererVersionString; rendererVersionString.SetUTF8(result.RendererVersion.GetString()); if (rendererVersionString.IsEmpty()) { rendererVersionString.SetUTF16(L"OpenGL Driver Version: Unknown"); } // Display a warning message if we can render, but not all graphics features will work. if (result.CanRender && (false == result.SupportsAllShaders)) { CMessageDlg messageDlg; CString sMessage; CString sRequiredVersion; sRequiredVersion.Format( _T("%d.%d"), result.MinVersionSupported.GetMajorNumber(), result.MinVersionSupported.GetMinorNumber()); sMessage.Format(IDS_OPENGL_VERSION_WARNING, sRequiredVersion, rendererVersionString.GetTCHAR()); messageDlg.SetTitle(IDS_WARNING); messageDlg.SetText(sMessage); messageDlg.SetDefaultText(IDS_OK); messageDlg.SetIconStyle(MB_ICONEXCLAMATION); if (messageDlg.DoModal() != ID_MSG_BUTTON2) { // User has chosen not to continue. Fail the validation test. mCoronaContainerControl.ShowWindow(SW_HIDE); return false; } } // Display a major warning only once if we cannot render reliable at all. // This will most likely happen if the OpenGL driver is too old. static bool sDisableCheckForGL21 = false; if (!sDisableCheckForGL21 && !result.CanRender) { CMessageDlg messageDlg; CString sMessage; CString sRequiredVersion; sRequiredVersion.Format( _T("%d.%d"), result.MinVersionSupported.GetMajorNumber(), result.MinVersionSupported.GetMinorNumber()); sMessage.Format(IDS_OPENGL21_VERSION_WARNING, sRequiredVersion, rendererVersionString.GetTCHAR()); messageDlg.SetTitle(IDS_WARNING); messageDlg.SetText(sMessage); messageDlg.SetDefaultText(IDS_CANCEL); messageDlg.SetAltText(IDS_IGNORE); messageDlg.SetIconStyle(MB_ICONEXCLAMATION); if (messageDlg.DoModal() != ID_MSG_BUTTON2) { // User has chosen not to continue. Fail the validation test. mCoronaContainerControl.ShowWindow(SW_HIDE); return false; } else { // User chose to ignore the warning. // In this case, never warn the user about this issue again so as not to annoy him/her. sDisableCheckForGL21 = true; } } // The system successfully meets Corona's minimum graphics requirements // ...or there is a graphics issue and the user has chosen to continue at his/her own risk. if (!mCoronaContainerControl.IsWindowVisible()) { mCoronaContainerControl.ShowWindow(SW_SHOW); } return true; } /// Gets a list of recent projects. void CSimulatorView::GetRecentDocs(Rtt::LightPtrArray<Rtt::RecentProjectInfo> *listPointer) { // Validate. if (!listPointer) { return; } // Delete all entries in the given list. listPointer->Clear(); // Fetch this application's recent file list. CRecentFileList *recentListPointer = ((CSimulatorApp*)AfxGetApp())->GetRecentFileList(); if (!recentListPointer) { return; } // Copy information in this app's recents list to the given list. WinString stringTranscoder; int listCount = recentListPointer->GetSize(); if (listCount > 10) { listCount = 10; } for (int index = 0; index < listCount; index++) { // Fetch the next file path in the recents list. // Note: Will be an empty string if there are no more recent files in the collection. CString lastFilePathName = (*recentListPointer)[index]; if (lastFilePathName.IsEmpty()) { continue; } // Create a recent project info object. Rtt::RecentProjectInfo *infoPointer = new Rtt::RecentProjectInfo(); if (!infoPointer) { continue; } // Copy the project's folder name to the info object. CString sTitle = lastFilePathName; sTitle = CCoronaProject::RemoveMainLua(sTitle); sTitle = sTitle.Right(sTitle.GetLength() - sTitle.ReverseFind(_T('\\')) - 1); stringTranscoder.SetTCHAR(sTitle); infoPointer->formattedString = stringTranscoder.GetUTF8(); // Copy the project's "main.lua" file path to the info object. stringTranscoder.SetTCHAR(lastFilePathName); infoPointer->fullURLString = stringTranscoder.GetUTF8(); // Add the info object to the given collection. listPointer->Append(infoPointer); } } /// <summary> /// <para>Removes menu items that the end-user should not have access to from the given menu.</para> /// <para>For example, the "Build\HTML5" menu item will be removed unless the registry has "ShowWebBuild" set.</para> /// </summary> /// <param name="menuPointer">Pointer to the menu to be scanned for items to be removed. Can be null.</param> void CSimulatorView::RemoveUnauthorizedMenuItemsFrom(CMenu* menuPointer) { // Validate. if (!menuPointer) { return; } // Fetch a pointer to the main application object. CSimulatorApp *applicationPointer = (CSimulatorApp*)AfxGetApp(); if (!applicationPointer) { return; } // Traverse the menu hierarchy for key menu items that should be removed, depending on the user's access level. // Note: We must iterate backwards since the below deletes menu items by index. for (int menuItemIndex = menuPointer->GetMenuItemCount() - 1; menuItemIndex >= 0; menuItemIndex--) { // If the next menu item is a submenu, then traverse its submenu items recursively. auto subMenuPointer = menuPointer->GetSubMenu(menuItemIndex); if (subMenuPointer) { // Traverse the submenu's items. RemoveUnauthorizedMenuItemsFrom(subMenuPointer); // If the submenu no longer contains any menu items, then remove the submenu. if (subMenuPointer->GetMenuItemCount() <= 0) { menuPointer->DeleteMenu(menuItemIndex, MF_BYPOSITION); continue; } } // Remove this menu item if the user does not have access. auto menuItemId = menuPointer->GetMenuItemID(menuItemIndex); if (menuItemId >= 0) { bool shouldRemove = false; switch (menuItemId) { case ID_BUILD_FOR_NXS: shouldRemove = ! applicationPointer->ShouldShowNXBuildDlg(); break; case ID_BUILD_FOR_LINUX: shouldRemove = ! applicationPointer->ShouldShowLinuxBuildDlg(); break; } if (shouldRemove) { menuPointer->DeleteMenu(menuItemIndex, MF_BYPOSITION); } } } } // DegressToRFType - Convert rotation in degress to RotateFlipType Gdiplus::RotateFlipType DegreesToRFType( int rotation ) { switch (rotation) { case 0: return Gdiplus::RotateNoneFlipNone; case 90: return Gdiplus::Rotate90FlipNone; case 180: return Gdiplus::Rotate180FlipNone; case 270: return Gdiplus::Rotate270FlipNone; } return Gdiplus::RotateNoneFlipNone; } #pragma endregion #pragma region CCoronaControlContainer Class int CSimulatorView::CCoronaControlContainer::OnCreate(LPCREATESTRUCT lpCreateStruct) { // Call the base class' method first. int result = CStatic::OnCreate(lpCreateStruct); if (-1 == result) { return -1; } // This center aligns this control's "Suspended" text horizontally and vertically. ModifyStyle(WS_TABSTOP, SS_CENTER | SS_CENTERIMAGE); // Create the Corona control. RECT bounds; bounds.top = 0; bounds.left = 0; bounds.bottom = lpCreateStruct->cy; bounds.right = lpCreateStruct->cx; mCoronaControl.Create( nullptr, WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, bounds, this, 1); mCoronaControl.SetFocus(); return 0; } HBRUSH CSimulatorView::CCoronaControlContainer::CtlColor(CDC* pDC, UINT nCtlColor) { pDC->SetTextColor(RGB(255, 255, 255)); pDC->SetBkMode(OPAQUE); pDC->SetBkColor(RGB(0, 0, 0)); return (HBRUSH)GetStockObject(BLACK_BRUSH); } void CSimulatorView::CCoronaControlContainer::OnSize(UINT nType, int cx, int cy) { // Resize the Corona control to match the new size of this container control mCoronaControl.SetWindowPos(nullptr, 0, 0, cx, cy, SWP_NOZORDER | SWP_NOMOVE); } CWnd& CSimulatorView::CCoronaControlContainer::GetCoronaControl() { return mCoronaControl; } #pragma endregion
31.507815
192
0.733231
[ "render", "object", "solid" ]
41a65a93ddd7578ac6ab2702c5fc981f464acd34
3,898
cpp
C++
modules/lablic/noisetexturegenerator.cpp
ayubatif/inviwo
7cfd00ba2c844983622185b2293848db22a32043
[ "BSD-2-Clause" ]
4
2018-01-21T20:38:47.000Z
2021-01-10T03:16:16.000Z
modules/lablic/noisetexturegenerator.cpp
ayubatif/inviwo
7cfd00ba2c844983622185b2293848db22a32043
[ "BSD-2-Clause" ]
null
null
null
modules/lablic/noisetexturegenerator.cpp
ayubatif/inviwo
7cfd00ba2c844983622185b2293848db22a32043
[ "BSD-2-Clause" ]
19
2018-09-09T19:43:30.000Z
2022-02-01T07:59:30.000Z
/********************************************************************* * Author : Himangshu Saikia * Init : Monday, October 02, 2017 - 13:31:36 * * Project : KTH Inviwo Modules * * License : Follows the Inviwo BSD license model ********************************************************************* */ #include <lablic/noisetexturegenerator.h> #include <labutils/rgbaimage.h> namespace inviwo { // The Class Identifier has to be globally unique. Use a reverse DNS naming scheme const ProcessorInfo NoiseTextureGenerator::processorInfo_{ "org.inviwo.NoiseTextureGenerator", // Class identifier "Noise Texture Generator", // Display name "KTH Labs", // Category CodeState::Experimental, // Code state Tags::None, // Tags }; const ProcessorInfo NoiseTextureGenerator::getProcessorInfo() const { return processorInfo_; } NoiseTextureGenerator::NoiseTextureGenerator() : Processor() , texOut_("texOut") , texSize_("texSize", "Texture Size", vec2(512, 512), vec2(1, 1), vec2(2048, 2048), vec2(1, 1)) // TODO: Register additional properties { // Register ports addPort(texOut_); // Register properties addProperty(texSize_); // TODO: Register additional properties } void NoiseTextureGenerator::process() { // The output of the generation process is an Image // With the given dimensions // With the data format DataVec4UInt8, this means values for RGB-alpha range between 0 and 255 auto outImage = std::make_shared<Image>(size2_t(texSize_.get().x, texSize_.get().y), DataVec4UInt8::get()); // Similar to ScalarField and VectorField, the RGBAImage has some methods to sample from and set // values RGBAImage noiseTexture(outImage); // Setting pixels in the image/texture // setPixelGrayScale will set the value to (val,val,val,255) at the pixel with indices (i,j) int val = 4; noiseTexture.setPixelGrayScale(size2_t(0, 0), val); // setPixel allows to set all color components (red,green,blue,alpha) at the pixel with indices // (i,j) noiseTexture.setPixel(size2_t(0, 0), vec4(val, val, val, 255)); // Reading from the image // readPixelGrayScale returns the averge of the three colors (red+green+blue)/3 at the pixel // with indices (i,j) double value = noiseTexture.readPixelGrayScale(size2_t(0, 0)); // readPixel returns all color components (red,green,blue,alpha) at the pixel with indices (i,j) dvec4 color = noiseTexture.readPixel(size2_t(0, 0)); LogProcessorInfo("The color at index (0,0) is " << color << " with grayscale value " << value << "."); // sample peforms bilinear interpolation. For (0.5,0.5) this would involve the values at pixels // (0,0), (1,0), (0,1), and (1,1) color = noiseTexture.sample(dvec2(0.5, 0.5)); // The grayscale version again does the same but returns an average of the three color values value = noiseTexture.sampleGrayScale(dvec2(0.5, 0.5)); LogProcessorInfo("The interpolated color at (0.5,0.5) is " << color << " with grayscale value " << value << "."); for (int j = 0; j < texSize_.get().y; j++) { for (int i = 0; i < texSize_.get().x; i++) { val = 256 / 2; // TODO: Randomly sample values for the texture, this produces the same gray value for // all pixels // A value within the ouput image is set by specifying pixel position and color noiseTexture.setPixelGrayScale(size2_t(i, j), val); // Alternatively, the entire color can be specified // noiseTexture.setPixel(size2_t(i, j), vec4(val, val, val, 255)); } } texOut_.setData(outImage); } } // namespace inviwo
41.468085
100
0.613391
[ "model" ]
41ae93f2abeb9f59d2051ff67833475e34ddf1e6
6,176
cpp
C++
Viewer/ecflowUI/src/DiagData.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/DiagData.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
Viewer/ecflowUI/src/DiagData.cpp
mpartio/ecflow
ea4b89399d1e7b897ff48c59b1e885e6d53cc8d6
[ "Apache-2.0" ]
null
null
null
//============================================================================ // Copyright 2009- ECMWF. // This software is licensed under the terms of the Apache Licence version 2.0 // which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. // In applying this licence, ECMWF does not waive the privileges and immunities // granted to it by virtue of its status as an intergovernmental organisation // nor does it submit to any jurisdiction. //============================================================================ #include "DiagData.hpp" #include "File_r.hpp" #include "File.hpp" #include "ModelColumn.hpp" #include "NodePath.hpp" #include "ServerHandler.hpp" #include "Str.hpp" #include "UiLog.hpp" #include "UIDebug.hpp" #include "VNode.hpp" #include "VItemPathParser.hpp" #include <QString> #include <QStringList> DiagData* DiagData::instance_=nullptr; DiagDataServerItem::DiagDataServerItem(const std::string& host,const std::string& port, size_t colNum) : host_(host), port_(port) { for(size_t i=0; i < colNum; i++) data_.push_back(std::vector<std::string>()); } const std::string& DiagDataServerItem::dataAt(int row,int column) const { return data_[column][row]; //static std::string emptyStr; //return emptyStr; } int DiagDataServerItem::findRowByPath(const std::string& path) const { for(size_t i=0; i < pathData_.size(); i++) if(pathData_[i] == path) return i; return -1; } bool DiagDataServerItem::checkSizes() const { size_t num=pathData_.size(); for(size_t i=0; i < data_.size(); i++) { if(data_[i].size() != num) return false; } return true; } DiagData::DiagData() = default; DiagData* DiagData::instance() { if(!instance_) instance_=new DiagData(); return instance_; } const std::string& DiagData::columnName(int i) const { if(i >=0 && i < static_cast<int>(columnNames_.size())) return columnNames_[i]; static std::string emptyStr; return emptyStr; } const std::string& DiagData::dataAt(VNode* vn,int column) const { static std::string emptyStr; if(!vn) return emptyStr; if(ServerHandler* sh=vn->server()) { if(DiagDataServerItem *d=findServerData(sh->host(),sh->port())) { int row=d->findRowByPath(vn->absNodePath()); if(row > -1) return d->dataAt(row,column); } } return emptyStr; } DiagDataServerItem* DiagData::findServerData(const std::string& host,const std::string& port) const { if(host.empty() || port.empty()) return nullptr; for(size_t i=0; i < serverData_.size(); i++) { if(serverData_[i]->host_ == host && serverData_[i]->port_ == port) return serverData_[i]; } return nullptr; } void DiagData::clear() { fileName_.clear(); columnNames_.clear(); for(size_t i=0; i < serverData_.size(); i++) { delete serverData_[i]; } serverData_.clear(); } void DiagData::load() { if(const char *df=getenv("ECFLOWUI_DIAG_FILE")) loadFile(std::string(df)); } void DiagData::loadFile(const std::string& fileName) { clear(); fileName_=fileName; /// The log file can be massive > 50Mb ecf::File_r diag_file(fileName_); if( !diag_file.ok() ) { UiLog().warn() << "DiagData::loadFile: Could not open diagnostics file " + fileName; return; } std::string line; //The first line is the header diag_file.getline(line); // default delimiter is /n //No header, no diag data can be read if(line.empty()) return; QString headerLine=QString::fromStdString(line); if(headerLine.startsWith("#")) headerLine=headerLine.mid(1); QStringList headerLst=headerLine.split(","); int pathColumnIndex=-1; for(int i=0; i < headerLst.count(); i++) { if(headerLst[i].compare("path",Qt::CaseInsensitive) == 0) pathColumnIndex=i; else columnNames_.push_back(headerLst[i].toStdString()); } if(pathColumnIndex == -1) { UiLog().warn() << "DiagData::loadFile: could not find node path column in file. Diagnostics cannot be loaded!"; return; } while ( diag_file.good() ) { diag_file.getline(line); // default delimiter is /n if(line.size() <= 1) continue; if(line[0] == '#') line=line.substr(1); //split by comma QStringList lst=QString::fromStdString(line).split(","); //When number of items does not match expected number we skip the line if(lst.count() != static_cast<int>(columnNames_.size()) + 1) continue; std::string path=lst[pathColumnIndex].toStdString(); std::string host, port; DiagDataServerItem* data=nullptr; VItemPathParser parser(path,VItemPathParser::DiagFormat); if(parser.itemType() != VItemPathParser::NoType) { data=findServerData(parser.host(),parser.port()); if(!data) { data=new DiagDataServerItem(parser.host(),parser.port(),columnNames_.size()); serverData_.push_back(data); } } else { continue; } data->pathData_.push_back(parser.node()); assert(data->data_.size() == columnNames_.size()); for(int i=0; i < lst.count(); i++) { QString val=lst[i]; #if 0 QStringList vals=lst[i].split(":"); QString val=lst[i]; if(vals.count() == 2) columnData_[i].push_back(vals[1].toStdString()); else columnData_[i].push_back(lst[i].toStdString()); #endif int idx=i; if(idx > pathColumnIndex) idx--; if(i != pathColumnIndex) data->data_[idx].push_back(val.toStdString()); } } updateTableModelColumn(); } void DiagData::updateTableModelColumn() { if(ModelColumn* mc=ModelColumn::def("table_columns")) { mc->setDiagData(this); } }
25.004049
119
0.583711
[ "vector" ]
41b160b7fa3d454a3288bdadcb63e3691b8f5617
544
cpp
C++
test/fcntl/iostream/sstram.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
1
2020-10-01T14:52:45.000Z
2020-10-01T14:52:45.000Z
test/fcntl/iostream/sstram.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
3
2020-06-19T01:24:51.000Z
2020-07-16T14:00:30.000Z
test/fcntl/iostream/sstram.cpp
6923403/C
d365021759e6d9078254b4b7b6455e0408e4b691
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <sstream> #include <vector> #include <string> using namespace std; void test1() { vector<string> ss; ifstream in; in.open("1.txt"); if(in) { string line; while(getline(in, line)) { ss.push_back(line); } } for(int i = 0; i < ss.size(); ++i) { istringstream iss(ss[i]) ; string word; while(iss >> word) { cout << word << endl; } } } int main() { test1(); }
13.948718
38
0.472426
[ "vector" ]
41b31b5548ae0d0d20239d9f6c912aa0592e19e3
12,645
cpp
C++
src/keymap.cpp
totalgee/zep
b128e5ba1c3ad00dffc857db686e531b4360863f
[ "MIT" ]
225
2020-09-16T09:19:39.000Z
2022-03-31T12:45:06.000Z
src/keymap.cpp
totalgee/zep
b128e5ba1c3ad00dffc857db686e531b4360863f
[ "MIT" ]
22
2020-09-23T18:45:53.000Z
2022-03-05T09:15:52.000Z
src/keymap.cpp
totalgee/zep
b128e5ba1c3ad00dffc857db686e531b4360863f
[ "MIT" ]
20
2020-10-05T11:20:03.000Z
2022-01-24T13:27:56.000Z
#include <cassert> #include <regex> #include "zep/keymap.h" #include "zep/mode.h" #include "zep/mcommon/logger.h" namespace Zep { // Keyboard mapping strings such as <PageDown> get converted here ExtKeys::Key MapStringToExKey(const std::string& str) { #define COMPARE(a, b) \ if (string_tolower(str) == #a) \ return b; COMPARE(return, ExtKeys::RETURN) COMPARE(escape, ExtKeys::ESCAPE) COMPARE(backspace, ExtKeys::BACKSPACE) COMPARE(left, ExtKeys::LEFT) COMPARE(right, ExtKeys::RIGHT) COMPARE(up, ExtKeys::UP) COMPARE(down, ExtKeys::DOWN) COMPARE(tab, ExtKeys::TAB) COMPARE(del, ExtKeys::DEL) COMPARE(home, ExtKeys::HOME) COMPARE(end, ExtKeys::END) COMPARE(pagedown, ExtKeys::PAGEDOWN) COMPARE(pageup, ExtKeys::PAGEUP) COMPARE(f1, ExtKeys::F1) COMPARE(f2, ExtKeys::F2) COMPARE(f3, ExtKeys::F3) COMPARE(f4, ExtKeys::F4) COMPARE(f5, ExtKeys::F5) COMPARE(f6, ExtKeys::F6) COMPARE(f7, ExtKeys::F7) COMPARE(f8, ExtKeys::F8) COMPARE(f9, ExtKeys::F9) COMPARE(f10, ExtKeys::F10) COMPARE(f11, ExtKeys::F11) COMPARE(f12, ExtKeys::F12) return ExtKeys::NONE; } // Keyboard mapping strings such as <PageDown> get converted here std::string keymap_string(const std::string& str) { return str; } // Splitting the input into groups of <> or ch std::string NextToken(std::string::const_iterator& itrChar, std::string::const_iterator itrEnd) { std::ostringstream str; // Find a group if (*itrChar == '<') { itrChar++; auto itrStart = itrChar; // Walk the group, ensuring we consistently output (C-)(S-)foo while (itrChar != itrEnd && *itrChar != '>') { itrChar++; } // Ensure <C-S- or variants, ie. capitalize for consistency if the mapping // was badly supplied auto strGroup = std::string(itrStart, itrChar); string_replace_in_place(strGroup, "c-", "C-"); string_replace_in_place(strGroup, "s-", "S-"); // Skip to the next if (itrChar != itrEnd) itrChar++; str << "<" << strGroup << ">"; } else { str << *itrChar++; } // Return the converted string return str.str(); } /* static bool ends_with(const std::string& str, const std::string& suffix) { return str.size() >= suffix.size() && 0 == str.compare(str.size() - suffix.size(), suffix.size(), suffix); } static bool starts_with(const std::string& str, const std::string& prefix) { return str.size() >= prefix.size() && 0 == str.compare(0, prefix.size(), prefix); } */ // Add a collection of commands to a collection of mappings bool keymap_add(const std::vector<KeyMap*>& maps, const std::vector<std::string>& commands, const StringId& commandId, KeyMapAdd option) { bool ret = true; for (auto& map : maps) { for (auto& cmd : commands) { if (!keymap_add(*map, cmd, commandId, option)) ret = false; } } return ret; } bool keymap_add(KeyMap& map, const std::string& strCommand, const StringId& commandId, KeyMapAdd option) { auto spCurrent = map.spRoot; std::ostringstream str; auto itrChar = strCommand.begin(); while (itrChar != strCommand.end()) { auto search = NextToken(itrChar, strCommand.end()); auto itrRoot = spCurrent->children.find(search); if (itrRoot == spCurrent->children.end()) { auto spNode = std::make_shared<CommandNode>(); spNode->token = search; spCurrent->children[search] = spNode; spCurrent = spNode; } else { spCurrent = itrRoot->second; } } if (spCurrent->commandId != 0 && option == KeyMapAdd::New) { assert(!"Adding twice?"); return false; } spCurrent->commandId = commandId; return true; } void keymap_dump(const KeyMap& map, std::ostringstream& str) { std::function<void(std::shared_ptr<CommandNode>, int)> fnDump; fnDump = [&](std::shared_ptr<CommandNode> node, int depth) { for (int i = 0; i < depth; i++) { str << " "; } str << node->token; if (node->commandId != 0) str << " : " << node->commandId.ToString(); str << std::endl; for (auto& child : node->children) { fnDump(child.second, depth + 2); } }; fnDump(map.spRoot, 0); } // std::isdigit asserts on unicode characters! bool isDigit(const char ch) { if (ch >= '0' && ch <= '9') { return true; } return false; } // Walk the tree of tokens, figuring out which command this is // Input to this function: // <C-x>fgh // i.e. Keyboard mappings are fed in as <> strings. void keymap_find(const KeyMap& map, const std::string& strCommand, KeyMapResult& findResult) { auto consumeDigits = [](std::shared_ptr<CommandNode>& spNode, std::string::const_iterator& itrChar, std::string::const_iterator itrEnd, std::vector<int>& result, std::ostringstream& str) { if (spNode->token == "<D>") { // Walk along grabbing digits auto itrStart = itrChar; while (itrChar != itrEnd && isDigit(*itrChar)) { itrChar++; } if (itrStart != itrChar) { auto token = std::string(itrStart, itrChar); try { // Grab the data, but continue to search for the next token result.push_back(std::stoi(token)); str << "(D:" << token << ")"; } catch (std::exception& ex) { ZEP_UNUSED(ex); ZLOG(DBG, ex.what()); } return true; } } return false; }; auto consumeChar = [](std::shared_ptr<CommandNode>& spNode, std::string::const_iterator& itrChar, std::string::const_iterator itrEnd, std::vector<char>& chars, std::ostringstream& str) { if (spNode->token == "<.>") { // Special match groups if (itrChar != itrEnd) { chars.push_back(*itrChar); str << "(." << *itrChar << ")"; itrChar++; return true; } } return false; }; auto consumeRegister = [](std::shared_ptr<CommandNode>& spNode, std::string::const_iterator& itrChar, std::string::const_iterator itrEnd, std::vector<char>& registers, std::ostringstream& str) { if (spNode->token == "<R>") { // Grab register if (itrChar != itrEnd && *itrChar == '"') { itrChar++; if (itrChar != itrEnd) { registers.push_back(*itrChar); str << "(\"" << *itrChar << ")"; itrChar++; } return true; } } return false; }; struct Captures { std::vector<int> captureNumbers; std::vector<char> captureChars; std::vector<char> captureRegisters; }; std::function<bool(std::shared_ptr<CommandNode>, std::string::const_iterator, std::string::const_iterator, const Captures& captures, KeyMapResult&)> fnSearch; fnSearch = [&](std::shared_ptr<CommandNode> spNode, std::string::const_iterator itrChar, std::string::const_iterator itrEnd, const Captures& captures, KeyMapResult& result) { for (auto& child : spNode->children) { auto spChildNode = child.second; std::string::const_iterator itr = itrChar; Captures nodeCaptures; std::ostringstream strCaptures; std::string token; // Consume wildcards if (consumeDigits(spChildNode, itr, itrEnd, nodeCaptures.captureNumbers, strCaptures)) { token = spChildNode->token; } else if (consumeRegister(spChildNode, itr, itrEnd, nodeCaptures.captureRegisters, strCaptures)) { token = spChildNode->token; } else if (consumeChar(spChildNode, itr, itrEnd, nodeCaptures.captureChars, strCaptures)) { token = spChildNode->token; } else { // Grab full <C-> tokens token = string_slurp_if(itr, itrEnd, '<', '>'); if (token.empty() && itr != itrEnd) { // ... or next char token = std::string(itr, itr + 1); string_eat_char(itr, itrEnd); } } if (token.empty() && child.second->commandId == StringId() && !spChildNode->children.empty()) { result.searchPath += "(...)"; result.needMoreChars = true; continue; } // We found a matching token or wildcard token at this level if (child.first == token) { // Remember what we found result.searchPath += strCaptures.str() + "(" + token + ")"; // Remember if this is a valid match for something result.foundMapping = spChildNode->commandId; // Append our capture groups to the current hierarchy level nodeCaptures.captureChars.insert(nodeCaptures.captureChars.end(), captures.captureChars.begin(), captures.captureChars.end()); nodeCaptures.captureNumbers.insert(nodeCaptures.captureNumbers.end(), captures.captureNumbers.begin(), captures.captureNumbers.end()); nodeCaptures.captureRegisters.insert(nodeCaptures.captureRegisters.end(), captures.captureRegisters.begin(), captures.captureRegisters.end()); // This node doesn't have a mapping, so look harder if (result.foundMapping == StringId()) { // There are more children, and we haven't got any more characters, keep asking for more if (!spChildNode->children.empty() && itr == itrEnd) { result.needMoreChars = true; } else { // Walk down to the next level if (fnSearch(spChildNode, itr, itrEnd, nodeCaptures, result)) return true; } } else { // This is the find result, note it and record the capture groups for the find result.searchPath += " : " + spChildNode->commandId.ToString(); result.captureChars = nodeCaptures.captureChars; result.captureNumbers = nodeCaptures.captureNumbers; result.captureRegisters = nodeCaptures.captureRegisters; result.needMoreChars = false; return true; } } }; // Searched and found nothing in this level return false; }; // fnSearch findResult.needMoreChars = false; Captures captures; bool found = fnSearch(map.spRoot, strCommand.begin(), strCommand.end(), captures, findResult); if (!found) { if (findResult.needMoreChars) { findResult.searchPath += "(...)"; } else { // Special case where the user typed a j followed by _not_ a k. // Return it as an insert command if (strCommand.size() == 2 && strCommand[0] == 'j') { findResult.needMoreChars = false; findResult.commandWithoutGroups = strCommand; findResult.searchPath += "(j.)"; } else { findResult.searchPath += "(Unknown)"; // Didn't find anything, return sanitized text for possible input auto itr = strCommand.begin(); auto token = string_slurp_if(itr, strCommand.end(), '<', '>'); if (token.empty()) { token = strCommand; } findResult.commandWithoutGroups = token; } } } //ZLOG(DBG, strCommand << " - " << findResult.searchPath); } } // namespace Zep
32.175573
198
0.533729
[ "vector" ]
41c0dfd188c479d813a782b32d660cfa72711a97
2,761
cpp
C++
leetcode/cpp/329.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
null
null
null
leetcode/cpp/329.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
null
null
null
leetcode/cpp/329.cpp
xpharry/leetcode_and_lintcode_battle
a06d966ad45bdbed6dda51cf0b480592fc4000d6
[ "MIT" ]
2
2020-09-29T21:59:43.000Z
2021-06-22T13:24:04.000Z
/* * DFS + DP * */ class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return 0; int res = 1, m = matrix.size(), n = matrix[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); // the longest length of the increasing array starting from i, j // dfs for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { res = max(res, dfs(matrix, dp, i, j)); } } return res; } int dfs(vector<vector<int>>& matrix, vector<vector<int>>& dp, int i, int j) { if(dp[i][j] > 0) return dp[i][j]; dp[i][j] = 1; int m = matrix.size(), n = matrix[0].size(); int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}}; for(int k = 0; k < 4; k++) { int x = i + dirs[k][0]; int y = j + dirs[k][1]; if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) { dp[i][j] = max(dp[i][j], 1+dfs(matrix, dp, x, y)); } } return dp[i][j]; } }; // Conclusion: // /* * BFS + DP * */ class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { if(matrix.empty() || matrix[0].empty()) return 0; int res = 1, m = matrix.size(), n = matrix[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); vector<vector<int>> dirs = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; for(int i = 0; i < m; i++) { for(int j = 0; j < n; j++) { if(dp[i][j]) continue; // bfs queue<pair<int, int>> q; q.push({i, j}); int level = 1; while(!q.empty()) { level++; int sz = q.size(); for(int k = 0; k < sz; k++) { auto cur = q.front(); q.pop(); for(int l = 0; l < 4; l++) { int x = cur.first + dirs[l][0]; int y = cur.second + dirs[l][1]; if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[cur.first][cur.second] && level > dp[x][y]) { dp[x][y] = level; res = max(res, level); q.push({x, y}); } } } } } } return res; } }; // Conclusion: //
29.688172
118
0.342992
[ "vector" ]
41c25e8eb8f336af6d4a670bc32e84b92ae27259
5,439
cpp
C++
src/impl/integrator/mlt.cpp
adruomnfd/pine
f7ed06f40a6025f4b479bfb4002242a6f9655430
[ "MIT" ]
1
2022-01-17T09:20:13.000Z
2022-01-17T09:20:13.000Z
src/impl/integrator/mlt.cpp
adruomnfd/pine
f7ed06f40a6025f4b479bfb4002242a6f9655430
[ "MIT" ]
1
2022-03-08T15:42:47.000Z
2022-03-12T11:12:16.000Z
src/impl/integrator/mlt.cpp
adruomnfd/pine
f7ed06f40a6025f4b479bfb4002242a6f9655430
[ "MIT" ]
null
null
null
#include <impl/integrator/mlt.h> #include <impl/integrator/path.h> #include <impl/integrator/bdpt.h> #include <impl/integrator/randomwalk.h> #include <core/scene.h> #include <pstd/tuple.h> namespace pine { MltIntegrator::MltIntegrator(const Parameters& params, Scene* scene) : Integrator(params, scene) { pstd::string baseMethod = params.GetString("baseMethod", "path"); SWITCH(baseMethod) { CASE("path") integrator = pstd::make_unique<PathIntegrator>(params, scene); CASE("bdpt") bdpt = pstd::make_unique<BDPTIntegrator>(params, scene); CASE("randomwalk") integrator = pstd::make_unique<RandomWalkIntegrator>(params, scene); DEFAULT { LOG_FATAL("[MltIntegrator]Unsupported base method &", baseMethod); integrator = pstd::make_unique<PathIntegrator>(params, scene); } } nMutations = (int64_t)Area(filmSize) * params.GetInt("mutationsPerPixel", samplesPerPixel); sigma = params.GetFloat("sigma", 0.01f); largeStepProbability = params.GetFloat("largeStepProbability", 0.3f); } static const int cameraStreamIndex = 0; static const int lightStreamIndex = 1; static const int connectionStreamIndex = 2; static const int nSampleStreams = 3; Spectrum MltIntegrator::L(Sampler& sampler, int depth, vec2& pFilm) { sampler.Be<MltSampler>().StartStream(cameraStreamIndex); int s, t, nStrategies; if (depth == 0) { nStrategies = 1; s = 0; t = 2; } else { nStrategies = depth + 2; s = sampler.Get1D() * nStrategies; t = nStrategies - s; } Vertex* cameraVertices = &bdpt->cameraVertices[threadIdx][0]; Vertex* lightVertices = &bdpt->lightVertices[threadIdx][0]; pFilm = sampler.Get2D(); if (GenerateCameraSubpath(scene, *bdpt, sampler, t, pFilm, cameraVertices) != t) return Spectrum(0.0f); sampler.Be<MltSampler>().StartStream(lightStreamIndex); if (GenerateLightSubpath(scene, *bdpt, sampler, s, lightVertices) != s) return Spectrum(0.0f); sampler.Be<MltSampler>().StartStream(connectionStreamIndex); return ConnectBDPT(*bdpt, lightVertices, cameraVertices, s, t, scene->camera, sampler, pFilm) * nStrategies; } void MltIntegrator::Render() { int64_t nMarkovChains = NumThreads() * 32; int64_t nMutationsPerChain = pstd::max(nMutations / nMarkovChains, 1l); int64_t nBootstrapSamples = nMutations / 32; ProgressReporter pr("Rendering", "MarkovChains", "Mutations", nMarkovChains, nMutationsPerChain); Timer timer; AtomicFloat atomicI; ParallelFor(nBootstrapSamples, [&](int index) { if (bdpt) { for (int depth = 0; depth < bdpt->maxDepth; depth++) { Sampler sampler = MltSampler(sigma, largeStepProbability, nSampleStreams, index * bdpt->maxDepth + depth); vec2 pFilm; Spectrum l = MltIntegrator::L(sampler, depth, pFilm); if (!l.HasInfs() && !l.HasNaNs()) atomicI.Add(l.y()); } } else { Sampler sampler = UniformSampler(1, index); vec2 pFilm = sampler.Get2D(); Ray ray = scene->camera.GenRay(pFilm, sampler.Get2D()); atomicI.Add(integrator->Li(ray, sampler).y()); } }); float I = (float)atomicI / nBootstrapSamples; ParallelFor(nMarkovChains, [&](int chainIndex) { ScopedPR(pr, chainIndex, chainIndex == nMarkovChains - 1, threadIdx == 0); RNG rng(chainIndex); Sampler sampler = MltSampler(sigma, largeStepProbability, bdpt ? nSampleStreams : 1, chainIndex); auto L = [&]() -> pstd::pair<vec2, Spectrum> { if (bdpt) { vec2 pFilm; Spectrum l = MltIntegrator::L(sampler, rng.Uniformf() * bdpt->maxDepth, pFilm); return {pFilm, l}; } else { vec2 pFilm = sampler.Get2D(); Ray ray = scene->camera.GenRay(pFilm, sampler.Get2D()); return {pFilm, integrator->Li(ray, sampler)}; } }; auto [pFilmCurrent, Lcurrent] = L(); for (int m = 0; m < nMutationsPerChain; m++) { sampler.StartNextSample(); auto [pFilmProposed, Lproposed] = L(); float pAccept = pstd::clamp(Lproposed.y() / Lcurrent.y(), 0.0f, 1.0f); if (Lcurrent.HasInfs() || Lcurrent.HasNaNs()) pAccept = 1.0f; float pdfCurrent = Lcurrent.y() / I; float pdfProposed = Lproposed.y() / I; Spectrum wCurrent = (1.0f - pAccept) * Lcurrent * SafeRcp(pdfCurrent); Spectrum wProposed = pAccept * Lproposed * SafeRcp(pdfProposed); if (!wCurrent.HasInfs() && !wCurrent.HasNaNs()) film->AddSplat(pFilmCurrent, wCurrent); if (!wProposed.HasInfs() && !wProposed.HasNaNs()) film->AddSplat(pFilmProposed, wProposed); if (rng.Uniformf() < pAccept) { pFilmCurrent = pFilmProposed; Lcurrent = Lproposed; sampler.Be<MltSampler>().Accept(); } else { sampler.Be<MltSampler>().Reject(); } } }); double dA = 1.0f / Area(filmSize); double N = nMutations; film->Finalize(1.0 / dA / N); } } // namespace pine
37.770833
99
0.593675
[ "render" ]
41c663673abe81f62e4b02dedc529c2f3965a090
4,452
cpp
C++
src/ros/DataManagementRos.cpp
robotics-upo/upo_nav_irl
cdb2d3fd539d0634401f9d23a48bd5a282dfc8d8
[ "BSD-3-Clause" ]
10
2018-05-10T14:14:29.000Z
2022-03-24T12:54:27.000Z
src/ros/DataManagementRos.cpp
wuyou33/upo_nav_irl
cdb2d3fd539d0634401f9d23a48bd5a282dfc8d8
[ "BSD-3-Clause" ]
1
2018-06-14T13:49:52.000Z
2018-06-15T08:37:10.000Z
src/ros/DataManagementRos.cpp
wuyou33/upo_nav_irl
cdb2d3fd539d0634401f9d23a48bd5a282dfc8d8
[ "BSD-3-Clause" ]
7
2018-09-16T10:56:42.000Z
2019-08-04T06:53:54.000Z
#include <upo_nav_irl/ros/DataManagementRos.h> upo_irl_ros::DataManagementRos::DataManagementRos(string dir) { data_dir_ = dir; } upo_irl_ros::DataManagementRos::~DataManagementRos() { } bool upo_irl_ros::DataManagementRos::loadData() { printf("\nReading demonstration bags...\n\n"); // we check if the directory is valid boost::filesystem::path my_path(data_dir_.c_str()); if(!boost::filesystem::exists(my_path) || !boost::filesystem::is_directory(my_path)) { ROS_ERROR("ERROR. Directory '%s' of demonstration samples does not exists or is not a directory", data_dir_.c_str()); return false; }else if(boost::filesystem::is_empty(my_path)) { ROS_ERROR("ERROR. Directory of demonstration samples is empty."); return false; } //The directory should contain bag files with trajectories. int ntrajs = 0; boost::filesystem::directory_iterator it_end; for(boost::filesystem::directory_iterator it_sc(my_path); it_sc != it_end; it_sc++ ) ntrajs++; printf("Trajectories detected: %u\n", ntrajs); ntrajs = 1; try{ // Get the files in the main directory boost::filesystem::directory_iterator end_it; for(boost::filesystem::directory_iterator it_files(my_path); it_files != end_it; it_files++ ) { trajectory_t trajectory; if( boost::filesystem::is_regular_file(it_files->status())) { printf("Loading trajectory %u. File name: %s\n", ntrajs, it_files->path().filename().c_str()); std::string direc_bag = string(it_files->path().c_str()); //ros::package::getPath("navigation_experiments") rosbag::Bag bag; try { bag.open(direc_bag, rosbag::bagmode::Read); } catch (rosbag::BagException& ex) { ROS_ERROR("Error opening bag file %s : %s", it_files->path().filename().c_str(), ex.what()); return false; } std::vector<std::string> topics; topics.push_back(std::string("robot")); topics.push_back(std::string("people")); topics.push_back(std::string("goal")); topics.push_back(std::string("obstacles")); topics.push_back(std::string("vels")); topics.push_back(std::string("robot_map")); rosbag::View view(bag, rosbag::TopicQuery(topics)); foreach(rosbag::MessageInstance const m, view) { if(m.getTopic()=="robot"){ geometry_msgs::PoseStamped::Ptr robo= m.instantiate<geometry_msgs::PoseStamped>(); trajectory.robot_data.push_back(*robo.get()); } else if(m.getTopic()=="people"){ upo_msgs::PersonPoseArrayUPO::Ptr ppl = m.instantiate<upo_msgs::PersonPoseArrayUPO>(); trajectory.people_data.push_back(*ppl.get()); } else if (m.getTopic()=="goal"){ geometry_msgs::PoseStamped::Ptr gol = m.instantiate<geometry_msgs::PoseStamped>(); trajectory.goal_data.push_back(*gol.get()); } else if (m.getTopic()=="obstacles"){ sensor_msgs::PointCloud2::Ptr obs = m.instantiate<sensor_msgs::PointCloud2>(); trajectory.obs_data.push_back(*obs.get()); } else if (m.getTopic()=="vels"){ geometry_msgs::Twist::Ptr vel = m.instantiate<geometry_msgs::Twist>(); trajectory.vel_data.push_back(*vel.get()); } else if (m.getTopic()=="robot_map"){ geometry_msgs::PoseStamped::Ptr rm = m.instantiate<geometry_msgs::PoseStamped>(); trajectory.robot_map_data.push_back(*rm.get()); } } bag.close(); ntrajs++; dataset_.push_back(trajectory); } else { ROS_ERROR("File %s, is not a regular file", it_files->path().filename().c_str()); return false; } } //end of the for loop demonstration files } catch(const boost::filesystem::filesystem_error& ex){ std::cout << "ERROR opening demonstrations files: " << ex.what() << '\n'; return false; } data_size_ = (int)dataset_.size(); return true; } geometry_msgs::PoseStamped upo_irl_ros::DataManagementRos::mapDataExists(int i) { geometry_msgs::PoseStamped p; p.header.frame_id = "map"; p.header.stamp = ros::Time::now(); p.pose.position.z = 0.0; if(dataset_[i].robot_map_data.empty()) { p.pose.position.x = 0.0; p.pose.position.y = 0.0; p.pose.orientation = tf::createQuaternionMsgFromYaw(0.0); }else { p.pose.position = dataset_[i].robot_map_data[0].pose.position; p.pose.orientation = dataset_[i].robot_map_data[0].pose.orientation; } return p; } geometry_msgs::PoseStamped upo_irl_ros::DataManagementRos::getRobotPose(int i) { return dataset_[i].robot_data[0]; }
30.493151
119
0.676325
[ "vector" ]
41c7e68c15a4e1b26afa9589073a5d2b0bcb4685
11,688
cc
C++
RAVL2/Math/Geometry/Euclidean/3D/Affine3d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/3D/Affine3d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Math/Geometry/Euclidean/3D/Affine3d.cc
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
// This file is part of RAVL, Recognition And Vision Library // Copyright (C) 2007, OmniPerception Ltd. // This code may be redistributed under the terms of the GNU Lesser // General Public License (LGPL). See the lgpl.licence file for details or // see http://www.gnu.org/copyleft/lesser.html // file-header-ends-here //! author="Charles Galambos" //! date="17/3/2007" //! docentry="Ravl.API.Math.Geometry.3D" #include "Ravl/Affine3d.hh" #include "Ravl/Matrix.hh" #include "Ravl/Vector.hh" #include "Ravl/Point2d.hh" #include "Ravl/Point3d.hh" #include "Ravl/SArray1dIter2.hh" #include "Ravl/LeastSquares.hh" #include "Ravl/Sums1d2.hh" namespace RavlN { //: Fit an affine transformation Affine3dC FitAffine(const SArray1dC<Point3dC> &org,const SArray1dC<Point3dC> &newPos,RealT &residual) { RavlAssertMsg(org.Size() == newPos.Size(),"Affine3dC FitAffine(), Point arrays must have the same size."); UIntT samples = org.Size(); if ( samples < 4 ) throw ExceptionC("Sample size too small in FitAffine(). "); MatrixC A(samples,4); VectorC b(samples); VectorC c(samples); VectorC d(samples); UIntT i = 0; for(SArray1dIter2C<Point3dC,Point3dC> it(org,newPos);it;it++,i++) { RealT x1, y1, z1, x2, y2, z2; x1=it.Data1()[0]; y1=it.Data1()[1]; z1=it.Data1()[2]; x2=it.Data2()[0]; y2=it.Data2()[1]; z2=it.Data2()[2]; A[i][0] = x1; A[i][1] = y1; A[i][2] = z1; A[i][3] = 1; b[i] = x2; c[i] = y2; d[i] = z2; } MatrixC tA = A.Copy(); MatrixC sA = A.Copy(); if(A.Rows() == A.Cols()) { // solve for solution vector residual = 0; if(!SolveIP(tA,b)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!SolveIP(sA,c)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!SolveIP(A,d)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); } else { if(!LeastSquaresQR_IP(tA,b,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!LeastSquaresQR_IP(sA,c,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!LeastSquaresQR_IP(A,d,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); } Matrix3dC sr(b[0],b[1],b[2], c[0],c[1],c[2], d[0],d[1],d[2]); Vector3dC tr(b[3],c[3],d[3]); return Affine3dC(sr,tr); } //: Fit points on a 2d plane (this assumes the z position is always zero) to a 3d position. Affine3dC FitAffine(const SArray1dC<Point2dC> &org,const SArray1dC<Point3dC> &newPos,RealT &residual) { RavlAssertMsg(org.Size() == newPos.Size(),"Affine3dC FitAffine(), Point arrays must have the same size."); UIntT samples = org.Size(); if ( samples < 3 ) throw ExceptionC("Sample size too small in FitAffine(). "); MatrixC A(samples,3); VectorC b(samples); VectorC c(samples); VectorC d(samples); UIntT i = 0; for(SArray1dIter2C<Point2dC,Point3dC> it(org,newPos);it;it++,i++) { RealT x1, y1, x2, y2, z2; x1=it.Data1()[0]; y1=it.Data1()[1]; x2=it.Data2()[0]; y2=it.Data2()[1]; z2=it.Data2()[2]; A[i][0] = x1; A[i][1] = y1; A[i][2] = 1; b[i] = x2; c[i] = y2; d[i] = z2; } MatrixC tA = A.Copy(); MatrixC sA = A.Copy(); if(A.Rows() == A.Cols()) { // solve for solution vector residual = 0; if(!SolveIP(tA,b)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!SolveIP(sA,c)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!SolveIP(A,d)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); } else { if(!LeastSquaresQR_IP(tA,b,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!LeastSquaresQR_IP(sA,c,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); if(!LeastSquaresQR_IP(A,d,residual)) throw ExceptionNumericalC("Dependent linear equations in FitAffine, 3d "); } Matrix3dC sr(b[0],b[1],0, c[0],c[1],0, d[0],d[1],0); // Fill in values as a rotation into the z axis. for(int i = 0;i < 3;i++) { RealT s = Sqr(sr[i][0]) + Sqr(sr[i][1]); if(s < 1.0) sr[i][2] = Sqrt(1-s); } Vector3dC tr(b[2],c[2],d[2]); return Affine3dC(sr,tr); } //: Fit an affine transformation given some directions and positions. // The transform takes a point and from newPos into dir's Affine3dC FitAffineDirection(const SArray1dC<Point3dC> &points,const SArray1dC<Vector3dC> &directions) { RavlAssert(points.Size() == directions.Size()); // Gather some stats about the 3d points. Sums1d2C sums[3]; for(SArray1dIterC<Point3dC> it(points);it;it++) { for(int i = 0;i < 3;i++) sums[i] += (*it)[i]; } Vector3dC gain; Vector3dC offset; for(int i = 0;i < 3;i++) { offset[i] = sums[i].Mean(); #if 1 RealT var = sums[i].Variance(false); if(IsNan(var) || IsInf(var)) { gain[i] = 1.0; } else gain[i] = 1.0/Sqrt(var); #else gain[i] = 1.0; #endif } // Normalise points and form matrix. MatrixC A(points.Size() * 3,12); // v := {v0,v1,v2}; // q := {q0,q1,q2}; // ar := {{ar00,ar01,a02},{ar10,ar11,ar12},{ar20,ar21,ar22}}; // at := {at0,at1,at2}; // CrossProduct(v,ar * q + at) = 0; // ar00 ar01 ar02 ar10 ar11 ar12 ar20 ar21 ar22 at0 at1 at2 // q -> v UIntT row = 0; for(SArray1dIter2C<Vector3dC,Point3dC> it(directions,points);it;it++) { Point3dC q = (it.Data2() - offset) * gain; Vector3dC v = it.Data1().Unit(); // v1*ar20*q0 +v1*ar21*q1 +v1*ar22*q2 -q2*v2*ar12 -q1*v2*ar11 -q0*v2*ar10 +v1*at2 -v2*at1 { A[row][ 0] = 0; // ar00 A[row][ 1] = 0; // ar01 A[row][ 2] = 0; // ar02 A[row][ 3] = -v[2] * q[0]; // ar10 A[row][ 4] = -v[2] * q[1]; // ar11 A[row][ 5] = -v[2] * q[2]; // ar12 A[row][ 6] = v[1] * q[0]; // ar20 A[row][ 7] = v[1] * q[1]; // ar21 A[row][ 8] = v[1] * q[2]; // ar22 A[row][ 9] = 0; // at0 A[row][10] = -v[2]; // at1 A[row][11] = v[1]; // at2 row++; } //v2*ar00*q0 +v2*ar01*q1 +v2*ar02*q2 -q2*v0*ar22 -q1*v0*ar21 -q0*v0*ar20 +v2*at0 -v0*at2 { A[row][ 0] = v[2] * q[0]; // ar00 A[row][ 1] = v[2] * q[1]; // ar01 A[row][ 2] = v[2] * q[2]; // ar02 A[row][ 3] = 0; // ar10 A[row][ 4] = 0; // ar11 A[row][ 5] = 0; // ar12 A[row][ 6] = -v[0] * q[0]; // ar20 A[row][ 7] = -v[0] * q[1]; // ar21 A[row][ 8] = -v[0] * q[2]; // ar22 A[row][ 9] = v[2]; // at0 A[row][10] = 0; // at1 A[row][11] = -v[0]; // at2 row++; } //v0*ar10*q0 +v0*ar11*q1 +v0*ar12*q2 -q2*v1*ar02 -q1*v1*ar01 -q0*v1*ar00 +v0*at1 -v1*at0 { A[row][ 0] = -v[1] * q[0]; // ar00 A[row][ 1] = -v[1] * q[1]; // ar01 A[row][ 2] = -v[1] * q[2]; // ar02 A[row][ 3] = v[0] * q[0]; // ar10 A[row][ 4] = v[0] * q[1]; // ar11 A[row][ 5] = v[0] * q[2]; // ar12 A[row][ 6] = 0; // ar20 A[row][ 7] = 0; // ar21 A[row][ 8] = 0; // ar22 A[row][ 9] = -v[1]; // at0 A[row][10] = v[0]; // at1 A[row][11] = 0; // at2 row++; } } RavlAssert(row == A.Rows()); VectorC v; LeastSquaresEq0Mag1(A,v); Matrix3dC SR(v[0]*gain[0],v[1]*gain[1],v[2]*gain[2], v[3]*gain[0],v[4]*gain[1],v[5]*gain[2], v[6]*gain[0],v[7]*gain[1],v[8]*gain[2]); Vector3dC T(v[9],v[10],v[11]); // (SR * In) + T; // q = (it.Data2() - offset) * gain; Affine3dC ret; // Is the solution a mirror image of the required one ? if(SR.Det() >= 0) ret = Affine3dC(SR,T - SR * offset); else ret = Affine3dC(SR * -1,(T - SR * offset) * -1); //std::cerr << "Aff=" << ret << " Det=" << ret.SRMatrix().Det() << "\n"; return ret; } //! Fit a rigid transform between the two point sets. // // See 'Least-Squares Estimation of Transformation Parametres Between Two Point Patterns' by // Shinji Umeyama. IEEE Transactions on Pattern Analysis and Machine Intelligence Vol 13, No 4 // April 1991. Page 376 // // TODO: This actually works with any number of dimentions. Generalise code. bool FitSimilarity(const SArray1dC<Point3dC> &points1, const SArray1dC<Point3dC> &points2, Matrix3dC &rotation, Vector3dC &translation, RealT &scale, bool forceUnitScale ) { // Compute the means. RealT n = points1.Size(); Point3dC mean1(0,0,0),mean2(0,0,0); for(SArray1dIter2C<Point3dC,Point3dC> it(points1,points2);it;it++) { mean1 += it.Data1(); mean2 += it.Data2(); } mean1 /= n; mean2 /= n; // Compute the covariance matrix. Matrix3dC covar(0,0,0, 0,0,0, 0,0,0); RealT ps1 = 0,ps2 = 0; for(SArray1dIter2C<Point3dC,Point3dC> it(points1,points2);it;it++) { Point3dC p1 = (it.Data1() - mean1); ps1 += Sqr(p1[0]) + Sqr(p1[1]) + Sqr(p1[2]); Point3dC p2 = (it.Data2() - mean2); ps2 += Sqr(p2[0]) + Sqr(p2[1]) + Sqr(p2[2]); for(int i = 0;i < 3;i++) { covar[i][0] += p1[0] * p2[i]; covar[i][1] += p1[1] * p2[i]; covar[i][2] += p1[2] * p2[i]; } } // Compute the scaling. scale = Sqrt(ps2/ps1); // Compute the rotation from the covariance matrix. covar /= n; Matrix3dC u,v; Vector3dC d = RavlN::SVD_IP(covar,u,v); // TODO :- Make this faster by avoiding use of so many temporaries. Matrix3dC s(1,0,0, 0,1,0, 0,0,1); // Correct mirroring. if((u.Det() * v.Det()) < 0) { s[2][2] = -1; d[2] *= -1; } rotation = u * s * v.T(); // Compute the translation. if(forceUnitScale) { translation = mean2 - rotation * mean1; } else { translation = mean2 - rotation * mean1 * scale; } return true; } //! Fit a rigid transform between the two point sets. //! If 'forceUnitScale' is true then unit scaling will be assumed. bool FitSimilarity(const SArray1dC<Point3dC> &points1, const SArray1dC<Point3dC> &points2, Affine3dC &transform, bool forceUnitScale ) { Matrix3dC rotation; Vector3dC translation; RealT scale; if(!FitSimilarity(points1,points2,rotation,translation,scale,forceUnitScale)) return false; if(forceUnitScale) transform = Affine3dC(rotation,translation); else transform = Affine3dC(rotation * scale,translation); return true; } }
29.892583
110
0.519507
[ "geometry", "vector", "transform", "3d" ]
41c8aaf7c9d2f08ac910b3191ca1de6b55103bd1
1,061
cpp
C++
cpp/scrabble-score/scrabble_score.cpp
RockLloque/Exercism
c437dd6cf3246576900c76c2dba775b6647e3347
[ "MIT" ]
null
null
null
cpp/scrabble-score/scrabble_score.cpp
RockLloque/Exercism
c437dd6cf3246576900c76c2dba775b6647e3347
[ "MIT" ]
null
null
null
cpp/scrabble-score/scrabble_score.cpp
RockLloque/Exercism
c437dd6cf3246576900c76c2dba775b6647e3347
[ "MIT" ]
null
null
null
/* * ===================================================================================== * * Filename: scrabble_score.cpp * * Description: * * Version: 1.0 * Created: 03.11.2015 15:44:52 * Revision: none * Compiler: gcc * * * ===================================================================================== */ #include "scrabble_score.h" #include <array> #include <cctype> /* for std::toupper */ #include <algorithm> /* for std::transform */ #include <map> /* for std::map */ namespace scrabble_score { static const std::map<char, unsigned> scrabbleValues { {'A',1}, {'E',1}, {'I',1}, {'O',1},{'U',1}, {'L',1}, {'N',1}, {'R',1},{'S',1},{'T',1}, {'D',2},{'G',2}, {'B',3},{'C',3},{'M',3}, {'P',3}, {'F',4},{'H',4},{'V',4},{'W',4},{'Y',4}, {'K',5}, {'J', 8}, {'X',8}, {'Q',10}, {'Z',10}}; unsigned score(std::string const& word) { return std::accumulate(word.begin(), word.end(), 0U, [] (unsigned scr, char c){ return scr + scrabbleValues.at(toupper(c));}); } }
24.113636
142
0.410933
[ "transform" ]
41cd86f11edd0a95329e3f0ade13ae57197b83ca
377
cpp
C++
Dataset/Leetcode/train/66/42.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/66/42.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/66/42.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: vector<int> XXX(vector<int>& digits) { for(int i=digits.size()-1;i>=0;i--){ digits[i]+=1; if(digits[i]==10){ digits[i]=0; }else{ return digits; }//end if }//end for digits.insert(digits.begin(),1); return digits; }//end method };
22.176471
44
0.440318
[ "vector" ]
41ceb481e8d4e122a2c46c59cfc6ba48af3d5756
4,083
cpp
C++
TI-PreCompiler/src/main.cpp
TeamIlluminate/TI-PreCompiler
ed8a2291402ffc6051b97d506d350e53f37a9d58
[ "MIT" ]
null
null
null
TI-PreCompiler/src/main.cpp
TeamIlluminate/TI-PreCompiler
ed8a2291402ffc6051b97d506d350e53f37a9d58
[ "MIT" ]
null
null
null
TI-PreCompiler/src/main.cpp
TeamIlluminate/TI-PreCompiler
ed8a2291402ffc6051b97d506d350e53f37a9d58
[ "MIT" ]
null
null
null
#include <iostream> #include <experimental/filesystem> #include <fstream> #include <ostream> #include <list> #include <algorithm> #include <string> namespace fs = std::experimental::filesystem; int main(int, char **) { std::cout << "\n(==|==========> TI-PreCompiler started! <==========(==|\n"; std::cout << "\nLoading serializable vtable...\n"; std::ifstream open; open.open("svtable.tipc"); std::list<std::string> source; std::string line; while (std::getline(open, line)) { source.push_back(line); } open.close(); for (std::string sType : source) { std::cout << "Serializable type: " << sType << '\n'; } std::cout << "\nGenereting serializable vtable...\n"; { fs::recursive_directory_iterator begin("src"); fs::recursive_directory_iterator end; std::vector<fs::path> subdirs; std::copy_if(begin, end, std::back_inserter(subdirs), [](const fs::path &path) { return fs::is_directory(path); }); } fs::recursive_directory_iterator begin("src"); fs::recursive_directory_iterator end; std::vector<fs::path> files; std::copy_if(begin, end, std::back_inserter(files), [](const fs::path &path_) { return fs::is_regular_file(path_) && (path_.extension() == ".h" || path_.extension() == ".cpp"); }); std::list<std::string> s_Types; std::string includes; //Вынес отдельно. В будущем будет юзабилити. std::string attribute = "//[Serializable]"; for (fs::path s_file : files) { std::ifstream sourceType; sourceType.open(s_file); std::string line; while (std::getline(sourceType, line)) { if (line.find(attribute) != std::string::npos) { s_Types.push_back(s_file.filename().replace_extension()); std::string st = s_file.native(); st.replace(0, 4, ""); includes += "#include \"" + st + "\"\n"; } } sourceType.close(); } std::cout << "\nComparing types" << '\n'; bool isGenereted = false; std::list<std::string> genTypes; for (std::string sType : s_Types) { for (std::string lType : source) { if (sType == lType) { std::cout << "Type " << sType << " already genereted!" << '\n'; isGenereted = true; } } if (!isGenereted) { std::cout << "Type: " << sType << " will be genereted!" << '\n'; genTypes.push_back(sType); isGenereted = false; } } std::cout << "\nSaving table..." << '\n'; std::ofstream save; save.open("svtable.tipc"); std::string sTable; for (std::string sType : s_Types) { sTable += sType + '\n'; } save << sTable; save.close(); std::string sTypeGen; for (auto genType : genTypes) { sTypeGen += "Serializable::RegisterComponentConstructor(\"" + genType + "\", []() -> shared_ptr<Component> { return make_shared<" + genType + ">(); });\n"; } std::list<std::string> SerType; SerType.push_back("#include \"Serializable.h\" \n"); SerType.push_back(includes); SerType.push_back("#pragma once\n"); SerType.push_back("namespace eng\n"); SerType.push_back("{\n"); SerType.push_back("class SerializableGenerator\n"); SerType.push_back("{\n"); SerType.push_back("public:\n"); SerType.push_back("SerializableGenerator()\n"); SerType.push_back("{\n"); SerType.push_back("Generate();\n"); SerType.push_back("}\n"); SerType.push_back("private:\n"); SerType.push_back("void Generate(){\n"); SerType.push_back(sTypeGen); SerType.push_back("}\n"); SerType.push_back("};\n"); SerType.push_back("}"); std::ofstream sGen; sGen.open("src/SerializableGenerator.cpp"); for(auto classGen : SerType) sGen << classGen; sGen.close(); std::cout << "\nSerializationGenerator class generated!" << '\n'; }
28.158621
163
0.560372
[ "vector" ]
41cec1536680b6d768006d59c89634b9e8d48588
3,175
cpp
C++
4.16/GameLiftFramework/Source/GameLiftFramework/Private/GameLiftClient.cpp
realityreflection/GameLiftFramework
09120c6d8c27231a76c3ccc9ac96c6faf6af0539
[ "MIT" ]
5
2017-06-14T12:56:43.000Z
2022-02-01T08:31:17.000Z
4.15/GameLiftFramework/Source/GameLiftFramework/Private/GameLiftClient.cpp
realityreflection/GameLiftFramework
09120c6d8c27231a76c3ccc9ac96c6faf6af0539
[ "MIT" ]
null
null
null
4.15/GameLiftFramework/Source/GameLiftFramework/Private/GameLiftClient.cpp
realityreflection/GameLiftFramework
09120c6d8c27231a76c3ccc9ac96c6faf6af0539
[ "MIT" ]
6
2017-06-06T04:40:15.000Z
2020-11-04T03:13:04.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "GameLiftFramework.h" #include "GameLiftClient.h" #include "GameLiftGameInstance.h" Aws::Client::ClientConfiguration UGameLiftClient::GetClientConfig(const char* Region, Aws::Http::Scheme Scheme) const { Aws::Client::ClientConfiguration config; config.scheme = Scheme; config.connectTimeoutMs = 30000; config.requestTimeoutMs = 30000; config.region = Region; if (IsLocalTest) { config.endpointOverride = TCHAR_TO_UTF8(*TestEndpoint); } return config; } void UGameLiftClient::SetUpAwsClient(const char* Region, Aws::Http::Scheme Scheme) { auto config = GetClientConfig(Region, Scheme); auto credential = Aws::Auth::SimpleAWSCredentialsProvider( TCHAR_TO_UTF8(*PublicKey), TCHAR_TO_UTF8(*PrivateKey)).GetAWSCredentials(); GLClient = Aws::MakeShared<Aws::GameLift::GameLiftClient>("GameLiftClient", credential, config); } void UGameLiftClient::CreateGameSession(const FString& RoomName, const FString& Password, int MaxCount) { Aws::GameLift::Model::CreateGameSessionRequest req; req.SetFleetId(TCHAR_TO_UTF8(*AliasId)); req.SetName(TCHAR_TO_UTF8(*RoomName)); req.SetMaximumPlayerSessionCount(MaxCount); auto outcome = GLClient->CreateGameSession(req); if (outcome.IsSuccess()) { auto gs = outcome.GetResult().GetGameSession(); OnCreateGame(gs); } else { auto msg = Aws::Utils::StringUtils::ToWString(outcome.GetError().GetMessage().c_str()); LOG_ERROR("fail : %s", msg.c_str()); } } void UGameLiftClient::OnCreateGame(const Aws::GameLift::Model::GameSession& Session) { } void UGameLiftClient::SearchGameSessions() { Aws::GameLift::Model::SearchGameSessionsRequest req; req.SetAliasId(TCHAR_TO_UTF8(*AliasId)); req.SetFilterExpression("hasAvailablePlayerSessions=true"); auto outcome = GLClient->SearchGameSessions(req); if (outcome.IsSuccess()) { GameSessions.Reset(); auto& games = outcome.GetResult().GetGameSessions(); for (auto& g : games) { if (g.GetCurrentPlayerSessionCount() == 0) continue; GameSessions.Add(g); } OnSearch(); } else { auto msg = Aws::Utils::StringUtils::ToWString(outcome.GetError().GetMessage().c_str()); LOG_ERROR("fail : %s", msg.c_str()); } } void UGameLiftClient::OnSearch() { } void UGameLiftClient::CreatePlayerSession(const Aws::GameLift::Model::GameSession& Session) { Aws::GameLift::Model::CreatePlayerSessionRequest req; req.SetGameSessionId(Session.GetGameSessionId().c_str()); req.SetPlayerId("TestClient"); auto outcome = GLClient->CreatePlayerSession(req); if (outcome.IsSuccess()) { auto& psess = outcome.GetResult().GetPlayerSession(); auto instance = Cast<UGameLiftGameInstance>(UGameplayStatics::GetGameInstance(GetWorld())); if (instance != nullptr) { instance->PlayerSessionId = outcome.GetResult().GetPlayerSession().GetPlayerSessionId().c_str(); } OnCreatePlayer(psess); } else { auto msg = Aws::Utils::StringUtils::ToWString(outcome.GetError().GetMessage().c_str()); LOG_ERROR("fail : %s", msg.c_str()); } } void UGameLiftClient::OnCreatePlayer(const Aws::GameLift::Model::PlayerSession& Session) { }
25
117
0.739213
[ "model" ]
41d39e47511feeec7b12ef8c29e4b3a9e049b8cb
1,663
hpp
C++
src/FrequencyGovernorImp.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/FrequencyGovernorImp.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/FrequencyGovernorImp.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #ifndef FREQUENCYGOVERNORIMP_HPP_INCLUDE #define FREQUENCYGOVERNORIMP_HPP_INCLUDE #include <memory> #include <vector> #include <string> #include "FrequencyGovernor.hpp" namespace geopm { class FrequencyGovernorImp : public FrequencyGovernor { public: FrequencyGovernorImp(); FrequencyGovernorImp(PlatformIO &platform_io, const PlatformTopo &platform_topo); virtual ~FrequencyGovernorImp(); void init_platform_io(void) override; int frequency_domain_type(void) const override; void adjust_platform(const std::vector<double> &frequency_request) override; bool do_write_batch(void) const override; bool set_frequency_bounds(double freq_min, double freq_max) override; double get_frequency_min() const override; double get_frequency_max() const override; double get_frequency_step() const override; void validate_policy(double &freq_min, double &freq_max) const override; private: double get_limit(const std::string &sig_name) const; PlatformIO &m_platform_io; const PlatformTopo &m_platform_topo; const double M_FREQ_STEP; const double M_PLAT_FREQ_MIN; const double M_PLAT_FREQ_MAX; double m_freq_min; double m_freq_max; bool m_do_write_batch; int m_freq_ctl_domain_type; std::vector<int> m_control_idx; std::vector<double> m_last_freq; }; } #endif
33.938776
93
0.664462
[ "vector" ]
41e394386b0112b3dc0656165d7cbd65bd8f7b5a
583
cpp
C++
14. Longest Common Prefix.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
3
2017-02-22T14:28:27.000Z
2017-04-26T16:26:06.000Z
14. Longest Common Prefix.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
null
null
null
14. Longest Common Prefix.cpp
qinenergy/leetCode
79f960795445470a16a4755b05aa05f99e5c616b
[ "MIT" ]
null
null
null
class Solution2 { public: string longestCommonPrefix(vector<string>& strs) { int size = strs.size(); string prefix, pre, pos; if (size == 0) return prefix; if (size == 1) return strs.front(); int i = 1, j = 0, l1 = 0, l2 = 0, l = 0; pre = strs.front(); do { pos = strs[i]; l1 = pre.size(); l2 = pos.size(); l = l1 <= l2 ? l1 : l2; for (j = 0; j < l; ++j) { if (pre[j] == pos[j]) prefix += pre[j]; else break; } ++i; pre = prefix; prefix.clear(); } while (i < size && pre.size() != 0); return pre; } };
20.103448
54
0.487136
[ "vector" ]
41f0a00ad87fc197d83730582e57622ee944748c
30,701
cpp
C++
src/caffe/backend/device_math_functions.cpp
naibaf7/caffe
29960153c828820b1abb55a5792283742f57caa2
[ "Intel", "BSD-2-Clause" ]
89
2015-04-20T01:25:01.000Z
2021-12-07T17:03:28.000Z
src/caffe/backend/device_math_functions.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
62
2015-06-18T13:11:20.000Z
2019-02-19T05:00:10.000Z
src/caffe/backend/device_math_functions.cpp
Miaomz/caffe-opencl
505693d54298b89cf83b54778479087cff2f3bd6
[ "Intel", "BSD-2-Clause" ]
30
2015-07-05T17:08:09.000Z
2022-02-10T13:16:02.000Z
#include "caffe/backend/device_program.hpp" #include "caffe/backend/device.hpp" #include "caffe/util/type_utils.hpp" namespace caffe { void Device::null_kernel(float arg) { shared_ptr<DeviceKernel> kernel = math_programs_[AUX_DATA_INDEX]->GetKernel("caffe_gpu_null_kernel"); kernel->add_arg(&arg); vector<size_t> work_size(1, 1); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } void Device::memset(const uint_tp n, const char alpha, vptr<char> x) { shared_ptr<DeviceKernel> kernel = math_programs_[AUX_DATA_INDEX]->GetKernel("caffe_gpu_memset"); kernel->add_arg(&n); kernel->add_arg(&alpha); kernel->add_arg(&x); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template<typename Dtype> void Device::set(const uint_tp n, const Dtype alpha, vptr<Dtype> x) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()]->GetKernel("caffe_gpu_set"); kernel->add_arg(&n); kernel->add_arg(&alpha); kernel->add_arg(&x); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::set(const uint_tp n, const half_fp alpha, vptr<half_fp> x); template void Device::set(const uint_tp n, const float alpha, vptr<float> x); template void Device::set(const uint_tp n, const double alpha, vptr<double> x); template void Device::set(const uint_tp n, const int8_t alpha, vptr<int8_t> x); template void Device::set(const uint_tp n, const int16_t alpha, vptr<int16_t> x); template void Device::set(const uint_tp n, const int32_t alpha, vptr<int32_t> x); template void Device::set(const uint_tp n, const int64_t alpha, vptr<int64_t> x); template void Device::set(const uint_tp n, const uint8_t alpha, vptr<uint8_t> x); template void Device::set(const uint_tp n, const uint16_t alpha, vptr<uint16_t> x); template void Device::set(const uint_tp n, const uint32_t alpha, vptr<uint32_t> x); template void Device::set(const uint_tp n, const uint64_t alpha, vptr<uint64_t> x); template<typename Dtype> void Device::add_scalar(const uint_tp n, const Dtype alpha, vptr<Dtype> x) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_add_scalar"); kernel->add_arg(&n); kernel->add_arg(&alpha); kernel->add_arg(&x); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::add_scalar(const uint_tp n, const half_fp alpha, vptr<half_fp> x); template void Device::add_scalar(const uint_tp n, const float alpha, vptr<float> x); template void Device::add_scalar(const uint_tp n, const double alpha, vptr<double> x); template void Device::add_scalar(const uint_tp n, const uint8_t alpha, vptr<uint8_t> x); template void Device::add_scalar(const uint_tp n, const uint16_t alpha, vptr<uint16_t> x); template void Device::add_scalar(const uint_tp n, const uint32_t alpha, vptr<uint32_t> x); template void Device::add_scalar(const uint_tp n, const uint64_t alpha, vptr<uint64_t> x); template<typename Dtype> void Device::scal(const uint_tp n, const Dtype alpha, vptr<Dtype> x) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_scal"); kernel->add_arg(&n); kernel->add_arg(&alpha); kernel->add_arg(&x); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::scal(const uint_tp n, const half_fp alpha, vptr<half_fp> x); template void Device::scal(const uint_tp n, const float alpha, vptr<float> x); template void Device::scal(const uint_tp n, const double alpha, vptr<double> x); template void Device::scal(const uint_tp n, const uint8_t alpha, vptr<uint8_t> x); template void Device::scal(const uint_tp n, const uint16_t alpha, vptr<uint16_t> x); template void Device::scal(const uint_tp n, const uint32_t alpha, vptr<uint32_t> x); template void Device::scal(const uint_tp n, const uint64_t alpha, vptr<uint64_t> x); template<typename Dtype> void Device::add(const uint_tp n, vptr<const Dtype> a, vptr<const Dtype> b, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_add"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&b); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::add(const uint_tp n, vptr<const half_fp> a, vptr<const half_fp> b, vptr<half_fp> y); template void Device::add(const uint_tp n, vptr<const float> a, vptr<const float> b, vptr<float> y); template void Device::add(const uint_tp n, vptr<const double> a, vptr<const double> b, vptr<double> y); template void Device::add(const uint_tp n, vptr<const uint8_t> a, vptr<const uint8_t> b, vptr<uint8_t> y); template void Device::add(const uint_tp n, vptr<const uint16_t> a, vptr<const uint16_t> b, vptr<uint16_t> y); template void Device::add(const uint_tp n, vptr<const uint32_t> a, vptr<const uint32_t> b, vptr<uint32_t> y); template void Device::add(const uint_tp n, vptr<const uint64_t> a, vptr<const uint64_t> b, vptr<uint64_t> y); template<typename Dtype> void Device::sub(const uint_tp n, vptr<const Dtype> a, vptr<const Dtype> b, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_sub"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&b); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::sub(const uint_tp n, vptr<const half_fp> a, vptr<const half_fp> b, vptr<half_fp> y); template void Device::sub(const uint_tp n, vptr<const float> a, vptr<const float> b, vptr<float> y); template void Device::sub(const uint_tp n, vptr<const double> a, vptr<const double> b, vptr<double> y); template void Device::sub(const uint_tp n, vptr<const uint8_t> a, vptr<const uint8_t> b, vptr<uint8_t> y); template void Device::sub(const uint_tp n, vptr<const uint16_t> a, vptr<const uint16_t> b, vptr<uint16_t> y); template void Device::sub(const uint_tp n, vptr<const uint32_t> a, vptr<const uint32_t> b, vptr<uint32_t> y); template void Device::sub(const uint_tp n, vptr<const uint64_t> a, vptr<const uint64_t> b, vptr<uint64_t> y); template<typename Dtype> void Device::mul(const uint_tp n, vptr<const Dtype> a, vptr<const Dtype> b, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_mul"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&b); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::mul(const uint_tp n, vptr<const half_fp> a, vptr<const half_fp> b, vptr<half_fp> y); template void Device::mul(const uint_tp n, vptr<const float> a, vptr<const float> b, vptr<float> y); template void Device::mul(const uint_tp n, vptr<const double> a, vptr<const double> b, vptr<double> y); template void Device::mul(const uint_tp n, vptr<const uint8_t> a, vptr<const uint8_t> b, vptr<uint8_t> y); template void Device::mul(const uint_tp n, vptr<const uint16_t> a, vptr<const uint16_t> b, vptr<uint16_t> y); template void Device::mul(const uint_tp n, vptr<const uint32_t> a, vptr<const uint32_t> b, vptr<uint32_t> y); template void Device::mul(const uint_tp n, vptr<const uint64_t> a, vptr<const uint64_t> b, vptr<uint64_t> y); template<typename Dtype> void Device::div(const uint_tp n, vptr<const Dtype> a, vptr<const Dtype> b, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_div"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&b); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::div(const uint_tp n, vptr<const half_fp> a, vptr<const half_fp> b, vptr<half_fp> y); template void Device::div(const uint_tp n, vptr<const float> a, vptr<const float> b, vptr<float> y); template void Device::div(const uint_tp n, vptr<const double> a, vptr<const double> b, vptr<double> y); template void Device::div(const uint_tp n, vptr<const uint8_t> a, vptr<const uint8_t> b, vptr<uint8_t> y); template void Device::div(const uint_tp n, vptr<const uint16_t> a, vptr<const uint16_t> b, vptr<uint16_t> y); template void Device::div(const uint_tp n, vptr<const uint32_t> a, vptr<const uint32_t> b, vptr<uint32_t> y); template void Device::div(const uint_tp n, vptr<const uint64_t> a, vptr<const uint64_t> b, vptr<uint64_t> y); template<typename Dtype> void Device::abs(const uint_tp n, vptr<const Dtype> a, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_abs"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::abs(const uint_tp n, vptr<const half_fp> a, vptr<half_fp> y); template void Device::abs(const uint_tp n, vptr<const float> a, vptr<float> y); template void Device::abs(const uint_tp n, vptr<const double> a, vptr<double> y); template void Device::abs(const uint_tp n, vptr<const uint8_t> a, vptr<uint8_t> y); template void Device::abs(const uint_tp n, vptr<const uint16_t> a, vptr<uint16_t> y); template void Device::abs(const uint_tp n, vptr<const uint32_t> a, vptr<uint32_t> y); template void Device::abs(const uint_tp n, vptr<const uint64_t> a, vptr<uint64_t> y); template<typename Dtype> void Device::exp(const uint_tp n, vptr<const Dtype> a, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_exp"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::exp(const uint_tp n, vptr<const half_fp> a, vptr<half_fp> y); template void Device::exp(const uint_tp n, vptr<const float> a, vptr<float> y); template void Device::exp(const uint_tp n, vptr<const double> a, vptr<double> y); template void Device::exp(const uint_tp n, vptr<const uint8_t> a, vptr<uint8_t> y); template void Device::exp(const uint_tp n, vptr<const uint16_t> a, vptr<uint16_t> y); template void Device::exp(const uint_tp n, vptr<const uint32_t> a, vptr<uint32_t> y); template void Device::exp(const uint_tp n, vptr<const uint64_t> a, vptr<uint64_t> y); template<typename Dtype> void Device::log(const uint_tp n, vptr<const Dtype> a, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_log"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::log(const uint_tp n, vptr<const half_fp> a, vptr<half_fp> y); template void Device::log(const uint_tp n, vptr<const float> a, vptr<float> y); template void Device::log(const uint_tp n, vptr<const double> a, vptr<double> y); template void Device::log(const uint_tp n, vptr<const uint8_t> a, vptr<uint8_t> y); template void Device::log(const uint_tp n, vptr<const uint16_t> a, vptr<uint16_t> y); template void Device::log(const uint_tp n, vptr<const uint32_t> a, vptr<uint32_t> y); template void Device::log(const uint_tp n, vptr<const uint64_t> a, vptr<uint64_t> y); template<typename Dtype> void Device::powx(const uint_tp n, vptr<const Dtype> a, const Dtype b, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()]->GetKernel("caffe_gpu_powx"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&b); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::powx(const uint_tp n, vptr<const half_fp> a, const half_fp b, vptr<half_fp> y); template void Device::powx(const uint_tp n, vptr<const float> a, const float b, vptr<float> y); template void Device::powx(const uint_tp n, vptr<const double> a, const double b, vptr<double> y); template void Device::powx(const uint_tp n, vptr<const uint8_t> a, const uint8_t b, vptr<uint8_t> y); template void Device::powx(const uint_tp n, vptr<const uint16_t> a, const uint16_t b, vptr<uint16_t> y); template void Device::powx(const uint_tp n, vptr<const uint32_t> a, const uint32_t b, vptr<uint32_t> y); template void Device::powx(const uint_tp n, vptr<const uint64_t> a, const uint64_t b, vptr<uint64_t> y); template<typename Dtype> void Device::sqrt(const uint_tp n, vptr<const Dtype> a, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_sqrt"); kernel->add_arg(&n); kernel->add_arg(&a); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::sqrt(const uint_tp n, vptr<const half_fp> a, vptr<half_fp> y); template void Device::sqrt(const uint_tp n, vptr<const float> a, vptr<float> y); template void Device::sqrt(const uint_tp n, vptr<const double> a, vptr<double> y); template void Device::sqrt(const uint_tp n, vptr<const uint8_t> a, vptr<uint8_t> y); template void Device::sqrt(const uint_tp n, vptr<const uint16_t> a, vptr<uint16_t> y); template void Device::sqrt(const uint_tp n, vptr<const uint32_t> a, vptr<uint32_t> y); template void Device::sqrt(const uint_tp n, vptr<const uint64_t> a, vptr<uint64_t> y); template<typename Dtype> void Device::sign(const uint_tp n, vptr<const Dtype> x, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_sign"); kernel->add_arg(&n); kernel->add_arg(&x); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::sign(const uint_tp n, vptr<const half_fp> x, vptr<half_fp> y); template void Device::sign(const uint_tp n, vptr<const float> x, vptr<float> y); template void Device::sign(const uint_tp n, vptr<const double> x, vptr<double> y); template void Device::sign(const uint_tp n, vptr<const uint8_t> x, vptr<uint8_t> y); template void Device::sign(const uint_tp n, vptr<const uint16_t> x, vptr<uint16_t> y); template void Device::sign(const uint_tp n, vptr<const uint32_t> x, vptr<uint32_t> y); template void Device::sign(const uint_tp n, vptr<const uint64_t> x, vptr<uint64_t> y); template<typename Dtype> void Device::sgnbit(const uint_tp n, vptr<const Dtype> x, vptr<Dtype> y) { shared_ptr<DeviceKernel> kernel = math_programs_[data_type_index<Dtype>()] ->GetKernel("caffe_gpu_signbit"); kernel->add_arg(&n); kernel->add_arg(&x); kernel->add_arg(&y); vector<size_t> work_size(1, n); vector<size_t> group; vector<size_t> local; this->get_threads(&work_size, &group, &local, kernel.get(), true); kernel->Execute(group, local); } template void Device::sgnbit(const uint_tp n, vptr<const half_fp> x, vptr<half_fp> y); template void Device::sgnbit(const uint_tp n, vptr<const float> x, vptr<float> y); template void Device::sgnbit(const uint_tp n, vptr<const double> x, vptr<double> y); template void Device::sgnbit(const uint_tp n, vptr<const uint8_t> x, vptr<uint8_t> y); template void Device::sgnbit(const uint_tp n, vptr<const uint16_t> x, vptr<uint16_t> y); template void Device::sgnbit(const uint_tp n, vptr<const uint32_t> x, vptr<uint32_t> y); template void Device::sgnbit(const uint_tp n, vptr<const uint64_t> x, vptr<uint64_t> y); template<typename Dtype, typename MItype, typename MOtype> string create_set_source(Device* dev, shared_ptr<DeviceProgram> program) { stringstream ss; ss << program->define_type<Dtype>("Dtype"); // Set { KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("alpha", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_set", args); ss << program->kernel_loop("uint_tp", "index", "n"); ss << "y[index] = alpha;" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } return ss.str(); } template<typename Dtype, typename MItype, typename MOtype> string create_source(Device* dev, shared_ptr<DeviceProgram> program) { stringstream ss; ss << program->helper_functions<Dtype>(); ss << program->define_type<Dtype>("Dtype"); // Add Scalar { KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("alpha", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_add_scalar", args); ss << program->kernel_loop("uint_tp", "index", "n"); ss << "y[index] += alpha;" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } // Add, Sub, Mul, Div vector<string> op_names = {"add", "sub", "mul", "div"}; vector<string> ops = {"+", "-", "*", "/"}; for (uint_tp i = 0; i < ops.size(); ++i) { string op_name = op_names[i]; string op = ops[i]; KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("a", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("b", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_" + op_name, args); ss << program->kernel_loop("uint_tp", "index", "n"); ss << "y[index] = a[index] " << op << " b[index];" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } // Powx { KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("a", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("alpha", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_powx", args); ss << program->kernel_loop("uint_tp", "index", "n"); ss << "if (alpha == (Dtype)2) {" << std::endl; string abs_fun; if (dev->backend() == BACKEND_CUDA) { abs_fun = "abs"; } else { abs_fun = "fabs"; } if (is_unsigned_integer_type<Dtype>()) { ss << "y[index] = (Dtype)(pow((float)abs(a[index]), (float)alpha));" << std::endl; } else { ss << "y[index] = pow((Dtype)" << abs_fun << "(a[index]), (Dtype)alpha);" << std::endl; } ss << "} else {" << std::endl; if (is_unsigned_integer_type<Dtype>()) { ss << "y[index] = (Dtype)(pow((float)a[index], (float)alpha));" << std::endl; } else { ss << "y[index] = pow((Dtype)a[index], (Dtype)alpha);" << std::endl; } ss << "}" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } // Abs, Exp, Log vector<string> func_names = {"exp", "log", "sqrt", "abs"}; vector<string> funcs = {"exp", "log", "sqrt"}; if (dev->backend() == BACKEND_CUDA || is_unsigned_integer_type<Dtype>()) { // CUDA and integer absolute value funcs.push_back("abs"); } else { // OpenCL float absolute value funcs.push_back("fabs"); } for (uint_tp i = 0; i < funcs.size(); ++i) { string func_name = func_names[i]; string func = funcs[i]; KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("a", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_" + func_name, args); ss << program->kernel_loop("uint_tp", "index", "n"); if (is_unsigned_integer_type<Dtype>() && !(func_name == "abs")) { ss << "y[index] = (Dtype)" << func << "((float)a[index]);" << std::endl; } else { ss << "y[index] = " << func << "(a[index]);" << std::endl; } ss << "}" << std::endl; ss << "}" << std::endl; } // Sign { KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("x", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_sign", args); ss << program->kernel_loop("uint_tp", "index", "n"); ss << "y[index] = ((Dtype)0 < x[index]) - (x[index] < (Dtype)0);" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } // Signbit { KernelArgs args; args.push_back(program->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(program->create_kernel_arg<Dtype>("x", KERNEL_ARG_CONST | KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); args.push_back(program->create_kernel_arg<Dtype>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << program->function("caffe_gpu_signbit", args); ss << program->kernel_loop("uint_tp", "index", "n"); if (is_unsigned_integer_type<Dtype>()) { ss << "y[index] = (Dtype)(x[index] < (Dtype)0);" << std::endl; } else { ss << "y[index] = signbit(x[index]);" << std::endl; } ss << "}" << std::endl; ss << "}" << std::endl; } return ss.str(); } void Device::CreateMathProgram() { for (int_tp i = 0; i < PROTO_DATA_INDEX_MAX; ++i) { this->math_programs_.push_back(this->CreateProgram()); stringstream ss; ss << this->math_programs_[i]->setup(); switch (i) { case AUX_DATA_INDEX: { // Memset { KernelArgs args; args.push_back(this->math_programs_[i] ->create_kernel_arg<uint_tp>("n", KERNEL_ARG_CONST)); args.push_back(this->math_programs_[i] ->create_kernel_arg<char>("alpha", KERNEL_ARG_CONST)); args.push_back(this->math_programs_[i] ->create_kernel_arg<char>("y", KERNEL_ARG_GLOBAL_MEM | KERNEL_ARG_MEM_OFFSET)); ss << this->math_programs_[i]->function("caffe_gpu_memset", args); ss << this->math_programs_[i]->kernel_loop("uint_tp", "index", "n"); ss << "y[index] = alpha;" << std::endl; ss << "}" << std::endl; ss << "}" << std::endl; } // Null kernel { KernelArgs args; args.push_back(this->math_programs_[i] ->create_kernel_arg<float>("arg", KERNEL_ARG_NONE)); ss << this->math_programs_[i] ->function("caffe_gpu_null_kernel", args); ss << "float out = arg;" << std::endl; ss << "}" << std::endl; } break; } case HALF_DATA_INDEX: { #ifdef USE_HALF ss << "#ifdef HALF_SUPPORT_AVAILABLE" << std::endl; ss << create_set_source<half_fp, half_fp, half_fp>(this, this->math_programs_[i]); ss << create_source<half_fp, half_fp, half_fp>(this, this->math_programs_[i]); ss << "#endif // HALF_SUPPORT_AVAILABLE" << std::endl; #endif // USE_HALF break; } case FLOAT_DATA_INDEX: { #ifdef USE_SINGLE ss << create_set_source<float, float, float>(this, this->math_programs_[i]); ss << create_source<float, float, float>(this, this->math_programs_[i]); #endif // USE_SINGLE break; } case DOUBLE_DATA_INDEX: { #ifdef USE_DOUBLE ss << "#ifdef DOUBLE_SUPPORT_AVAILABLE" << std::endl; ss << create_set_source<double, double, double>(this, this->math_programs_[i]); ss << create_source<double, double, double>(this, this->math_programs_[i]); ss << "#endif // DOUBLE_SUPPORT_AVAILABLE" << std::endl; #endif // USE_DOUBLE break; } case UINT8_DATA_INDEX: { ss << create_set_source<uint8_t, uint8_t, uint8_t>(this, this->math_programs_[i]); ss << create_source<uint8_t, uint8_t, uint8_t>(this, this->math_programs_[i]); break; } case UINT16_DATA_INDEX: { ss << create_set_source<uint16_t, uint16_t, uint16_t>(this, this->math_programs_[i]); ss << create_source<uint16_t, uint16_t, uint16_t>(this, this->math_programs_[i]); break; } case UINT32_DATA_INDEX: { ss << create_set_source<uint32_t, uint32_t, uint32_t>(this, this->math_programs_[i]); ss << create_source<uint32_t, uint32_t, uint32_t>(this, this->math_programs_[i]); break; } case UINT64_DATA_INDEX: { ss << create_set_source<uint64_t, uint64_t, uint64_t>(this, this->math_programs_[i]); ss << create_source<uint64_t, uint64_t, uint64_t>(this, this->math_programs_[i]); break; } case INT8_DATA_INDEX: { ss << create_set_source<int8_t, int8_t, int8_t>(this, this->math_programs_[i]); break; } case INT16_DATA_INDEX: { ss << create_set_source<int16_t, int16_t, int16_t>(this, this->math_programs_[i]); break; } case INT32_DATA_INDEX: { ss << create_set_source<int32_t, int32_t, int32_t>(this, this->math_programs_[i]); break; } case INT64_DATA_INDEX: { ss << create_set_source<int64_t, int64_t, int64_t>(this, this->math_programs_[i]); break; } } this->math_programs_[i]->set_source(ss.str()); this->math_programs_[i]->Compile(true, true); } } } // namespace caffe
35.698837
81
0.615908
[ "vector" ]
41f1300b92fa46857d371b922c0f544add26276a
11,113
cpp
C++
src/mainServer.cpp
matrigato/RedesTrab
e28879cdc077a59a888f17e6c10cfc5112bb4674
[ "Unlicense" ]
null
null
null
src/mainServer.cpp
matrigato/RedesTrab
e28879cdc077a59a888f17e6c10cfc5112bb4674
[ "Unlicense" ]
null
null
null
src/mainServer.cpp
matrigato/RedesTrab
e28879cdc077a59a888f17e6c10cfc5112bb4674
[ "Unlicense" ]
null
null
null
#include "Chat.hpp" #include "Socket.hpp" #include "mainServer.hpp" #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <netdb.h> #include <iostream> #include <thread> #include <vector> #include <poll.h> MainServer :: MainServer (unsigned short int port){ isOpen = false; //prepara os usuarios em espera waitingUsers = (UserData*)malloc(sizeof(UserData) * 20); for(int i = 0; i < 20; i++){ waitingUsers[i] = UserData(); waitingUsers[i].isConnected = false; } //prepara as salas for (size_t i = 0; i < 5; i++) { rooms[i] = ChatRoom(); rooms[i].userNum = -1; } // create socket sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd == -1){ std:: cout << "\n\rSERVER_LOG: SOCKET_ERROR" << std:: endl; return; } int opt = 1; if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt, sizeof(opt))) { perror("setsockopt"); exit(EXIT_FAILURE); } // Bind socket to IP / port struct sockaddr_in hint; hint.sin_family = AF_INET; hint.sin_port = htons((uint16_t) port); // htons changes byte order //inet_pton(AF_INET, "0.0.0.0", &hint.sin_addr); hint.sin_addr.s_addr = INADDR_ANY; // or inet_addr(ipv4 string) if(bind(sockfd, (struct sockaddr*) &hint, sizeof(hint)) == -1){ // Can't bind std:: cout << "\n\rSERVER_LOG: BIND_ERROR" << std:: endl; return; } // Mark the socket for listening in if(listen(sockfd, 25) == -1){ // Can't listen std:: cout << "\n\rSERVER_LOG: LISTEN_ERROR" << std:: endl; return; } std:: cout << "\n\rSERVER_LOG: Servidor aberto." << std:: endl; whatsMyName(); isOpen = true; } //imprime na tela o nome do servidor void MainServer :: whatsMyName(){ char name[99]; if(gethostname(name,99)!= 0){ std::cout << "I don't know my name."<< std::endl; return; } std::cout << "My name is "<< name << std::endl; } void MainServer :: acceptC(){ if(!isOpen){ std:: cout << "\n\rSERVER_LOG: fechando server." << std:: endl; return ; } if(tempUser != -1)//user waiting { return; } struct pollfd fds[1]; fds[0].fd = sockfd; fds[0].events = 0; fds[0].events |= POLLIN; if(poll(fds,1,3000) == 0) // no one is trying to connect return; struct sockaddr_in client; socklen_t clientSize = sizeof(client); int newConnectionSocket ; std:: cout << "\n\rSERVER_LOG: ERRNO_B_ACCEPT: " << errno << std:: endl; newConnectionSocket = accept(sockfd, (struct sockaddr*) &client, &clientSize); // new socket number std:: cout << "\n\rSERVER_LOG: ERRNO_A_ACCEPT: " << errno << std:: endl; //verifica se teve algum problema no accept e continua o processo if(newConnectionSocket != -1){ //gera o ip do client na forma de string char ipStr[50]; inet_ntop(AF_INET, (struct sockaddr*)&client.sin_addr, ipStr, 50); strcpy(tempIp,ipStr); tempUser= newConnectionSocket; } } //adiciona o novo usuario e se prepara para receber/enviar mensagens void MainServer :: setUserToWaiting(UserData user, int sock){ int pos; for(int i = 0; i < 20; i++){ if(!waitingUsers[i].isConnected){ waitingUsers[i] = user; pos = i; break; } } listenUser(pos,sock); } void MainServer :: listenUser(int id, int sock){ char buffer[4096]; struct pollfd fds[1]; fds[0].fd = sock; fds[0].events = 0; fds[0].events |= POLLIN; //first message strcpy(buffer,"Para se conectar utilize o comando /join seguido do nome da sala que gostaria de entrar."); waitingUsers[id].sendNewM(buffer,4096); sendChatRooms(id); //recive user name int Recv = waitingUsers[id].receive(buffer, 4096); if(strncmp(buffer,"/start ",7)==0){ for (size_t i = 0; i < 50; i++) waitingUsers[id].userName[i] = buffer[i+7]; } while (true) { if(poll(fds,1,3000) != 0){ bzero(buffer,4096); int bytesRecv = waitingUsers[id].receive(buffer, 4096); if(bytesRecv == -1){ std::cerr << "\n\rSERVER_LOG: There was a connection issue with an user" << std::endl; //remove o usuario da fila de espera waitingUsers[id].closeSocket(); removeWaitingUser(id); break; } else if(bytesRecv == 0 || strcmp(buffer,"/quit")==0){ std::cout << "\n\rSERVER_LOG: One user disconnected" << std::endl; //remove o usuario da fila de espera waitingUsers[id].closeSocket(); removeWaitingUser(id); break; } else if(strncmp(buffer, "/join ",6) == 0){ int size = strlen(buffer); if (size > 6) { //get the room name char roomName[50]; int i; for (i = 0; i < size - 6; i++) { roomName[i] = buffer[i + 6]; } roomName[i] = '\0'; //verify allowed name bool allowed = true; if(roomName[0] != '&' && roomName[0] != '#'){ strcpy(buffer,"O nome do canal deve começar com # ou &."); allowed = false; } for(i = 1; roomName[i] != '\0'; i++){ if(!allowed) break; switch(roomName[i]){ case ' ': strcpy(buffer,"Espaços não são permitidos no nome do canal."); allowed = false; break; case ',': strcpy(buffer,"Vírgulas não são permitidas no nome do canal."); allowed = false; break; case 7: strcpy(buffer,"Control G não é permitido no nome do canal."); allowed = false; break; } } if(allowed){ //verify repeated name int roomId = getRoomByName(roomName); if(roomId != -1){ std::cout << "\n\rSERVER_LOG: um usuario esta entrando na sala "<< rooms[roomId].roomName << std::endl; //adiciona o usuario na sala UserData user = waitingUsers[id]; //remove o usuario da fila de espera removeWaitingUser(id); if(rooms[roomId].userNum > -1 && rooms[roomId].userNum < 20 ){ rooms[roomId].addUserFromServer(user, sock); break; } } else{ roomId = newRoom(roomName); if(roomId != -1){ std::cout << "\n\rSERVER_LOG: um usuario criou a sala "<< rooms[roomId].roomName << std::endl; //adiciona o usuario na sala UserData user = waitingUsers[id]; //remove o usuario da fila de espera removeWaitingUser(id); rooms[roomId].addUserFromServer(user, sock); break; } } } else{ waitingUsers[id].sendNewM(buffer,4096); // Mensagem sobre caracteres invalidos } strcpy(buffer, "\n\rSERVER_LOG: ERRO; não foi possivel se connectar/criar a sala desejada, tente novamente."); waitingUsers[id].sendNewM(buffer,4096); } } strcpy(buffer,"Para se conectar utilize o comando /join seguido do nome da sala que gostaria de entrar."); waitingUsers[id].sendNewM(buffer,4096); sendChatRooms(id); } } } //procura uma sala com nome name, retorna o id da sala ou -1 int MainServer :: getRoomByName(char * name){ if(chatNum <= 0) return -1; for (int i = 0; i < 5; i++) { if(strcmp(name, rooms[i].roomName) == 0 && rooms[i].userNum > -1) return i; } return -1; } //cria uma nova sala com o nome name, retorna o id da sala ou -1 int MainServer :: newRoom(char * name){ //cant creat a new room if(chatNum >= 20) return -1; //create a new room for (int i = 0; i < 20; i++) { if(rooms[i].userNum == -1){ rooms[i] = ChatRoom(); strcpy(rooms[i].roomName, name); chatNum++; return i; } } //error return -1; } //remove o usuario na posicao id void MainServer :: removeWaitingUser(int id){ //remove o usuario anterior e fica pronto para receber um novo waitingUsers[id] = UserData(); waitingUsers[id].isConnected = false; waitingUserNum--; verifyServer(); } //manda para o usuario indicado pelo id as sala que estão sendo utilizadas no momento void MainServer :: sendChatRooms(int id){ char buffer[4096]; bzero(buffer, 4096); if(chatNum > 0){ strcpy(buffer,"\nSalas abertas:"); for (int i = 0; i < 5; i++) { if(rooms[i].userNum >= 0){ strcat(buffer,"\n\t"); strcat(buffer,rooms[i].roomName); } } strcat(buffer,"\n"); //send to user waitingUsers[id].sendNewM(buffer,4096); } else if( chatNum == 0){ strcpy(buffer, "\nNão temos nenhuma sala no momento; você pode criar a sua própria sala utilizando o comando /join"); waitingUsers[id].sendNewM(buffer,4096); } } void MainServer :: verifyServer(){ if(!isOpen) return; int num = 0; for(int i = 0; i < 20; i++){ if(rooms[i].userNum >= 0) num++; } chatNum = num; if(num <= 0 && waitingUserNum <= 0){ closeServer(); } } void MainServer :: closeServer(){ if(isOpen){ isOpen = false; waitingUserNum = -1; chatNum = -1; close(sockfd); } } void MainServer :: startUser(){ if(tempUser != -1){ UserData newUser(tempUser); int sock = tempUser; strcpy(newUser.userIp,tempIp); // printf("\nIP: %s\n", newUser.userIp); strcpy(tempIp, ""); tempUser = -1; waitingUserNum++; setUserToWaiting(newUser,sock); } }
28.715762
131
0.496896
[ "vector" ]
41f24350dc119e7b9937a834e39484da088fe6f5
2,487
cpp
C++
test/testDof.cpp
RealTimeBiomechanics/ceinms2
1074afabc40249d374778f320e43ee4bc4e77f0b
[ "Apache-2.0" ]
4
2020-05-07T07:12:04.000Z
2021-10-07T10:25:03.000Z
test/testDof.cpp
RealTimeBiomechanics/ceinms2
1074afabc40249d374778f320e43ee4bc4e77f0b
[ "Apache-2.0" ]
null
null
null
test/testDof.cpp
RealTimeBiomechanics/ceinms2
1074afabc40249d374778f320e43ee4bc4e77f0b
[ "Apache-2.0" ]
3
2020-05-15T00:48:56.000Z
2021-09-01T05:00:13.000Z
#include <ceinms2/NMSmodel.h> #include <ceinms2/Dof.h> #include <ceinms2/Lloyd2003Muscle.h> #include <ceinms2/LinearActuator.h> #include <ceinms2/testingUtilities.h> #include <iostream> using namespace ceinms; auto getDefaultMuscle() { ceinms::Lloyd2003Muscle::Parameters p; p.damping = 0.1; p.maxContractionVelocity = 1; p.maxIsometricForce = 1; p.optimalFiberLength = 1; p.pennationAngleAtOptimalFiberLength = 0; p.percentageChange = 0.15; p.strengthCoefficient = 1; p.tendonSlackLength = 1; ceinms::Lloyd2003Muscle muscle(p); muscle.setName("muscle"); return muscle; } int testDofConnectionWithNMSmodel() { using MyNMSmodel = NMSmodel<LinearActuator, Dof>; MyNMSmodel model; ceinms::LinearActuator muscle; muscle.setName("mtu1"); model.addComponent(muscle); muscle.setName("mtu2"); model.addComponent(muscle); muscle.setName("mtu3"); model.addComponent(muscle); model.addInput<Activation>("mtu1"); model.addInput<Activation>("mtu2"); model.addInput<Activation>("mtu3"); ceinms::Dof dof({ 3 }); dof.setName("dof1"); model.addComponent(dof); model.addInput<MomentArmsOnDof>("dof1"); model.connect<Activation, LinearActuator>(); model.connect<LinearActuator, Dof>(Socket("mtu1"), Socket{ "dof1", 0 }); model.connect<LinearActuator, Dof>(Socket("mtu2"), Socket{ "dof1", 1 }); model.connect<LinearActuator, Dof>(Socket("mtu3"), Socket{ "dof1", 2 }); model.connect<MomentArmsOnDof, Dof>(); model.setInput(vector<Activation>{ 1., 1., 1. }); model.setInput(vector{ MomentArmsOnDof{ { 1., 1., 1. } } }); model.evaluate(0.01); return !(model.getComponent<Dof>("dof1").getOutput<Torque>() == 3.); } int testDof() { ceinms::Dof d({ 3 }); std::vector<DoubleT> forces{ 1., 2., 3. }; std::vector<DoubleT> momentArms{ 1., 1. / 2., 1. / 3. }; d.setForces(forces); d.setMomentArms(momentArms); d.calculateOutput(); std::cout << d.getOutput<Torque>() << std::endl; d.setInput(std::vector{ Force{ 1. }, Force{ 2. }, Force{ 3. } }); d.setInput(std::vector{ MomentArm{ 2. }, MomentArm{ 2. / 2. }, MomentArm{ 2. / 3. } }); d.calculateOutput(); std::cout << d.getOutput<Torque>() << std::endl; return 0; } int main() { bool failed = false; failed |= runTest(&testDof, "Compile test"); failed |= runTest(&testDofConnectionWithNMSmodel, "Works within NMS model"); return failed; }
29.607143
91
0.648975
[ "vector", "model" ]
41f542f33889b713096e5d154d4713fe52775304
6,738
cpp
C++
codeforces/practice/ShrelockAndQueriesOnTheGraph.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
3
2020-02-08T10:34:16.000Z
2020-02-09T10:23:19.000Z
codeforces/practice/ShrelockAndQueriesOnTheGraph.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
null
null
null
codeforces/practice/ShrelockAndQueriesOnTheGraph.cpp
Shahraaz/CP_S5
2cfb5467841d660c1e47cb8338ea692f10ca6e60
[ "MIT" ]
2
2020-10-02T19:05:32.000Z
2021-09-08T07:01:49.000Z
// Optimise #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; // #define MULTI_TEST #ifdef LOCAL #define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__); #define pc(...) PC(#__VA_ARGS__, __VA_ARGS__); template <typename T, typename U> ostream &operator<<(ostream &out, const pair<T, U> &p) { out << '[' << p.first << ", " << p.second << ']'; return out; } template <typename Arg> void PC(const char *name, Arg &&arg) { while (*name == ',' || *name == ' ') name++; std::cerr << name << " { "; for (const auto &v : arg) cerr << v << ' '; cerr << " }\n"; } template <typename Arg1, typename... Args> void PC(const char *names, Arg1 &&arg1, Args &&... args) { while (*names == ',' || *names == ' ') names++; const char *comma = strchr(names, ','); std::cerr.write(names, comma - names) << " { "; for (const auto &v : arg1) cerr << v << ' '; cerr << " }\n"; PC(comma, args...); } template <typename Arg1> void ZZ(const char *name, Arg1 &&arg1) { std::cerr << name << " = " << arg1 << endl; } template <typename Arg1, typename... Args> void ZZ(const char *names, Arg1 &&arg1, Args &&... args) { const char *comma = strchr(names + 1, ','); std::cerr.write(names, comma - names) << " = " << arg1; ZZ(comma, args...); } #else #define db(...) #define pc(...) #endif using ll = long long; template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; #define f first #define s second #define pb push_back #define all(v) v.begin(), v.end() auto TimeStart = chrono::steady_clock::now(); auto seed = TimeStart.time_since_epoch().count(); std::mt19937 rng(seed); template <typename T> using Random = std::uniform_int_distribution<T>; const int NAX = 1e5 + 5, MOD = 1000000007; vector<int> E[NAX]; // Bridge tree vector<int> graph[NAX]; //Original graph int U[NAX], V[NAX]; bool isBridge[NAX]; bool visited[NAX]; int arr[NAX]; int cmpno; queue<int> Q[NAX]; int L[NAX], P[19][NAX]; int vis = 0; int C[NAX], S[NAX]; int start[NAX], finish[NAX], now; int compo[NAX], T; void dfsLcaBridgeTree(int u, int p) { L[u] = p != -1 ? L[p] + 1 : 1; P[0][u] = p; start[u] = ++now; for (int j = 1; j < 19; j++) { int x = P[j - 1][u]; if (x < 0) break; P[j][u] = P[j - 1][x]; } ++vis; for (size_t i = 0; i < E[u].size(); i++) { int v = E[u][i]; if (v == p) continue; dfsLcaBridgeTree(v, u); } finish[u] = ++now; } bool isAncestor(int u, int a) { if (u == a) return true; return start[u] < start[a] && finish[u] > finish[a]; } int lca(int p, int q) { int log, i; if (L[p] < L[q]) swap(p, q); for (log = 1; (1 << log) <= L[p]; log++) ; for (int i = log - 1; i >= 0; i--) if (L[p] - (1 << i) >= L[q]) p = P[i][p]; if (p == q) return p; for (int i = log - 1; i >= 0; i--) if (P[i][p] != -1 && P[i][p] != P[i][q]) p = P[i][p], q = P[i][q]; return P[0][p]; } int adj(int u, int e) { return U[e] == u ? V[e] : U[e]; } int getDist(int a, int b, int lca) { return L[a] + L[b] - 2 * L[lca]; } int dfs0BridgeTree(int u, int edge) { visited[u] = 1; int dbe = arr[u] = T++; for (size_t i = 0; i < graph[u].size(); i++) { int e = graph[u][i]; int w = adj(u, e); // db(u, i, w); if (!visited[w]) dbe = min(dbe, dfs0BridgeTree(w, e)); else if (e != edge) dbe = min(dbe, arr[w]); } // cout << u << ' ' << edge << ' ' << dbe << ' ' << arr[u] << '\n'; if (dbe == arr[u] && edge != -1) { isBridge[edge] = true; // cout << "Bridge " << edge << '\n'; } return dbe; } void dfsBridgeTreeContruction(int v) { int currcmp = cmpno; Q[currcmp].push(v); visited[v] = 1; while (!Q[currcmp].empty()) { int u = Q[currcmp].front(); Q[currcmp].pop(); compo[u] = currcmp; for (size_t i = 0; i < graph[u].size(); i++) { int e = graph[u][i]; int w = adj(u, e); if (visited[w]) continue; if (isBridge[e]) { cmpno++; E[cmpno].pb(currcmp); E[currcmp].pb(cmpno); dfsBridgeTreeContruction(w); } else { Q[currcmp].push(w); visited[w] = 1; } } } } pair<int, int> getCommanPath(int u, int a, int v, int b) { if (!isAncestor(v, a)) return {0, 0}; int x = lca(a, b); if (L[v] < L[u]) { if (isAncestor(u, x)) return {u, x}; } else if (isAncestor(v, x)) return {v, x}; return {0, 0}; } int getAnswer(int a, int b, int c, int d) { int u = lca(a, b), v = lca(c, d); int ret = getDist(a, b, u); pair<int, int> X; X = getCommanPath(u, a, v, c); ret -= getDist(X.f, X.s, lca(X.f, X.s)); X = getCommanPath(u, a, v, d); ret -= getDist(X.f, X.s, lca(X.f, X.s)); X = getCommanPath(u, b, v, c); ret -= getDist(X.f, X.s, lca(X.f, X.s)); X = getCommanPath(u, b, v, d); ret -= getDist(X.f, X.s, lca(X.f, X.s)); return ret; } class Solution { private: public: Solution() {} ~Solution() {} void solveCase() { int n, m, q; cin >> n >> m >> q; for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; --u, --v; U[i] = v; V[i] = u; graph[u].pb(i); graph[v].pb(i); // cout << u << ' ' << v << ' ' << i << '\n'; } // cout << '\n'; dfs0BridgeTree(0, -1); memset(visited, 0, sizeof visited); dfsBridgeTreeContruction(0); dfsLcaBridgeTree(0, -1); while (q--) { int a, b, c, d; cin >> a >> b >> c >> d; --a, --b, --c, --d; cout << getAnswer(compo[c], compo[d], compo[a], compo[b]) << '\n'; } } }; int32_t main() { #ifndef LOCAL ios_base::sync_with_stdio(0); cin.tie(0); #endif int t = 1; #ifdef MULTI_TEST cin >> t; #endif Solution mySolver; for (int i = 1; i <= t; ++i) { mySolver.solveCase(); #ifdef TIME cerr << "Case #" << i << ": Time " << chrono::duration<double>(chrono::steady_clock::now() - TimeStart).count() << " s.\n"; TimeStart = chrono::steady_clock::now(); #endif } return 0; }
23.154639
131
0.469724
[ "vector" ]
41fa59a04b060ed32c52e422f55895ed098f8049
11,731
cpp
C++
SmoothDisplacementMapping/src/SmoothDisplacementMappingApp.cpp
astellato/Cinder-Samples
50d9658aed28bdab849e5540f9abb34b4620688e
[ "Unlicense" ]
1
2016-06-15T07:06:33.000Z
2016-06-15T07:06:33.000Z
SmoothDisplacementMapping/src/SmoothDisplacementMappingApp.cpp
astellato/Cinder-Samples
50d9658aed28bdab849e5540f9abb34b4620688e
[ "Unlicense" ]
null
null
null
SmoothDisplacementMapping/src/SmoothDisplacementMappingApp.cpp
astellato/Cinder-Samples
50d9658aed28bdab849e5540f9abb34b4620688e
[ "Unlicense" ]
null
null
null
/* Copyright (c) 2010-2012, Paul Houx - All rights reserved. This code is intended for use with the Cinder C++ library: http://libcinder.org Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "cinder/Camera.h" #include "cinder/ImageIo.h" #include "cinder/MayaCamUI.h" #include "cinder/Surface.h" #include "cinder/app/AppBasic.h" #include "cinder/gl/gl.h" #include "cinder/gl/Fbo.h" #include "cinder/gl/GlslProg.h" #include "cinder/gl/Texture.h" #include "cinder/gl/Vbo.h" using namespace ci; using namespace ci::app; using namespace std; class SmoothDisplacementMappingApp : public AppBasic { public: void prepareSettings( Settings *settings ); void setup(); void update(); void draw(); void resize(); void mouseMove( MouseEvent event ); void mouseDown( MouseEvent event ); void mouseDrag( MouseEvent event ); void mouseUp( MouseEvent event ); void keyDown( KeyEvent event ); void keyUp( KeyEvent event ); private: void createMesh(); void createTextures(); bool compileShaders(); void renderDisplacementMap(); void renderNormalMap(); void resetCamera(); private: bool mDrawTextures; bool mDrawWireframe; bool mDrawOriginalMesh; bool mEnableShader; float mAmplitude; float mAmplitudeTarget; MayaCamUI mMayaCam; CameraPersp mCamera; gl::Fbo mDispMapFbo; gl::GlslProg mDispMapShader; gl::Fbo mNormalMapFbo; gl::GlslProg mNormalMapShader; gl::VboMesh mVboMesh; gl::GlslProg mMeshShader; gl::Texture mBackgroundTexture; gl::GlslProg mBackgroundShader; }; void SmoothDisplacementMappingApp::prepareSettings(Settings *settings) { settings->setTitle("Vertex Displacement Mapping with Smooth Normals"); settings->setWindowSize( 1280, 720 ); settings->setFrameRate( 500.0f ); } void SmoothDisplacementMappingApp::setup() { mDrawTextures = false; mDrawWireframe = false; mDrawOriginalMesh = false; mEnableShader = true; mAmplitude = 0.0f; mAmplitudeTarget = 10.0f; // initialize our camera resetCamera(); // load and compile shaders if( ! compileShaders() ) quit(); // create the basic mesh (a flat plane) createMesh(); // create the textures createTextures(); // create the frame buffer objects for the displacement map and the normal map gl::Fbo::Format fmt; fmt.enableDepthBuffer(false); fmt.setWrap( GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE ); // use a single channel (red) for the displacement map fmt.setColorInternalFormat( GL_R32F ); mDispMapFbo = gl::Fbo(256, 256, fmt); // use 3 channels (rgb) for the normal map fmt.setColorInternalFormat( GL_RGB32F_ARB ); //requires ARB on Mac mNormalMapFbo = gl::Fbo(256, 256, fmt); } void SmoothDisplacementMappingApp::update() { mAmplitude += 0.02f * (mAmplitudeTarget - mAmplitude); // render displacement map renderDisplacementMap(); // render normal map renderNormalMap(); } void SmoothDisplacementMappingApp::draw() { gl::clear(); // render background if( mBackgroundTexture && mBackgroundShader ) { mBackgroundShader.bind(); mBackgroundShader.uniform( "texture", 0 ); mBackgroundShader.uniform( "hue", float( 0.025 * getElapsedSeconds() ) ); gl::draw( mBackgroundTexture, getWindowBounds() ); mBackgroundShader.unbind(); }//*/ // if enabled, show the displacement and normal maps if(mDrawTextures) { gl::color( Color(0.05f, 0.05f, 0.05f) ); gl::draw( mDispMapFbo.getTexture(), Vec2f(0,0) ); gl::color( Color(1, 1, 1) ); gl::draw( mNormalMapFbo.getTexture(), Vec2f(256,0) ); } // setup the 3D camera gl::pushMatrices(); gl::setMatrices( mCamera ); // setup render states gl::enableAdditiveBlending(); if(mDrawWireframe) gl::enableWireframe(); // draw undisplaced mesh if enabled if(mDrawOriginalMesh) { gl::color( ColorA(1, 1, 1, 0.2f) ); gl::draw( mVboMesh ); } if( mDispMapFbo && mNormalMapFbo && mMeshShader ) { // bind the displacement and normal maps, each to their own texture unit mDispMapFbo.getTexture().bind(0); mNormalMapFbo.getTexture().bind(1); // render our mesh using vertex displacement mMeshShader.bind(); mMeshShader.uniform( "displacement_map", 0 ); mMeshShader.uniform( "normal_map", 1 ); mMeshShader.uniform( "falloff_enabled", mEnableShader ); gl::color( Color::white() ); gl::draw( mVboMesh ); mMeshShader.unbind(); // unbind texture maps mNormalMapFbo.unbindTexture(); mDispMapFbo.unbindTexture(); } // clean up after ourselves gl::disableWireframe(); gl::disableAlphaBlending(); gl::popMatrices();//*/ } void SmoothDisplacementMappingApp::resetCamera() { mCamera.setEyePoint( Vec3f( 0.0f, 0.0f, 130.0f ) ); mCamera.setCenterOfInterestPoint( Vec3f( 0.0f, 0.0f, 0.0f ) ) ; mMayaCam.setCurrentCam( mCamera ); } void SmoothDisplacementMappingApp::renderDisplacementMap() { if( mDispMapShader && mDispMapFbo ) { mDispMapFbo.bindFramebuffer(); { // clear the color buffer gl::clear(); // setup viewport and matrices glPushAttrib( GL_VIEWPORT_BIT ); gl::setViewport( mDispMapFbo.getBounds() ); gl::pushMatrices(); gl::setMatricesWindow( mDispMapFbo.getSize(), false ); // render the displacement map mDispMapShader.bind(); mDispMapShader.uniform( "time", float( getElapsedSeconds() ) ); mDispMapShader.uniform( "amplitude", mAmplitude ); gl::drawSolidRect( mDispMapFbo.getBounds() ); mDispMapShader.unbind(); // clean up after ourselves gl::popMatrices(); glPopAttrib(); } mDispMapFbo.unbindFramebuffer(); } } void SmoothDisplacementMappingApp::renderNormalMap() { if( mNormalMapShader && mNormalMapFbo ) { mNormalMapFbo.bindFramebuffer(); { // setup viewport and matrices glPushAttrib( GL_VIEWPORT_BIT ); gl::setViewport( mNormalMapFbo.getBounds() ); gl::pushMatrices(); gl::setMatricesWindow( mNormalMapFbo.getSize(), false ); // clear the color buffer gl::clear(); // bind the displacement map mDispMapFbo.getTexture().bind(0); // render the normal map mNormalMapShader.bind(); mNormalMapShader.uniform( "texture", 0 ); mNormalMapShader.uniform( "amplitude", 4.0f ); Area bounds = mNormalMapFbo.getBounds(); //bounds.expand(-1, -1); gl::drawSolidRect( bounds ); mNormalMapShader.unbind(); // clean up after ourselves mDispMapFbo.getTexture().unbind(); gl::popMatrices(); glPopAttrib(); } mNormalMapFbo.unbindFramebuffer(); } } bool SmoothDisplacementMappingApp::compileShaders() { try { // this shader will render all colors using a change in hue mBackgroundShader = gl::GlslProg( loadAsset("background_vert.glsl"), loadAsset("background_frag.glsl") ); // this shader will render a displacement map to a floating point texture, updated every frame mDispMapShader = gl::GlslProg( loadAsset("displacement_map_vert.glsl"), loadAsset("displacement_map_frag.glsl") ); // this shader will create a normal map based on the displacement map mNormalMapShader = gl::GlslProg( loadAsset("normal_map_vert.glsl"), loadAsset("normal_map_frag.glsl") ); // this shader will use the displacement and normal maps to displace vertices of a mesh mMeshShader = gl::GlslProg( loadAsset("mesh_vert.glsl"), loadAsset("mesh_frag.glsl") ); } catch( const std::exception &e ) { console() << e.what() << std::endl; return false; } return true; } void SmoothDisplacementMappingApp::resize() { // if window is resized, update camera aspect ratio mCamera.setAspectRatio( getWindowAspectRatio() ); mMayaCam.setCurrentCam( mCamera ); } void SmoothDisplacementMappingApp::mouseMove( MouseEvent event ) { } void SmoothDisplacementMappingApp::mouseDown( MouseEvent event ) { // handle user input mMayaCam.mouseDown( event.getPos() ); } void SmoothDisplacementMappingApp::mouseDrag( MouseEvent event ) { // handle user input mMayaCam.mouseDrag( event.getPos(), event.isLeftDown(), event.isMiddleDown(), event.isRightDown() ); mCamera = mMayaCam.getCamera(); } void SmoothDisplacementMappingApp::mouseUp( MouseEvent event ) { } void SmoothDisplacementMappingApp::keyDown( KeyEvent event ) { switch( event.getCode() ) { case KeyEvent::KEY_ESCAPE: // quit quit(); break; case KeyEvent::KEY_f: // toggle full screen setFullScreen( !isFullScreen() ); break; case KeyEvent::KEY_m: // toggle original mesh mDrawOriginalMesh = !mDrawOriginalMesh; break; case KeyEvent::KEY_s: // reload shaders compileShaders(); break; case KeyEvent::KEY_t: // toggle draw textures mDrawTextures = !mDrawTextures; break; case KeyEvent::KEY_v: // toggle vertical sync gl::enableVerticalSync( !gl::isVerticalSyncEnabled() ); break; case KeyEvent::KEY_w: // toggle wire frame mDrawWireframe = !mDrawWireframe; break; case KeyEvent::KEY_SPACE: // reset camera resetCamera(); break; case KeyEvent::KEY_a: if( mAmplitudeTarget < 10.0f ) mAmplitudeTarget = 10.0f; else mAmplitudeTarget = 0.0f; break; case KeyEvent::KEY_q: mEnableShader = !mEnableShader; break; } } void SmoothDisplacementMappingApp::keyUp( KeyEvent event ) { } void SmoothDisplacementMappingApp::createMesh() { // use the TriMesh class to easily construct the vertex buffer object TriMesh mesh; // create vertex, normal and texcoord buffers const int RES_X = 400; const int RES_Z = 100; const Vec3f size(200.0f, 1.0f, 50.0f); for(int x=0;x<RES_X;++x) { for(int z=0;z<RES_Z;++z) { float u = float(x) / RES_X; float v = float(z) / RES_Z; mesh.appendVertex( size * Vec3f( u - 0.5f , 0.0f, v - 0.5f ) ); mesh.appendNormal( Vec3f::yAxis() ); mesh.appendTexCoord( Vec2f( u, v ) ); } } // create index buffer vector< uint32_t > indices; for(int x=0;x<RES_X-1;++x) { for(int z=0;z<RES_Z-1;++z) { uint32_t i = x * RES_Z + z; indices.push_back( i ); indices.push_back( i + 1 ); indices.push_back( i + RES_Z ); indices.push_back( i + RES_Z ); indices.push_back( i + 1 ); indices.push_back( i + RES_Z + 1 ); } } mesh.appendIndices( &indices.front(), indices.size() ); // construct vertex buffer object gl::VboMesh::Layout layout; layout.setStaticPositions(); layout.setStaticTexCoords2d(); layout.setStaticIndices(); layout.setStaticNormals(); mVboMesh = gl::VboMesh( mesh, layout ); } void SmoothDisplacementMappingApp::createTextures() { try { mBackgroundTexture = gl::Texture( loadImage( loadAsset( "background.png") ) ); } catch( const std::exception &e ) { console() << "Could not load image: " << e.what() << std::endl; } } CINDER_APP_BASIC( SmoothDisplacementMappingApp, RendererGl )
26.480813
117
0.718779
[ "mesh", "render", "object", "vector", "3d" ]
5100090887e728cb02d6dc92df68a6bb7ae4110f
3,902
cpp
C++
Testbed/Tests/VerticalStack.cpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
88
2017-07-13T18:12:40.000Z
2022-03-23T03:43:11.000Z
Testbed/Tests/VerticalStack.cpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
388
2017-07-13T04:32:09.000Z
2021-11-10T20:59:23.000Z
Testbed/Tests/VerticalStack.cpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
18
2017-07-20T16:14:57.000Z
2021-06-20T07:17:23.000Z
/* * Original work Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * Modified work Copyright (c) 2021 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "../Framework/Test.hpp" #include <array> namespace testbed { class VerticalStack : public Test { public: static inline const auto registered = RegisterTest("Vertical Stack", MakeUniqueTest<VerticalStack>); enum { e_columnCount = 5, e_rowCount = 10 // e_columnCount = 1, // e_rowCount = 1 }; VerticalStack() { m_bulletshape = CreateShape( GetWorld(), DiskShapeConf{}.UseRadius(0.25_m).UseDensity(20_kgpm2).UseRestitution(Real(0.05))); const auto ground = CreateBody(GetWorld()); Attach(GetWorld(), ground, CreateShape(GetWorld(), EdgeShapeConf{Vec2(-40.0f, 0.0f) * 1_m, Vec2(40.0f, 0.0f) * 1_m})); Attach(GetWorld(), ground, CreateShape(GetWorld(), EdgeShapeConf{Vec2(20.0f, 0.0f) * 1_m, Vec2(20.0f, 20.0f) * 1_m})); const float xs[] = {0.0f, -10.0f, -5.0f, 5.0f, 10.0f}; assert(e_columnCount <= sizeof(xs) / sizeof(xs[0])); const auto hdim = Real{0.1f}; // 0.5f is less stable than 1.0f for boxes not at origin (x of 0) const auto shape = CreateShape( GetWorld(), PolygonShapeConf{}.UseDensity(1_kgpm2).UseFriction(Real(0.3)).SetAsBox( hdim * 1_m, hdim * 1_m)); for (auto j = 0; j < e_columnCount; ++j) { for (auto i = 0; i < e_rowCount; ++i) { BodyConf bd; bd.type = BodyType::Dynamic; bd.linearAcceleration = GetGravity(); const auto x = 0.0f; // const auto x = RandomFloat(-0.02f, 0.02f); // const auto x = i % 2 == 0 ? -0.01f : 0.01f; // bd.position = Vec2(xs[j] + x, (hdim - hdim/20) + (hdim * 2 - hdim / 20) * i); bd.location = Vec2(xs[j] + x, (i + 1) * hdim * 4) * 1_m; Attach(GetWorld(), CreateBody(GetWorld(), bd), shape); } } m_bullet = InvalidBodyID; RegisterForKey(GLFW_KEY_COMMA, GLFW_PRESS, 0, "Launch a bullet.", [&](KeyActionMods) { if (IsValid(m_bullet)) { Destroy(GetWorld(), m_bullet); m_bullet = InvalidBodyID; } { BodyConf bd; bd.type = BodyType::Dynamic; bd.linearAcceleration = GetGravity(); bd.bullet = true; bd.location = Vec2(-31.0f, 5.0f) * 1_m; m_bullet = CreateBody(GetWorld(), bd); Attach(GetWorld(), m_bullet, m_bulletshape); SetVelocity(GetWorld(), m_bullet, Velocity{Vec2(400.0f, 0.0f) * 1_mps, 0_rpm}); } }); } BodyID m_bullet; ShapeID m_bulletshape = InvalidShapeID; }; } // namespace testbed
37.883495
96
0.576115
[ "shape" ]
eee1434fd2fa43389080590b9ae3eefbadafd17d
3,644
cpp
C++
src/Modules/WorldMenu/WorldMenuItemRepository.cpp
eegeo/cardboard-vr-integration
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
8
2017-07-02T01:14:29.000Z
2021-06-19T07:14:38.000Z
src/Modules/WorldMenu/WorldMenuItemRepository.cpp
eegeo/cardboard-vr-demo
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
null
null
null
src/Modules/WorldMenu/WorldMenuItemRepository.cpp
eegeo/cardboard-vr-demo
3f0c3d0f1b7ddaa6b2ef980e46ead71c8a85a260
[ "BSD-2-Clause" ]
5
2018-02-07T07:43:51.000Z
2020-01-24T12:29:25.000Z
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include "WorldMenuItemRepository.h" #include "WorldMenuItem.h" #include "IWorldMenuItemObserver.h" #include <algorithm> namespace Eegeo { namespace UI { namespace WorldMenu { WorldMenuItemRepository::WorldMenuItemRepository() { } WorldMenuItemRepository::~WorldMenuItemRepository() { m_observers.clear(); m_worldMenuItem.clear(); } void WorldMenuItemRepository::AddWorldMenuItem(WorldMenuItem* pWorldMenuItemToAdd) { m_worldMenuItem.push_back(pWorldMenuItemToAdd); for (int i = 0; i < m_observers.size(); i++) { m_observers[i]->OnWorldMenuItemAdded(*pWorldMenuItemToAdd); } } void WorldMenuItemRepository::RemoveWorldMenuItem(WorldMenuItem* pWorldMenuItemToRemove) { std::vector<WorldMenuItem*>::iterator position = std::find(m_worldMenuItem.begin(), m_worldMenuItem.end(), pWorldMenuItemToRemove); if (position != m_worldMenuItem.end()) { m_worldMenuItem.erase(position); for (int i = 0; i < m_observers.size(); i++) { m_observers[i]->OnWorldMenuItemRemoved(*pWorldMenuItemToRemove); } } } int WorldMenuItemRepository::GetNumOfWorldMenuItems() const { return (int)m_worldMenuItem.size(); } WorldMenuItem* WorldMenuItemRepository::GetWorldMenuItemAtIndex(int worldMenuItemIndex) const { return m_worldMenuItem[worldMenuItemIndex]; } WorldMenuItem* WorldMenuItemRepository::GetWorldMenuItemById(TWorldMenuItemId id) const { for (int i=0; i<GetNumOfWorldMenuItems(); i++) { if (m_worldMenuItem[i]->GetId() == id) { return m_worldMenuItem[i]; } } return NULL; } void WorldMenuItemRepository::AddWorldMenuObserver(IWorldMenuItemObserver* pObserverToAdd) { m_observers.push_back(pObserverToAdd); } void WorldMenuItemRepository::RemoveWorldMenuObserver(IWorldMenuItemObserver* pObserverToRemove) { std::vector<IWorldMenuItemObserver*>::iterator position = std::find(m_observers.begin(), m_observers.end(), pObserverToRemove); if (position != m_observers.end()) m_observers.erase(position); } bool WorldMenuItemRepository::ContainsWorldMenuItem(const WorldMenuItem* pWorldMenuItemToCheck) const { for (int i=0; i<GetNumOfWorldMenuItems(); i++) { if (m_worldMenuItem[i] == pWorldMenuItemToCheck) { return true; } } return false; } bool WorldMenuItemRepository::ContainsWorldMenuItemId(TWorldMenuItemId worldMenuItemId) const { if (GetWorldMenuItemById(worldMenuItemId) != NULL) { return true; } return false; } } } }
36.079208
147
0.518112
[ "vector" ]
eef4c7560698feaf77c57afeccd0f38b1c2f93fe
980
cpp
C++
MoravaEngine/src/Mesh/Quad.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Mesh/Quad.cpp
imgui-works/MoravaEngine_opengl_vulkan_2d_3d_game_engine
b8e6ee3c3c890e9b8cf5de7bcb564b32f6767b6b
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Mesh/Quad.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#include "Quad.h" #include "GL/glew.h" Quad::Quad() : Mesh() { float quadVertices[] = { // positions // texture Coords -1.0f, -1.0f, 0.0f, 0.0f, 1.0f, // bottom left 1.0f, -1.0f, 0.0f, 1.0f, 1.0f, // bottom right -1.0f, 1.0f, 0.0f, 0.0f, 0.0f, // top left 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, // top right }; // setup plane VAO unsigned int m_VBO = 0; glGenVertexArrays(1, &m_VAO); glGenBuffers(1, &m_VBO); glBindVertexArray(m_VAO); glBindBuffer(GL_ARRAY_BUFFER, m_VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float))); } void Quad::Render() { glBindVertexArray(m_VAO); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glBindVertexArray(0); } Quad::~Quad() { }
24.5
96
0.65
[ "mesh", "render" ]
eef7d0be0ecf0aa66f5280d74a9016d0271d29dc
8,919
cpp
C++
Source/WhiteNoise/private/WNCharacter.cpp
CarstenZarbock/WhiteNoise
306a0126ef0bf83ca9f906aea6b48c99eca1f38f
[ "MIT" ]
9
2017-07-22T23:14:23.000Z
2021-03-25T19:14:58.000Z
Source/WhiteNoise/private/WNCharacter.cpp
CarstenZarbock/WhiteNoise
306a0126ef0bf83ca9f906aea6b48c99eca1f38f
[ "MIT" ]
1
2020-08-29T12:11:38.000Z
2020-08-29T12:11:38.000Z
Source/WhiteNoise/private/WNCharacter.cpp
CarstenZarbock/WhiteNoise
306a0126ef0bf83ca9f906aea6b48c99eca1f38f
[ "MIT" ]
2
2018-08-05T08:09:09.000Z
2018-08-13T07:41:01.000Z
// Copyright 2016 Carsten Zarbock / Rebound-Software #include "WhiteNoise.h" #include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h" #include "WNCharacter.h" #include "Door_SwingSingle.h" AWhiteNoiseCharacter::AWhiteNoiseCharacter() { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; GetCapsuleComponent()->OnComponentHit.AddDynamic(this, &AWhiteNoiseCharacter::OnHit); GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f); bUseControllerRotationPitch = false; bUseControllerRotationYaw = false; bUseControllerRotationRoll = false; GetCharacterMovement()->bOrientRotationToMovement = false; //no character oritation to movement GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f); GetCharacterMovement()->bConstrainToPlane = true; GetCharacterMovement()->bSnapToPlaneAtStart = true; WeaponThrowArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("WeaponThrowArm")); WeaponThrowArm->SetupAttachment(RootComponent); WeaponThrowArm->TargetArmLength = 150.0f; WeaponThrowArm->bDoCollisionTest = true; CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom")); CameraBoom->SetupAttachment(RootComponent); CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does CameraBoom->TargetArmLength = 800.0f; CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f); CameraBoom->bDoCollisionTest = false; // no collision test, celing gets ignored TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera")); TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName); TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm WeaponGripPoint = CreateDefaultSubobject<USceneComponent>(TEXT("WeaponGripPoint")); WeaponGripPoint->SetupAttachment(this->GetMesh()); this->CurrentWeapon = nullptr; this->LockedEnemy = nullptr; } void AWhiteNoiseCharacter::BeginPlay() { Super::BeginPlay(); /* mesh(es) not initialised in constructor, attach at beginplay */ WeaponGripPoint->AttachToComponent(this->GetMesh(), FAttachmentTransformRules(EAttachmentRule::SnapToTarget, true), TEXT("RightHand")); /* reset relative rotation after attachement */ WeaponGripPoint->SetRelativeRotation(FQuat::MakeFromEuler(FVector(-90.0f, 170.0f, 80.0f))); //todo: Better solution? } void AWhiteNoiseCharacter::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComponent, FVector NormalImpulse, const FHitResult& Hit) { ADoorSwingSingle* Door = Cast<ADoorSwingSingle>(OtherActor); if (Door) { Door->Open(this->GetActorLocation() - Door->GetActorLocation()); } } void AWhiteNoiseCharacter::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); this->HandleEnemyLock(); if (this->bIsFiring) { this->WeaponFire_Execute(); } } void AWhiteNoiseCharacter::HandleMovement(FVector worldDirection, float fRate) { this->AddMovementInput(worldDirection, fRate); } void AWhiteNoiseCharacter::HandleRotation(FVector worldPosition) { FVector vecDirection = this->GetActorLocation() - worldPosition; vecDirection = FVector(vecDirection.X, vecDirection.Y, 0); vecDirection *= -1; //todo: fix calc /* currently only face upper body mesh */ FRotator TargetRot = FRotationMatrix::MakeFromX(vecDirection).Rotator(); this->UpperBodyRotation = TargetRot; //todo: handle lower torso rotation, set sidewalk & backwards animations //currently lower torso is facing walk direction, upper body is facing look direction, //results in weird spine rotation } void AWhiteNoiseCharacter::CameraFreeMove(FVector worldDirection, float fRate) { FVector RelLoc = this->TopDownCameraComponent->GetRelativeTransform().GetLocation(); RelLoc += worldDirection * fRate; if (RelLoc.Z >= this->MaxFreeCamDistance || RelLoc.Z <= (this->MaxFreeCamDistance * -1)) { RelLoc.Z = this->TopDownCameraComponent->GetRelativeTransform().GetLocation().Z; } if (RelLoc.Y >= this->MaxFreeCamDistance || RelLoc.Y <= (this->MaxFreeCamDistance * -1)) { RelLoc.Y = this->TopDownCameraComponent->GetRelativeTransform().GetLocation().Y; } this->TopDownCameraComponent->SetRelativeLocation(RelLoc); } void AWhiteNoiseCharacter::ResetFreeCam() { this->TopDownCameraComponent->SetRelativeLocation(FVector(0, 0, 0)); } bool AWhiteNoiseCharacter::CameraFreeMoveToggle(const bool bIsCameraFreeMovement) { /* if Cutscene (e.g.) return false; */ this->bIsCameraFreeMovement = bIsCameraFreeMovement; if (!this->bIsCameraFreeMovement) { this->ResetFreeCam(); } return this->bIsCameraFreeMovement; } FVector AWhiteNoiseCharacter::GetMouseCursorPosition() const { //todo: -replace GetWord()->GetFirstPlayerController() with a Multiplayer compatible solution (Local Splitscreen / Serverside), if needed FHitResult Hit; GetWorld()->GetFirstPlayerController()->GetHitResultUnderCursor(ECC_Visibility, false, Hit); if (Hit.bBlockingHit) { return Hit.ImpactPoint; } return{ 0, 0, 0 }; //todo: Add failed return to avoid wrong reaction } void AWhiteNoiseCharacter::ManualRotation(const FVector worldPosition) { if (!this->bHasLockedEnemy) { this->HandleRotation(worldPosition); } } void AWhiteNoiseCharacter::HandleEnemyLock() { if (this->bHasLockedEnemy && this->LockedEnemy != nullptr) { if (this->LockedEnemy->IsValidLowLevel()) { if (this->LockedEnemy->IsAlive()) { this->HandleRotation(this->LockedEnemy->GetActorLocation()); } else { this->LockedEnemy = nullptr; this->bHasLockedEnemy = false; } } } } bool AWhiteNoiseCharacter::LockEnemy(ANPC* LockedEnemy) { if (LockedEnemy != nullptr && LockedEnemy->IsValidLowLevel()) { this->bHasLockedEnemy = true; this->LockedEnemy = LockedEnemy; } else { this->bHasLockedEnemy = false; this->LockedEnemy = nullptr; } return this->bHasLockedEnemy; } void AWhiteNoiseCharacter::Input_Pickup() { //todo: Add a check, if mouse cursor points on a weapon. Pick up first. for (TActorIterator<AWeapon> ActorItr(GetWorld()); ActorItr; ++ActorItr) { AWeapon* WeaponActor = *ActorItr; if (WeaponActor != nullptr && WeaponActor->IsValidLowLevel()) { if (WeaponActor->GetState() == EWeaponState::WS_WORLD) { float fDistance = FVector::Dist(this->GetActorLocation(), WeaponActor->GetActorLocation()); if (fDistance <= this->WeaponPickupDistance) { this->WeaponPickup(WeaponActor); return; } } } } } void AWhiteNoiseCharacter::ForceWeaponEquip(AWeapon* weaponActor) { if (weaponActor != nullptr && weaponActor->IsValidLowLevel()) { this->WeaponPickup(weaponActor); } } void AWhiteNoiseCharacter::WeaponPickup(AWeapon* weaponActor) { if (this->CurrentWeapon != nullptr) { this->WeaponDrop(); } weaponActor->ChangeState(EWeaponState::WS_EQUIP); this->CurrentWeapon = weaponActor; weaponActor->AttachToComponent(this->WeaponGripPoint, FAttachmentTransformRules::SnapToTargetNotIncludingScale); this->CurrentAnimation = weaponActor->GetTargetAnimation(); } void AWhiteNoiseCharacter::WeaponDrop() { if (this->CurrentWeapon != nullptr && this->CurrentWeapon->IsValidLowLevel()) { this->CurrentWeapon->DetachRootComponentFromParent(true); FVector newLocation = this->WeaponThrowArm->GetSocketLocation(USpringArmComponent::SocketName); this->CurrentWeapon->SetActorLocation(newLocation); this->CurrentWeapon->ChangeState(EWeaponState::WS_WORLD); this->CurrentWeapon = nullptr; this->CurrentAnimation = ETargetAnimation::TA_NORMAL; } } void AWhiteNoiseCharacter::WeaponThrow() { if (this->CurrentWeapon != nullptr && this->CurrentWeapon->IsValidLowLevel() && !this->bIsCameraFreeMovement) { AWeapon* weaponActor = this->CurrentWeapon; this->WeaponDrop(); const float throwForce = 100000.0f; //todo: calculate the force weaponActor->ChangeState(EWeaponState::WS_THROWN); weaponActor->WeaponMesh->AddImpulseAtLocation((this->UpperBodyRotation.Vector() * throwForce), weaponActor->GetActorLocation()); } } void AWhiteNoiseCharacter::WeaponFire_Execute() { if (this->CurrentWeapon != nullptr && this->CurrentWeapon->IsValidLowLevel() && !this->bIsCameraFreeMovement) { if (this->LockedEnemy == nullptr) { this->CurrentWeapon->Fire(this->GetMouseCursorPosition()); } else { if (this->LockedEnemy->IsValidLowLevel()) { this->CurrentWeapon->Fire(this->LockedEnemy->GetActorLocation()); } } } } void AWhiteNoiseCharacter::WeaponFire_Start() { if (this->CurrentWeapon != nullptr && this->CurrentWeapon->IsValidLowLevel() && !this->bIsCameraFreeMovement) { if (this->CurrentWeapon->GetWeaponType() == EWeaponType::WT_SINGLE) { this->WeaponFire_Execute(); } else if (this->CurrentWeapon->GetWeaponType() == EWeaponType::WT_AUTOMATIC) { this->bIsFiring = true; } } } void AWhiteNoiseCharacter::WeaponFire_Stop() { this->bIsFiring = false; }
29.533113
170
0.754793
[ "mesh", "vector" ]
eef81aadf2ac37ab35783b105ce05d80df3d4724
18,388
cpp
C++
src/plugins/azoth/contactlistdelegate.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/azoth/contactlistdelegate.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
src/plugins/azoth/contactlistdelegate.cpp
MellonQ/leechcraft
71cbb238d2dade56b3865278a6a8e6a58c217fc5
[ "BSL-1.0" ]
null
null
null
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Boost Software License - Version 1.0 - August 17th, 2003 * * Permission is hereby granted, free of charge, to any person or organization * obtaining a copy of the software and accompanying documentation covered by * this license (the "Software") to use, reproduce, display, distribute, * execute, and transmit the Software, and to prepare derivative works of the * Software, and to permit third-parties to whom the Software is furnished to * do so, all subject to the following: * * The copyright notices in the Software and this entire statement, including * the above license grant, this restriction and the following disclaimer, * must be included in all copies of the Software, in whole or in part, and * all derivative works of the Software, unless such copies or derivative * works are solely in the form of machine-executable object code generated by * a source language processor. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. **********************************************************************/ #include "contactlistdelegate.h" #include <algorithm> #include <QPainter> #include <QPixmap> #include <QApplication> #include <QAbstractProxyModel> #include <QTreeView> #include <util/sys/resourceloader.h> #include <util/xpc/defaulthookproxy.h> #include <interfaces/media/audiostructs.h> #include "interfaces/azoth/iclentry.h" #include "interfaces/azoth/isupportgeolocation.h" #include "interfaces/azoth/iaccount.h" #include "interfaces/azoth/iextselfinfoaccount.h" #include "interfaces/azoth/ihavecontacttune.h" #include "interfaces/azoth/ihavecontactmood.h" #include "interfaces/azoth/ihavecontactactivity.h" #include "core.h" #include "xmlsettingsmanager.h" #include "util.h" #include "resourcesmanager.h" namespace LeechCraft { namespace Azoth { const int CPadding = 2; ContactListDelegate::ContactListDelegate (QTreeView* parent) : QStyledItemDelegate (parent) , ContactHeight_ (24) , View_ (parent) { handleShowAvatarsChanged (); handleShowClientIconsChanged (); handleActivityIconsetChanged (); handleMoodIconsetChanged (); handleSystemIconsetChanged (); handleShowStatusesChanged (); handleHighlightGroupsChanged (); handleContactHeightChanged (); XmlSettingsManager::Instance ().RegisterObject ("ShowAvatars", this, "handleShowAvatarsChanged"); XmlSettingsManager::Instance ().RegisterObject ("ShowClientIcons", this, "handleShowClientIconsChanged"); XmlSettingsManager::Instance ().RegisterObject ("ActivityIcons", this, "handleActivityIconsetChanged"); XmlSettingsManager::Instance ().RegisterObject ("MoodIcons", this, "handleMoodIconsetChanged"); XmlSettingsManager::Instance ().RegisterObject ("SystemIcons", this, "handleSystemIconsetChanged"); XmlSettingsManager::Instance ().RegisterObject ("ShowStatuses", this, "handleShowStatusesChanged"); XmlSettingsManager::Instance ().RegisterObject ("HighlightGroups", this, "handleHighlightGroupsChanged"); XmlSettingsManager::Instance ().RegisterObject ("RosterContactHeight", this, "handleContactHeightChanged"); Core::Instance ().RegisterHookable (this); } void ContactListDelegate::paint (QPainter *painter, const QStyleOptionViewItem& sopt, const QModelIndex& index) const { QStyleOptionViewItemV4 o = sopt; Core::CLEntryType type = index.data (Core::CLREntryType).value<Core::CLEntryType> (); painter->save (); switch (type) { case Core::CLETAccount: DrawAccount (painter, o, index); break; case Core::CLETCategory: DrawCategory (painter, o, index); break; case Core::CLETContact: o.rect.adjust (-1.2 * View_->indentation (), 0, 0, 0); DrawContact (painter, o, index); break; } painter->restore (); } QSize ContactListDelegate::sizeHint (const QStyleOptionViewItem& option, const QModelIndex& index) const { QSize size = QStyledItemDelegate::sizeHint (option, index); switch (index.data (Core::CLREntryType).value<Core::CLEntryType> ()) { case Core::CLETContact: if (size.height () < ContactHeight_) size.setHeight (ContactHeight_); break; case Core::CLETAccount: size.setHeight (size.height () * 1.5); break; case Core::CLETCategory: const int textHeight = option.fontMetrics.height (); size.setHeight (qMax (textHeight + CPadding * 2, size.height ())); break; } return size; } void ContactListDelegate::DrawAccount (QPainter *painter, QStyleOptionViewItemV4 o, const QModelIndex& index) const { QStyle *style = o.widget ? o.widget->style () : QApplication::style (); painter->save (); painter->setRenderHints (QPainter::HighQualityAntialiasing | QPainter::Antialiasing); style->drawPrimitive (QStyle::PE_PanelButtonCommand, &o, painter, o.widget); painter->restore (); o.font.setBold (true); QStyledItemDelegate::paint (painter, o, index); const auto acc = index.data (Core::CLRAccountObject).value<IAccount*> (); const auto extAcc = qobject_cast<IExtSelfInfoAccount*> (acc->GetQObject ()); QIcon accIcon = extAcc ? extAcc->GetAccountIcon () : QIcon (); if (accIcon.isNull ()) accIcon = qobject_cast<IProtocol*> (acc->GetParentProtocol ())->GetProtocolIcon (); const QRect& r = o.rect; const int iconSize = r.height () - 2 * CPadding; QImage avatarImg; if (extAcc) avatarImg = extAcc->GetSelfAvatar (); if (avatarImg.isNull ()) avatarImg = ResourcesManager::Instance ().GetDefaultAvatar (iconSize); else avatarImg = avatarImg.scaled (iconSize, iconSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); QPoint pxDraw = o.rect.topRight () - QPoint (CPadding, 0); if (!avatarImg.isNull ()) { pxDraw.rx () -= avatarImg.width (); const QPoint delta { 0, (r.height () - avatarImg.height ()) / 2 }; painter->drawPixmap (pxDraw + delta, QPixmap::fromImage (avatarImg)); pxDraw.rx () -= CPadding; } if (!accIcon.isNull ()) { const int size = std::min (16, iconSize); const QPixmap& px = accIcon.pixmap (size, size); pxDraw.rx () -= px.width (); const QPoint delta { 0, (r.height () - px.height ()) / 2 }; painter->drawPixmap (pxDraw + delta, px); } } namespace { QPair<int, int> GetCounts (const QModelIndex& index) { const int visibleCount = index.model ()->rowCount (index); auto model = index.model (); auto sourceIndex = index; while (auto proxyModel = qobject_cast<const QAbstractProxyModel*> (model)) { model = proxyModel->sourceModel (); sourceIndex = proxyModel->mapToSource (sourceIndex); } if (model->rowCount (sourceIndex) != visibleCount) return { visibleCount, model->rowCount (sourceIndex) }; const auto numOnline = index.data (Core::CLRNumOnline).toInt (); return { numOnline, visibleCount }; } } void ContactListDelegate::DrawCategory (QPainter *painter, QStyleOptionViewItemV4 o, const QModelIndex& index) const { const QRect& r = o.rect; auto style = o.widget ? o.widget->style () : QApplication::style (); style->drawPrimitive (HighlightGroups_ ? QStyle::PE_PanelButtonCommand : QStyle::PE_PanelItemViewRow, &o, painter, o.widget); const int unread = index.data (Core::CLRUnreadMsgCount).toInt (); if (unread) { painter->save (); const QString& text = QString (" %1 :: ").arg (unread); QFont unreadFont = o.font; unreadFont.setBold (true); int unreadSpace = CPadding + QFontMetrics (unreadFont).width (text); painter->setFont (unreadFont); painter->drawText (r.left () + CPadding, r.top () + CPadding, unreadSpace, r.height () - 2 * CPadding, Qt::AlignVCenter | Qt::AlignLeft, text); painter->restore (); o.rect.setLeft (unreadSpace + o.rect.left ()); } QStyledItemDelegate::paint (painter, o, index); o.state &= ~(QStyle::State_Selected | QStyle::State_MouseOver); const int textWidth = o.fontMetrics.width (index.data ().value<QString> () + " "); const int rem = r.width () - textWidth; const auto& counts = GetCounts (index); const QString& str = QString (" %1/%2 ") .arg (counts.first) .arg (counts.second); painter->save (); painter->setRenderHints (QPainter::HighQualityAntialiasing | QPainter::Antialiasing); if (rem >= o.fontMetrics.width (str)) { if (o.state & QStyle::State_Selected) painter->setPen (o.palette.color (QPalette::HighlightedText)); QFont font = painter->font (); font.setItalic (true); painter->setFont (font); const QRect numRect (r.left () + textWidth - 1, r.top () + CPadding, rem - 1, r.height () - 2 * CPadding); painter->drawText (numRect, Qt::AlignVCenter | Qt::AlignRight, str); } painter->restore (); } void ContactListDelegate::DrawContact (QPainter *painter, QStyleOptionViewItemV4 option, const QModelIndex& index) const { QObject *entryObj = index.data (Core::CLREntryObject).value<QObject*> (); ICLEntry *entry = qobject_cast<ICLEntry*> (entryObj); const bool isMUC = entry->GetEntryType () == ICLEntry::EntryType::MUC; QStyle *style = option.widget ? option.widget->style () : QApplication::style (); const QRect& r = option.rect; const int sHeight = r.height (); const int iconSize = sHeight - 2 * CPadding; const int clientIconSize = (iconSize > 16) ? 16 : iconSize; const QIcon& stateIcon = index.data (Qt::DecorationRole).value<QIcon> (); QString name = index.data (Qt::DisplayRole).value<QString> (); const QString status = entry->GetStatus ().StatusString_.replace ('\n', ' '); const QImage& avatarImg = ShowAvatars_ ? Core::Instance ().GetAvatar (entry, iconSize) : QImage (); const int unreadNum = index.data (Core::CLRUnreadMsgCount).toInt (); const QString& unreadStr = unreadNum ? QString (" %1 :: ").arg (unreadNum) : QString (); if (ShowStatuses_ && !status.isEmpty ()) name += " (" + status + ")"; const bool selected = option.state & QStyle::State_Selected; const QColor fgColor = selected ? option.palette.color (QPalette::HighlightedText) : option.palette.color (QPalette::Text); QFont unreadFont; int unreadSpace = 0; if (unreadNum) { unreadFont = option.font; unreadFont.setBold (true); unreadSpace = CPadding + QFontMetrics (unreadFont).width (unreadStr); } const int textShift = 2 * CPadding + iconSize + unreadSpace; const QStringList& vars = entry->Variants (); const auto& clientIcons = GetContactIcons (index, entry, vars); const int clientsIconsWidth = clientIcons.isEmpty () ? 0 : clientIcons.size () * (clientIconSize + CPadding); /* text for width is total width minus shift of the text from * the left (textShift) minus space for avatar (if present) with * paddings minus space for client icons and paddings between * them: there are N-1 paddings inbetween if there are N icons. */ const int textWidth = r.width () - textShift - (isMUC || !ShowAvatars_ ? 0 : (iconSize + 2 * CPadding)) - clientsIconsWidth; QPixmap pixmap (r.size ()); pixmap.fill (option.palette.color (QPalette::Base)); QPainter p (&pixmap); if (selected || (option.state & QStyle::State_MouseOver)) { QStyleOptionViewItemV4 bgOpt = option; bgOpt.rect.moveTopLeft (QPoint (0, 0)); style->drawPrimitive (QStyle::PE_PanelItemViewItem, &bgOpt, &p, option.widget); } p.setPen (fgColor); if (unreadNum) { p.setFont (unreadFont); p.drawText (textShift - unreadSpace, CPadding, textWidth, r.height () - 2 * CPadding, Qt::AlignVCenter | Qt::AlignLeft, unreadStr); } p.setFont (option.font); p.drawText (textShift, CPadding, textWidth, r.height () - 2 * CPadding, Qt::AlignVCenter | Qt::AlignLeft, option.fontMetrics.elidedText (name, Qt::ElideRight, textWidth)); const QPixmap& stateIconPx = stateIcon.pixmap (iconSize, iconSize); p.drawPixmap (QPoint (CPadding, (sHeight - stateIconPx.height ()) / 2), stateIconPx); if (!avatarImg.isNull ()) p.drawPixmap (QPoint (textShift + textWidth + clientsIconsWidth + CPadding, CPadding), QPixmap::fromImage (avatarImg)); int currentShift = textShift + textWidth + CPadding; for (const auto& icon : clientIcons) { const auto& px = icon.pixmap (clientIconSize, clientIconSize); p.drawPixmap (QPoint { currentShift, (sHeight - px.size ().height ()) / 2 }, px); currentShift += clientIconSize + CPadding; } painter->drawPixmap (option.rect, pixmap); } QList<QIcon> ContactListDelegate::GetContactIcons (const QModelIndex& index, ICLEntry *entry, const QStringList& vars) const { QList<QIcon> clientIcons; const bool isMUC = entry->GetEntryType () == ICLEntry::EntryType::MUC; if (!isMUC && ShowClientIcons_) { const auto& iconsMap = ResourcesManager::Instance ().GetClientIconForEntry (entry); for (int i = 0; i < std::min (vars.size (), 4); ++i) clientIcons << iconsMap [vars.at (i)]; clientIcons.erase (std::remove_if (clientIcons.begin (), clientIcons.end (), [] (const QIcon& icon) { return icon.isNull (); }), clientIcons.end ()); } if (entry->GetEntryType () == ICLEntry::EntryType::PrivateChat) { const QByteArray& aff = index.data (Core::CLRAffiliation).toByteArray (); const QIcon& icon = ResourcesManager::Instance ().GetAffIcon (aff); if (!icon.isNull ()) clientIcons.prepend (icon); } if (vars.isEmpty ()) { emit hookCollectContactIcons (IHookProxy_ptr { new Util::DefaultHookProxy }, entry->GetQObject (), clientIcons); return clientIcons; } if (const auto ihca = qobject_cast<IHaveContactActivity*> (entry->GetQObject ())) { QString iconName; for (const auto& var : vars) { const auto& info = ihca->GetUserActivity (var); iconName = GetActivityIconName (info.General_, info.Specific_); if (!iconName.isEmpty ()) { iconName.prepend (ActivityIconset_ + '/'); break; } } auto icon = ActivityIconCache_ [iconName]; if (icon.isNull ()) icon = QIcon (ResourcesManager::Instance () .GetResourceLoader (ResourcesManager::RLTActivityIconLoader)-> GetIconPath (iconName)); if (!icon.isNull ()) { clientIcons.prepend (icon); ActivityIconCache_ [iconName] = icon; } } if (const auto ihcm = qobject_cast<IHaveContactMood*> (entry->GetQObject ())) { QString iconName; for (const auto& var : vars) { iconName = ihcm->GetUserMood (var).Mood_; if (!iconName.isEmpty ()) { iconName [0] = iconName.at (0).toUpper (); iconName.prepend (MoodIconset_ + '/'); break; } } auto icon = MoodIconCache_ [iconName]; if (icon.isNull ()) icon = QIcon (ResourcesManager::Instance () .GetResourceLoader (ResourcesManager::RLTMoodIconLoader)-> GetIconPath (iconName)); if (!icon.isNull ()) { clientIcons.prepend (icon); MoodIconCache_ [iconName] = icon; } } if (const auto ihct = qobject_cast<IHaveContactTune*> (entry->GetQObject ())) { if (std::any_of (vars.begin (), vars.end (), [ihct] (const QString& var) { const auto& info = ihct->GetUserTune (var); return !info.Artist_.isEmpty () || !info.Album_.isEmpty (); })) LoadSystemIcon ("/notification_roster_tune", clientIcons); } if (auto geoloc = qobject_cast<ISupportGeolocation*> (entry->GetParentAccount ()->GetQObject ())) { const auto& info = geoloc->GetUserGeolocationInfo (entry->GetQObject (), vars.value (0)); if (!info.isEmpty ()) LoadSystemIcon ("/geolocation", clientIcons); } emit hookCollectContactIcons (IHookProxy_ptr { new Util::DefaultHookProxy }, entry->GetQObject (), clientIcons); return clientIcons; } void ContactListDelegate::LoadSystemIcon (const QString& name, QList<QIcon>& clientIcons) const { const QString& iconName = SystemIconset_ + name; QIcon icon = SystemIconCache_ [iconName]; if (icon.isNull ()) icon = QIcon (ResourcesManager::Instance () .GetResourceLoader (ResourcesManager::RLTSystemIconLoader)-> GetIconPath (iconName)); if (!icon.isNull ()) { clientIcons.prepend (icon); SystemIconCache_ [iconName] = icon; } } void ContactListDelegate::handleShowAvatarsChanged () { ShowAvatars_ = XmlSettingsManager::Instance () .property ("ShowAvatars").toBool (); } void ContactListDelegate::handleShowClientIconsChanged () { ShowClientIcons_ = XmlSettingsManager::Instance () .property ("ShowClientIcons").toBool (); } void ContactListDelegate::handleActivityIconsetChanged () { ActivityIconCache_.clear (); ActivityIconset_ = XmlSettingsManager::Instance () .property ("ActivityIcons").toString (); } void ContactListDelegate::handleMoodIconsetChanged () { MoodIconCache_.clear (); MoodIconset_ = XmlSettingsManager::Instance () .property ("MoodIcons").toString (); } void ContactListDelegate::handleSystemIconsetChanged () { SystemIconCache_.clear (); SystemIconset_ = XmlSettingsManager::Instance () .property ("SystemIcons").toString (); } void ContactListDelegate::handleShowStatusesChanged () { ShowStatuses_ = XmlSettingsManager::Instance () .property ("ShowStatuses").toBool (); View_->viewport ()->update (); View_->update (); } void ContactListDelegate::handleHighlightGroupsChanged () { HighlightGroups_ = XmlSettingsManager::Instance () .property ("HighlightGroups").toBool (); View_->viewport ()->update (); View_->update (); } void ContactListDelegate::handleContactHeightChanged () { ContactHeight_ = XmlSettingsManager::Instance () .property ("RosterContactHeight").toInt (); if (ContactHeight_ <= 0) ContactHeight_ = 24; View_->setIconSize (QSize (ContactHeight_, ContactHeight_)); View_->viewport ()->update (); View_->update (); } } }
30.852349
105
0.686263
[ "object", "model" ]
eefd5b0e90e6d0d6320dee5f2d7f3f4023ea7230
8,266
cc
C++
src/systems/thruster/Thruster.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
198
2020-04-15T16:56:09.000Z
2022-03-27T12:31:08.000Z
src/systems/thruster/Thruster.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
1,220
2020-04-15T18:10:29.000Z
2022-03-31T22:37:06.000Z
src/systems/thruster/Thruster.cc
jasmeet0915/ign-gazebo
fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2
[ "ECL-2.0", "Apache-2.0" ]
134
2020-04-15T16:59:57.000Z
2022-03-26T08:51:31.000Z
/* * Copyright (C) 2021 Open Source Robotics Foundation * * 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 <memory> #include <mutex> #include <string> #include <ignition/math/Helpers.hh> #include <ignition/plugin/Register.hh> #include <ignition/transport/Node.hh> #include <ignition/msgs.hh> #include "ignition/gazebo/components/AngularVelocity.hh" #include "ignition/gazebo/components/ChildLinkName.hh" #include "ignition/gazebo/components/LinearVelocity.hh" #include "ignition/gazebo/components/JointAxis.hh" #include "ignition/gazebo/components/Pose.hh" #include "ignition/gazebo/components/World.hh" #include "ignition/gazebo/Link.hh" #include "ignition/gazebo/Model.hh" #include "ignition/gazebo/Util.hh" #include "Thruster.hh" using namespace ignition; using namespace gazebo; using namespace systems; class ignition::gazebo::systems::ThrusterPrivateData { /// \brief Mutex for read/write access to class public: std::mutex mtx; /// \brief Thrust output by propeller in N public: double thrust = 0.0; /// \brief The link entity which will spin public: ignition::gazebo::Entity linkEntity; /// \brief Axis along which the propeller spins public: ignition::math::Vector3d jointAxis; /// \brief ignition node for handling transport public: ignition::transport::Node node; /// \brief The PID which controls the rpm public: ignition::math::PID rpmController; /// \brief maximum input force [N], default: 1000N public: double cmdMax = 1000; /// \brief minimum input force [N], default: 1000N public: double cmdMin = -1000; /// \brief Thrust coefficient relating the /// propeller rpm to the thrust public: double thrustCoefficient = 1; /// \brief Density of fluid in kgm^-3, default: 1000kgm^-3 public: double fluidDensity = 1000; /// \brief Diameter of propeller in m, default: 0.02 public: double propellerDiameter = 0.02; /// \brief callback for handling thrust update public: void OnCmdThrust(const ignition::msgs::Double &_msg); /// \brief function which computes rpm from thrust public: double ThrustToAngularVec(double thrust); }; ///////////////////////////////////////////////// Thruster::Thruster() { this->dataPtr = std::make_unique<ThrusterPrivateData>(); } ///////////////////////////////////////////////// Thruster::~Thruster() { } ///////////////////////////////////////////////// void Thruster::Configure( const ignition::gazebo::Entity &_entity, const std::shared_ptr<const sdf::Element> &_sdf, ignition::gazebo::EntityComponentManager &_ecm, ignition::gazebo::EventManager &/*_eventMgr*/) { // Get namespace std::string ns {""}; if (_sdf->HasElement("namespace")) { ns = _sdf->Get<std::string>("namespace"); } // Get joint name if (!_sdf->HasElement("joint_name")) { ignerr << "No joint to treat as propeller found \n"; return; } auto jointName = _sdf->Get<std::string>("joint_name"); // Get thrust coefficient if (!_sdf->HasElement("thrust_coefficient")) { ignerr << "Failed to get thrust_coefficient" << "\n"; return; } this->dataPtr->thrustCoefficient = _sdf->Get<double>("thrust_coefficient"); // Get propeller diameter if (!_sdf->HasElement("propeller_diameter")) { ignerr << "Failed to get propeller_diameter \n"; } this->dataPtr->propellerDiameter = _sdf->Get<double>("propeller_diameter"); // Get fluid density, default to water otherwise if (_sdf->HasElement("fluid_density")) { this->dataPtr->fluidDensity = _sdf->Get<double>("fluid_density"); } igndbg << "Setting fluid density to: " << this->dataPtr->fluidDensity << "\n"; // Create model object, to access convenient functions auto model = ignition::gazebo::Model(_entity); auto jointEntity = model.JointByName(_ecm, jointName); auto childLink = _ecm.Component<ignition::gazebo::components::ChildLinkName>(jointEntity); this->dataPtr->jointAxis = _ecm.Component<ignition::gazebo::components::JointAxis>(jointEntity) ->Data().Xyz(); std::string thrusterTopic = ignition::transport::TopicUtils::AsValidTopic( "/model/" + ns + "/joint/" + jointName + "/cmd_pos"); this->dataPtr->node.Subscribe( thrusterTopic, &ThrusterPrivateData::OnCmdThrust, this->dataPtr.get()); // Get link entity this->dataPtr->linkEntity = model.LinkByName(_ecm, childLink->Data()); // Create an angular velocity component if one is not present. if (!_ecm.Component<ignition::gazebo::components::AngularVelocity>( this->dataPtr->linkEntity)) { _ecm.CreateComponent(this->dataPtr->linkEntity, ignition::gazebo::components::AngularVelocity()); } // Create an angular velocity component if one is not present. if (!_ecm.Component<ignition::gazebo::components::WorldAngularVelocity>( this->dataPtr->linkEntity)) { _ecm.CreateComponent(this->dataPtr->linkEntity, ignition::gazebo::components::WorldAngularVelocity()); } double p = 0.1; double i = 0; double d = 0; double iMax = 1; double iMin = -1; double cmdMax = this->dataPtr->ThrustToAngularVec(this->dataPtr->cmdMax); double cmdMin = this->dataPtr->ThrustToAngularVec(this->dataPtr->cmdMin); double cmdOffset = 0; if (_sdf->HasElement("p_gain")) { p = _sdf->Get<double>("p_gain"); } if (!_sdf->HasElement("i_gain")) { i = _sdf->Get<double>("i_gain"); } if (!_sdf->HasElement("d_gain")) { d = _sdf->Get<double>("d_gain"); } this->dataPtr->rpmController.Init( p, i, d, iMax, iMin, cmdMax, cmdMin, cmdOffset); } ///////////////////////////////////////////////// void ThrusterPrivateData::OnCmdThrust(const ignition::msgs::Double &_msg) { std::lock_guard<std::mutex> lock(mtx); this->thrust = ignition::math::clamp(ignition::math::fixnan(_msg.data()), this->cmdMin, this->cmdMax); } ///////////////////////////////////////////////// double ThrusterPrivateData::ThrustToAngularVec(double _thrust) { // Thrust is proportional to the Rotation Rate squared // See Thor I Fossen's "Guidance and Control of ocean vehicles" p. 246 auto propAngularVelocity = sqrt(abs( _thrust / (this->fluidDensity * this->thrustCoefficient * pow(this->propellerDiameter, 4)))); propAngularVelocity *= (_thrust > 0) ? 1: -1; return propAngularVelocity; } ///////////////////////////////////////////////// void Thruster::PreUpdate( const ignition::gazebo::UpdateInfo &_info, ignition::gazebo::EntityComponentManager &_ecm) { if (_info.paused) return; ignition::gazebo::Link link(this->dataPtr->linkEntity); auto pose = worldPose(this->dataPtr->linkEntity, _ecm); // TODO(arjo129): add logic for custom coordinate frame auto unitVector = pose.Rot().RotateVector( this->dataPtr->jointAxis.Normalize()); double desiredThrust; { std::lock_guard<std::mutex> lock(this->dataPtr->mtx); desiredThrust = this->dataPtr->thrust; } // Thrust is proportional to the Rotation Rate squared // See Thor I Fossen's "Guidance and Control of ocean vehicles" p. 246 auto desiredPropellerAngVel = this->dataPtr->ThrustToAngularVec(desiredThrust); auto currentAngular = (link.WorldAngularVelocity(_ecm))->Dot(unitVector); auto angularError = currentAngular - desiredPropellerAngVel; double torque = 0.0; if (abs(angularError) > 0.1) torque = this->dataPtr->rpmController.Update(angularError, _info.dt); link.AddWorldWrench( _ecm, unitVector * this->dataPtr->thrust, unitVector * torque); } IGNITION_ADD_PLUGIN( Thruster, System, Thruster::ISystemConfigure, Thruster::ISystemPreUpdate) IGNITION_ADD_PLUGIN_ALIAS(Thruster, "ignition::gazebo::systems::Thruster")
29.521429
80
0.675175
[ "object", "model" ]
e10014c0808b02988427baf01ea61dc1dbeda1ce
1,839
hpp
C++
include/periphery/serial.hpp
mpb27/cpp-periphery
4e3cd1bc054ab4e0e964ec54d8e0ebea5d964f13
[ "MIT" ]
2
2020-11-15T01:17:34.000Z
2021-05-07T16:44:03.000Z
include/periphery/serial.hpp
mpb27/cpp-periphery
4e3cd1bc054ab4e0e964ec54d8e0ebea5d964f13
[ "MIT" ]
null
null
null
include/periphery/serial.hpp
mpb27/cpp-periphery
4e3cd1bc054ab4e0e964ec54d8e0ebea5d964f13
[ "MIT" ]
2
2020-03-19T07:51:12.000Z
2020-10-22T18:31:00.000Z
/* * cpp-periphery * https://github.com/mpb27/cpp-periphery * License: MIT */ #ifndef PERIPHERY_SERIAL_HPP #define PERIPHERY_SERIAL_HPP #include <cstdlib> #include <cstdint> #include <cstring> #include <chrono> #include <ostream> #include <string> #include <periphery/buffer.hpp> namespace periphery { class Serial { public: enum class DataBits { Five, Six, Seven, Eight }; enum class StopBits { One, Two }; enum class Parity { None, Even, Odd }; enum class Handshake { None, RtsCts, XonXoff, RtsCtsXonXoff }; /* Constructor and Destructor. */ Serial(const std::string& path, uint32_t baudrate, DataBits databits, Parity parity, StopBits stopbits, Handshake handshake); Serial(const std::string& path, uint32_t baudrate, DataBits databits, Parity parity, StopBits stopbits); Serial(const std::string& path, uint32_t baudrate); ~Serial(); /* Disable copy constructor and copy assignment. */ Serial(const Serial&) = delete; Serial& operator=(const Serial&) = delete; /* Should we include getters and setters? */ /* Nope, just instantiate serial again. */ bool poll(std::chrono::milliseconds timeout) const; void flush() const; unsigned int input_waiting() const; unsigned int output_waiting() const; void write(const_buffer buf) const; void write(const std::string& data) const; int read (mutable_buffer buf) const; void read_all (mutable_buffer buf) const; int read_timeout (mutable_buffer buf, std::chrono::milliseconds timeout) const; int read_all_timeout (mutable_buffer buf, std::chrono::milliseconds timeout) const; //std::vector<uint8_t> read(size_t len, std::chrono::milliseconds timeout) const; private: int fd_; }; } // ... namespace periphery ... #endif // ... PERIPHERY_SERIAL_HPP ...
27.447761
129
0.695487
[ "vector" ]
e10120cf752e57e3573dcaff62fd12dfe418484a
38,959
cpp
C++
libtcod-1.5.1-mingw32/libtcod-1.5.1/samples/doctcod/doctcod.cpp
KitRobinson/rogue
aeb4df46d8d228a56b21669aa74302a3db136092
[ "bzip2-1.0.6" ]
null
null
null
libtcod-1.5.1-mingw32/libtcod-1.5.1/samples/doctcod/doctcod.cpp
KitRobinson/rogue
aeb4df46d8d228a56b21669aa74302a3db136092
[ "bzip2-1.0.6" ]
null
null
null
libtcod-1.5.1-mingw32/libtcod-1.5.1/samples/doctcod/doctcod.cpp
KitRobinson/rogue
aeb4df46d8d228a56b21669aa74302a3db136092
[ "bzip2-1.0.6" ]
null
null
null
/* * libtcod 1.5.1 * Copyright (c) 2008,2009,2010 Jice & Mingos * 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. * * The name of Jice or Mingos may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY JICE AND MINGOS ``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 JICE OR MINGOS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // This is libtcod doc generator // it parses .hpp files and use javadoc-like comments to build the doc // work-in-progress!! #include <stdio.h> #include <ctype.h> #include <sys/stat.h> #include "libtcod.hpp" // index.html categories static const char *categs[] = {"", "Core","Base toolkits","Roguelike toolkits", NULL }; // a function parameter struct ParamData { char *name; char *desc; }; // data about a libtcod function struct FuncData { char *title;// function name char *desc; // general description char *cpp; // C++ function char *c; // C function char *cs; // C# function char *py; // python function char *lua; // lua function TCODList<ParamData *> params; // parameters table char *cppEx; // C++ example char *cEx; // C example char *csEx; // C# example char *pyEx; // python example char *luaEx; // lua example FuncData() : title(NULL),desc(NULL),cpp(NULL),c(NULL),cs(NULL),py(NULL),lua(NULL), cppEx(NULL),cEx(NULL),csEx(NULL),pyEx(NULL),luaEx(NULL) {} }; // data about a documentation page struct PageData { // parsed data char *name; // page symbolic name char *title;// page title char *desc; // description on top of page char *fatherName; // symbolic name of father page if any char *filename; // .hpp file from which it comes char *categoryName; // category for level 0 pages TCODList<FuncData *>funcs; // functions in this page PageData() : name(NULL),title(NULL),desc(NULL), fatherName(NULL), filename(NULL),categoryName((char *)""),father(NULL),next(NULL),prev(NULL), fileOrder(0),order(0),numKids(0),pageNum(NULL), url(NULL), breadCrumb(NULL), prevLink((char *)""),nextLink((char*)""),colorTable(false) {} // computed data PageData *father; PageData *next; PageData *prev; int fileOrder; // page number in its hpp file int order; // page number in it's father int numKids; // number of sub pages inside this one char *pageNum; // 1.2 and so on... char *url; // page URL (ex.: 1.2.2.html) char *breadCrumb; char *prevLink; // link to prev page in breadcrumb char *nextLink; // link to next page in breadcrumb bool colorTable; }; struct Config { bool generateCpp; bool generateC; bool generatePy; bool generateCs; bool generateLua; }; Config config = {true,true,true,true,true}; TCODList<PageData *> pages; // root page corresponding to index.html PageData *root=NULL; // page currently parsed PageData *curPage=NULL; // function currently parsed FuncData *curFunc=NULL; // get an identifier at txt pos and put a strdup copy in result // returns the position after the identifier char *getIdentifier(char *txt, char **result) { while (isspace(*txt)) txt++; char *end=txt; while (!isspace(*end)) end++; *end=0; *result=strdup(txt); return end+1; } // get the end of line from txt and put a strdup copy in result // returns the position after the current line char *getLineEnd(char *txt, char **result) { while (isspace(*txt)) txt++; char *end=txt; while (*end && *end != '\n') end++; bool fileEnd = (*end == 0); *end=0; *result=strdup(txt); return fileEnd ? end : end+1; } // get the data from txt up to the next @ directive and put a strdup copy in result // returns the position at the next @ (or end of file) char *getParagraph(char *txt, char **result) { while (isspace(*txt)) txt++; char *end=txt; while (*end && *end != '@') end++; bool fileEnd = (*end == 0); *end=0; *result=strdup(txt); if ( ! fileEnd ) *end='@'; return end; } // get the data from txt up to the next @ directive and put a strdup copy in result // returns the position at the next @ (or end of file) char *getCodeParagraph(char *txt, char **result) { // for code, skip only up to the first \n to allow indentation detection while (isspace(*txt) && *txt != '\n') txt++; if ( *txt == '\n') txt++; char *end=txt; while (*end && *end != '@') end++; bool fileEnd = (*end == 0); *end=0; *result=strdup(txt); if ( ! fileEnd ) *end='@'; return end; } // check if the string starts with keyword bool startsWith(const char *txt, const char *keyword) { return strncmp(txt,keyword,strlen(keyword)) == 0; } // check if the string ends with keyword bool endsWith(const char *txt, const char *keyword) { return strncmp(txt+strlen(txt)-strlen(keyword),keyword,strlen(keyword)) == 0; } // print in the file, replace \n by <br> void printHtml(FILE *f, const char *txt) { bool intable=false; while (*txt) { if ( strncmp(txt,"<table",6) == 0 ) { intable=true; } else if ( intable && strncmp(txt,"</table>",8) == 0 ) { intable=false; } if ( !intable && *txt == '\n' ) fprintf(f,"<br />"); else if ( *txt == '\r' ) {} // ignore else { fputc(*txt,f); } txt++; } } struct ColorModifier { const char *name; float satCoef; float valCoef; }; #define NB_COLOR_MOD 8 ColorModifier colorModifiers[NB_COLOR_MOD] = { {"desaturated", 0.5f,0.5f}, {"lightest",0.25f,1.0f}, {"lighter",0.35f,1.0f}, {"light",0.55f,1.0f}, {"",1.0f,1.0f}, {"dark",1.0f,0.75f}, {"darker",1.0f,0.5f}, {"darkest",1.0f,0.25f}, }; struct Color { char *name; TCODColor col; bool category; Color() : category(false) {} }; TCODList<Color> colors; int greyLevels[] = {223,191,159,127,95,63,31}; // generate the color table from parsed colors void printColorTable(FILE *f) { fprintf(f,"<table class=\"color\">\n"); bool needHeader=true; int categ=0; for ( Color *col=colors.begin(); col!=colors.end(); col++) { if ( col->category ) { // a color category fprintf(f,"<tr><td></td><th colspan=\"8\">%s</th></tr>\n",col->name); needHeader=true; categ++; } else if ( categ == 1 ){ // computed colors if ( needHeader ) fprintf(f,"<tr><td></td><td>desaturated</td><td>lightest</td><td>lighter</td><td>light</td><td>normal</td><td>dark</td><td>darker</td><td>darkest</td></tr>\n"); needHeader=false; fprintf(f,"<tr><td>%s</td>",col->name); for (int cm =0; cm < NB_COLOR_MOD; cm++ ) { if ( colorModifiers[cm].name[0] != 0 ) col->name[0]=toupper(col->name[0]); float h,s,v; col->col.getHSV(&h,&s,&v); s *= colorModifiers[cm].satCoef; v *= colorModifiers[cm].valCoef; TCODColor modcol; modcol.setHSV(h,s,v); fprintf(f,"<td title=\"%s%s: %d,%d,%d\" style=\"background-color: rgb(%d,%d,%d)\"></td>", colorModifiers[cm].name,col->name,modcol.r,modcol.g,modcol.b, modcol.r,modcol.g,modcol.b); col->name[0]=tolower(col->name[0]); } fprintf(f,"</tr>\n"); } else if (strcmp(col->name,"grey")==0 ) { // grey colors fprintf(f,"<tr><td colspan=\"2\">&nbsp;</td><td>lightest</td><td>lighter</td><td>light</td><td>normal</td><td>dark</td><td>darker</td><td>darkest</td></tr>\n"); fprintf(f,"<tr><td>grey</td><td>&nbsp;</td><td title=\"lightestGrey: 223,223,223\" style=\"background-color: rgb(223, 223, 223);\"></td><td title=\"lighterGrey: 191,191,191\" style=\"background-color: rgb(191, 191, 191);\"></td><td title=\"lightGrey: 159,159,159\" style=\"background-color: rgb(159, 159, 159);\"></td><td title=\"grey: 127,127,127\" style=\"background-color: rgb(127, 127, 127);\"></td><td title=\"darkGrey: 95,95,95\" style=\"background-color: rgb(95, 95, 95);\"></td><td title=\"darkerGrey: 63,63,63\" style=\"background-color: rgb(63, 63, 63);\"></td><td title=\"darkestGrey: 31,31,31\" style=\"background-color: rgb(31, 31, 31);\"></td></tr>\n"); } else if ( strcmp(col->name,"sepia") == 0 ) { // sepia colors fprintf(f,"<tr><td>sepia</td><td>&nbsp;</td><td title=\"lightestSepia: 222,211,195\" style=\"background-color: rgb(222, 211, 195);\"></td><td title=\"lighterSepia: 191,171,143\" style=\"background-color: rgb(191, 171, 143);\"></td><td title=\"lightSepia: 158,134,100\" style=\"background-color: rgb(158, 134, 100);\"></td><td title=\"sepia: 127,101,63\" style=\"background-color: rgb(127, 101, 63);\"></td><td title=\"darkSepia: 94,75,47\" style=\"background-color: rgb(94, 75, 47);\"></td><td title=\"darkerSepia: 63,50,31\" style=\"background-color: rgb(63, 50, 31);\"></td><td title=\"darkestSepia: 31,24,15\" style=\"background-color: rgb(31, 24, 15);\"></td></tr>"); } else { // miscellaneous colors fprintf(f,"<tr><td>%s</td><td title=\"%s: %d,%d,%d\" style=\"background-color: rgb(%d,%d,%d)\"></td></tr>\n", col->name, col->name,col->col.r,col->col.g,col->col.b, col->col.r,col->col.g,col->col.b); } } fprintf(f,"</table>"); } // print in the file, coloring syntax using the provided lexer void printSyntaxColored(FILE *f, TCODLex *lex) { char *pos=lex->getPos(); int indent=0; // detect first line indentation while ( isspace(*pos) ) { indent++; pos++; } int tok=lex->parse(); // fix indentation until real code begins bool lineBegin=true; while (tok != TCOD_LEX_ERROR && tok != TCOD_LEX_EOF ) { const char *spanClass=NULL; switch (tok) { case TCOD_LEX_SYMBOL : spanClass = "code-symbol"; break; case TCOD_LEX_KEYWORD : spanClass = "code-keyword"; break; case TCOD_LEX_STRING : spanClass = "code-string"; break; case TCOD_LEX_CHAR : spanClass = "code-character"; break; case TCOD_LEX_INTEGER : case TCOD_LEX_FLOAT : spanClass = "code-value"; break; case TCOD_LEX_COMMENT : spanClass = "code-comment"; break; case TCOD_LEX_IDEN : if ( startsWith(lex->getToken(),"TCOD_") && endsWith(lex->getToken(),"_t") ) spanClass = "code-tcod"; // tcod type else { char *ptr=(char *)lex->getToken(); bool isDefine=true; while (isDefine && *ptr) { if ( *ptr >= 'a' && *ptr <= 'z' ) isDefine=false; ptr++; } if ( isDefine ) spanClass="code-tcod"; // tcod constant } break; default : break; } if ( spanClass ) { fprintf(f, "<span class=\"%s\">",spanClass); } while ( pos != lex->getPos() ) { if ( *pos == '\r' ) {} else if (*pos == '\n' ) { fprintf(f,"<br />"); pos += indent; lineBegin=true; } else if ( lineBegin && *pos == '\t' ) { fprintf(f,"&nbsp;&nbsp;&nbsp;&nbsp;"); } else if ( lineBegin && *pos == ' ' ) { fprintf(f,"&nbsp;"); } else { fputc(*pos,f); if ( ! isspace(*pos) ) lineBegin=false; } pos++; } if ( spanClass ) { fprintf(f, "</span>"); } tok=lex->parse(); } if ( tok == TCOD_LEX_ERROR ) { printf ("ERROR while coloring syntax : %s in '%s'\n",TCOD_lex_get_last_error(),lex->getToken()); } } // print in the file, coloring syntax using C++ rules void printCppCode(FILE *f, const char *txt) { static const char *symbols[] = { "::","->","++","--","->*",".*","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","^=","|=","<<=",">>=","...", "(",")","[","]",".","+","-","!","~","*","&","|","%","/","<",">","=","^","?",":",";","{","}",",", NULL }; static const char *keywords[] = { "and","and_eq","asm","auto","bitand","bitor","bool","break","case","catch","char","class","compl","const","const_cast","continue", "default","delete","do","double","dynamic_cast","else","enum","explicit","export","extern","false","float","for","friend","goto", "if","inline","int","long","mutable","namespace","new","not","not_eq","operator","or","or_eq","private","protected","public", "register","reinterpret_cast","return","short","signed","sizeof","static","static_cast","struct","switch","template","this", "throw","true","try","typedef","typeid","typename","union","unsigned","using","virtual","void","volatile","wchar_t","while", "xor","xor_eq", "int8","int8_t","int16","int16_t","int32","int32_t","int64","int64_t", "uint8","uint8_t","uint16","uint16_t","uint32","uint32_t","uint64","uint64_t", NULL }; TCODLex lex(symbols,keywords,"//","/*","*/",NULL,"\"",TCOD_LEX_FLAG_NESTING_COMMENT|TCOD_LEX_FLAG_TOKENIZE_COMMENTS); lex.setDataBuffer((char *)txt); printSyntaxColored(f,&lex); } // print in the file, coloring syntax using C rules void printCCode(FILE *f, const char *txt) { static const char *symbols[] = { "->","++","--","<<",">>","<=",">=","==","!=","&&","||","*=","/=","+=","-=","%=","<<=",">>=","&=","^=","|=","...", "{","}","(",")","[","]",".","&","*","+","-","~","!","/","%","<",">","^","|","?",":","=",",",";", }; static const char *keywords[] = { "auto","break","case","char","const","continue","default","do","double","else","enum","extern","float","for","goto","if","int", "long","register","return","short","signed","sizeof","static","struct","switch","typedef","union","unsigned","void","volatile", "while", "int8","int8_t","int16","int16_t","int32","int32_t","int64","int64_t","bool", "uint8","uint8_t","uint16","uint16_t","uint32","uint32_t","uint64","uint64_t", NULL }; TCODLex lex(symbols,keywords,"//","/*","*/",NULL,"\"",TCOD_LEX_FLAG_NESTING_COMMENT|TCOD_LEX_FLAG_TOKENIZE_COMMENTS); lex.setDataBuffer((char *)txt); printSyntaxColored(f,&lex); } // print in the file, coloring syntax using python rules void printPyCode(FILE *f, const char *txt) { static const char *symbols[] = { "**","&&","||","!=","<>","==","<=",">=","+=","-=","**=","*=","//=","/=","%=","|=","^=","<<=",">>=", "+","-","^","*","/","%","&","|","^","<",">","(",")","[","]","{","}",",",":",".","`","=",";","@", NULL }; static const char *keywords[] = { "and","as","assert","break","class","continue","def","del","elif","else","except","exec","finally","for", "from","global","if","import","in","is","lambda","not","or","pass","print","raise","return","try","while", "with","yield", "True","False", NULL }; TCODLex lex(symbols,keywords,"#","\"\"\"","\"\"\"",NULL,"\"\'",TCOD_LEX_FLAG_NESTING_COMMENT|TCOD_LEX_FLAG_TOKENIZE_COMMENTS); lex.setDataBuffer((char *)txt); printSyntaxColored(f,&lex); } // print in the file, coloring syntax using C# rules void printCSCode(FILE *f, const char *txt) { static const char *symbols[] = { "++","--","->","<<",">>","<=",">=","==","!=","&&","||","+=","-=","*=","/=","%=","&=","|=","^=","<<=",">>=","??", ".","(",")","[","]","{","}","+","-","!","~","&","*","/","%","<",">","^","|","?",":",",","=",";", NULL }; static const char *keywords[] = { "abstract","as","base","bool","break","byte","case","catch","char","checked","class","const","continue","decimal","default", "delegate","do","double","else","enum","event","explicit","extern","false","finally","fixed","float","for","foreach","goto", "implicit","in","int","interface","internal","is","lock","long","namespace","new","null","object","operator","out","override", "params","private","protected","public","readonly","ref","return","sbyte","sealed","short","sizeof","stackalloc","static", "string","struct","switch","this","throw","true","try","typeof","uint","ulong","unchecked","unsafe","ushort","using","virtual", "volatile","void","while", "get","partial","set","value","where","yield", NULL }; TCODLex lex(symbols,keywords,"//","/*","*/",NULL,"\"",TCOD_LEX_FLAG_NESTING_COMMENT|TCOD_LEX_FLAG_TOKENIZE_COMMENTS); lex.setDataBuffer((char *)txt); printSyntaxColored(f,&lex); } // print in the file, coloring syntax using Lua rules void printLuaCode(FILE *f, const char *txt) { static const char *symbols[] = { "==","~=","<=",">=","...","..", "+","-","/","*","%","^","<",">",",","(",")","#","{","}","[","]","=",";",":",".", NULL }; static const char *keywords[] = { "and","break","do","else","elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while", NULL }; TCODLex lex(symbols,keywords,"--","--[[","]]",NULL,"\"\'",TCOD_LEX_FLAG_NESTING_COMMENT|TCOD_LEX_FLAG_TOKENIZE_COMMENTS); lex.setDataBuffer((char *)txt); printSyntaxColored(f,&lex); } // get a page by its name or NULL if it doesn't exist PageData *getPage(const char *name) { for (PageData **it=pages.begin();it!=pages.end();it++) { if (strcmp((*it)->name,name)==0) return *it; } return NULL; } // find the previous page of same level (NULL if none) PageData *getPrev(PageData *page) { for (PageData **it=pages.begin();it!=pages.end();it++) { if ( (*it)->father == page->father && (*it)->order == page->order-1 ) return *it; } return NULL; } // find the next page of same level (NULL if none) PageData *getNext(PageData *page) { for (PageData **it=pages.begin();it!=pages.end();it++) { if ( (*it)->father == page->father && (*it)->order == page->order+1 ) return *it; } return NULL; } // load a text file into memory. get rid of \r char *loadTextFile(const char *filename) { // load the file into memory (should probably use mmap instead that crap...) struct stat _st; FILE *f = fopen( filename, "r" ); if ( f == NULL ) { printf("WARN : cannot open '%s'\n", filename); return NULL; } if ( stat( filename, &_st ) == -1 ) { fclose(f); printf("WARN : cannot stat '%s'\n", filename ); return NULL; } char *buf = (char*)calloc(sizeof(char),(_st.st_size + 1)); char *ptr=buf; // can't rely on size to read because of MS/DOS dumb CR/LF handling while ( fgets(ptr, _st.st_size,f ) ) { ptr += strlen(ptr); } fclose(f); // remove \r ptr = buf; while (*ptr) { if ( *ptr == '\r') { char *ptr2=ptr; while ( *ptr2 ) { *ptr2 = *(ptr2+1); ptr2++; } } ptr++; } return buf; } // parse a .hpp file and generate corresponding PageData void parseFile(char *filename) { printf ("INFO : parsing file %s\n",filename); char *buf=loadTextFile(filename); if ( ! buf ) return; // now scan javadocs int fileOrder=1; char *ptr = strstr(buf,"/**"); while (ptr) { char *end = strstr(ptr,"*/"); if ( end ) { // parse the javadoc *end=0; char *directive = strchr(ptr,'@'); while ( directive ) { if ( startsWith(directive,"@PageName") ) { char *pageName=NULL; directive = getIdentifier(directive+sizeof("@PageName"),&pageName); curPage=getPage(pageName); curFunc=NULL; if(!curPage) { // non existing page. create a new one curPage=new PageData(); pages.push(curPage); curPage->filename = strdup(filename); curPage->fileOrder=fileOrder++; curPage->name=pageName; curFunc=NULL; } } else if ( startsWith(directive,"@PageTitle") ) { directive = getLineEnd(directive+sizeof("@PageTitle"),&curPage->title); } else if ( startsWith(directive,"@PageDesc") ) { directive = getParagraph(directive+sizeof("@PageDesc"),&curPage->desc); } else if ( startsWith(directive,"@PageFather") ) { directive = getIdentifier(directive+sizeof("@PageFather"),&curPage->fatherName); } else if ( startsWith(directive,"@PageCategory") ) { directive = getLineEnd(directive+sizeof("@PageCategory"),&curPage->categoryName); } else if ( startsWith(directive,"@FuncTitle") ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); directive = getLineEnd(directive+sizeof("@FuncTitle"),&curFunc->title); } else if ( startsWith(directive,"@ColorTable") ) { directive += sizeof("@ColorTable"); curPage->colorTable=true; } else if ( startsWith(directive,"@ColorCategory") ) { Color col; directive=getLineEnd(directive+sizeof("@ColorCategory"),&col.name); col.category=true; colors.push(col); } else if ( startsWith(directive,"@Color") ) { Color col; directive=getIdentifier(directive+sizeof("@Color"),&col.name); sscanf(directive,"%d,%d,%d",&col.col.r,&col.col.g,&col.col.b); colors.push(col); while (! isspace(*directive)) directive++; } else if ( startsWith(directive,"@FuncDesc") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getParagraph(directive+sizeof("@FuncDesc"),&curFunc->desc); } else if ( startsWith(directive,"@CppEx") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@CppEx")-1,&curFunc->cppEx); } else if ( startsWith(directive,"@C#Ex") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@C#Ex")-1,&curFunc->csEx); } else if ( startsWith(directive,"@CEx") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@CEx")-1,&curFunc->cEx); } else if ( startsWith(directive,"@PyEx") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@PyEx")-1,&curFunc->pyEx); } else if ( startsWith(directive,"@LuaEx") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@LuaEx")-1,&curFunc->luaEx); } else if ( startsWith(directive,"@Cpp") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@Cpp")-1,&curFunc->cpp); } else if ( startsWith(directive,"@C#") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@C#")-1,&curFunc->cs); } else if ( startsWith(directive,"@C") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@C")-1,&curFunc->c); } else if ( startsWith(directive,"@Py") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@Py")-1,&curFunc->py); } else if ( startsWith(directive,"@Lua") ) { if (! curFunc ) { curFunc=new FuncData(); curPage->funcs.push(curFunc); } directive = getCodeParagraph(directive+sizeof("@Lua")-1,&curFunc->lua); } else if ( startsWith(directive,"@Param") ) { ParamData *param=new ParamData(); curFunc->params.push(param); directive = getIdentifier(directive+sizeof("@Param"),&param->name); directive = getParagraph(directive,&param->desc); } else { char *tmp; directive = getIdentifier(directive,&tmp); printf ("WARN unknown directive '%s'\n",tmp); free(tmp); } directive = strchr(directive,'@'); } ptr=strstr(end+2,"/**"); } else ptr=NULL; } } // computes the page tree and auto-numbers pages void buildTree() { // get the list of root (level 0) pages TCODList<PageData *>rootPages; for (PageData **it=pages.begin();it!=pages.end();it++) { // page requires at least a @PageName and @PageTitle if (! (*it)->name ) { printf ("ERROR : page #%d (%s) in %s has no @PageName\n", (*it)->fileOrder,(*it)->name ? (*it)->name : "null", (*it)->filename); it=pages.remove(it); continue; } if (! (*it)->title ) { printf ("ERROR : page #%d (%s) in %s has no @PageTitle\n", (*it)->fileOrder,(*it)->name ? (*it)->name : "null",(*it)->filename); it=pages.remove(it); continue; } if ( (*it)->fatherName == NULL ) rootPages.push(*it); } // first, order the level 0 pages according to their category int categId=0; while ( categs[categId] ) { for (PageData **it=pages.begin();it!=pages.end();it++) { if ( (*it)->fatherName == NULL && strcmp((*it)->categoryName,categs[categId]) == 0 ) { // new root page root->numKids++; (*it)->father=root; (*it)->order=root->numKids; char tmp[1024]; sprintf(tmp,"%d",(*it)->order); (*it)->pageNum=strdup(tmp); sprintf(tmp,"doc/html2/%s.html",(*it)->name); (*it)->url=strdup(tmp); sprintf(tmp,"<a onclick=\"link('../index2.html')\">Index</a> &gt; <a onclick=\"link('%s.html')\">%s. %s</a>", (*it)->name,(*it)->pageNum,(*it)->title); (*it)->breadCrumb=strdup(tmp); rootPages.remove(*it); } } categId++; } // pages with unknown categories for ( PageData **it=rootPages.begin(); it != rootPages.end(); it++) { printf ("ERROR : unknown category '%s' in page '%s'\n",(*it)->categoryName,(*it)->name); pages.remove(*it); } // build the subpages tree for (PageData **it=pages.begin();it!=pages.end();it++) { if ( (*it)->fatherName != NULL ) { // sub-page. find its daddy and order (*it)->father=getPage((*it)->fatherName); if ( ! (*it)->father ) { printf ("ERROR : unknown father '%s' for page '%s'\n", (*it)->fatherName,(*it)->name); it=pages.remove(it); continue; } (*it)->father->numKids++; (*it)->order=(*it)->father->numKids; } } // now compute sub-page numbers TCODList<PageData *> hierarchy; bool missing=true; while ( missing ) { missing=false; for (PageData **it=pages.begin();it!=pages.end();it++) { if ((*it)->pageNum == NULL ) { PageData *page=*it; if ( page->father->pageNum == NULL ) { missing=true; } else { char tmp[256]; sprintf(tmp,"%s.%d", page->father->pageNum,page->order); page->pageNum = strdup(tmp); sprintf(tmp,"doc/html2/%s.html",page->name); page->url=strdup(tmp); } } } } // now compute prev/next links and breadcrumbs for sub pages for (PageData **it=pages.begin();it!=pages.end();it++) { PageData *page=*it; page->prev=getPrev(page); // prev link if ( page->prev ) { char tmp[1024]; sprintf (tmp, "<a class=\"prev\" onclick=\"link('%s.html')\">%s. %s</a>", page->prev->name,page->prev->pageNum,page->prev->title); page->prevLink=strdup(tmp); } // next link page->next=getNext(page); if ( page->next ) { char tmp[1024]; sprintf (tmp, "%s<a class=\"next\" onclick=\"link('%s.html')\">%s. %s</a>", page->prev ? "| " : "", page->next->name,page->next->pageNum,page->next->title); page->nextLink=strdup(tmp); } // breadCrumb if (! page->breadCrumb ) { char tmp[1024]; TCODList<PageData *> hierarchy; PageData *curPage=page; while ( curPage ) { hierarchy.push(curPage); curPage=curPage->father; } char *ptr=tmp; ptr[0]=0; while ( ! hierarchy.isEmpty() ) { curPage=hierarchy.pop(); if ( curPage == root ) { sprintf(ptr, "<a onclick=\"link('../%s.html')\">%s</a>", curPage->name,curPage->title); } else { sprintf(ptr, " &gt; <a onclick=\"link('%s.html')\">%s. %s</a>", curPage->name,curPage->pageNum,curPage->title); } ptr += strlen(ptr); } page->breadCrumb =strdup(tmp); } } } // return the subpage # kidNum PageData *getKidByNum(PageData *father, int kidNum) { for (PageData **it=pages.begin(); it != pages.end(); it++) { if ( (*it)->father == father && (*it)->order == kidNum ) { return *it; } } return NULL; } // print subpage TOC for a standard (not index.htlm) page void printStandardPageToc(FILE *f,PageData *page) { if ( page->numKids > 0 ) { fprintf(f,"<div id=\"toc\"><ul>"); for (int kidId=1;kidId <= page->numKids; kidId++) { // find the kid # kidId PageData *kid = getKidByNum(page,kidId); if ( kid ) { if ( kid->numKids > 0 ) { // level 2 fprintf (f,"<li class=\"haschildren\"><a onclick=\"link('%s%s.html')\">%s. %s</a><ul>\n", page==root ? "html2/":"", kid->name,kid->pageNum,kid->title); int kidKidId=1; while (kidKidId <= kid->numKids ) { PageData *kidKid=NULL; // find the kid # kidKidId of kidId kidKid=getKidByNum(kid,kidKidId); if ( kidKid ) { fprintf(f,"<li><a onclick=\"link('%s%s.html')\">%s. %s</a></li>\n", page==root ? "html2/":"", kidKid->name,kidKid->pageNum,kidKid->title); } kidKidId++; } fprintf(f,"</ul></li>\n"); } else { fprintf(f,"<li><a onclick=\"link('%s%s.html')\">%s. %s</a></li>\n", page==root ? "html2/":"", kid->name,kid->pageNum,kid->title); } } } fprintf(f,"</ul></div>\n"); } } // print index.html TOC void printRootPageToc(FILE *f,PageData *page) { int categId=0; fprintf(f,"<div id=\"toc\"><ul>"); while ( categs[categId] ) { if ( categId > 0 ) fprintf(f, "<li class=\"cat\">%s</li>\n",categs[categId]); for ( int kidId=1;kidId <= page->numKids; kidId++ ) { PageData *kid = getKidByNum(page,kidId); if ( kid && strcmp(kid->categoryName,categs[categId]) ==0 ) { if ( kid->numKids > 0 ) { // level 2 fprintf (f,"<li class=\"haschildren\"><a onclick=\"link('%s%s.html')\">%s. %s</a><ul>\n", page==root ? "html2/":"", kid->name,kid->pageNum,kid->title); int kidKidId=1; while (kidKidId <= kid->numKids ) { PageData *kidKid=getKidByNum(kid,kidKidId); if ( kidKid ) { fprintf(f,"<li><a onclick=\"link('%s%s.html')\">%s. %s</a></li>\n", page==root ? "html2/":"", kidKid->name,kidKid->pageNum,kidKid->title); } kidKidId++; } fprintf(f,"</ul></li>\n"); } else { fprintf(f,"<li><a onclick=\"link('%s%s.html')\">%s. %s</a></li>\n", page==root ? "html2/":"", kid->name,kid->pageNum,kid->title); } } } categId++; } fprintf(f,"</ul></div>\n"); } void printLanguageFilterForm(FILE *f, const char *langCode, const char *langName, bool onoff) { fprintf(f,"<input type=\"checkbox\" id=\"chk_%s\" name=\"chk_%s\" onchange=\"enable('%s',this.checked)\" %s %s><label %s for='chk_%s'> %s </label>", langCode,langCode,langCode, onoff ? "checked='checked'" : "", onoff ? "":"disabled='disabled'", onoff ? "" : "class='disabled'", langCode,langName); } // generate a .html file for one page void genPageDocFromTemplate(PageData *page) { char *pageTpl=loadTextFile("samples/doctcod/page.tpl"); if (! pageTpl) return; FILE *f = fopen(page->url,"wt"); while (*pageTpl) { if ( strncmp(pageTpl,"${TITLE}",8) == 0 ) { // navigator window's title fprintf(f,page->title); pageTpl+=8; } else if ( strncmp(pageTpl,"${SCRIPT}",9) == 0 ) { // javascript file (not the same for index.html and other pages) if (page == root) fprintf(f,"js/doctcod.js"); else fprintf(f,"../js/doctcod.js"); pageTpl+=9; } else if ( strncmp(pageTpl,"${STYLESHEET}",13) == 0 ) { // css file (not the same for index.html and other pages) if (page == root) fprintf(f,"css/style.css"); else fprintf(f,"../css/style.css"); pageTpl+=13; } else if ( strncmp(pageTpl,"${LOCATION}",11) == 0 ) { // breadcrumb fprintf(f,page->breadCrumb); pageTpl+=11; } else if ( strncmp(pageTpl,"${FILTER_FORM}",14) == 0 ) { printLanguageFilterForm(f,"c","C",config.generateC); printLanguageFilterForm(f,"cpp","C++",config.generateCpp); printLanguageFilterForm(f,"cs","C#",config.generateCs); printLanguageFilterForm(f,"py","Py",config.generatePy); printLanguageFilterForm(f,"lua","Lua",config.generateLua); pageTpl+=14; } else if ( strncmp(pageTpl,"${PREV_LINK}",12) == 0 ) { // prev page link fprintf(f,page->prevLink); pageTpl+=12; } else if ( strncmp(pageTpl,"${NEXT_LINK}",12) == 0 ) { // next page link fprintf(f,page->nextLink); pageTpl+=12; } else if ( strncmp(pageTpl,"${PAGE_TITLE}",13) == 0 ) { // page title if ( page == root ) fprintf(f,page->desc); else fprintf(f,"%s. %s",page->pageNum, page->title); pageTpl+=13; } else if ( strncmp(pageTpl,"${PAGE_CONTENT}",15) == 0 ) { pageTpl+=15; // sub pages toc if ( page == root ) printRootPageToc(f,page); else printStandardPageToc(f,page); // functions toc if ( page->funcs.size() > 1 ) { fprintf(f,"<div id=\"toc\"><ul>\n"); int i=0; for ( FuncData **fit=page->funcs.begin(); fit != page->funcs.end(); fit++,i++) { FuncData *funcData=*fit; if ( funcData->title ) { fprintf(f, "<li><a href=\"#%d\">%s</a></li>", i,funcData->title); } } fprintf(f,"</ul></div>\n"); } // page description if ( page != root && page->desc ) { fprintf(f,"<p>"); printHtml(f,page->desc); fprintf(f,"</p>\n"); if ( page->colorTable ) printColorTable(f); } // functions int i=0; for ( FuncData **fit=page->funcs.begin(); fit != page->funcs.end(); fit++,i++) { FuncData *funcData=*fit; // title and description fprintf(f,"<a name=\"%d\"></a>",i); if (funcData->title) fprintf(f,"<h3>%s</h3>\n",funcData->title); if (funcData->desc) { fprintf(f,"<p>"); printHtml(f,funcData->desc); fprintf(f,"</p>\n"); } // functions for each language fprintf(f,"<div class=\"code\">"); if (config.generateCpp && funcData->cpp) { fprintf(f,"<p class=\"cpp\">"); printCppCode(f,funcData->cpp); fprintf(f,"</p>\n"); } if (config.generateC && funcData->c) { fprintf(f,"<p class=\"c\">"); printCCode(f,funcData->c); fprintf(f,"</p>\n"); } if (config.generatePy && funcData->py) { fprintf(f,"<p class=\"py\">"); printPyCode(f,funcData->py); fprintf(f,"</p>\n"); } if (config.generateCs && funcData->cs) { fprintf(f,"<p class=\"cs\">"); printCSCode(f,funcData->cs); fprintf(f,"</p>\n"); } if (config.generateLua && funcData->lua) { fprintf(f,"<p class=\"lua\">"); printLuaCode(f,funcData->lua); fprintf(f,"</p>\n"); } fprintf(f,"</div>\n"); // parameters table if ( !funcData->params.isEmpty()) { fprintf(f,"<table class=\"param\"><tbody><tr><th>Parameter</th><th>Description</th></tr>"); bool hilite=true; for ( ParamData **pit = funcData->params.begin(); pit != funcData->params.end(); pit++) { if ( hilite ) fprintf(f,"<tr class=\"hilite\">"); else fprintf(f,"<tr>"); fprintf(f,"<td>%s</td><td>",(*pit)->name); printHtml(f,(*pit)->desc); fprintf(f,"</td></tr>\n"); hilite=!hilite; } fprintf(f,"</tbody></table>"); } // examples if ( funcData->cppEx || funcData->cEx || funcData->pyEx ) { fprintf(f,"<h6>Example:</h6><div class=\"code\">\n"); if (config.generateCpp && funcData->cppEx) { fprintf(f,"<p class=\"cpp\">"); printCppCode(f,funcData->cppEx); fprintf(f,"</p>\n"); } if (config.generateC && funcData->cEx) { fprintf(f,"<p class=\"c\">"); printCCode(f,funcData->cEx); fprintf(f,"</p>\n"); } if (config.generatePy && funcData->pyEx) { fprintf(f,"<p class=\"py\">"); printPyCode(f,funcData->pyEx); fprintf(f,"</p>\n"); } if (config.generateCs && funcData->csEx) { fprintf(f,"<p class=\"cs\">"); printCSCode(f,funcData->csEx); fprintf(f,"</p>\n"); } if (config.generateLua && funcData->luaEx) { fprintf(f,"<p class=\"lua\">"); printLuaCode(f,funcData->luaEx); fprintf(f,"</p>\n"); } fprintf(f,"</div><hr>\n"); } } } else { fputc(*pageTpl,f); pageTpl++; } } fclose(f); } // export to HTML void genDoc() { // generates the doc for each page for (PageData **it=pages.begin();it!=pages.end();it++) { printf ("Generating %s - %s...\n",(*it)->pageNum,(*it)->title); genPageDocFromTemplate(*it); } genPageDocFromTemplate(root); } // main func int main(int argc, char *argv[]) { // parse command line arguments // -c -cpp -py -cs -lua : enable only the languages if ( argc > 1 ) { config.generateCpp=false; config.generateC=false; config.generatePy=false; config.generateCs=false; config.generateLua=false; } for (int pnum=1; pnum < argc; pnum++) { if ( strcmp(argv[pnum],"-c") == 0 ) config.generateC=true; else if ( strcmp(argv[pnum],"-cpp") == 0 ) config.generateCpp=true; else if ( strcmp(argv[pnum],"-cs") == 0 ) config.generateCs=true; else if ( strcmp(argv[pnum],"-py") == 0 ) config.generatePy=true; else if ( strcmp(argv[pnum],"-lua") == 0 ) config.generateLua=true; } TCODList<char *> files=TCODSystem::getDirectoryContent("include", "*.hpp"); // hardcoded index page char tmp[128]; root = new PageData(); root->name=(char *)"index2"; root->title=(char *)"Index"; root->pageNum=(char *)""; root->breadCrumb=(char *)"<a onclick=\"link('index2.html')\">Index</a>"; root->url=(char *)"doc/index2.html"; sprintf(tmp,"The Doryen Library v%s - table of contents",TCOD_STRVERSION); root->desc=strdup(tmp); // parse the *.hpp files for ( char **it=files.begin(); it != files.end(); it++) { char tmp[128]; sprintf(tmp,"include/%s",*it); parseFile(tmp); } // computations buildTree(); // html export genDoc(); }
36.376284
675
0.576529
[ "object" ]
e103be4ac75227a8c3f1165b083558d04e55a445
14,722
cpp
C++
include/Repository.cpp
phoebe-leong/githubapicpp
168751f12744d1a8bf6868d52995e979fb67bfc3
[ "Apache-2.0" ]
3
2017-08-09T08:11:03.000Z
2021-06-26T02:53:44.000Z
include/Repository.cpp
phoebe-leong/githubapicpp
168751f12744d1a8bf6868d52995e979fb67bfc3
[ "Apache-2.0" ]
4
2017-08-15T14:03:08.000Z
2021-07-04T23:59:51.000Z
include/Repository.cpp
phoebe-leong/githubapicpp
168751f12744d1a8bf6868d52995e979fb67bfc3
[ "Apache-2.0" ]
1
2021-06-26T04:27:48.000Z
2021-06-26T04:27:48.000Z
// // Created by Ilya Durdyev on 10.08.17. // #include "Repository.h" int githubapicpp::Repository::getId() const { return id; } void githubapicpp::Repository::setId(int id) { Repository::id = id; } const std::string &githubapicpp::Repository::getName() const { return name; } void githubapicpp::Repository::setName(const std::string &name) { Repository::name = name; } const std::string &githubapicpp::Repository::getFullName() const { return fullName; } void githubapicpp::Repository::setFullName(const std::string &fullName) { Repository::fullName = fullName; } bool githubapicpp::Repository::isIsPrivate() const { return isPrivate; } void githubapicpp::Repository::setIsPrivate(bool isPrivate) { Repository::isPrivate = isPrivate; } const std::string &githubapicpp::Repository::getHtmUrl() const { return htmUrl; } void githubapicpp::Repository::setHtmUrl(const std::string &htmUrl) { Repository::htmUrl = htmUrl; } const std::string &githubapicpp::Repository::getDescription() const { return description; } void githubapicpp::Repository::setDescription(const std::string &description) { Repository::description = description; } bool githubapicpp::Repository::isFork() const { return fork; } void githubapicpp::Repository::setFork(bool fork) { Repository::fork = fork; } const std::string &githubapicpp::Repository::getUrl() const { return url; } void githubapicpp::Repository::setUrl(const std::string &url) { Repository::url = url; } const std::string &githubapicpp::Repository::getForksUrl() const { return forksUrl; } void githubapicpp::Repository::setForksUrl(const std::string &forksUrl) { Repository::forksUrl = forksUrl; } const std::string &githubapicpp::Repository::getKeysUrl() const { return keysUrl; } void githubapicpp::Repository::setKeysUrl(const std::string &keysUrl) { Repository::keysUrl = keysUrl; } const std::string &githubapicpp::Repository::getCollaboratorsUrl() const { return collaboratorsUrl; } void githubapicpp::Repository::setCollaboratorsUrl(const std::string &collaboratorsUrl) { Repository::collaboratorsUrl = collaboratorsUrl; } const std::string &githubapicpp::Repository::getTeamsUrl() const { return teamsUrl; } void githubapicpp::Repository::setTeamsUrl(const std::string &teamsUrl) { Repository::teamsUrl = teamsUrl; } const std::string &githubapicpp::Repository::getHooksUrl() const { return hooksUrl; } void githubapicpp::Repository::setHooksUrl(const std::string &hooksUrl) { Repository::hooksUrl = hooksUrl; } const std::string &githubapicpp::Repository::getIssueEventsUrl() const { return issueEventsUrl; } void githubapicpp::Repository::setIssueEventsUrl(const std::string &issueEventsUrl) { Repository::issueEventsUrl = issueEventsUrl; } const std::string &githubapicpp::Repository::getEventsUrl() const { return eventsUrl; } void githubapicpp::Repository::setEventsUrl(const std::string &eventsUrl) { Repository::eventsUrl = eventsUrl; } const std::string &githubapicpp::Repository::getAssigneesUrl() const { return assigneesUrl; } void githubapicpp::Repository::setAssigneesUrl(const std::string &assigneesUrl) { Repository::assigneesUrl = assigneesUrl; } const std::string &githubapicpp::Repository::getBranchesUrl() const { return branchesUrl; } void githubapicpp::Repository::setBranchesUrl(const std::string &branchesUrl) { Repository::branchesUrl = branchesUrl; } const std::string &githubapicpp::Repository::getTagsUrl() const { return tagsUrl; } void githubapicpp::Repository::setTagsUrl(const std::string &tagsUrl) { Repository::tagsUrl = tagsUrl; } const std::string &githubapicpp::Repository::getBlobsUrl() const { return blobsUrl; } void githubapicpp::Repository::setBlobsUrl(const std::string &blobsUrl) { Repository::blobsUrl = blobsUrl; } const std::string &githubapicpp::Repository::getGitTagsUrl() const { return gitTagsUrl; } void githubapicpp::Repository::setGitTagsUrl(const std::string &gitTagsUrl) { Repository::gitTagsUrl = gitTagsUrl; } const std::string &githubapicpp::Repository::getGitRefsUrl() const { return gitRefsUrl; } void githubapicpp::Repository::setGitRefsUrl(const std::string &gitRefsUrl) { Repository::gitRefsUrl = gitRefsUrl; } const std::string &githubapicpp::Repository::getTreesUrl() const { return treesUrl; } void githubapicpp::Repository::setTreesUrl(const std::string &treesUrl) { Repository::treesUrl = treesUrl; } const std::string &githubapicpp::Repository::getStatusesUrl() const { return statusesUrl; } void githubapicpp::Repository::setStatusesUrl(const std::string &statusesUrl) { Repository::statusesUrl = statusesUrl; } const std::string &githubapicpp::Repository::getLanguagesUrl() const { return languagesUrl; } void githubapicpp::Repository::setLanguagesUrl(const std::string &languagesUrl) { Repository::languagesUrl = languagesUrl; } const std::string &githubapicpp::Repository::getStargazersUrl() const { return stargazersUrl; } void githubapicpp::Repository::setStargazersUrl(const std::string &stargazersUrl) { Repository::stargazersUrl = stargazersUrl; } const std::string &githubapicpp::Repository::getContributorsUrl() const { return contributorsUrl; } void githubapicpp::Repository::setContributorsUrl(const std::string &contributorsUrl) { Repository::contributorsUrl = contributorsUrl; } const std::string &githubapicpp::Repository::getSubscribersUrl() const { return subscribersUrl; } void githubapicpp::Repository::setSubscribersUrl(const std::string &subscribersUrl) { Repository::subscribersUrl = subscribersUrl; } const std::string &githubapicpp::Repository::getSubscriptionUrl() const { return subscriptionUrl; } void githubapicpp::Repository::setSubscriptionUrl(const std::string &subscriptionUrl) { Repository::subscriptionUrl = subscriptionUrl; } const std::string &githubapicpp::Repository::getCommitsUrl() const { return commitsUrl; } void githubapicpp::Repository::setCommitsUrl(const std::string &commitsUrl) { Repository::commitsUrl = commitsUrl; } const std::string &githubapicpp::Repository::getGitCommitsUrl() const { return gitCommitsUrl; } void githubapicpp::Repository::setGitCommitsUrl(const std::string &gitCommitsUrl) { Repository::gitCommitsUrl = gitCommitsUrl; } const std::string &githubapicpp::Repository::getCommentsUrl() const { return commentsUrl; } void githubapicpp::Repository::setCommentsUrl(const std::string &commentsUrl) { Repository::commentsUrl = commentsUrl; } const std::string &githubapicpp::Repository::getIssueCommentUrl() const { return issueCommentUrl; } void githubapicpp::Repository::setIssueCommentUrl(const std::string &issueCommentUrl) { Repository::issueCommentUrl = issueCommentUrl; } const std::string &githubapicpp::Repository::getContentsUrl() const { return contentsUrl; } void githubapicpp::Repository::setContentsUrl(const std::string &contentsUrl) { Repository::contentsUrl = contentsUrl; } const std::string &githubapicpp::Repository::getCompareUrl() const { return compareUrl; } void githubapicpp::Repository::setCompareUrl(const std::string &compareUrl) { Repository::compareUrl = compareUrl; } const std::string &githubapicpp::Repository::getMergesUrl() const { return mergesUrl; } void githubapicpp::Repository::setMergesUrl(const std::string &mergesUrl) { Repository::mergesUrl = mergesUrl; } const std::string &githubapicpp::Repository::getArchiveUrl() const { return archiveUrl; } void githubapicpp::Repository::setArchiveUrl(const std::string &archiveUrl) { Repository::archiveUrl = archiveUrl; } const std::string &githubapicpp::Repository::getDownloadsUrl() const { return downloadsUrl; } void githubapicpp::Repository::setDownloadsUrl(const std::string &downloadsUrl) { Repository::downloadsUrl = downloadsUrl; } const std::string &githubapicpp::Repository::getIssuesUrl() const { return issuesUrl; } void githubapicpp::Repository::setIssuesUrl(const std::string &issuesUrl) { Repository::issuesUrl = issuesUrl; } const std::string &githubapicpp::Repository::getPullsUrl() const { return pullsUrl; } void githubapicpp::Repository::setPullsUrl(const std::string &pullsUrl) { Repository::pullsUrl = pullsUrl; } const std::string &githubapicpp::Repository::getMilestonesUrl() const { return milestonesUrl; } void githubapicpp::Repository::setMilestonesUrl(const std::string &milestonesUrl) { Repository::milestonesUrl = milestonesUrl; } const std::string &githubapicpp::Repository::getNotificationsUrl() const { return notificationsUrl; } void githubapicpp::Repository::setNotificationsUrl(const std::string &notificationsUrl) { Repository::notificationsUrl = notificationsUrl; } const std::string &githubapicpp::Repository::getLabelsUrl() const { return labelsUrl; } void githubapicpp::Repository::setLabelsUrl(const std::string &labelsUrl) { Repository::labelsUrl = labelsUrl; } const std::string &githubapicpp::Repository::getReleasesUrl() const { return releasesUrl; } void githubapicpp::Repository::setReleasesUrl(const std::string &releasesUrl) { Repository::releasesUrl = releasesUrl; } const std::string &githubapicpp::Repository::getDeploymentsUrl() const { return deploymentsUrl; } void githubapicpp::Repository::setDeploymentsUrl(const std::string &deploymentsUrl) { Repository::deploymentsUrl = deploymentsUrl; } const std::string &githubapicpp::Repository::getGitUrl() const { return gitUrl; } void githubapicpp::Repository::setGitUrl(const std::string &gitUrl) { Repository::gitUrl = gitUrl; } const std::string &githubapicpp::Repository::getSshUrl() const { return sshUrl; } void githubapicpp::Repository::setSshUrl(const std::string &sshUrl) { Repository::sshUrl = sshUrl; } const std::string &githubapicpp::Repository::getCloneUrl() const { return cloneUrl; } void githubapicpp::Repository::setCloneUrl(const std::string &cloneUrl) { Repository::cloneUrl = cloneUrl; } const std::string &githubapicpp::Repository::getSvnUrl() const { return svnUrl; } void githubapicpp::Repository::setSvnUrl(const std::string &svnUrl) { Repository::svnUrl = svnUrl; } const std::string &githubapicpp::Repository::getHomepage() const { return homepage; } void githubapicpp::Repository::setHomepage(const std::string &homepage) { Repository::homepage = homepage; } int githubapicpp::Repository::getSize() const { return size; } void githubapicpp::Repository::setSize(int size) { Repository::size = size; } short githubapicpp::Repository::getStargazersCount() const { return stargazersCount; } void githubapicpp::Repository::setStargazersCount(short stargazersCount) { Repository::stargazersCount = stargazersCount; } short githubapicpp::Repository::getWatchersCount() const { return watchersCount; } void githubapicpp::Repository::setWatchersCount(short watchersCount) { Repository::watchersCount = watchersCount; } const std::string &githubapicpp::Repository::getLanguage() const { return language; } void githubapicpp::Repository::setLanguage(const std::string &language) { Repository::language = language; } bool githubapicpp::Repository::isHasIssues() const { return hasIssues; } void githubapicpp::Repository::setHasIssues(bool hasIssues) { Repository::hasIssues = hasIssues; } bool githubapicpp::Repository::isHasProjects() const { return hasProjects; } void githubapicpp::Repository::setHasProjects(bool hasProjects) { Repository::hasProjects = hasProjects; } bool githubapicpp::Repository::isHasDownloads() const { return hasDownloads; } void githubapicpp::Repository::setHasDownloads(bool hasDownloads) { Repository::hasDownloads = hasDownloads; } bool githubapicpp::Repository::isHasWiki() const { return hasWiki; } void githubapicpp::Repository::setHasWiki(bool hasWiki) { Repository::hasWiki = hasWiki; } bool githubapicpp::Repository::isHasPages() const { return hasPages; } void githubapicpp::Repository::setHasPages(bool hasPages) { Repository::hasPages = hasPages; } short githubapicpp::Repository::getForksCount() const { return forksCount; } void githubapicpp::Repository::setForksCount(short forksCount) { Repository::forksCount = forksCount; } const std::string &githubapicpp::Repository::getMirrorUrl() const { return mirrorUrl; } void githubapicpp::Repository::setMirrorUrl(const std::string &mirrorUrl) { Repository::mirrorUrl = mirrorUrl; } short githubapicpp::Repository::getOpenIssuesCount() const { return openIssuesCount; } void githubapicpp::Repository::setOpenIssuesCount(short openIssuesCount) { Repository::openIssuesCount = openIssuesCount; } short githubapicpp::Repository::getForks() const { return forks; } void githubapicpp::Repository::setForks(short forks) { Repository::forks = forks; } short githubapicpp::Repository::getOpenIssues() const { return openIssues; } void githubapicpp::Repository::setOpenIssues(short openIssues) { Repository::openIssues = openIssues; } short githubapicpp::Repository::getWatchers() const { return watchers; } void githubapicpp::Repository::setWatchers(short watchers) { Repository::watchers = watchers; } const std::string &githubapicpp::Repository::getDefaultBranch() const { return defaultBranch; } void githubapicpp::Repository::setDefaultBranch(const std::string &defaultBranch) { Repository::defaultBranch = defaultBranch; } const std::vector<std::string> &githubapicpp::Repository::getTopics() const { return topics; } void githubapicpp::Repository::setTopics(const std::vector<std::string> &topics) { Repository::topics = topics; } const githubapicpp::Organization &githubapicpp::Repository::getOrganization() const { return organization; } void githubapicpp::Repository::setOrganization(const githubapicpp::Organization &organization) { Repository::organization = organization; } githubapicpp::Repository *githubapicpp::Repository::getParent() const { return parent; } void githubapicpp::Repository::setParent(githubapicpp::Repository *parent) { Repository::parent = parent; } githubapicpp::Repository *githubapicpp::Repository::getSource() const { return source; } void githubapicpp::Repository::setSource(githubapicpp::Repository *source) { Repository::source = source; } githubapicpp::User *githubapicpp::Repository::getOwner() const { return owner; } void githubapicpp::Repository::setOwner(githubapicpp::User *owner) { Repository::owner = owner; }
26.010601
96
0.750102
[ "vector" ]
e108bea0999a15c7c1b9af5054362a5c0e60b405
4,633
cxx
C++
graphics/VTK-7.0.0/Filters/HyperTree/Testing/Cxx/TestHyperTreeGridTernary2DBiMaterial.cxx
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
4
2016-03-30T14:31:52.000Z
2019-02-02T05:01:32.000Z
graphics/VTK-7.0.0/Filters/HyperTree/Testing/Cxx/TestHyperTreeGridTernary2DBiMaterial.cxx
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
graphics/VTK-7.0.0/Filters/HyperTree/Testing/Cxx/TestHyperTreeGridTernary2DBiMaterial.cxx
hlzz/dotfiles
0591f71230c919c827ba569099eb3b75897e163e
[ "BSD-3-Clause" ]
null
null
null
/*================================================================== Program: Visualization Toolkit Module: TestHyperTreeGridTernary2DBiMaterial.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. ===================================================================*/ // .SECTION Thanks // This test was written by Philippe Pebay, Kitware 2013 // This work was supported in part by Commissariat a l'Energie Atomique (CEA/DIF) #include "vtkHyperTreeGridGeometry.h" #include "vtkHyperTreeGridSource.h" #include "vtkCamera.h" #include "vtkCellData.h" #include "vtkDataSetMapper.h" #include "vtkNew.h" #include "vtkPolyDataMapper.h" #include "vtkProperty.h" #include "vtkRegressionTestImage.h" #include "vtkRenderer.h" #include "vtkRenderWindow.h" #include "vtkRenderWindowInteractor.h" #include "vtkShrinkFilter.h" int TestHyperTreeGridTernary2DBiMaterial( int argc, char* argv[] ) { // Hyper tree grids vtkNew<vtkHyperTreeGridSource> htGrid1; htGrid1->SetMaximumLevel( 3 ); htGrid1->SetOrigin( 0., 0., 0. ); htGrid1->SetGridSize( 2, 1, 1 ); htGrid1->SetGridScale( 1., 1., 1. ); htGrid1->SetDimension( 2 ); htGrid1->SetBranchFactor( 3 ); htGrid1->UseMaterialMaskOn(); htGrid1->SetDescriptor( ".R|.R..R..R.|......... ......... ........." ); htGrid1->SetMaterialMask( "11|110110110|110110110 110110110 110110110" ); vtkNew<vtkHyperTreeGridSource> htGrid2; htGrid2->SetMaximumLevel( 3 ); htGrid2->SetOrigin( 1., 0., 0. ); htGrid2->SetGridSize( 2, 1, 1 ); htGrid2->SetGridScale( 1., 1., 1. ); htGrid2->SetDimension( 2 ); htGrid2->SetBranchFactor( 3 ); htGrid2->UseMaterialMaskOn(); htGrid2->SetDescriptor( "R.|.R..R..R.|......... ......... ........." ); htGrid2->SetMaterialMask( "11|011011011|011011011 011011011 011011011" ); // Geometries vtkNew<vtkHyperTreeGridGeometry> geometry1; geometry1->SetInputConnection( htGrid1->GetOutputPort() ); vtkNew<vtkHyperTreeGridGeometry> geometry2; geometry2->SetInputConnection( htGrid2->GetOutputPort() ); // Shrinks vtkNew<vtkShrinkFilter> shrink1; shrink1->SetInputConnection( geometry1->GetOutputPort() ); shrink1->SetShrinkFactor( .8 ); // Mappers geometry1->Update(); vtkPolyData* pd1 = geometry1->GetOutput(); geometry2->Update(); vtkPolyData* pd2 = geometry2->GetOutput(); vtkMapper::SetResolveCoincidentTopologyToPolygonOffset(); vtkNew<vtkDataSetMapper> mapper1; mapper1->SetInputConnection( shrink1->GetOutputPort() ); mapper1->SetScalarRange( pd1->GetCellData()->GetScalars()->GetRange() ); vtkNew<vtkPolyDataMapper> mapper2; mapper2->SetInputConnection( geometry2->GetOutputPort() ); mapper2->ScalarVisibilityOff(); // Actors vtkNew<vtkActor> actor1; actor1->SetMapper( mapper1.GetPointer() ); vtkNew<vtkActor> actor2; actor2->SetMapper( mapper2.GetPointer() ); actor2->GetProperty()->SetRepresentationToWireframe(); actor2->GetProperty()->SetColor( 0., 0., 0. ); actor2->GetProperty()->SetLineWidth( 2 ); // Camera double bd1[6]; pd1->GetBounds( bd1 ); double bd2[6]; pd2->GetBounds( bd2 ); double bd[4]; for ( int i = 0; i < 3; ++ i ) { bd[i] = bd1[i] < bd2[i] ? bd1[i] : bd2[i]; ++ i; bd[i] = bd1[i] > bd2[i] ? bd1[i] : bd2[i]; } vtkNew<vtkCamera> camera; camera->SetClippingRange( 1., 100. ); double xc = .5 * ( bd[0] + bd[1] ); double yc = .5 * ( bd[2] + bd[3] ); camera->SetFocalPoint( xc, yc, 0. ); camera->SetPosition( xc, yc, 2. ); // Renderer vtkNew<vtkRenderer> renderer; renderer->SetActiveCamera( camera.GetPointer() ); renderer->SetBackground( 1., 1., 1. ); renderer->AddActor( actor1.GetPointer() ); renderer->AddActor( actor2.GetPointer() ); // Render window vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer( renderer.GetPointer() ); renWin->SetSize( 600, 200 ); renWin->SetMultiSamples( 0 ); // Interactor vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow( renWin.GetPointer() ); // Render and test renWin->Render(); int retVal = vtkRegressionTestImageThreshold( renWin.GetPointer(), 20 ); if ( retVal == vtkRegressionTester::DO_INTERACTOR ) { iren->Start(); } return !retVal; }
33.572464
82
0.649687
[ "render" ]
e10990af39ea0c4cb78e8386de229bdcf044a0b5
7,081
cpp
C++
ZeroLibraries/Serialization/Serialization.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
1
2022-03-26T21:08:19.000Z
2022-03-26T21:08:19.000Z
ZeroLibraries/Serialization/Serialization.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
ZeroLibraries/Serialization/Serialization.cpp
jodavis42/ZeroPhysicsTestbed
e84a3f6faf16b7a4242dc049121b5338e80039f8
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// \file Serialization.cpp /// Implementation of the Serializer interface. /// /// Authors: Chris Peters, Joshua Claeys /// Copyright 2010-2016, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #include "Precompiled.hpp" namespace Zero { //--------------------------------------------------------------- Data Attributes namespace SerializationAttributes { DefineStringConstant(Id); DefineStringConstant(InheritId); DefineStringConstant(ChildOrderOverride); DefineStringConstant(LocallyAdded); DefineStringConstant(LocallyRemoved); } //****************************************************************************** DataAttribute::DataAttribute(StringParam name, StringParam value) : mName(name), mValue(value) { } const Guid PolymorphicNode::cInvalidUniqueNodeId = (Guid)-1; //------------------------------------------------------------- Polymorphic Info //****************************************************************************** PolymorphicInfo::PolymorphicInfo() : mTypeName(nullptr) , mUniqueNodeId(PolymorphicNode::cInvalidUniqueNodeId) , mFieldName(nullptr) , mFlags(0) { } //------------------------------------------------------------------- Serializer //****************************************************************************** Serializer::Serializer() { mSerializationContext = NULL; mPatching = false; } //****************************************************************************** Serializer::~Serializer() { } //****************************************************************************** void* Serializer::GetSerializationContext() { return mSerializationContext; } //****************************************************************************** void Serializer::SetSerializationContext(void* context) { mSerializationContext = context; } //****************************************************************************** SerializerMode::Enum Serializer::GetMode() { return mMode; } //****************************************************************************** SerializerType::Enum Serializer::GetType() { return mSerializerType; } //****************************************************************************** bool Serializer::Start(BoundType* type, cstr fieldName, StructType structType) { return Start(type->Name.c_str(), fieldName, structType); } //****************************************************************************** void Serializer::End(BoundType* type, StructType structType) { End(type->Name.c_str(), structType); } //****************************************************************************** void Serializer::StartPolymorphic(cstr typeName) { PolymorphicInfo info; info.mTypeName = typeName; StartPolymorphicInternal(info); } //****************************************************************************** void Serializer::StartPolymorphic(cstr typeName, PolymorphicSaveFlags::Enum flags) { PolymorphicInfo info; info.mTypeName = typeName; info.mFlags.SetFlag(flags); StartPolymorphicInternal(info); } //****************************************************************************** void Serializer::StartPolymorphic(BoundType* objectType) { Handle object; object.StoredType = objectType; StartPolymorphic(object); } //****************************************************************************** void Serializer::StartPolymorphic(HandleParam object) { PolymorphicInfo info; info.mTypeName = object.StoredType->Name.c_str(); info.mObject = object; StartPolymorphicInternal(info); } //****************************************************************************** void Serializer::StartPolymorphicInheritence(cstr typeName, cstr dataInheritanceId) { PolymorphicInfo info; info.mTypeName = typeName; info.mInheritanceId = dataInheritanceId; StartPolymorphicInternal(info); } //****************************************************************************** void Serializer::StartPolymorphicInheritence(cstr typeName, cstr dataInheritanceId, PolymorphicSaveFlags::Enum flags) { PolymorphicInfo info; info.mTypeName = typeName; info.mInheritanceId = dataInheritanceId; info.mFlags.SetFlag(flags); StartPolymorphicInternal(info); } //****************************************************************************** void Serializer::StartPolymorphicInternal(const PolymorphicInfo& info) { Error(cPolymorphicSerializationError); } //****************************************************************************** void Serializer::AddSubtractivePolymorphicNode(BoundType* boundType, Guid nodeId) { AddSubtractivePolymorphicNode(boundType->Name.c_str(), nodeId); } //****************************************************************************** bool Serializer::SimpleField(cstr typeName, cstr fieldName, StringRange& stringRange) { DoNotifyError("Unimplemented function", "SimpleField not implemented"); return true; } //****************************************************************************** DataBlock Serializer::ExtractAsDataBlock() { return DataBlock(); } //****************************************************************************** String Serializer::DebugLocation() { return "Unknown"; } //****************************************************************************** void EncodeBinary(ByteBufferBlock& buffer, String& encodedOut) { // We should replace this with a base64 encoding of zipped data // Just hexify the code right now (+1 for a version number character) StringNode* node = String::AllocateNode(buffer.Size() * 2 + 1); node->Data[0] = '0'; for (size_t i = 0; i < buffer.Size(); ++i) { byte c = buffer.GetBegin()[i]; byte high = c / 16; byte low = c % 16; high += (high < 10) ? '0' : 'A'; low += (low < 10) ? '0' : 'A'; node->Data[i * 2 + 1] = high; node->Data[i * 2 + 2] = low; } encodedOut = String(node); } //****************************************************************************** bool DecodeBinary(ByteBufferBlock& buffer, const String& encoded) { // If there's no data to decode, then early out if (encoded.Empty()) return false; byte version = *encoded.Data(); if (version == '0') { size_t bufferSize = (encoded.SizeInBytes() - 1) / 2; buffer.SetData(new byte[bufferSize], bufferSize, true); for (size_t i = 0; i < bufferSize; ++i) { byte high = encoded.Data()[i * 2 + 1]; byte low = encoded.Data()[i * 2 + 2]; high -= (high < 'A') ? '0' : 'A'; low -= (low < 'A') ? '0' : 'A'; buffer.GetBegin()[i] = high * 16 + low; } return true; } Error("Unexpected binary version"); return false; } }//namespace Zero
29.627615
86
0.462364
[ "object" ]