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
1382002fadb392f38f20e18e990026111bdd3b1a
11,198
cpp
C++
third_party/maya/lib/usdMaya/shadingModeDisplayColor.cpp
marsupial/USD
98d49911893d59be5a9904a29e15959affd530ec
[ "BSD-3-Clause" ]
9
2021-03-31T21:23:48.000Z
2022-03-05T09:29:27.000Z
third_party/maya/lib/usdMaya/shadingModeDisplayColor.cpp
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
null
null
null
third_party/maya/lib/usdMaya/shadingModeDisplayColor.cpp
unity3d-jp/USD
0f146383613e1efe872ea7c85aa3536f170fcda2
[ "BSD-3-Clause" ]
2
2016-12-13T00:53:40.000Z
2020-05-04T07:32:53.000Z
// // Copyright 2016 Pixar // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "usdMaya/shadingModeRegistry.h" #include "usdMaya/translatorLook.h" #include "pxr/base/gf/gamma.h" #include "pxr/usd/usd/stage.h" #include "pxr/usd/usdGeom/gprim.h" #include "pxr/usd/usdGeom/primvar.h" #include "pxr/usd/usdRi/lookAPI.h" #include "pxr/usd/usdRi/risBxdf.h" #include "pxr/usd/usdShade/tokens.h" #include <maya/MColor.h> #include <maya/MFnDependencyNode.h> #include <maya/MFnLambertShader.h> #include <maya/MGlobal.h> #include <maya/MObject.h> #include <maya/MPlug.h> #include <maya/MString.h> TF_DEFINE_PRIVATE_TOKENS( _tokens, (displayColor) (displayOpacity) (diffuseColor) (transmissionColor) (transparency) ((MayaShaderName, "lambert")) ); DEFINE_SHADING_MODE_EXPORTER(displayColor, context) { MStatus status; MFnDependencyNode ssDepNode(context->GetSurfaceShader(), &status); if (not status) { return; } MFnLambertShader lambertFn(ssDepNode.object(), &status ); if (not status) { return; } const PxrUsdMayaShadingModeExportContext::AssignmentVector& assignments = context->GetAssignments(); if (assignments.empty()) { return; } const UsdStageRefPtr& stage = context->GetUsdStage(); MColor mayaColor = lambertFn.color(); MColor mayaTransparency = lambertFn.transparency(); GfVec3f color = GfConvertDisplayToLinear( GfVec3f(mayaColor[0], mayaColor[1], mayaColor[2])); GfVec3f transparency = GfConvertDisplayToLinear( GfVec3f(mayaTransparency[0], mayaTransparency[1], mayaTransparency[2])); VtArray<GfVec3f> displayColorAry; displayColorAry.push_back(color); // The simple UsdGeomGprim display shading schema only allows for a // scalar opacity. We compute it as the unweighted average of the // components since it would be ridiculous to apply the inverse weighting // (of the common graycale conversion) on re-import // The average is compute from the Maya color as is VtArray<float> displayOpacityAry; float transparencyAvg = (mayaTransparency[0] + mayaTransparency[1] + mayaTransparency[2]) / 3.0; if (transparencyAvg > 0){ displayOpacityAry.push_back(1.0 - transparencyAvg); } TF_FOR_ALL(iter, assignments) { const SdfPath &boundPrimPath = iter->first; const VtIntArray &faceIndices = iter->second; if (not faceIndices.empty()) continue; UsdPrim boundPrim = stage->GetPrimAtPath(boundPrimPath); if (boundPrim) { UsdGeomGprim primSchema(boundPrim); // Set color if not already authored // // XXX: Note that this will not update the display color // in the presence of a SdfValueBlock which is a valid // 'authored value opinion' in the eyes of Usd. if (not primSchema.GetDisplayColorAttr() .HasAuthoredValueOpinion()) { // not animatable primSchema.GetDisplayColorPrimvar().Set(displayColorAry); } if (transparencyAvg > 0 and not primSchema.GetDisplayOpacityAttr() .HasAuthoredValueOpinion()) { // not animatable primSchema.GetDisplayOpacityPrimvar().Set(displayOpacityAry); } } else { MGlobal::displayError("No prim bound to:" + MString(boundPrimPath.GetText())); } } bool makeLookPrim = true; if (makeLookPrim) { if (UsdShadeLook look = UsdShadeLook(context->MakeStandardLookPrim(assignments))) { // Create a Diffuse RIS shader for the Look. // Although Maya can't yet make use of it, downstream apps // can make use of Look interface attributes, so create one to // drive the shader's color. // // NOTE! We do not set any values directly on the shaders; // instead we set the values only on the look's interface, // emphasizing that the interface is a value provider for // its shading networks. UsdShadeInterfaceAttribute dispColorIA = look.CreateInterfaceAttribute( _tokens->displayColor, SdfValueTypeNames->Color3f); dispColorIA.Set(VtValue(color)); UsdPrim lookPrim = look.GetPrim(); std::string shaderName = TfStringPrintf("%s_lambert", lookPrim.GetName().GetText()); TfToken shaderPrimName(shaderName); UsdRiRisBxdf bxdfSchema = UsdRiRisBxdf::Define( stage, lookPrim.GetPath().AppendChild(shaderPrimName)); bxdfSchema.CreateFilePathAttr(VtValue(SdfAssetPath("PxrDiffuse"))); UsdShadeParameter diffuse = bxdfSchema.CreateParameter(_tokens->diffuseColor, SdfValueTypeNames->Color3f); UsdRiLookAPI(look).SetInterfaceRecipient(dispColorIA, diffuse); // Make an interface attr for transparency, which we will hook up // to the shader, and a displayOpacity, for any shader that might // want to consume it. Only author a *value* if we got a // non-zero transparency UsdShadeInterfaceAttribute transparencyIA = look.CreateInterfaceAttribute(_tokens->transparency, SdfValueTypeNames->Color3f); UsdShadeInterfaceAttribute dispOpacityIA = look.CreateInterfaceAttribute(_tokens->displayOpacity, SdfValueTypeNames->Float); // PxrDiffuse's transmissionColor may not produce similar // results to MfnLambertShader's transparency, but it's in // the general ballpark... UsdShadeParameter transmission = bxdfSchema.CreateParameter(_tokens->transmissionColor, SdfValueTypeNames->Color3f); UsdRiLookAPI(look).SetInterfaceRecipient(transparencyIA, transmission); if (transparencyAvg > 0){ transparencyIA.Set(VtValue(transparency)); dispOpacityIA.Set(VtValue((float)(1.0-transparencyAvg))); } } } } DEFINE_SHADING_MODE_IMPORTER(displayColor, context) { const UsdShadeLook& shadeLook = context->GetShadeLook(); const UsdGeomGprim& primSchema = context->GetBoundPrim(); MStatus status; // Note that we always couple the source of the displayColor with the // source of the displayOpacity. It would not make sense to get the // displayColor from a bound Look, while getting the displayOpacity from // the gprim itself, for example, even if the Look did not have // displayOpacity authored. When the Look or gprim does not have // displayOpacity authored, we fall back to full opacity. bool gotDisplayColorAndOpacity=false; // Get Display Color from USD (linear) and convert to Display GfVec3f linearDisplayColor(.5,.5,.5), linearTransparency(0, 0, 0); if (not shadeLook or not shadeLook.GetInterfaceAttribute(_tokens->displayColor).GetAttr().Get(&linearDisplayColor)) { VtArray<GfVec3f> gprimDisplayColor(1); if (primSchema and primSchema.GetDisplayColorPrimvar().ComputeFlattened(&gprimDisplayColor)) { linearDisplayColor=gprimDisplayColor[0]; VtArray<float> gprimDisplayOpacity(1); if (primSchema.GetDisplayOpacityPrimvar().GetAttr() .HasAuthoredValueOpinion() and primSchema.GetDisplayOpacityPrimvar().ComputeFlattened(&gprimDisplayOpacity)) { float trans = 1.0 - gprimDisplayOpacity[0]; linearTransparency = GfVec3f(trans, trans, trans); } gotDisplayColorAndOpacity = true; } else { MString warn = MString("Unable to retrieve DisplayColor on Look: "); warn += shadeLook ? shadeLook.GetPrim().GetPath().GetText() : "<NONE>"; warn += " or GPrim: "; warn += primSchema ? primSchema.GetPrim().GetPath().GetText() : "<NONE>"; MGlobal::displayWarning(warn); } } else { shadeLook .GetInterfaceAttribute(_tokens->transparency) .GetAttr() .Get(&linearTransparency); gotDisplayColorAndOpacity = true; } GfVec3f displayColor = GfConvertLinearToDisplay(linearDisplayColor); GfVec3f transparencyColor = GfConvertLinearToDisplay(linearTransparency); if (gotDisplayColorAndOpacity) { std::string shaderName(_tokens->MayaShaderName.GetText()); SdfPath shaderParentPath = SdfPath::AbsoluteRootPath(); if (shadeLook) { const UsdPrim& shadeLookPrim = shadeLook.GetPrim(); shaderName = TfStringPrintf("%s_%s", shadeLookPrim.GetName().GetText(), _tokens->MayaShaderName.GetText()); shaderParentPath = shadeLookPrim.GetPath(); } MString mShaderName(shaderName.c_str()); // Construct the lambert shader MFnLambertShader lambertFn; MObject shadingObj = lambertFn.create(); lambertFn.setName( mShaderName ); lambertFn.setColor(MColor(displayColor[0], displayColor[1], displayColor[2])); lambertFn.setTransparency(MColor(transparencyColor[0], transparencyColor[1], transparencyColor[2])); const SdfPath lambertPath = shaderParentPath.AppendChild( TfToken(lambertFn.name().asChar())); context->AddCreatedObject(lambertPath, shadingObj); // Connect the lambert surfaceShader to the Shading Group (set) return lambertFn.findPlug("outColor", &status); } return MPlug(); }
41.783582
108
0.633149
[ "object" ]
138a1906414e5e3a0bcecd0eb81986e1465c8939
19,497
cpp
C++
ext/ttcrypt/rsa_key.cpp
porzione/ttcrypt
1b01f248fd8889f26f4942d386274cae7c002d26
[ "BSD-3-Clause" ]
null
null
null
ext/ttcrypt/rsa_key.cpp
porzione/ttcrypt
1b01f248fd8889f26f4942d386274cae7c002d26
[ "BSD-3-Clause" ]
null
null
null
ext/ttcrypt/rsa_key.cpp
porzione/ttcrypt
1b01f248fd8889f26f4942d386274cae7c002d26
[ "BSD-3-Clause" ]
null
null
null
// // RsaKey.cpp // zcoin // // Created by Sergey Chernov on 02.06.14. // Copyright (c) 2014 thrift. All rights reserved. // /* 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <future> #include "rsa_key.h" #include "ttcrypt.h" using namespace ttcrypt; using namespace thrift; namespace ttcrypt { static byte_buffer mgf1(const byte_buffer& z, size_t l) { const size_t hLen = 20; byte_buffer t; for (unsigned i = 0; i <= l / hLen; i++) { t += sha1(z + i2osp(i, 4)); } return byte_buffer(t, 0, l - 1); } byte_buffer eme_oaep_encode(const byte_buffer& message, size_t emLen, const byte_buffer* p, const byte_buffer* pseed) { const size_t hLen = 20; const size_t hLen2 = 2 * hLen; size_t mLen = message.size(); if (emLen <= hLen2 + 1) throw rsa_key::error("padded length too small"); if (mLen >= emLen - 1 - hLen2 || mLen > emLen - 2 * hLen2 - 1) throw rsa_key::error("message too long"); auto ps = byte_buffer::pad('\0', emLen - mLen - hLen2 - 1); auto pHash = sha1(p ? *p : ""); auto db = pHash + ps + "\001" + message; auto seed = (pseed != 0) ? *pseed : byte_buffer::random(hLen); auto dbMask = mgf1(seed, emLen - hLen); auto maskedDb = db ^ dbMask; auto seedMask = mgf1(maskedDb, hLen); auto maskedSeed = seed ^ seedMask; return maskedSeed + maskedDb; } byte_buffer eme_oaep_decode(const byte_buffer& message, const byte_buffer* p) { const size_t hLen = 20; if (message.size() < hLen * 2 + 1) throw rsa_key::error("message is too short"); byte_buffer maskedSeed(message, 0, hLen - 1); byte_buffer maskedDb(message, hLen, -1); auto seedMask = mgf1(maskedDb, hLen); auto seed = maskedSeed ^ seedMask; auto db_mask = mgf1(seed, message.size() - hLen); auto db = maskedDb ^ db_mask; auto pHash = sha1(p ? *p : ""); int index = db.index_of('\001', hLen); if (index < 0) throw rsa_key::error("message is invalid (no 1)"); byte_buffer pHash2(db, 0, hLen - 1); byte_buffer ps(db, hLen, index - 1); byte_buffer m(db, index + 1, -1); for (auto x : ps) { if (x != '\0') throw rsa_key::error("message is invalid (zero padding)"); } if (pHash2 != pHash) throw rsa_key::error("wrong p value"); return m; } byte_buffer rsa_key::rsadp(const byte_buffer& ciphertext) const { big_integer c = ciphertext; if (c >= n - 1) throw rsa_key::error("ciphertext is too long"); if (fast_key) { // Fast auto m1 = powmod_sec((c % p), dp, p); auto m2 = powmod_sec((c % q), dq, q); auto h = ((m1 - m2) * q_inv) % p; return i2osp(m2 + q * h, byte_size - 1); } else { // slow c^d mod n if (d == 0) throw rsa_key::error("missing private key"); return i2osp(powmod_sec(c, d, n), byte_size - 1); } } byte_buffer emsa_pss_encode(const byte_buffer& message, size_t emBits, byte_buffer (*hash)(const byte_buffer&), const byte_buffer *_salt = 0) { auto mHash = hash(message); auto hLen = mHash.size(); // TODO: implement bits logic! auto emLen = (emBits + 7) / 8; // required: emLen < hLen + sLen + 2 size_t sLen; byte_buffer salt; if (_salt) { salt = *_salt; sLen = salt.size(); } else { sLen = emLen - hLen - 2; salt = byte_buffer::random(sLen); } if (emLen < hLen + sLen + 2) throw rsa_key::error("invliad salt length"); auto M1 = byte_buffer::pad('\0', 8) + mHash + salt; auto H = hash(M1); auto PS = byte_buffer::pad('\0', emLen - sLen - hLen - 2); auto DB = PS.append_byte(1) + salt; auto dbMask = mgf1(H, emLen - hLen - 1); auto maskedDb = DB ^ dbMask; // Clear leftmost bits auto clear_bits = 8 * emLen - emBits; if (clear_bits > 0) maskedDb.set(0, clear_left_bits(maskedDb.at(0), clear_bits)); return maskedDb + H + "\xbc"; } bool emsa_pss_verify(const byte_buffer& source_message, const byte_buffer& encoded_message, size_t emBits, byte_buffer (*hash)(const byte_buffer&), size_t sLen) { auto mHash = hash(source_message); auto emLen = (emBits + 7) / 8; size_t hLen = mHash.size(); if (sLen == 0) sLen = emLen - hLen - 2; if (emLen < hLen + sLen + 2 || encoded_message[-1] != 0xbc) return false; byte_buffer maskedDB(encoded_message, 0, emLen - hLen - 2); // range is inclusive! // Check MSB bits are cleared auto clear_bits = 8 * emLen - emBits; if (clear_bits > 0) { byte bitmask = 0x80; for (unsigned bit_no = 0; bit_no++ < clear_bits;) { if ((maskedDB[0] & bitmask) != 0) // Compiler should optimize this return false; } } byte_buffer H(encoded_message, emLen - hLen - 1, emLen - 2); // range inclusive auto dbMask = mgf1(H, emLen - hLen - 1); auto DB = maskedDB ^ dbMask; DB.set(0, clear_left_bits(DB[0], clear_bits)); for (unsigned i = 0; i < emLen - hLen - sLen - 2; i++) { if (DB[i] != 0) { return false; } } if (DB[emLen - hLen - sLen - 2] != 1) return false; byte_buffer salt(DB, -sLen, -1); auto M1 = byte_buffer::pad('\0', 8) + mHash + salt; auto H1 = hash(M1); return H == H1; } // Note that signing does not require blinding - it is not prone to the // timing attack byte_buffer rsa_key::rsasp1(const byte_buffer &message) const { big_integer m = message; if (m >= n) throw rsa_key::error("message representative is too long"); if (fast_key) { // Fast auto s1 = powmod(m % p, dp, p); auto s2 = powmod(m % q, dq, q); auto h = (s1 - s2) * q_inv % p; auto s = s2 + q * h; return i2osp(s, byte_size); } else { // slow if (d == 0) throw rsa_key::error("missing private key"); return i2osp(powmod(m, d, n), byte_size); } } byte_buffer rsa_key::rsavp1(const byte_buffer& signature) const { big_integer s = signature; if (s > n - 1) throw invalid_argument("signature representative too big"); require_public_key(); return i2osp(powmod_sec(s, e, n), byte_size); } bool rsa_key::verify(const byte_buffer& message, const byte_buffer& signature, byte_buffer (*hash)(const byte_buffer&), size_t s_len) const { if (signature.size() != byte_size) return false; try { return emsa_pss_verify(message, rsavp1(signature), bits_size - 1, hash, s_len); } catch (const invalid_argument& e) { return false; } } void rsa_key::normalize_key() { if (n == 0) n = p * q; if ((dp == 0 || dq == 0 || q_inv == 0) && p != 0 && q != 0) { dp = inverse(e, p - 1); dq = inverse(e, q - 1); q_inv = inverse(q, p); fast_key = true; } else fast_key = p != 0 && q != 0 && dp != 0 && dq != 0 && q_inv != 0; bits_size = n.bit_length(); byte_size = (bits_size + 7) / 8; } static big_integer prime(unsigned bits) { // Set 2 MSB bits to ensire we git enough big pq // and calculate margin big_integer r = (1_b << (bits - 2)) + (1_b << (bits - 1)); big_integer s = (1_b << bits) - 1; while (1) { auto p = next_prime(big_integer::random_between(r, s)); if (p <= s) return p; // loop if prime is too big (unlikely) } throw logic_error("failed prime generation"); } rsa_key rsa_key::generate(unsigned int k, size_t e) { if (e == 0) e = 0x10001; if (e < 3 || (e != 0x10001 && !big_integer(e).is_prime())) throw rsa_key::error("exponent should be prime number >= 3"); // v2.2 Algorithm while (true) { #ifdef NO_FUTURE auto q = prime(k - k / 2); auto p = prime(k/2); #else auto future = std::async(std::launch::async, [k] {return prime(k/2);}); auto q = prime(k - k / 2); auto p = future.get(); #endif if (p == q) continue; auto n = p * q; if (n.bit_length() != k) { // logic error: bit length mismatch, regenerating continue; } auto Ln = lcm(p - 1, q - 1); if (gcd(e, Ln) != 1) continue; if (p > q) swap(p, q); return rsa_key(n, e, p, q); } throw logic_error("pq generation failed"); } void rsa_key::set(const string& name, const thrift::big_integer &value) { switch (name[0]) { case 'e': e = value; break; case 'p': this->p = value; break; case 'q': if (name == "qinv" || name == "q_inv") q_inv = value; else q = value; break; case 'n': n = value; break; case 'd': if (name == "dp") { dp = value; } else if (name == "dq") { dq = value; } else d = value; break; default: throw error("unknown paramerer "); break; } } unordered_map<string, big_integer> rsa_key::get_params(bool include_all) const noexcept { unordered_map<string, big_integer> params; if (n != 0) { params["n"] = n; } if (e != 0) { params["e"] = e; } if (p != 0) { params["p"] = p; } if (q != 0) { params["q"] = q; } if (d != 0 && ((p == 0 && q == 0) || include_all)) { params["d"] = q; } if (dp != 0 && include_all) { params["dp"] = dp; } if (dq != 0 && include_all) { params["dq"] = dq; } if (q_inv != 0 && include_all) { params["qinv"] = q_inv; } return params; } static ostream *pout; #define LHEX(text,data) {*pout<<text<<":\n"<<data.hex(16)<<endl;} #define REQUIRE(x) if(!(x)){*pout<<"Failed "<<(#x)<<" @"<<__FILE__<<":"<<__LINE__<<endl; return false;} bool rsa_key::self_test(ostream& out) { pout = &out; { out << "we start..." << endl; big_integer mi = pow(2_b,1024) - 173_b; if( big_integer(mi.to_byte_buffer()) != mi ) { out << "Decoding problem" << endl; return false; } byte_buffer res = i2osp(65537_b); if( res.hex() != "01 00 01") { out << "i2osp fail: " << res.hex() << endl; return false; } mi = os2ip(res); if( mi != 65537_b ) { out << "I2OSP/OS2IP failure: Result is not 65537: " << mi << endl; return false; } mi = pow(2_b,1023) - 1_b; byte_buffer x = rsadp( rsaep(mi.to_byte_buffer()) ); if( big_integer(x) != mi ) { out << "Big integer failure: " << big_integer(x) << endl; return false; } byte_buffer src("hello!"); if( i2osp( os2ip(src), 6) != src ) { out << "Failed osp2: " << i2osp( os2ip(src), 6) << endl; return false; } string sres = i2osp(254,3).hex(); if( sres != "00 00 fe" ) { out << "i20sp padding failure: " << sres << endl; return false; } if( sha1("abc") != decode_hex("a9993e36 4706816a ba3e2571 7850c26c 9cd0d89d") ) { out << "SHA1 failed: " << sha1("abc").hex() << endl; return false; } if( sha1("") != decode_hex("da39a3ee 5e6b4b0d 3255bfef 95601890 afd80709") ) { out << "SHA1 of empty string failed: " << sha1("").hex() << endl; return false; } res = eme_oaep_decode(eme_oaep_encode(src, 127, 0, 0), 0); if( res != src ) { out << "OAEP failed: " << res; return false; } } { out << "RSAES test" << endl; auto message = decode_hex("d4 36 e9 95 69 fd 32 a7 c8 a0 5b bc 90 d3 2c 49"); auto seed = decode_hex("aa fd 12 f6 59 ca e6 34 89 b4 79 e5 07 6d de c2 f0 6c b5 8f"); auto encoded_message = decode_hex("\ eb 7a 19 ac e9 e3 00 63 50 e3 29 50 4b 45 e2 ca 82 31 0b 26 dc d8 7d 5c 68\ f1 ee a8 f5 52 67 c3 1b 2e 8b b4 25 1f 84 d7 e0 b2 c0 46 26 f5 af f9 3e dc\ fb 25 c9 c2 b3 ff 8a e1 0e 83 9a 2d db 4c dc fe 4f f4 77 28 b4 a1 b7 c1 36\ 2b aa d2 9a b4 8d 28 69 d5 02 41 21 43 58 11 59 1b e3 92 f9 82 fb 3e 87 d0\ 95 ae b4 04 48 db 97 2f 3a c1 4f 7b c2 75 19 52 81 ce 32 d2 f1 b7 6d 4d 35\ 3e 2d"); auto encrypted_message = decode_hex("\ 12 53 e0 4d c0 a5 39 7b b4 4a 7a b8 7e 9b f2 a0 39 a3 3d 1e 99 6f c8 2a 94\ cc d3 00 74 c9 5d f7 63 72 20 17 06 9e 52 68 da 5d 1c 0b 4f 87 2c f6 53 c1\ 1d f8 23 14 a6 79 68 df ea e2 8d ef 04 bb 6d 84 b1 c3 1d 65 4a 19 70 e5 78\ 3b d6 eb 96 a0 24 c2 ca 2f 4a 90 fe 9f 2e f5 c9 c1 40 e5 bb 48 da 95 36 ad\ 87 00 c8 4f c9 13 0a de a7 4e 55 8d 51 a7 4d df 85 d8 b5 0d e9 68 38 d6 06\ 3e 09 55"); auto n = decode_hex("\ bb f8 2f 09 06 82 ce 9c 23 38 ac 2b 9d a8 71 f7 36 8d 07 ee d4 10 43 a4\ 40 d6 b6 f0 74 54 f5 1f b8 df ba af 03 5c 02 ab 61 ea 48 ce eb 6f cd 48\ 76 ed 52 0d 60 e1 ec 46 19 71 9d 8a 5b 8b 80 7f af b8 e0 a3 df c7 37 72\ 3e e6 b4 b7 d9 3a 25 84 ee 6a 64 9d 06 09 53 74 88 34 b2 45 45 98 39 4e\ e0 aa b1 2d 7b 61 a5 1f 52 7a 9a 41 f6 c1 68 7f e2 53 72 98 ca 2a 8f 59\ 46 f8 e5 fd 09 1d bd cb"); unsigned e = 0x11; auto p = decode_hex("\ ee cf ae 81 b1 b9 b3 c9 08 81 0b 10 a1 b5 60 01 99 eb 9f 44 ae f4 fd a4\ 93 b8 1a 9e 3d 84 f6 32 12 4e f0 23 6e 5d 1e 3b 7e 28 fa e7 aa 04 0a 2d\ 5b 25 21 76 45 9d 1f 39 75 41 ba 2a 58 fb 65 99"); auto q = decode_hex("\ c9 7f b1 f0 27 f4 53 f6 34 12 33 ea aa d1 d9 35 3f 6c 42 d0 88 66 b1 d0\ 5a 0f 20 35 02 8b 9d 86 98 40 b4 16 66 b4 2e 92 ea 0d a3 b4 32 04 b5 cf\ ce 33 52 52 4d 04 16 a5 a4 41 e7 00 af 46 15 03"); // auto dP = decode_hex("\ // 54 49 4c a6 3e ba 03 37 e4 e2 40 23 fc d6 9a 5a eb 07 dd dc 01 83 a4 d0\ // ac 9b 54 b0 51 f2 b1 3e d9 49 09 75 ea b7 74 14 ff 59 c1 f7 69 2e 9a 2e\ // 20 2b 38 fc 91 0a 47 41 74 ad c9 3c 1f 67 c9 81"); // // auto dQ = decode_hex("\ // 47 1e 02 90 ff 0a f0 75 03 51 b7 f8 78 86 4c a9 61 ad bd 3a 8a 7e 99 1c\ // 5c 05 56 a9 4c 31 46 a7 f9 80 3f 8f 6f 8a e3 42 e9 31 fd 8a e4 7a 22 0d\ // 1b 99 a4 95 84 98 07 fe 39 f9 24 5a 98 36 da 3d"); // // auto qInv = decode_hex("\ // b0 6c 4f da bb 63 01 19 8d 26 5b db ae 94 23 b3 80 f2 71 f7 34 53 88 50\ // 93 07 7f cd 39 e2 11 9f c9 86 32 15 4f 58 83 b1 67 a9 67 bf 40 2b 4e 9e\ // 2e 0f 96 56 e6 98 ea 36 66 ed fb 25 79 80 39 f7"); rsa_key key(n, e, p, q); key.debug_seed(seed); REQUIRE( key.encrypt(message).hex() == encrypted_message.hex() ); REQUIRE( key.decrypt(encrypted_message).hex() == message.hex() ); rsa_key key2(n, e, p, q); REQUIRE( key2.is_private() == true); REQUIRE( key2.decrypt(encrypted_message).hex() == message.hex() ); } { out << "Sign test" << endl; auto signing_salt = decode_hex("e3 b5 d5 d0 02 c1 bc e5 0c 2b 65 ef 88 a1 88 d8 3b ce 7e 61"); auto message = decode_hex("85 9e ef 2f d7 8a ca 00 30 8b dc 47 11 93 bf 55" "bf 9d 78 db 8f 8a 67 2b 48 46 34 f3 c9 c2 6e 64" "78 ae 10 26 0f e0 dd 8c 08 2e 53 a5 29 3a f2 17" "3c d5 0c 6d 5d 35 4f eb f7 8b 26 02 1c 25 c0 27" "12 e7 8c d4 69 4c 9f 46 97 77 e4 51 e7 f8 e9 e0" "4c d3 73 9c 6b bf ed ae 48 7f b5 56 44 e9 ca 74" "ff 77 a5 3c b7 29 80 2f 6e d4 a5 ff a8 ba 15 98" "90 fc"); auto EM = decode_hex( "66 e4 67 2e 83 6a d1 21 ba 24 4b ed 65 76 b8 67" "d9 a4 47 c2 8a 6e 66 a5 b8 7d ee 7f bc 7e 65 af" "50 57 f8 6f ae 89 84 d9 ba 7f 96 9a d6 fe 02 a4" "d7 5f 74 45 fe fd d8 5b 6d 3a 47 7c 28 d2 4b a1" "e3 75 6f 79 2d d1 dc e8 ca 94 44 0e cb 52 79 ec" "d3 18 3a 31 1f c8 96 da 1c b3 93 11 af 37 ea 4a" "75 e2 4b db fd 5c 1d a0 de 7c ec df 1a 89 6f 9d" "8b c8 16 d9 7c d7 a2 c4 3b ad 54 6f be 8c fe bc"); //# RSA modulus n: auto n = decode_hex("\ a2 ba 40 ee 07 e3 b2 bd 2f 02 ce 22 7f 36 a1 95\ 02 44 86 e4 9c 19 cb 41 bb bd fb ba 98 b2 2b 0e\ 57 7c 2e ea ff a2 0d 88 3a 76 e6 5e 39 4c 69 d4\ b3 c0 5a 1e 8f ad da 27 ed b2 a4 2b c0 00 fe 88\ 8b 9b 32 c2 2d 15 ad d0 cd 76 b3 e7 93 6e 19 95\ 5b 22 0d d1 7d 4e a9 04 b1 ec 10 2b 2e 4d e7 75\ 12 22 aa 99 15 10 24 c7 cb 41 cc 5e a2 1d 00 ee\ b4 1f 7c 80 08 34 d2 c6 e0 6b ce 3b ce 7e a9 a5"); //# RSA public exponent e: auto e = 0x010001; // //# Prime p: auto p = decode_hex("\ d1 7f 65 5b f2 7c 8b 16 d3 54 62 c9 05 cc 04 a2\ 6f 37 e2 a6 7f a9 c0 ce 0d ce d4 72 39 4a 0d f7\ 43 fe 7f 92 9e 37 8e fd b3 68 ed df f4 53 cf 00\ 7a f6 d9 48 e0 ad e7 57 37 1f 8a 71 1e 27 8f 6b"); //# Prime q: auto q = decode_hex("\ c6 d9 2b 6f ee 74 14 d1 35 8c e1 54 6f b6 29 87\ 53 0b 90 bd 15 e0 f1 49 63 a5 e2 63 5a db 69 34\ 7e c0 c0 1b 2a b1 76 3f d8 ac 1a 59 2f b2 27 57\ 46 3a 98 24 25 bb 97 a3 a4 37 c5 bf 86 d0 3f 2f"); auto signature = decode_hex("\ 8d aa 62 7d 3d e7 59 5d 63 05 6c 7e c6 59 e5 44\ 06 f1 06 10 12 8b aa e8 21 c8 b2 a0 f3 93 6d 54\ dc 3b dc e4 66 89 f6 b7 95 1b b1 8e 84 05 42 76\ 97 18 d5 71 5d 21 0d 85 ef bb 59 61 92 03 2c 42\ be 4c 29 97 2c 85 62 75 eb 6d 5a 45 f0 5f 51 87\ 6f c6 74 3d ed dd 28 ca ec 9b b3 0e a9 9e 02 c3\ 48 82 69 60 4f e4 97 f7 4c cd 7c 7f ca 16 71 89\ 71 23 cb d3 0d ef 5d 54 a2 b5 53 6a d9 0a 74 7e"); auto padded = emsa_pss_encode(message, 1023, sha1, &signing_salt); REQUIRE( padded.hex() == EM.hex() ); REQUIRE(true == emsa_pss_verify(message, padded, 1023, sha1, signing_salt.size())); REQUIRE(false == emsa_pss_verify(message+"!", padded, 1023, sha1, signing_salt.size())); padded.set(0, padded[0] ^ 3); REQUIRE(false == emsa_pss_verify(message, padded, 1023, sha1, signing_salt.size())); rsa_key key(n, e, p, q); auto s = key.sign(message, sha1, &signing_salt); REQUIRE( s == signature ); REQUIRE( key.verify(message, s, sha1, signing_salt.size()) == true ); s = key.sign(message+"!", sha1, &signing_salt); REQUIRE( s != signature ); } return true; } }
32.934122
116
0.543263
[ "3d" ]
138c607086fe5be08f9e4f2bad9fa8f1428221a0
4,629
cpp
C++
src/implicit_shape_model/features/features_rift.cpp
Pandinosaurus/PointCloudDonkey
13bc486cf422dbd75cac395cb79503896c583bed
[ "BSD-3-Clause" ]
10
2018-12-21T13:42:45.000Z
2020-11-09T02:13:29.000Z
src/implicit_shape_model/features/features_rift.cpp
Pandinosaurus/PointCloudDonkey
13bc486cf422dbd75cac395cb79503896c583bed
[ "BSD-3-Clause" ]
null
null
null
src/implicit_shape_model/features/features_rift.cpp
Pandinosaurus/PointCloudDonkey
13bc486cf422dbd75cac395cb79503896c583bed
[ "BSD-3-Clause" ]
6
2019-02-03T12:17:19.000Z
2019-11-22T01:36:03.000Z
/* * BSD 3-Clause License * * Full text: https://opensource.org/licenses/BSD-3-Clause * * Copyright (c) 2018, Viktor Seib * All rights reserved. * */ #include "features_rift.h" #define PCL_NO_PRECOMPILE #include <pcl/point_types_conversion.h> #include <pcl/features/intensity_gradient.h> #include <pcl/features/rift.h> namespace ism3d { FeaturesRIFT::FeaturesRIFT() { addParameter(m_radius, "Radius", 0.1); } FeaturesRIFT::~FeaturesRIFT() { } pcl::PointCloud<ISMFeature>::Ptr FeaturesRIFT::iComputeDescriptors(pcl::PointCloud<PointT>::ConstPtr pointCloud, pcl::PointCloud<pcl::Normal>::ConstPtr normals, pcl::PointCloud<PointT>::ConstPtr pointCloudWithoutNaNNormals, pcl::PointCloud<pcl::Normal>::ConstPtr normalsWithoutNaN, pcl::PointCloud<pcl::ReferenceFrame>::Ptr referenceFrames, pcl::PointCloud<PointT>::Ptr keypoints, pcl::search::Search<PointT>::Ptr search) { // NOTE: point cloud MUST contain RGB data, otherwise results will be meaningless const int rift_distance_bins = 8; // original value: 4 const int rift_gradient_bins = 16; // original value: 8 const int rift_size = rift_distance_bins * rift_gradient_bins; // Object for storing the point cloud with intensity value. pcl::PointCloud<pcl::PointXYZI>::Ptr cloudIntensity(new pcl::PointCloud<pcl::PointXYZI>); // Object for storing the point cloud with intensity value. pcl::PointCloud<pcl::PointXYZI>::Ptr keypointsIntensity(new pcl::PointCloud<pcl::PointXYZI>); // Convert the RGB to intensity. pcl::PointCloud<PointT> cloud = *pointCloudWithoutNaNNormals; pcl::PointCloudXYZRGBtoXYZI(cloud, *cloudIntensity); pcl::PointCloud<PointT> keypoints_cloud = *keypoints; pcl::PointCloudXYZRGBtoXYZI(keypoints_cloud, *keypointsIntensity); // Object for storing the intensity gradients. pcl::PointCloud<pcl::IntensityGradient>::Ptr gradients(new pcl::PointCloud<pcl::IntensityGradient>); // Compute the intensity gradients. pcl::IntensityGradientEstimation <pcl::PointXYZI, pcl::Normal, pcl::IntensityGradient, pcl::common::IntensityFieldAccessor<pcl::PointXYZI> > ge; ge.setInputCloud(cloudIntensity); ge.setInputNormals(normalsWithoutNaN); ge.setRadiusSearch(m_radius); ge.compute(*gradients); pcl::search::KdTree<pcl::PointXYZI>::Ptr kdtree(new pcl::search::KdTree<pcl::PointXYZI>); // Object for storing the RIFT descriptor for each point. pcl::PointCloud<pcl::Histogram<rift_size> >::Ptr descriptors(new pcl::PointCloud<pcl::Histogram<rift_size> >()); // RIFT estimation object pcl::RIFTEstimation<pcl::PointXYZI, pcl::IntensityGradient, pcl::Histogram<rift_size> > rift; rift.setInputCloud(keypointsIntensity); rift.setSearchSurface(cloudIntensity); rift.setSearchMethod(kdtree); rift.setInputGradient(gradients); // Set the intensity gradients to use. rift.setRadiusSearch(m_radius); // Radius, to get all neighbors within. rift.setNrDistanceBins(rift_distance_bins); // Set the number of bins to use in the distance dimension. rift.setNrGradientBins(rift_gradient_bins); // Set the number of bins to use in the gradient orientation dimension. rift.compute(*descriptors); // create descriptor point cloud pcl::PointCloud<ISMFeature>::Ptr features(new pcl::PointCloud<ISMFeature>()); features->resize(descriptors->size()); for (int i = 0; i < (int)descriptors->size(); i++) { ISMFeature& feature = features->at(i); const pcl::Histogram<rift_size>& riftd = descriptors->at(i); // store the descriptor feature.descriptor.resize(rift_size); for (int j = 0; j < feature.descriptor.size(); j++) feature.descriptor[j] = riftd.histogram[j]; } return features; } std::string FeaturesRIFT::getTypeStatic() { return "RIFT"; } std::string FeaturesRIFT::getType() const { return FeaturesRIFT::getTypeStatic(); } }
42.861111
135
0.615252
[ "object" ]
ca5d73fc64ed4a454f1ecb6fde7e6d369aaf6482
841
cpp
C++
leetcode/october-challenge/week-3/Asteroid-Collision.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-08T19:28:40.000Z
2020-10-08T19:28:40.000Z
leetcode/october-challenge/week-3/Asteroid-Collision.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
null
null
null
leetcode/october-challenge/week-3/Asteroid-Collision.cpp
joaquinmd93/competitive-programming
681424abd777cc0a3059e1ee66ae2cee958178da
[ "MIT" ]
1
2020-10-24T02:32:27.000Z
2020-10-24T02:32:27.000Z
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { stack<int> s; vector<int> ans; for (int i = 0; i < asteroids.size(); ++i) { int a = asteroids[i]; if (a > 0) s.push(a); while (!s.empty() && -a > s.top()) s.pop(); if (a < 0 && s.empty()) ans.push_back(a); if (!s.empty() && -a == s.top()) s.pop(); } vector<int> rev; int m = s.size(); for (int i = 0; i < m; ++i) { rev.push_back(s.top()); s.pop(); } for (int i = m-1; i >= 0; --i) { ans.push_back(rev[i]); } return ans; } };
25.484848
59
0.332937
[ "vector" ]
ca618fe7c7ec0560e299c1703df1d8f35a3372fc
800
cpp
C++
leetcode.com/0129 Sum Root to Leaf Numbers/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0129 Sum Root to Leaf Numbers/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0129 Sum Root to Leaf Numbers/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int ans{0}; void number(TreeNode* root, int currentSum) { currentSum += root -> val; if (root -> left != nullptr) number(root -> left, currentSum * 10); if (root -> right != nullptr) number(root -> right, currentSum * 10); if (root -> left == nullptr && root -> right == nullptr) ans += currentSum; } int sumNumbers(TreeNode* root) { if (root == nullptr) return 0; number(root, 0); return ans; } };
20.512821
64
0.5
[ "vector" ]
ca657c5904b6c5128fb1ebb6966dec6bf9935c3e
3,641
cpp
C++
test/core/network/sync_protocol_observer_test.cpp
Harrm/kagome
22932bbbbf2f09712ca81b9e6256492f84cf2a46
[ "Apache-2.0" ]
null
null
null
test/core/network/sync_protocol_observer_test.cpp
Harrm/kagome
22932bbbbf2f09712ca81b9e6256492f84cf2a46
[ "Apache-2.0" ]
null
null
null
test/core/network/sync_protocol_observer_test.cpp
Harrm/kagome
22932bbbbf2f09712ca81b9e6256492f84cf2a46
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "network/impl/sync_protocol_observer_impl.hpp" #include <gtest/gtest.h> #include <boost/optional.hpp> #include <functional> #include "mock/core/blockchain/block_header_repository_mock.hpp" #include "mock/core/blockchain/block_tree_mock.hpp" #include "mock/libp2p/host/host_mock.hpp" #include "primitives/block.hpp" #include "testutil/gmock_actions.hpp" #include "testutil/literals.hpp" #include "testutil/outcome.hpp" using namespace kagome; using namespace blockchain; using namespace network; using namespace primitives; using namespace common; using namespace libp2p; using namespace peer; using testing::_; using testing::Ref; using testing::Return; using testing::ReturnRef; class SynchronizerTest : public testing::Test { public: void SetUp() override { block1_.header.parent_hash.fill(2); block1_hash_.fill(3); block2_.header.parent_hash = block1_hash_; block2_hash_.fill(4); sync_protocol_observer_ = std::make_shared<SyncProtocolObserverImpl>(tree_, headers_); } std::shared_ptr<HostMock> host_ = std::make_shared<HostMock>(); PeerInfo peer_info_{"my_peer"_peerid, {}}; std::shared_ptr<BlockTreeMock> tree_ = std::make_shared<BlockTreeMock>(); std::shared_ptr<BlockHeaderRepositoryMock> headers_ = std::make_shared<BlockHeaderRepositoryMock>(); std::shared_ptr<SyncProtocolObserver> sync_protocol_observer_; Block block1_{{{}, 2}, {{{0x11, 0x22}}, {{0x55, 0x66}}}}, block2_{{{}, 3}, {{{0x13, 0x23}}, {{0x35, 0x63}}}}; Hash256 block1_hash_{}, block2_hash_{}; }; /** * @given synchronizer * @when a request for blocks arrives * @then an expected response is formed @and sent */ TEST_F(SynchronizerTest, ProcessRequest) { // GIVEN BlocksRequest received_request{1, BlocksRequest::kBasicAttributes, block1_hash_, boost::none, Direction::DESCENDING, boost::none}; EXPECT_CALL(*tree_, getChainByBlock(block1_hash_, false, 10)) .WillOnce(Return(std::vector<BlockHash>{block1_hash_, block2_hash_})); EXPECT_CALL(*headers_, getBlockHeader(BlockId{block1_hash_})) .WillOnce(Return(block1_.header)); EXPECT_CALL(*headers_, getBlockHeader(BlockId{block2_hash_})) .WillOnce(Return(block2_.header)); EXPECT_CALL(*tree_, getBlockBody(BlockId{block1_hash_})) .WillOnce(Return(block1_.body)); EXPECT_CALL(*tree_, getBlockBody(BlockId{block2_hash_})) .WillOnce(Return(block2_.body)); EXPECT_CALL(*tree_, getBlockJustification(BlockId{block1_hash_})) .WillOnce(Return(::outcome::failure(boost::system::error_code{}))); EXPECT_CALL(*tree_, getBlockJustification(BlockId{block2_hash_})) .WillOnce(Return(::outcome::failure(boost::system::error_code{}))); // WHEN EXPECT_OUTCOME_TRUE( response, sync_protocol_observer_->onBlocksRequest(received_request)); // THEN ASSERT_EQ(response.id, received_request.id); const auto &received_blocks = response.blocks; ASSERT_EQ(received_blocks.size(), 2); ASSERT_EQ(received_blocks[0].hash, block1_hash_); ASSERT_EQ(received_blocks[0].header, block1_.header); ASSERT_EQ(received_blocks[0].body, block1_.body); ASSERT_FALSE(received_blocks[0].justification); ASSERT_EQ(received_blocks[1].hash, block2_hash_); ASSERT_EQ(received_blocks[1].header, block2_.header); ASSERT_EQ(received_blocks[1].body, block2_.body); ASSERT_FALSE(received_blocks[1].justification); }
32.508929
76
0.713815
[ "vector" ]
ca658f420a0785324c62864aabaca3c4fb0ef388
3,437
cc
C++
src/callow/solver/Eispack.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
4
2015-03-07T16:20:23.000Z
2020-02-10T13:40:16.000Z
src/callow/solver/Eispack.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
3
2018-02-27T21:24:22.000Z
2020-12-16T00:56:44.000Z
src/callow/solver/Eispack.cc
baklanovp/libdetran
820efab9d03ae425ccefb9520bdb6c086fdbf939
[ "MIT" ]
9
2015-03-07T16:20:26.000Z
2022-01-29T00:14:23.000Z
//----------------------------------*-C++-*-----------------------------------// /** * @file Eispack.cc * @brief Eispack member definitions * @note Copyright (C) 2013 Jeremy Roberts */ //----------------------------------------------------------------------------// #include "Eispack.hh" #include "callow/matrix/MatrixDense.hh" #include <complex> namespace callow { //----------------------------------------------------------------------------// Eispack::Eispack(const double tol, const int maxit, int which) : EigenSolver(tol, maxit, "eispack") , d_which_value(which) { /* ... */ } //----------------------------------------------------------------------------// void Eispack::set_operators(SP_matrix A, SP_matrix B, SP_db db) { Require(A); Insist(dynamic_cast<MatrixDense*>(A.bp()), "Need a dense matrix for use with Eispack"); d_A = A; if (B) { Insist(dynamic_cast<MatrixDense*>(B.bp()), "Need a dense matrix for use with Eispack"); d_B = B; } } //----------------------------------------------------------------------------// void Eispack::solve_complete(MatrixDense &V_R, MatrixDense &V_I, Vector &E_R, Vector &E_I) { Require(d_A); MatrixDense &A = *dynamic_cast<MatrixDense*>(d_A.bp()); // Use copies so the originals are not overwritten MatrixDense tmp_A(A); int m = A.number_rows(); int matz = 1; // positive to get the eigenvectors int ierr = 0; if (d_B) { MatrixDense &B = *dynamic_cast<MatrixDense*>(d_B.bp()); // Use copies so the originals are not overwritten MatrixDense tmp_B(B); //MatrixDense &tmp_B = B; Vector E_D(m, 0.0); matz=1; tmp_A.print_matlab("A.out"); tmp_B.print_matlab("B.out"); rgg_(&m, &m, &tmp_A[0], &tmp_B[0], &E_R[0], &E_I[0], &E_D[0], &matz, &V_R[0], &ierr); Assert(!ierr); // scale the eigenvalues E_R.divide(E_D); E_I.divide(E_D); } else { int* iv1(new int[m]); double *fv1(new double[m]); rg_(&m, &m, &tmp_A[0], &E_R[0], &E_I[0], &matz, &V_R[0], iv1, fv1, &ierr); delete [] iv1; delete [] fv1; } } //----------------------------------------------------------------------------// void Eispack::solve_impl(Vector &x, Vector &x0) { int m = d_A->number_columns(); MatrixDense V_R(m, m, 0.0); MatrixDense V_I(m, m, 0.0); Vector E_R(m, 0.0); Vector E_I(m, 0.0); solve_complete(V_R, V_I, E_R, E_I); for (int i = 0; i < E_I.size(); ++i) { printf(" %4i %12.4e %12.4e \n ", i, E_R[i], E_I[i]); } // Extract the eigenvector corresponding to the max (or min) real value double wanted_E = E_R[0]; int wanted_i = 0; for (int i = 1; i < m; ++i) { if ( (E_R[i] > wanted_E && d_which_value == 1) || (E_R[i] < wanted_E && d_which_value == 0) ) { wanted_E = E_R[i]; wanted_i = i; } } for (int i = 0; i < m; ++i) { x[i] = V_R(i, wanted_i); } x.scale(1.0 / x.norm(L2)); /// Store the eigenvalue d_lambda = wanted_E; } } // end namespace callow //----------------------------------------------------------------------------// // end of file Eispack.cc //----------------------------------------------------------------------------//
26.037879
80
0.4405
[ "vector" ]
ca69026fda81f712a01efe11064dcdb5f1ab810a
7,826
cc
C++
test/unittests/interpreter/bytecode-register-optimizer-unittest.cc
ibmruntimes/v8ppc
538162502416b1b1e7253e5cd6e87821e19df04f
[ "BSD-3-Clause" ]
31
2016-04-09T20:25:03.000Z
2022-02-11T08:52:06.000Z
test/unittests/interpreter/bytecode-register-optimizer-unittest.cc
andrewlow/v8ppc
538162502416b1b1e7253e5cd6e87821e19df04f
[ "BSD-3-Clause" ]
12
2015-01-02T18:51:45.000Z
2016-04-02T19:18:10.000Z
test/unittests/interpreter/bytecode-register-optimizer-unittest.cc
ibmruntimes/v8ppc
538162502416b1b1e7253e5cd6e87821e19df04f
[ "BSD-3-Clause" ]
10
2016-04-16T22:27:33.000Z
2022-01-31T09:43:40.000Z
// Copyright 2016 the V8 project 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 "src/v8.h" #include "src/factory.h" #include "src/interpreter/bytecode-label.h" #include "src/interpreter/bytecode-register-optimizer.h" #include "src/objects-inl.h" #include "src/objects.h" #include "test/unittests/test-utils.h" namespace v8 { namespace internal { namespace interpreter { class BytecodeRegisterOptimizerTest : public BytecodePipelineStage, public TestWithIsolateAndZone { public: BytecodeRegisterOptimizerTest() {} ~BytecodeRegisterOptimizerTest() override { delete register_allocator_; } void Initialize(int number_of_parameters, int number_of_locals) { register_allocator_ = new TemporaryRegisterAllocator(zone(), number_of_locals); register_optimizer_ = new (zone()) BytecodeRegisterOptimizer( zone(), register_allocator_, number_of_parameters, this); } void Write(BytecodeNode* node) override { output_.push_back(*node); } void WriteJump(BytecodeNode* node, BytecodeLabel* label) override { output_.push_back(*node); } void BindLabel(BytecodeLabel* label) override {} void BindLabel(const BytecodeLabel& target, BytecodeLabel* label) override {} Handle<BytecodeArray> ToBytecodeArray( Isolate* isolate, int fixed_register_count, int parameter_count, Handle<FixedArray> handle_table) override { return Handle<BytecodeArray>(); } TemporaryRegisterAllocator* allocator() { return register_allocator_; } BytecodeRegisterOptimizer* optimizer() { return register_optimizer_; } Register NewTemporary() { return Register(allocator()->BorrowTemporaryRegister()); } void KillTemporary(Register reg) { allocator()->ReturnTemporaryRegister(reg.index()); } size_t write_count() const { return output_.size(); } const BytecodeNode& last_written() const { return output_.back(); } const std::vector<BytecodeNode>* output() { return &output_; } private: TemporaryRegisterAllocator* register_allocator_; BytecodeRegisterOptimizer* register_optimizer_; std::vector<BytecodeNode> output_; }; // Sanity tests. TEST_F(BytecodeRegisterOptimizerTest, WriteNop) { Initialize(1, 1); BytecodeNode node(Bytecode::kNop); optimizer()->Write(&node); CHECK_EQ(write_count(), 1); CHECK_EQ(node, last_written()); } TEST_F(BytecodeRegisterOptimizerTest, WriteNopExpression) { Initialize(1, 1); BytecodeNode node(Bytecode::kNop); node.source_info().MakeExpressionPosition(3); optimizer()->Write(&node); CHECK_EQ(write_count(), 1); CHECK_EQ(node, last_written()); } TEST_F(BytecodeRegisterOptimizerTest, WriteNopStatement) { Initialize(1, 1); BytecodeNode node(Bytecode::kNop); node.source_info().MakeStatementPosition(3); optimizer()->Write(&node); CHECK_EQ(write_count(), 1); CHECK_EQ(node, last_written()); } TEST_F(BytecodeRegisterOptimizerTest, TemporaryMaterializedForJump) { Initialize(1, 1); Register temp = NewTemporary(); BytecodeNode node(Bytecode::kStar, temp.ToOperand()); optimizer()->Write(&node); CHECK_EQ(write_count(), 0); BytecodeLabel label; BytecodeNode jump(Bytecode::kJump, 0); optimizer()->WriteJump(&jump, &label); CHECK_EQ(write_count(), 2); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kStar); CHECK_EQ(output()->at(0).operand(0), temp.ToOperand()); CHECK_EQ(output()->at(1).bytecode(), Bytecode::kJump); } TEST_F(BytecodeRegisterOptimizerTest, TemporaryMaterializedForBind) { Initialize(1, 1); Register temp = NewTemporary(); BytecodeNode node(Bytecode::kStar, temp.ToOperand()); optimizer()->Write(&node); CHECK_EQ(write_count(), 0); BytecodeLabel label; optimizer()->BindLabel(&label); CHECK_EQ(write_count(), 1); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kStar); CHECK_EQ(output()->at(0).operand(0), temp.ToOperand()); } // Basic Register Optimizations TEST_F(BytecodeRegisterOptimizerTest, TemporaryNotEmitted) { Initialize(3, 1); Register parameter = Register::FromParameterIndex(1, 3); BytecodeNode node0(Bytecode::kLdar, parameter.ToOperand()); optimizer()->Write(&node0); CHECK_EQ(write_count(), 0); Register temp = NewTemporary(); BytecodeNode node1(Bytecode::kStar, NewTemporary().ToOperand()); optimizer()->Write(&node1); CHECK_EQ(write_count(), 0); KillTemporary(temp); CHECK_EQ(write_count(), 0); BytecodeNode node2(Bytecode::kReturn); optimizer()->Write(&node2); CHECK_EQ(write_count(), 2); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kLdar); CHECK_EQ(output()->at(0).operand(0), parameter.ToOperand()); CHECK_EQ(output()->at(1).bytecode(), Bytecode::kReturn); } TEST_F(BytecodeRegisterOptimizerTest, StoresToLocalsImmediate) { Initialize(3, 1); Register parameter = Register::FromParameterIndex(1, 3); BytecodeNode node0(Bytecode::kLdar, parameter.ToOperand()); optimizer()->Write(&node0); CHECK_EQ(write_count(), 0); Register local = Register(0); BytecodeNode node1(Bytecode::kStar, local.ToOperand()); optimizer()->Write(&node1); CHECK_EQ(write_count(), 1); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kMov); CHECK_EQ(output()->at(0).operand(0), parameter.ToOperand()); CHECK_EQ(output()->at(0).operand(1), local.ToOperand()); BytecodeNode node2(Bytecode::kReturn); optimizer()->Write(&node2); CHECK_EQ(write_count(), 3); CHECK_EQ(output()->at(1).bytecode(), Bytecode::kLdar); CHECK_EQ(output()->at(1).operand(0), local.ToOperand()); CHECK_EQ(output()->at(2).bytecode(), Bytecode::kReturn); } TEST_F(BytecodeRegisterOptimizerTest, TemporaryNotMaterializedForInput) { Initialize(3, 1); Register parameter = Register::FromParameterIndex(1, 3); Register temp0 = NewTemporary(); Register temp1 = NewTemporary(); BytecodeNode node0(Bytecode::kMov, parameter.ToOperand(), temp0.ToOperand()); optimizer()->Write(&node0); BytecodeNode node1(Bytecode::kMov, parameter.ToOperand(), temp1.ToOperand()); optimizer()->Write(&node1); CHECK_EQ(write_count(), 0); BytecodeNode node2(Bytecode::kCallJSRuntime, 0, temp0.ToOperand(), 1); optimizer()->Write(&node2); CHECK_EQ(write_count(), 1); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kCallJSRuntime); CHECK_EQ(output()->at(0).operand(0), 0); CHECK_EQ(output()->at(0).operand(1), parameter.ToOperand()); CHECK_EQ(output()->at(0).operand(2), 1); } TEST_F(BytecodeRegisterOptimizerTest, RangeOfTemporariesMaterializedForInput) { Initialize(3, 1); Register parameter = Register::FromParameterIndex(1, 3); Register temp0 = NewTemporary(); Register temp1 = NewTemporary(); BytecodeNode node0(Bytecode::kLdaSmi, 3); optimizer()->Write(&node0); CHECK_EQ(write_count(), 1); BytecodeNode node1(Bytecode::kStar, temp0.ToOperand()); optimizer()->Write(&node1); BytecodeNode node2(Bytecode::kMov, parameter.ToOperand(), temp1.ToOperand()); optimizer()->Write(&node2); CHECK_EQ(write_count(), 1); BytecodeNode node3(Bytecode::kCallJSRuntime, 0, temp0.ToOperand(), 2); optimizer()->Write(&node3); CHECK_EQ(write_count(), 4); CHECK_EQ(output()->at(0).bytecode(), Bytecode::kLdaSmi); CHECK_EQ(output()->at(0).operand(0), 3); CHECK_EQ(output()->at(1).bytecode(), Bytecode::kStar); CHECK_EQ(output()->at(1).operand(0), temp0.ToOperand()); CHECK_EQ(output()->at(2).bytecode(), Bytecode::kMov); CHECK_EQ(output()->at(2).operand(0), parameter.ToOperand()); CHECK_EQ(output()->at(2).operand(1), temp1.ToOperand()); CHECK_EQ(output()->at(3).bytecode(), Bytecode::kCallJSRuntime); CHECK_EQ(output()->at(3).operand(0), 0); CHECK_EQ(output()->at(3).operand(1), temp0.ToOperand()); CHECK_EQ(output()->at(3).operand(2), 2); } } // namespace interpreter } // namespace internal } // namespace v8
35.572727
79
0.719141
[ "vector" ]
ca6a776d19a70056e396977c3cf369b44f8320cc
38,258
hpp
C++
include/VROSC/ModularDrumsDataController.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/ModularDrumsDataController.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/ModularDrumsDataController.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: VROSC.InstrumentDataController #include "VROSC/InstrumentDataController.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: VROSC namespace VROSC { // Forward declaring type: ModularDrumsDataModel class ModularDrumsDataModel; // Forward declaring type: EmpadData class EmpadData; // Forward declaring type: WidgetSettings class WidgetSettings; } // Forward declaring namespace: System namespace System { // Forward declaring type: Action`1<T> template<typename T> class Action_1; // Forward declaring type: Action class Action; } // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Vector3 struct Vector3; // Forward declaring type: Quaternion struct Quaternion; } // Completed forward declares // Type namespace: VROSC namespace VROSC { // Forward declaring type: ModularDrumsDataController class ModularDrumsDataController; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::ModularDrumsDataController); DEFINE_IL2CPP_ARG_TYPE(::VROSC::ModularDrumsDataController*, "VROSC", "ModularDrumsDataController"); // Type namespace: VROSC namespace VROSC { // Size: 0x2C #pragma pack(push, 1) // Autogenerated type: VROSC.ModularDrumsDataController // [TokenAttribute] Offset: FFFFFFFF class ModularDrumsDataController : public ::VROSC::InstrumentDataController { public: // Nested type: ::VROSC::ModularDrumsDataController::$$c__DisplayClass27_0 class $$c__DisplayClass27_0; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Int32 _nextInstanceId // Size: 0x4 // Offset: 0x28 int nextInstanceId; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating conversion operator: operator int constexpr operator int() const noexcept { return nextInstanceId; } // Get static field: static public System.Action`1<VROSC.ModularDrumsDataController> OnDataLoaded static ::System::Action_1<::VROSC::ModularDrumsDataController*>* _get_OnDataLoaded(); // Set static field: static public System.Action`1<VROSC.ModularDrumsDataController> OnDataLoaded static void _set_OnDataLoaded(::System::Action_1<::VROSC::ModularDrumsDataController*>* value); // Get instance field reference: private System.Int32 _nextInstanceId int& dyn__nextInstanceId(); // private VROSC.ModularDrumsDataModel get_DataModel() // Offset: 0x8B7080 ::VROSC::ModularDrumsDataModel* get_DataModel(); // public VROSC.EmpadData GetEmpadData(System.Int32 instanceId) // Offset: 0x8B77A4 ::VROSC::EmpadData* GetEmpadData(int instanceId); // public System.Int32 CreateEmpad(System.Int32 groupId) // Offset: 0x8B78F8 int CreateEmpad(int groupId); // public System.Int32 CreateEmpad(VROSC.EmpadData otherEmpad) // Offset: 0x8B7A84 int CreateEmpad(::VROSC::EmpadData* otherEmpad); // public System.Void RemoveEmpad(System.Int32 empadId) // Offset: 0x8B7BA0 void RemoveEmpad(int empadId); // public System.Collections.Generic.List`1<System.Int32> GetGroupEmpads(System.Int32 groupId) // Offset: 0x8B7CAC ::System::Collections::Generic::List_1<int>* GetGroupEmpads(int groupId); // public System.Int32 GetFixedEmpadId(System.Int32 groupId) // Offset: 0x8B68AC int GetFixedEmpadId(int groupId); // public System.Int32 GetEmpadGroupId(System.Int32 instanceId) // Offset: 0x8B7E5C int GetEmpadGroupId(int instanceId); // public System.Int32 GetEmpadSampleId(System.Int32 instanceId) // Offset: 0x8B7F44 int GetEmpadSampleId(int instanceId); // public System.Int32 GetEmpadSelectedSampleIndex(System.Int32 instanceId) // Offset: 0x8B802C int GetEmpadSelectedSampleIndex(int instanceId); // public System.Void SetEmpadSample(System.Int32 instanceId, System.Int32 sampleIndex) // Offset: 0x8B8270 void SetEmpadSample(int instanceId, int sampleIndex); // public System.Void SetEmpadMidiNote(System.Int32 instanceId, System.Int32 midiNote) // Offset: 0x8B84EC void SetEmpadMidiNote(int instanceId, int midiNote); // public System.String GetEmpadDisplayName(System.Int32 instanceId) // Offset: 0x8B85F4 ::StringW GetEmpadDisplayName(int instanceId); // public System.Int32 GetEmpadMidiNote(System.Int32 instanceId) // Offset: 0x8B88D8 int GetEmpadMidiNote(int instanceId); // public System.Boolean IsEmpadPressureSensitive(System.Int32 instanceId) // Offset: 0x8B89C0 bool IsEmpadPressureSensitive(int instanceId); // public System.Int32 GetEmpadPitch(System.Int32 instanceId) // Offset: 0x8B8AB0 int GetEmpadPitch(int instanceId); // public System.Single GetEmpadSize(System.Int32 instanceId) // Offset: 0x8B8B98 float GetEmpadSize(int instanceId); // public UnityEngine.Vector3 GetEmpadPosition(System.Int32 instanceId) // Offset: 0x8B8C80 ::UnityEngine::Vector3 GetEmpadPosition(int instanceId); // public UnityEngine.Quaternion GetEmpadRotation(System.Int32 instanceId) // Offset: 0x8B8DA0 ::UnityEngine::Quaternion GetEmpadRotation(int instanceId); // public System.Void SetIsPressureSensitive(System.Int32 instanceId, System.Boolean isPressureSensitive) // Offset: 0x8B8EF0 void SetIsPressureSensitive(int instanceId, bool isPressureSensitive); // public System.Void SetPitch(System.Int32 instanceId, System.Int32 pitch) // Offset: 0x8B8FFC void SetPitch(int instanceId, int pitch); // public System.Void SetEmpadSize(System.Int32 instanceId, System.Single size) // Offset: 0x8B9104 void SetEmpadSize(int instanceId, float size); // public System.Void SetEmpadPosition(System.Int32 instanceId, UnityEngine.Vector3 position) // Offset: 0x8B9218 void SetEmpadPosition(int instanceId, ::UnityEngine::Vector3 position); // public System.Void SetEmpadRotation(System.Int32 instanceId, UnityEngine.Quaternion rotation) // Offset: 0x8B939C void SetEmpadRotation(int instanceId, ::UnityEngine::Quaternion rotation); // public override System.Boolean get_IsOpen() // Offset: 0x8B7164 // Implemented from: VROSC.InstrumentDataController // Base method: System.Boolean InstrumentDataController::get_IsOpen() bool get_IsOpen(); // public override System.Void set_IsOpen(System.Boolean value) // Offset: 0x8B718C // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_IsOpen(System.Boolean value) void set_IsOpen(bool value); // public override UnityEngine.Vector3 get_Position() // Offset: 0x8B71D0 // Implemented from: VROSC.InstrumentDataController // Base method: UnityEngine.Vector3 InstrumentDataController::get_Position() ::UnityEngine::Vector3 get_Position(); // public override System.Void set_Position(UnityEngine.Vector3 value) // Offset: 0x8B71F8 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_Position(UnityEngine.Vector3 value) void set_Position(::UnityEngine::Vector3 value); // public override UnityEngine.Quaternion get_Rotation() // Offset: 0x8B7260 // Implemented from: VROSC.InstrumentDataController // Base method: UnityEngine.Quaternion InstrumentDataController::get_Rotation() ::UnityEngine::Quaternion get_Rotation(); // public override System.Void set_Rotation(UnityEngine.Quaternion value) // Offset: 0x8B7288 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_Rotation(UnityEngine.Quaternion value) void set_Rotation(::UnityEngine::Quaternion value); // public override UnityEngine.Vector3 get_Scale() // Offset: 0x8B72F8 // Implemented from: VROSC.InstrumentDataController // Base method: UnityEngine.Vector3 InstrumentDataController::get_Scale() ::UnityEngine::Vector3 get_Scale(); // public override System.Void set_Scale(UnityEngine.Vector3 value) // Offset: 0x8B7320 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_Scale(UnityEngine.Vector3 value) void set_Scale(::UnityEngine::Vector3 value); // public override System.Boolean get_Quantize() // Offset: 0x8B7388 // Implemented from: VROSC.InstrumentDataController // Base method: System.Boolean InstrumentDataController::get_Quantize() bool get_Quantize(); // public override System.Void set_Quantize(System.Boolean value) // Offset: 0x8B73A8 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_Quantize(System.Boolean value) void set_Quantize(bool value); // public override System.Single get_QuantizeTolerance() // Offset: 0x8B73E4 // Implemented from: VROSC.InstrumentDataController // Base method: System.Single InstrumentDataController::get_QuantizeTolerance() float get_QuantizeTolerance(); // public override System.Void set_QuantizeTolerance(System.Single value) // Offset: 0x8B7404 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_QuantizeTolerance(System.Single value) void set_QuantizeTolerance(float value); // public override System.Int32 get_QuantizeBeatDivision() // Offset: 0x8B7444 // Implemented from: VROSC.InstrumentDataController // Base method: System.Int32 InstrumentDataController::get_QuantizeBeatDivision() int get_QuantizeBeatDivision(); // public override System.Void set_QuantizeBeatDivision(System.Int32 value) // Offset: 0x8B7464 // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::set_QuantizeBeatDivision(System.Int32 value) void set_QuantizeBeatDivision(int value); // public System.Void .ctor() // Offset: 0x8B70FC // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::.ctor() // Base method: System.Void BaseDataController::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static ModularDrumsDataController* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::ModularDrumsDataController::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<ModularDrumsDataController*, creationType>())); } // public override System.Void ApplyDefaults(VROSC.WidgetSettings widgetDefaultSettings) // Offset: 0x8B749C // Implemented from: VROSC.InstrumentDataController // Base method: System.Void InstrumentDataController::ApplyDefaults(VROSC.WidgetSettings widgetDefaultSettings) void ApplyDefaults(::VROSC::WidgetSettings* widgetDefaultSettings); // public override System.Void LoadData(System.String sessionId, System.Action onSuccess, System.Action`1<VROSC.Error> onFailure) // Offset: 0x8B7670 // Implemented from: VROSC.BaseDataController // Base method: System.Void BaseDataController::LoadData(System.String sessionId, System.Action onSuccess, System.Action`1<VROSC.Error> onFailure) void LoadData(::StringW sessionId, ::System::Action* onSuccess, ::System::Action_1<::VROSC::Error>* onFailure); }; // VROSC.ModularDrumsDataController #pragma pack(pop) static check_size<sizeof(ModularDrumsDataController), 40 + sizeof(int)> __VROSC_ModularDrumsDataControllerSizeCheck; static_assert(sizeof(ModularDrumsDataController) == 0x2C); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_DataModel // Il2CppName: get_DataModel template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::VROSC::ModularDrumsDataModel* (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_DataModel)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_DataModel", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadData // Il2CppName: GetEmpadData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::VROSC::EmpadData* (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadData)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::CreateEmpad // Il2CppName: CreateEmpad template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::CreateEmpad)> { static const MethodInfo* get() { static auto* groupId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "CreateEmpad", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{groupId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::CreateEmpad // Il2CppName: CreateEmpad template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(::VROSC::EmpadData*)>(&VROSC::ModularDrumsDataController::CreateEmpad)> { static const MethodInfo* get() { static auto* otherEmpad = &::il2cpp_utils::GetClassFromName("VROSC", "EmpadData")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "CreateEmpad", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{otherEmpad}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::RemoveEmpad // Il2CppName: RemoveEmpad template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::RemoveEmpad)> { static const MethodInfo* get() { static auto* empadId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "RemoveEmpad", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{empadId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetGroupEmpads // Il2CppName: GetGroupEmpads template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::List_1<int>* (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetGroupEmpads)> { static const MethodInfo* get() { static auto* groupId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetGroupEmpads", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{groupId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetFixedEmpadId // Il2CppName: GetFixedEmpadId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetFixedEmpadId)> { static const MethodInfo* get() { static auto* groupId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetFixedEmpadId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{groupId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadGroupId // Il2CppName: GetEmpadGroupId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadGroupId)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadGroupId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadSampleId // Il2CppName: GetEmpadSampleId template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadSampleId)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadSampleId", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadSelectedSampleIndex // Il2CppName: GetEmpadSelectedSampleIndex template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadSelectedSampleIndex)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadSelectedSampleIndex", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetEmpadSample // Il2CppName: SetEmpadSample template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, int)>(&VROSC::ModularDrumsDataController::SetEmpadSample)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* sampleIndex = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetEmpadSample", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, sampleIndex}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetEmpadMidiNote // Il2CppName: SetEmpadMidiNote template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, int)>(&VROSC::ModularDrumsDataController::SetEmpadMidiNote)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* midiNote = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetEmpadMidiNote", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, midiNote}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadDisplayName // Il2CppName: GetEmpadDisplayName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::StringW (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadDisplayName)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadDisplayName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadMidiNote // Il2CppName: GetEmpadMidiNote template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadMidiNote)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadMidiNote", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::IsEmpadPressureSensitive // Il2CppName: IsEmpadPressureSensitive template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::IsEmpadPressureSensitive)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "IsEmpadPressureSensitive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadPitch // Il2CppName: GetEmpadPitch template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadPitch)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadPitch", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadSize // Il2CppName: GetEmpadSize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadSize)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadPosition // Il2CppName: GetEmpadPosition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadPosition)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::GetEmpadRotation // Il2CppName: GetEmpadRotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Quaternion (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::GetEmpadRotation)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "GetEmpadRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetIsPressureSensitive // Il2CppName: SetIsPressureSensitive template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, bool)>(&VROSC::ModularDrumsDataController::SetIsPressureSensitive)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* isPressureSensitive = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetIsPressureSensitive", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, isPressureSensitive}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetPitch // Il2CppName: SetPitch template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, int)>(&VROSC::ModularDrumsDataController::SetPitch)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* pitch = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetPitch", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, pitch}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetEmpadSize // Il2CppName: SetEmpadSize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, float)>(&VROSC::ModularDrumsDataController::SetEmpadSize)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* size = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetEmpadSize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, size}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetEmpadPosition // Il2CppName: SetEmpadPosition template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, ::UnityEngine::Vector3)>(&VROSC::ModularDrumsDataController::SetEmpadPosition)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* position = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetEmpadPosition", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, position}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::SetEmpadRotation // Il2CppName: SetEmpadRotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int, ::UnityEngine::Quaternion)>(&VROSC::ModularDrumsDataController::SetEmpadRotation)> { static const MethodInfo* get() { static auto* instanceId = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; static auto* rotation = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "SetEmpadRotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{instanceId, rotation}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_IsOpen // Il2CppName: get_IsOpen template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_IsOpen)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_IsOpen", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_IsOpen // Il2CppName: set_IsOpen template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(bool)>(&VROSC::ModularDrumsDataController::set_IsOpen)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_IsOpen", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_Position // Il2CppName: get_Position template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_Position)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_Position // Il2CppName: set_Position template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(::UnityEngine::Vector3)>(&VROSC::ModularDrumsDataController::set_Position)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_Position", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_Rotation // Il2CppName: get_Rotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Quaternion (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_Rotation)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_Rotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_Rotation // Il2CppName: set_Rotation template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(::UnityEngine::Quaternion)>(&VROSC::ModularDrumsDataController::set_Rotation)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Quaternion")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_Rotation", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_Scale // Il2CppName: get_Scale template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::UnityEngine::Vector3 (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_Scale)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_Scale", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_Scale // Il2CppName: set_Scale template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(::UnityEngine::Vector3)>(&VROSC::ModularDrumsDataController::set_Scale)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Vector3")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_Scale", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_Quantize // Il2CppName: get_Quantize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_Quantize)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_Quantize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_Quantize // Il2CppName: set_Quantize template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(bool)>(&VROSC::ModularDrumsDataController::set_Quantize)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_Quantize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_QuantizeTolerance // Il2CppName: get_QuantizeTolerance template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<float (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_QuantizeTolerance)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_QuantizeTolerance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_QuantizeTolerance // Il2CppName: set_QuantizeTolerance template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(float)>(&VROSC::ModularDrumsDataController::set_QuantizeTolerance)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Single")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_QuantizeTolerance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::get_QuantizeBeatDivision // Il2CppName: get_QuantizeBeatDivision template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (VROSC::ModularDrumsDataController::*)()>(&VROSC::ModularDrumsDataController::get_QuantizeBeatDivision)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "get_QuantizeBeatDivision", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::set_QuantizeBeatDivision // Il2CppName: set_QuantizeBeatDivision template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(int)>(&VROSC::ModularDrumsDataController::set_QuantizeBeatDivision)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "set_QuantizeBeatDivision", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::ApplyDefaults // Il2CppName: ApplyDefaults template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(::VROSC::WidgetSettings*)>(&VROSC::ModularDrumsDataController::ApplyDefaults)> { static const MethodInfo* get() { static auto* widgetDefaultSettings = &::il2cpp_utils::GetClassFromName("VROSC", "WidgetSettings")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "ApplyDefaults", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{widgetDefaultSettings}); } }; // Writing MetadataGetter for method: VROSC::ModularDrumsDataController::LoadData // Il2CppName: LoadData template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::ModularDrumsDataController::*)(::StringW, ::System::Action*, ::System::Action_1<::VROSC::Error>*)>(&VROSC::ModularDrumsDataController::LoadData)> { static const MethodInfo* get() { static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* onSuccess = &::il2cpp_utils::GetClassFromName("System", "Action")->byval_arg; static auto* onFailure = &::il2cpp_utils::MakeGeneric(::il2cpp_utils::GetClassFromName("System", "Action`1"), ::std::vector<const Il2CppClass*>{::il2cpp_utils::GetClassFromName("VROSC", "Error")})->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::ModularDrumsDataController*), "LoadData", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, onSuccess, onFailure}); } };
61.115016
229
0.764494
[ "object", "vector" ]
ca6d2a08fcf974d5a4393b6db029be4cf38f206a
2,933
hpp
C++
mod/meta/type/type.hpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
1
2019-02-02T07:07:32.000Z
2019-02-02T07:07:32.000Z
mod/meta/type/type.hpp
kniz/wrd
a8c9e8bd2f7b240ff64a3b80e7ebc7aff2775ba6
[ "MIT" ]
25
2016-09-23T16:36:19.000Z
2019-02-12T14:14:32.000Z
mod/meta/type/type.hpp
kniz/World
13b0c8c7fdc6280efcb2135dc3902754a34e6d06
[ "MIT" ]
null
null
null
#pragma once #include "../common.hpp" namespace wrd { /// @remark type returning Ttype<type> as result of getType() /// because this func always returns metaclass no matter of what me type is, /// users need to care about getting meta of metaclass on calling getType(). /// for example, /// Thing& thing1 = ...; // let's assume that got from outside. /// Object obj; /// /// wbool compare = obj.isSub(thing1.getType()); // user intend to get class of Thing. /// // however, value 'compare' will definitely be false if /// // thing was actually a retrived one by calling Thing.getType() before. /// /// // because type::getType() will return Ttype<Ttype<T> >, /// // that stmt will be translated that checks object vs Ttype<T>. class _wout type { WRD_DECL_ME(type) public: virtual ~type() {} wbool operator==(const me& rhs) const; wbool operator!=(const me& rhs) const; virtual wbool isTemplate() const = 0; virtual wbool isAbstract() const = 0; virtual const std::string& getName() const = 0; /// @brief create an instance to be refered this type. /// @remark available when the type defines a ctor without any params. /// @return return an address of new instance, however, if ctor without any params /// isn't defined, then returns null. virtual void* make() const = 0; template <typename T> T* makeAs() const { // c++ is not allow for covariant against void*. // that's is why I make another variant func of already made make(). return (T*) make(); } virtual wcnt size() const = 0; virtual wbool init(); virtual wbool rel(); virtual const type& getSuper() const = 0; virtual const wbool& isInit() const = 0; /// returns all most derived class from this class. const types& getLeafs() const; const types& getSubs() const; const types& getSupers() const; wbool isSuper(const type& it) const; template <typename T> wbool isSuper() const; wbool isSub(const type& it) const { return it.isSuper(*this); } template <typename T> wbool isSub() const; const type& getStatic() const WRD_UNCONST_FUNC(_getStatic()) protected: // type: virtual types& _getSubs() = 0; virtual types& _getSupers() = 0; virtual type& _getStatic() const = 0; void _setInit(wbool newState); virtual void _onAddSubClass(const me& subClass); virtual types** _onGetLeafs() const = 0; void _setLeafs(types* newLeafs) const; private: wbool _logInitOk(wbool res); void _findLeafs(const type& cls, types& tray) const; }; }
38.592105
102
0.582339
[ "object" ]
ca6fbc9edd95449b901a44432ea9b132ae8cb363
15,547
cpp
C++
lib/core/src/rodsLog.cpp
macdaliot/irods
568c4fde540e8f83ccb7478af10178b09f9d2697
[ "BSD-3-Clause" ]
null
null
null
lib/core/src/rodsLog.cpp
macdaliot/irods
568c4fde540e8f83ccb7478af10178b09f9d2697
[ "BSD-3-Clause" ]
null
null
null
lib/core/src/rodsLog.cpp
macdaliot/irods
568c4fde540e8f83ccb7478af10178b09f9d2697
[ "BSD-3-Clause" ]
null
null
null
/*** Copyright (c), The Regents of the University of California *** *** For more information please refer to files in the COPYRIGHT directory ***/ //Creates irods_error_map #define MAKE_IRODS_ERROR_MAP #include "rodsErrorTable.h" const static std::map<const int, const std::string> irods_error_map = irods_error_map_construction::irods_error_map; #include "rods.h" #include "irods_socket_information.hpp" #ifdef SYSLOG #ifndef windows_platform #include <syslog.h> #endif #endif #include "rodsLog.h" #include "rcGlobalExtern.h" #include "rcMisc.h" #include <time.h> #include <map> #include <string> #include <algorithm> #include <functional> #include <unordered_map> #include <sys/time.h> #include "irods_exception.hpp" #include "irods_logger.hpp" #ifndef windows_platform #include <unistd.h> #endif #ifdef windows_platform #include "irodsntutil.hpp" #endif #define BIG_STRING_LEN MAX_NAME_LEN+300 #include <stdarg.h> static int verbosityLevel = LOG_ERROR; static int sqlVerbosityLevel = 0; pid_t myPid = 0; #ifdef windows_platform static void rodsNtElog( char *msg ); #endif std::string create_log_error_prefix() { std::string ret("remote addresses: "); try { std::vector<int> fds = get_open_socket_file_descriptors(); std::vector<std::string> remote_addresses; remote_addresses.reserve(fds.size()); for (const auto fd : fds) { std::string remote_address = socket_fd_to_remote_address(fd); if (remote_address != "") { remote_addresses.push_back(std::move(remote_address)); } } if (remote_addresses.size() == 0) { ret = ""; return ret; } std::sort(remote_addresses.begin(), remote_addresses.end()); auto new_end = std::unique(remote_addresses.begin(), remote_addresses.end()); remote_addresses.erase(new_end, remote_addresses.end()); for (size_t i=0; i<remote_addresses.size()-1; ++i) { ret += remote_addresses[i]; ret += ", "; } ret += remote_addresses.back(); } catch (const irods::exception& e) { ret = ""; return ret; } return ret; } void forward_to_syslog(int _log_level, const std::string& _msg) { if (CLIENT_PT == ::ProcessType) { return; } // clang-format off using log_level = int; using msg_handler = std::function<void(const std::string&)>; // clang-format on namespace exp = irods::experimental; static const auto trace = [](const auto& _msg) { exp::log::legacy::trace(_msg); }; static const auto debug = [](const auto& _msg) { exp::log::legacy::debug(_msg); }; static const auto info = [](const auto& _msg) { exp::log::legacy::info(_msg); }; static const auto warn = [](const auto& _msg) { exp::log::legacy::warn(_msg); }; static const auto error = [](const auto& _msg) { exp::log::legacy::error(_msg); }; static const auto critical = [](const auto& _msg) { exp::log::legacy::critical(_msg); }; // clang-format off static const std::unordered_map<log_level, msg_handler> msg_handlers{ {LOG_DEBUG10, trace}, {LOG_DEBUG9, trace}, {LOG_DEBUG8, trace}, {LOG_DEBUG7, debug}, {LOG_DEBUG6, debug}, {LOG_NOTICE, info}, {LOG_WARNING, warn}, {LOG_ERROR, error}, {LOG_SYS_WARNING, critical}, {LOG_SYS_FATAL, critical} }; // clang-format on if (const auto iter = msg_handlers.find(_log_level); std::end(msg_handlers) != iter) { (iter->second)(_msg); } else { info(_msg); } } /* Log or display a message. The level argument indicates how severe the message is, and depending on the verbosityLevel may or may not be recorded. This is used by both client and server code. */ void rodsLog( int level, const char *formatStr, ... ) { time_t timeValue; FILE *errOrOut; va_list ap; #ifdef SYSLOG char *myZone = getenv( "spProxyRodsZone" ); #endif int okToLog = 0; char extraInfo[100]; #ifdef windows_platform char nt_log_msg[2048]; #endif if ( level <= verbosityLevel ) { okToLog = 1; } if ( level == LOG_SQL ) { okToLog = 1; } if ( !okToLog ) { return; } va_start( ap, formatStr ); char * message = ( char * )malloc( sizeof( char ) * BIG_STRING_LEN ); int len = vsnprintf( message, BIG_STRING_LEN, formatStr, ap ); if ( len + 1 > BIG_STRING_LEN ) { va_end( ap ); va_start( ap, formatStr ); free( message ); message = ( char * )malloc( sizeof( char ) * ( len + 1 ) ); vsnprintf( message, len + 1, formatStr, ap ); } va_end( ap ); extraInfo[0] = '\0'; #ifndef windows_platform errOrOut = stdout; #endif if ( ProcessType == SERVER_PT || ProcessType == AGENT_PT || ProcessType == RE_SERVER_PT ) { char timeBuf[100]; time( &timeValue ); rstrcpy( timeBuf, ctime( &timeValue ), 90 ); timeBuf[19] = '\0'; myPid = getpid(); snprintf( extraInfo, 100 - 1, "%s pid:%d ", timeBuf + 4, myPid ); } else { #ifndef windows_platform if ( level <= LOG_ERROR || level == LOG_SQL ) { errOrOut = stderr; } #endif } std::string prefix = ""; if ( level == LOG_SQL ) { prefix = "LOG_SQL"; } if ( level == LOG_SYS_FATAL ) { prefix = "SYSTEM FATAL"; } if ( level == LOG_SYS_WARNING ) { prefix = "SYSTEM WARNING"; } if ( level == LOG_ERROR ) { prefix = create_log_error_prefix(); prefix += " ERROR"; } if ( level == LOG_NOTICE ) { prefix = "NOTICE"; } if ( level == LOG_WARNING ) { prefix = "WARNING"; } #ifdef SYSLOG if ( level == LOG_DEBUG ) { prefix = "DEBUG"; } if ( level == LOG_DEBUG10 ) { prefix = "DEBUG1"; } if ( level == LOG_DEBUG9 ) { prefix = "DEBUG2"; } if ( level == LOG_DEBUG8 ) { prefix = "DEBUG3"; } if ( ProcessType == SERVER_PT || ProcessType == AGENT_PT || ProcessType == RE_SERVER_PT ) #else if ( level == LOG_DEBUG ) { prefix = "DEBUG"; } if ( level == LOG_DEBUG10 ) { prefix = "DEBUG1"; } if ( level == LOG_DEBUG9 ) { prefix = "DEBUG2"; } if ( level == LOG_DEBUG8 ) { prefix = "DEBUG3"; } if ( message[strlen( message ) - 1] == '\n' ) #endif { #ifdef SYSLOG #ifdef SYSLOG_FACILITY_CODE syslog( SYSLOG_FACILITY_CODE | LOG_NOTICE, "%s - %s: %s", myZone, prefix.c_str(), message ); #else syslog( LOG_DAEMON | LOG_NOTICE, "%s - %s: %s", myZone, prefix.c_str(), message ); #endif #else #ifndef windows_platform fprintf( errOrOut, "%s%s: %s", extraInfo, prefix.c_str(), message ); #else sprintf( nt_log_msg, "%s%s: %s", extraInfo, prefix.c_str(), message ); rodsNtElog( nt_log_msg ); #endif #endif } else { #ifndef windows_platform fprintf( errOrOut, "%s%s: %s\n", extraInfo, prefix.c_str(), message ); #else sprintf( nt_log_msg, "%s%s: %s\n", extraInfo, prefix.c_str(), message ); rodsNtElog( nt_log_msg ); #endif } #ifndef windows_platform fflush( errOrOut ); #endif forward_to_syslog(level, message); free( message ); } /* same as rodsLog plus putting the msg in myError too. Need to merge with * rodsLog */ void rodsLogAndErrorMsg( int level, rError_t *myError, int status, const char *formatStr, ... ) { char *prefix; time_t timeValue; FILE *errOrOut; va_list ap; char errMsg[ERR_MSG_LEN]; char extraInfo[100]; #ifdef windows_platform char nt_log_msg[2048]; #endif if ( level > verbosityLevel ) { return; } va_start( ap, formatStr ); char * message = ( char * )malloc( sizeof( char ) * BIG_STRING_LEN ); int len = vsnprintf( message, BIG_STRING_LEN, formatStr, ap ); if ( len + 1 > BIG_STRING_LEN ) { va_end( ap ); va_start( ap, formatStr ); free( message ); message = ( char * )malloc( sizeof( char ) * ( len + 1 ) ); vsnprintf( message, len + 1, formatStr, ap ); } va_end( ap ); extraInfo[0] = '\0'; errOrOut = stdout; if ( ProcessType == SERVER_PT || ProcessType == AGENT_PT || ProcessType == RE_SERVER_PT ) { char timeBuf[100]; time( &timeValue ); rstrcpy( timeBuf, ctime( &timeValue ), 90 ); timeBuf[19] = '\0'; myPid = getpid(); snprintf( extraInfo, 100 - 1, "%s pid:%d ", timeBuf + 4, myPid ); } else { if ( level <= LOG_ERROR || level == LOG_SQL ) { errOrOut = stderr; } } prefix = ""; if ( level == LOG_SQL ) { prefix = "LOG_SQL"; } if ( level == LOG_SYS_FATAL ) { prefix = "SYSTEM FATAL"; } if ( level == LOG_SYS_WARNING ) { prefix = "SYSTEM WARNING"; } if ( level == LOG_ERROR ) { prefix = "ERROR"; } if ( level == LOG_NOTICE ) { prefix = "NOTICE"; } if ( level == LOG_WARNING ) { prefix = "WARNING"; } if ( level <= LOG_DEBUG ) { prefix = "DEBUG"; } const size_t message_len = strlen( message ); if ( message_len > 0 && message[message_len - 1] == '\n' ) { #ifndef windows_platform fprintf( errOrOut, "%s%s: %s", extraInfo, prefix, message ); if ( myError != NULL ) { snprintf( errMsg, ERR_MSG_LEN, "%s: %s", prefix, message ); addRErrorMsg( myError, status, errMsg ); } #else sprintf( nt_log_msg, "%s%s: %s", extraInfo, prefix, message ); rodsNtElog( nt_log_msg ); #endif } else { #ifndef windows_platform fprintf( errOrOut, "%s%s: %s\n", extraInfo, prefix, message ); if ( myError != NULL ) { snprintf( errMsg, ERR_MSG_LEN, "%s: %s\n", prefix, message ); addRErrorMsg( myError, status, errMsg ); } #else sprintf( nt_log_msg, "%s%s: %s\n", extraInfo, prefix, message ); rodsNtElog( nt_log_msg ); #endif } #ifndef windows_platform fflush( errOrOut ); #endif forward_to_syslog(level, message); free( message ); } /* Change the verbosityLevel of reporting. The input value is the new minimum level of message to report. */ void rodsLogLevel( int level ) { verbosityLevel = level; } int getRodsLogLevel() { return ( verbosityLevel ); } /* Request sql logging. */ void rodsLogSqlReq( int onOrOff ) { sqlVerbosityLevel = onOrOff; } void rodsLogSql( const char *sql ) { myPid = getpid(); if ( sqlVerbosityLevel ) rodsLog( LOG_SQL, "pid: %d sql: %s", myPid, sql ); } void rodsLogSqlResult( char *stat ) { myPid = getpid(); if ( sqlVerbosityLevel ) rodsLog( LOG_SQL, "pid: %d result: %s", myPid, stat ); } /* Convert an iRODS error code to the corresponding name. */ const char * rodsErrorName( int errorValue, char **subName ) { int testVal = errorValue / 1000; if ( subName ) { int subCode = errorValue - ( testVal * 1000 ); *subName = subCode && errorValue < 0 ? strdup( strerror( -subCode ) ) : strdup( "" ); } const std::map<const int, const std::string>::const_iterator search = irods_error_map.find( testVal * 1000 ); if ( search == irods_error_map.end() ) { return ( "Unknown iRODS error" ); } return search->second.c_str(); } /* Convert an error code to a string and log it. This was originally called rodsLogError, but was renamed when we created the new rodsLogError below. This is no longer used ( rodsLogError can be called with the same arguments). */ void rodsLogErrorOld( int level, int rodsErrorCode, char *textStr ) { char *errSubName = NULL; if ( level < verbosityLevel ) { return; } const char * errName = rodsErrorName( rodsErrorCode, &errSubName ); if ( textStr && strlen( textStr ) > 0 ) { rodsLog( level, "%s Error: %d: %s, %s", textStr, rodsErrorCode, errName, errSubName ); } else { rodsLog( level, "Error: %d: %s, %s", rodsErrorCode, errName, errSubName ); } free( errSubName ); } /* Like rodsLogError but with full rodsLog functionality too. Converts the errorcode to a string, and possibly a subcode string, and includes that at the end of a regular log message (with variable arguments). */ void rodsLogError( int level, int rodsErrorCode, char *formatStr, ... ) { char *errSubName = NULL; va_list ap; if ( level > verbosityLevel ) { return; } va_start( ap, formatStr ); char * message = ( char * )malloc( sizeof( char ) * BIG_STRING_LEN ); int len = vsnprintf( message, BIG_STRING_LEN, formatStr, ap ); if ( len + 1 > BIG_STRING_LEN ) { va_end( ap ); va_start( ap, formatStr ); free( message ); message = ( char * )malloc( sizeof( char ) * ( len + 1 ) ); vsnprintf( message, len + 1, formatStr, ap ); } va_end( ap ); const char * errName = rodsErrorName( rodsErrorCode, &errSubName ); if ( strlen( errSubName ) > 0 ) { rodsLog( level, "%s status = %d %s, %s", message, rodsErrorCode, errName, errSubName ); } else { rodsLog( level, "%s status = %d %s", message, rodsErrorCode, errName ); } free( message ); free( errSubName ); } #ifdef windows_platform static void rodsNtElog( char *msg ) { char log_fname[1024]; int fd; int t; if ( ProcessType == CLIENT_PT ) { fprintf( stderr, "%s", msg ); return; } t = strlen( msg ); if ( msg[t - 1] == '\n' ) { msg[t - 1] = '\0'; t = t - 1; } if ( iRODSNtServerRunningConsoleMode() ) { t = strlen( msg ); if ( msg[t - 1] == '\n' ) { fprintf( stderr, "%s", msg ); } else { fprintf( stderr, "%s\n", msg ); } return; } t = strlen( msg ); if ( msg[t - 1] != '\n' ) { msg[t] = '\n'; msg[t + 1] = '\0'; t = t + 1; } iRODSNtGetLogFilenameWithPath( log_fname ); fd = iRODSNt_open( log_fname, O_APPEND | O_WRONLY, 1 ); _write( fd, msg, t ); _close( fd ); } #endif /* * This function will generate an ISO 8601 formatted * date/time stamp for use in log messages. The format * will be 'YYYYMMDDThhmmss.uuuuuuZ' where: * * YYYY - is the year * MM - is the month (01-12) * DD - is the day (01-31) * hh - is the hour (00-24) * mm - is the minute (00-59) * ss - is the second (00-59) * u+ - are the number of microseconds. * * The date/time stamp is in UTC time. */ void generateLogTimestamp( char *ts, int tsLen ) { struct timeval tv; struct tm utc; char timestamp[TIME_LEN]; if ( ts == NULL ) { return; } gettimeofday( &tv, NULL ); gmtime_r( &tv.tv_sec, &utc ); strftime( timestamp, TIME_LEN, "%Y%m%dT%H%M%S", &utc ); /* 8 characters of '.uuuuuuZ' + nul */ if ( tsLen < ( int )strlen( timestamp ) + 9 ) { return; } snprintf( ts, strlen( timestamp ) + 9, "%s.%06dZ", timestamp, ( int )tv.tv_usec ); }
26.440476
116
0.571043
[ "vector" ]
ca72c0e0f2cae3e221e9a7f751342f2de14a1928
6,031
cpp
C++
src/TightCommunityDistances.cpp
mgeorgoulopoulos/ScerSeg
3dbded187d55b64b676cae6a6607cd44533237d7
[ "MIT" ]
1
2021-06-30T10:14:54.000Z
2021-06-30T10:14:54.000Z
src/TightCommunityDistances.cpp
mgeorgoulopoulos/ScerSeg
3dbded187d55b64b676cae6a6607cd44533237d7
[ "MIT" ]
null
null
null
src/TightCommunityDistances.cpp
mgeorgoulopoulos/ScerSeg
3dbded187d55b64b676cae6a6607cd44533237d7
[ "MIT" ]
1
2022-03-01T12:16:18.000Z
2022-03-01T12:16:18.000Z
/* Copyright 2021 Michael Georgoulopoulos 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. */ /* This program samples distances in 3D space between: (1) genes found in TightCommunities db table and (2) random pairs of genes. Also, we always sample pairs from different chromosomes in order to remove the community advantage of being consecutive. Results are written to TSV file (one column for (1) and a second for (2)) for further analysis. */ #include <utils/Vec3D.h> #include <QFile> #include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery> #include <QString> #include <QTextStream> #include <QVector> #include <algorithm> #include <random> namespace { struct Gene { QString name; int chromosome = 0; Vec3D position; }; QVector<Gene> loadGenes(QSqlDatabase &db, const QString &whereClause = "") { QVector<Gene> result; const QString sql = QString("SELECT Gene, x, y, z, Chromosome FROM Loci %1 " "ORDER BY Chromosome, Start") .arg(whereClause); QSqlQuery query(sql, db); while (query.next()) { Gene gene; gene.name = query.value(0).toString(); gene.position.x = query.value(1).toDouble(); gene.position.y = query.value(2).toDouble(); gene.position.z = query.value(3).toDouble(); gene.chromosome = query.value(4).toInt(); result.push_back(gene); } if (query.lastError().type() != QSqlError::NoError) throw(QString("Failed to process query: %1\nDBTEXT: %2") .arg(sql) .arg(query.lastError().databaseText())); return result; } void sampleDistances(QSqlDatabase &db) { const QVector<Gene> genes = loadGenes(db); const QVector<Gene> tightGenes = loadGenes(db, "WHERE Gene IN (SELECT Gene FROM TightCommunities)"); printf("%d genes\n", genes.size()); printf("%d genes in tight groups\n", tightGenes.size()); // Break into chromosomes QMap<int, QVector<Gene>> tightGroupsMap; for (const Gene &gene : tightGenes) { tightGroupsMap[gene.chromosome].push_back(gene); } QVector<QVector<Gene>> tightGroups; for (const int chromosome : tightGroupsMap.keys()) { printf("Chromosome %d: group of size %d\n", chromosome, tightGroupsMap[chromosome].size()); tightGroups.push_back(tightGroupsMap[chromosome]); } // Do the same for gene pool QMap<int, QVector<Gene>> geneMap; for (const Gene &gene : genes) { geneMap[gene.chromosome].push_back(gene); } QVector<QVector<Gene>> geneGroups; for (const int chromosome : geneMap.keys()) { geneGroups.push_back(geneMap[chromosome]); } std::default_random_engine generator; std::uniform_int_distribution<int> distribution(0, genes.size() - 1); auto randomInt = [&](int maximumExcl) { return distribution(generator) % maximumExcl; }; // Output distributions to tsv const QString filename = "Results/TightCommunityDistances.tsv"; QFile file(filename); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) throw QString("Failed to open file %1 for writing\n").arg(filename); QTextStream out(&file); // Take samples int chanceWinCount = 0; const int sampleCount = 1000; int atomicSampleCount = 0; for (int i = 0; i < sampleCount; i++) { // Visit all pairs of groups for (int groupIndex1 = 0; groupIndex1 < tightGroups.size(); groupIndex1++) { const QVector<Gene> &group1 = tightGroups[groupIndex1]; const QVector<Gene> &randomGroup1 = geneGroups[groupIndex1]; for (int groupIndex2 = groupIndex1 + 1; groupIndex2 < tightGroups.size(); groupIndex2++) { const QVector<Gene> &group2 = tightGroups[groupIndex2]; const QVector<Gene> &randomGroup2= geneGroups[groupIndex2]; // Take random genes from group1 & 2 const Gene &tightGene1 = group1[randomInt(group1.size())]; const Gene &tightGene2 = group2[randomInt(group2.size())]; const double tightDistance = Vec3D::distance(tightGene1.position, tightGene2.position); // Take random genes from general population const Gene &randomGene1 = randomGroup1[randomInt(randomGroup1.size())]; const Gene &randomGene2 = randomGroup2[randomInt(randomGroup2.size())]; const double randomDistance = Vec3D::distance(randomGene1.position, randomGene2.position); out << tightDistance << '\t' << randomDistance << '\n'; if (tightDistance < randomDistance) chanceWinCount++; atomicSampleCount++; } } } // end for (N samples) double pValue = (double)chanceWinCount / (double)atomicSampleCount; printf("%d samples taken\n", atomicSampleCount); printf("p-value: %f\n", pValue); } } // end anonymous namespace int main(int argc, char *argv[]) { const QString &filename = "Results/yeast.sqlite"; if (!QFile::exists(filename)) { printf("No such file: %s\n", filename.toUtf8().data()); return 0; } QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName(filename); if (!db.open()) { printf("Failed to open file: %s\n", filename.toUtf8().data()); } try { sampleDistances(db); } catch (QString errorMessage) { printf("ERROR: %s\n", errorMessage.toUtf8().data()); return 0; } db.close(); printf("Full success\n"); return 0; }
31.411458
85
0.719284
[ "3d" ]
ca774be0d11420a05275c784681415043fdc2316
12,167
cpp
C++
inference-engine/src/vpu/graph_transformer/src/parsed_config.cpp
Dimitri1/openvino
05d97220d21a2ed91377524883485fdadf660761
[ "Apache-2.0" ]
3
2020-02-09T23:25:37.000Z
2021-01-19T09:44:12.000Z
inference-engine/src/vpu/graph_transformer/src/parsed_config.cpp
Dimitri1/openvino
05d97220d21a2ed91377524883485fdadf660761
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/graph_transformer/src/parsed_config.cpp
Dimitri1/openvino
05d97220d21a2ed91377524883485fdadf660761
[ "Apache-2.0" ]
2
2020-04-18T16:24:39.000Z
2021-01-19T09:42:19.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vpu/parsed_config.hpp> #include <vector> #include <unordered_map> #include <unordered_set> #include <sstream> #include <string> #include <memory> #include <map> #include <debug.h> #include <cpp_interfaces/exception2status.hpp> #include <details/caseless.hpp> #include <ie_plugin_config.hpp> namespace vpu { namespace { template<typename I, typename T, typename C> void check_input(const I &input, const T &options, const C &check) { for (auto &&option : options) { auto input_entry = input.find(option.first); if (input_entry == input.end()) { continue; } auto input_key = input_entry->first; auto input_val = input_entry->second; auto values = option.second; if (!check(values, input_val)) { THROW_IE_EXCEPTION << "Incorrect value " << "\"" << input_val << "\"" << " for key " << input_key; } } } void checkStridesConfig(std::string configStrides) { try { configStrides.pop_back(); auto tensorStrides = InferenceEngine::details::split(configStrides, "],"); for (const auto& stride : tensorStrides) { auto pair = InferenceEngine::details::split(stride, "["); auto message = "Invalid config value '" + stride + "' for VPU_TENSOR_STRIDES, does not match the pattern: tensor_name[strides]"; IE_ASSERT(pair.size() == 2) << message; auto strideValues = InferenceEngine::details::split(pair.at(1), ","); for (auto entry : strideValues) { std::stoi(entry); } } } catch(const std::out_of_range& e) { auto message = "Invalid config value for VPU_TENSOR_STRIDES, values out of range of unsigned int"; THROW_IE_EXCEPTION << message; } catch(const std::invalid_argument& e) { auto message = "Invalid config value for VPU_TENSOR_STRIDES, can't cast values to unsigned int"; THROW_IE_EXCEPTION << message; } } } // namespace ParsedConfig::ParsedConfig(ConfigMode configMode): ParsedConfigBase(configMode) {} void ParsedConfig::checkInvalidValues(const std::map<std::string, std::string> &config) const { ParsedConfigBase::checkInvalidValues(config); const std::unordered_map<std::string, std::unordered_set<std::string>> supported_values = { { VPU_CONFIG_KEY(COMPUTE_LAYOUT), { VPU_CONFIG_VALUE(AUTO), VPU_CONFIG_VALUE(NCHW), VPU_CONFIG_VALUE(NHWC), VPU_CONFIG_VALUE(NCDHW), VPU_CONFIG_VALUE(NDHWC) }}, { VPU_CONFIG_KEY(COPY_OPTIMIZATION), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(PACK_DATA_IN_CMX), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(IGNORE_UNKNOWN_LAYERS), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { CONFIG_KEY(PERF_COUNT), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(HW_STAGES_OPTIMIZATION), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(HW_ADAPTIVE_MODE), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(HW_INJECT_STAGES), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(HW_POOL_CONV_MERGE), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(PERF_REPORT_MODE), { VPU_CONFIG_VALUE(PER_LAYER), VPU_CONFIG_VALUE(PER_STAGE) }}, { VPU_CONFIG_KEY(IGNORE_IR_STATISTIC), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, { VPU_CONFIG_KEY(HW_DILATION), { CONFIG_VALUE(YES), CONFIG_VALUE(NO) }}, }; checkSupportedValues(supported_values, config); IE_SUPPRESS_DEPRECATED_START auto config_norm = config.find(VPU_CONFIG_KEY(INPUT_NORM)); if (config_norm != config.end()) { std::map<std::string, float> configFloat = {{VPU_CONFIG_KEY(INPUT_NORM), std::stof(config_norm->second)}}; const std::unordered_map<std::string, std::unordered_set<float>> unsupported_values = { { VPU_CONFIG_KEY(INPUT_NORM), { 0.0f } } }; auto doesNotContain = [](const std::unordered_set<float> &unsupported, float option) { return unsupported.find(option) == unsupported.end(); }; check_input(configFloat, unsupported_values, doesNotContain); } IE_SUPPRESS_DEPRECATED_END auto number_of_shaves = config.find(VPU_CONFIG_KEY(NUMBER_OF_SHAVES)); auto number_of_CMX = config.find(VPU_CONFIG_KEY(NUMBER_OF_CMX_SLICES)); if (number_of_shaves != config.end()) { try { std::stoi(number_of_shaves->second); } catch(...) { THROW_IE_EXCEPTION << "Invalid config value for VPU_NUMBER_OF_SHAVES, can't cast to unsigned int"; } } if (number_of_CMX != config.end()) { try { std::stoi(number_of_CMX->second); } catch(...) { THROW_IE_EXCEPTION << "Invalid config value for VPU_NUMBER_OF_CMX_SLICES, can't cast to unsigned int"; } } if ((number_of_shaves != config.end()) && (number_of_CMX == config.end())) { THROW_IE_EXCEPTION << "You should set both option for resource management: VPU_NUMBER_OF_CMX_SLICES and VPU_NUMBER_OF_SHAVES"; } if ((number_of_shaves == config.end()) && (number_of_CMX != config.end())) { THROW_IE_EXCEPTION << "You should set both option for resource management: VPU_NUMBER_OF_CMX_SLICES and VPU_NUMBER_OF_SHAVES"; } auto tensor_strides = config.find(VPU_CONFIG_KEY(TENSOR_STRIDES)); if (tensor_strides != config.end()) { checkStridesConfig(tensor_strides->second); } } std::unordered_set<std::string> ParsedConfig::getCompileOptions() const { IE_SUPPRESS_DEPRECATED_START return { VPU_CONFIG_KEY(TENSOR_STRIDES), VPU_CONFIG_KEY(COMPUTE_LAYOUT), VPU_CONFIG_KEY(NETWORK_CONFIG), VPU_CONFIG_KEY(HW_ADAPTIVE_MODE), VPU_CONFIG_KEY(COPY_OPTIMIZATION), VPU_CONFIG_KEY(PACK_DATA_IN_CMX), VPU_CONFIG_KEY(DETECT_NETWORK_BATCH), VPU_CONFIG_KEY(IGNORE_UNKNOWN_LAYERS), VPU_CONFIG_KEY(NONE_LAYERS), VPU_CONFIG_KEY(HW_STAGES_OPTIMIZATION), VPU_CONFIG_KEY(HW_WHITE_LIST), VPU_CONFIG_KEY(HW_BLACK_LIST), VPU_CONFIG_KEY(CUSTOM_LAYERS), VPU_CONFIG_KEY(NUMBER_OF_SHAVES), VPU_CONFIG_KEY(NUMBER_OF_CMX_SLICES), VPU_CONFIG_KEY(HW_INJECT_STAGES), VPU_CONFIG_KEY(HW_POOL_CONV_MERGE), VPU_CONFIG_KEY(IGNORE_IR_STATISTIC), VPU_CONFIG_KEY(HW_DILATION), VPU_CONFIG_KEY(INPUT_NORM), VPU_CONFIG_KEY(INPUT_BIAS), }; IE_SUPPRESS_DEPRECATED_END } std::unordered_set<std::string> ParsedConfig::getRuntimeOptions() const { auto runtimeOptions = ParsedConfigBase::getRuntimeOptions(); std::unordered_set<std::string> specificOptions = { CONFIG_KEY(PERF_COUNT), VPU_CONFIG_KEY(PRINT_RECEIVE_TENSOR_TIME), CONFIG_KEY(CONFIG_FILE), VPU_CONFIG_KEY(PERF_REPORT_MODE) }; runtimeOptions.insert(specificOptions.begin(), specificOptions.end()); return runtimeOptions; } std::unordered_set<std::string> ParsedConfig::getKnownOptions() const { std::unordered_set<std::string> knownOptions; auto compileOptions = getCompileOptions(); knownOptions.insert(compileOptions.begin(), compileOptions.end()); auto runtimeOptions = getRuntimeOptions(); knownOptions.insert(runtimeOptions.begin(), runtimeOptions.end()); return knownOptions; } std::map<std::string, std::string> ParsedConfig::getDefaultConfig() const { return {}; } void ParsedConfig::configure(const std::map<std::string, std::string> &config) { ParsedConfigBase::configure(config); static const std::unordered_map<std::string, ComputeLayout> layouts { { VPU_CONFIG_VALUE(AUTO), ComputeLayout::AUTO }, { VPU_CONFIG_VALUE(NCHW), ComputeLayout::NCHW }, { VPU_CONFIG_VALUE(NHWC), ComputeLayout::NHWC }, { VPU_CONFIG_VALUE(NCDHW), ComputeLayout::NCDHW }, { VPU_CONFIG_VALUE(NDHWC), ComputeLayout::NDHWC } }; setOption(compileConfig.forceLayout, layouts, config, VPU_CONFIG_KEY(COMPUTE_LAYOUT)); static const std::unordered_map<std::string, bool> switches = { { CONFIG_VALUE(YES), true }, { CONFIG_VALUE(NO), false } }; setOption(compileConfig.detectBatch, switches, config, VPU_CONFIG_KEY(DETECT_NETWORK_BATCH)); setOption(compileConfig.copyOptimization, switches, config, VPU_CONFIG_KEY(COPY_OPTIMIZATION)); setOption(compileConfig.packDataInCmx, switches, config, VPU_CONFIG_KEY(PACK_DATA_IN_CMX)); setOption(compileConfig.ignoreUnknownLayers, switches, config, VPU_CONFIG_KEY(IGNORE_UNKNOWN_LAYERS)); setOption(compileConfig.hwOptimization, switches, config, VPU_CONFIG_KEY(HW_STAGES_OPTIMIZATION)); setOption(compileConfig.hwAdaptiveMode, switches, config, VPU_CONFIG_KEY(HW_ADAPTIVE_MODE)); setOption(compileConfig.injectSwOps, switches, config, VPU_CONFIG_KEY(HW_INJECT_STAGES)); setOption(compileConfig.mergeHwPoolToConv, switches, config, VPU_CONFIG_KEY(HW_POOL_CONV_MERGE)); setOption(compileConfig.ignoreIRStatistic, switches, config, VPU_CONFIG_KEY(IGNORE_IR_STATISTIC)); setOption(compileConfig.hwDilation, switches, config, VPU_CONFIG_KEY(HW_DILATION)); setOption(compileConfig.noneLayers, config, VPU_CONFIG_KEY(NONE_LAYERS)); setOption(compileConfig.hwWhiteList, config, VPU_CONFIG_KEY(HW_WHITE_LIST)); setOption(compileConfig.hwBlackList, config, VPU_CONFIG_KEY(HW_BLACK_LIST)); setOption(compileConfig.networkConfig, config, VPU_CONFIG_KEY(NETWORK_CONFIG)); /* priority is set to VPU configuration file over plug-in config */ setOption(compileConfig.customLayers, config, VPU_CONFIG_KEY(CUSTOM_LAYERS)); if (compileConfig.customLayers.empty()) { setOption(compileConfig.customLayers, config, CONFIG_KEY(CONFIG_FILE)); } setOption(compileConfig.numSHAVEs, config, VPU_CONFIG_KEY(NUMBER_OF_SHAVES), [](const std::string &src) { return std::stoi(src); }); setOption(compileConfig.numCMXSlices, config, VPU_CONFIG_KEY(NUMBER_OF_CMX_SLICES), [](const std::string &src) { return std::stoi(src); }); setOption(compileConfig.ioStrides, config, VPU_CONFIG_KEY(TENSOR_STRIDES), [](const std::string &src) { auto configStrides = src; configStrides.pop_back(); auto inputs = InferenceEngine::details::split(configStrides, "],"); std::map<std::string, std::vector<int> > stridesMap; for (const auto& input : inputs) { std::vector<int> strides; auto pair = InferenceEngine::details::split(input, "["); auto strideValues = InferenceEngine::details::split(pair.at(1), ","); for (const auto& stride : strideValues) { strides.insert(strides.begin(), std::stoi(stride)); } stridesMap.insert({pair.at(0), strides}); } return stridesMap; }); setOption(printReceiveTensorTime, switches, config, VPU_CONFIG_KEY(PRINT_RECEIVE_TENSOR_TIME)); setOption(perfCount, switches, config, CONFIG_KEY(PERF_COUNT)); static const std::unordered_map<std::string, PerfReport> perfReports { { VPU_CONFIG_VALUE(PER_LAYER), PerfReport::PerLayer }, { VPU_CONFIG_VALUE(PER_STAGE), PerfReport::PerStage }, }; setOption(perfReport, perfReports, config, VPU_CONFIG_KEY(PERF_REPORT_MODE)); IE_SUPPRESS_DEPRECATED_START setOption(compileConfig.inputScale, config, VPU_CONFIG_KEY(INPUT_NORM), [](const std::string &src) { return 1.f / std::stof(src); }); setOption(compileConfig.inputBias, config, VPU_CONFIG_KEY(INPUT_BIAS), [](const std::string &src) { return std::stof(src); }); IE_SUPPRESS_DEPRECATED_END } } // namespace vpu
40.96633
140
0.674119
[ "vector" ]
ca7899fb398da9728132c22a3eb7d9b3303d302c
1,075
hpp
C++
scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.hpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
7
2020-11-26T01:07:26.000Z
2021-12-14T07:45:19.000Z
scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.hpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
null
null
null
scsdk/c++/scsdk/standard_cyborg/algorithms/PrincipalAxes.hpp
StandardCyborg/scsdk
92f80bf2a580ebaafa6b0d1052d90d5c8f6682f7
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 Standard Cyborg 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 <vector> #pragma once namespace standard_cyborg { namespace sc3d{ class Geometry; } namespace math { struct Mat3x4; struct Vec3; } namespace algorithms { standard_cyborg::math::Mat3x4 computeNormalwisePrincipalAxes(const sc3d::Geometry& geometry); standard_cyborg::math::Mat3x4 computePointwisePrincipalAxes(const sc3d::Geometry& geometry); standard_cyborg::math::Mat3x4 computePointwisePrincipalAxes(const std::vector<standard_cyborg::math::Vec3>& positions); } } // namespace StandardCyborg
25
119
0.792558
[ "geometry", "vector" ]
ca7a0cc4bbf6f4e4d2dc732b2d7e186e476fba8e
3,556
cpp
C++
src/armnn/layers/FullyConnectedLayer.cpp
Project-Xtended/external_armnn
c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94
[ "MIT" ]
2
2021-12-09T15:14:04.000Z
2021-12-10T01:37:53.000Z
src/armnn/layers/FullyConnectedLayer.cpp
Project-Xtended/external_armnn
c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94
[ "MIT" ]
null
null
null
src/armnn/layers/FullyConnectedLayer.cpp
Project-Xtended/external_armnn
c5e1bbf9fc8ecbb8c9eb073a1550d4c8c15fce94
[ "MIT" ]
3
2022-01-23T11:34:40.000Z
2022-02-12T15:51:37.000Z
// // Copyright © 2017 Arm Ltd and Contributors. All rights reserved. // SPDX-License-Identifier: MIT // #include "FullyConnectedLayer.hpp" #include "LayerCloneBase.hpp" #include <armnn/TypesUtils.hpp> #include <backendsCommon/CpuTensorHandle.hpp> #include <backendsCommon/WorkloadData.hpp> #include <backendsCommon/WorkloadFactory.hpp> namespace armnn { FullyConnectedLayer::FullyConnectedLayer(const FullyConnectedDescriptor& param, const char* name) : LayerWithParameters(1, 1, LayerType::FullyConnected, param, name) { } std::unique_ptr<IWorkload> FullyConnectedLayer::CreateWorkload(const IWorkloadFactory& factory) const { // on this level constant data should not be released.. ARMNN_ASSERT_MSG(m_Weight != nullptr, "FullyConnectedLayer: Weights data should not be null."); FullyConnectedQueueDescriptor descriptor; descriptor.m_Weight = m_Weight.get(); if (m_Param.m_BiasEnabled) { ARMNN_ASSERT_MSG(m_Bias != nullptr, "FullyConnectedLayer: Bias data should not be null."); descriptor.m_Bias = m_Bias.get(); } SetAdditionalInfo(descriptor); return factory.CreateFullyConnected(descriptor, PrepInfoAndDesc(descriptor)); } FullyConnectedLayer* FullyConnectedLayer::Clone(Graph& graph) const { auto layer = CloneBase<FullyConnectedLayer>(graph, m_Param, GetName()); layer->m_Weight = m_Weight ? std::make_unique<ScopedCpuTensorHandle>(*m_Weight) : nullptr; if (layer->m_Param.m_BiasEnabled) { layer->m_Bias = m_Bias ? std::make_unique<ScopedCpuTensorHandle>(*m_Bias) : nullptr; } return std::move(layer); } std::vector<TensorShape> FullyConnectedLayer::InferOutputShapes(const std::vector<TensorShape>& inputShapes) const { ARMNN_ASSERT(inputShapes.size() == 2); const TensorShape& inputShape = inputShapes[0]; const TensorShape weightShape = inputShapes[1]; // Output for FC is [1, w[1]]. unsigned int batches = inputShape[0]; unsigned int dimIdx = m_Param.m_TransposeWeightMatrix ? 0 : 1; return std::vector<TensorShape>({ TensorShape({batches, weightShape[dimIdx]})}); } void FullyConnectedLayer::ValidateTensorShapesFromInputs() { const TensorShape& outputShape = GetOutputSlot(0).GetTensorInfo().GetShape(); VerifyShapeInferenceType(outputShape, m_ShapeInferenceMethod); // check if we m_Weight data is not nullptr ARMNN_ASSERT_MSG(m_Weight != nullptr, "FullyConnectedLayer: Weights data should not be null."); auto inferredShapes = InferOutputShapes({GetInputSlot(0).GetConnection()->GetTensorInfo().GetShape(), m_Weight->GetTensorInfo().GetShape() }); ARMNN_ASSERT(inferredShapes.size() == 1); ARMNN_ASSERT(inferredShapes[0].GetDimensionality() == Dimensionality::Specified); ValidateAndCopyShape(outputShape, inferredShapes[0], m_ShapeInferenceMethod, "FullyConnectedLayer"); } Layer::ConstantTensors FullyConnectedLayer::GetConstantTensorsByRef() { return {m_Weight, m_Bias}; } void FullyConnectedLayer::Accept(ILayerVisitor& visitor) const { ConstTensor weightsTensor(m_Weight->GetTensorInfo(), m_Weight->Map(true)); Optional<ConstTensor> optionalBiasTensor = EmptyOptional(); if (GetParameters().m_BiasEnabled) { ConstTensor biasTensor(m_Bias->GetTensorInfo(), m_Bias->GetConstTensor<void>()); optionalBiasTensor = Optional<ConstTensor>(biasTensor); } visitor.VisitFullyConnectedLayer(this, GetParameters(), weightsTensor, optionalBiasTensor, GetName()); } } // namespace armnn
33.866667
114
0.736783
[ "vector" ]
ca7a3f9b7b56f634fbaec000dc8519d221a9c9b7
624
cpp
C++
models/ops/src/cpu/ms_deform_attn_cpu.cpp
weijiawu/TransVTSpotter
7c55aacd074d06529e79d5959a8555f571f7d3e2
[ "MIT" ]
51
2021-08-05T13:27:38.000Z
2022-03-28T01:19:15.000Z
models/ops/src/cpu/ms_deform_attn_cpu.cpp
weijiawu/TransVTSpotter
7c55aacd074d06529e79d5959a8555f571f7d3e2
[ "MIT" ]
8
2021-09-17T15:06:39.000Z
2022-03-30T12:09:11.000Z
models/ops/src/cpu/ms_deform_attn_cpu.cpp
weijiawu/TransVTSpotter
7c55aacd074d06529e79d5959a8555f571f7d3e2
[ "MIT" ]
6
2021-11-29T05:17:20.000Z
2022-01-22T14:02:23.000Z
#include <vector> #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> at::Tensor ms_deform_attn_cpu_forward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const int im2col_step) { AT_ERROR("Not implement on cpu"); } std::vector<at::Tensor> ms_deform_attn_cpu_backward( const at::Tensor &value, const at::Tensor &spatial_shapes, const at::Tensor &sampling_loc, const at::Tensor &attn_weight, const at::Tensor &grad_output, const int im2col_step) { AT_ERROR("Not implement on cpu"); }
20.8
37
0.695513
[ "vector" ]
ca7d879fc466607f78bf0549a7139ba3e0e0eac1
4,300
cpp
C++
test_problems/diamondSurf/runDiamond.cpp
VishalKandala/Cantera-1.7
750786f9b845a56fc177a9f1d5a9c5bb6ebd87cc
[ "BSD-3-Clause" ]
null
null
null
test_problems/diamondSurf/runDiamond.cpp
VishalKandala/Cantera-1.7
750786f9b845a56fc177a9f1d5a9c5bb6ebd87cc
[ "BSD-3-Clause" ]
null
null
null
test_problems/diamondSurf/runDiamond.cpp
VishalKandala/Cantera-1.7
750786f9b845a56fc177a9f1d5a9c5bb6ebd87cc
[ "BSD-3-Clause" ]
null
null
null
/** * @file runDiamond.cpp * */ // Example // // Note that this example needs updating. It works fine, but is // written in a way that is less than transparent or // user-friendly. This could be rewritten using class Interface to // make things simpler. #include <iostream> #include <string> #include <vector> #include <string> #include <iomanip> using namespace std; #ifdef DEBUG_HKM int iDebug_HKM = 0; #endif /*****************************************************************/ /*****************************************************************/ /*****************************************************************/ static void printUsage() { } #ifdef SRCDIRTREE #include "ct_defs.h" #include "ctml.h" #include "GasKinetics.h" #include "importCTML.h" #include "ThermoPhase.h" #include "InterfaceKinetics.h" #else #include "Cantera.h" #include "kernel/ct_defs.h" #include "kernel/ctml.h" #include "kernel/GasKinetics.h" #include "kernel/importCTML.h" #include "kernel/ThermoPhase.h" #include "kernel/InterfaceKinetics.h" #endif using namespace Cantera; void printDbl(double val) { if (fabs(val) < 5.0E-17) { cout << " nil"; } else { cout << val; } } int main(int argc, char** argv) { int i, k; string infile = "diamond.xml"; try { XML_Node *xc = new XML_Node(); string path = findInputFile(infile); ctml::get_CTML_Tree(xc, path); XML_Node * const xg = xc->findNameID("phase", "gas"); ThermoPhase *gasTP = newPhase(*xg); int nsp = gasTP->nSpecies(); cout << "Number of species = " << nsp << endl; XML_Node * const xd = xc->findNameID("phase", "diamond"); ThermoPhase *diamondTP = newPhase(*xd); int nsp_diamond = diamondTP->nSpecies(); cout << "Number of species in diamond = " << nsp_diamond << endl; XML_Node * const xs = xc->findNameID("phase", "diamond_100"); ThermoPhase *diamond100TP = newPhase(*xs); int nsp_d100 = diamond100TP->nSpecies(); cout << "Number of species in diamond_100 = " << nsp_d100 << endl; vector<ThermoPhase *> phaseList; phaseList.push_back(gasTP); phaseList.push_back(diamondTP); phaseList.push_back(diamond100TP); InterfaceKinetics *iKin_ptr = new InterfaceKinetics(); importKinetics(*xs, phaseList, iKin_ptr); int nr = iKin_ptr->nReactions(); cout << "Number of reactions = " << nr << endl; double x[20]; for (i = 0; i < 20; i++) x[i] = 0.0; x[0] = 0.0010; x[1] = 0.9888; x[2] = 0.0002; x[3] = 0.0100; double p = 20.0*OneAtm/760.0; gasTP->setState_TPX(1200., p, x); for (i = 0; i < 20; i++) x[i] = 0.0; int i0 = diamond100TP->speciesIndex("c6H*"); x[i0] = 0.1; int i1 = diamond100TP->speciesIndex("c6HH"); x[i1] = 0.9; diamond100TP->setState_TX(1200., x); for (i = 0; i < 20; i++) x[i] = 0.0; x[0] = 1.0; diamondTP->setState_TPX(1200., p, x); iKin_ptr->advanceCoverages(100.); double src[20]; for (i = 0; i < 20; i++) src[i] = 0.0; iKin_ptr->getNetProductionRates(src); double sum = 0.0; double naH = 0.0; for (k = 0; k < 13; k++) { if (k < 4) { naH = gasTP->nAtoms(k, 0); } else if (k == 4) { naH = 0; } else if (k > 4) { int itp = k - 5; naH = diamond100TP->nAtoms(itp, 0); } cout << k << " " << naH << " " ; printDbl(src[k]); cout << endl; sum += naH * src[k]; } cout << "sum = "; printDbl(sum); cout << endl; double mwd = diamondTP->molecularWeight(0); double dens = diamondTP->density(); double gr = src[4] * mwd / dens; gr *= 1.0E6 * 3600.; cout << "growth rate = " << gr << " microns per hour" << endl; diamond100TP->getMoleFractions(x); cout << "Coverages:" << endl; for (k = 0; k < 8; k++) { cout << k << " " << diamond100TP->speciesName(k) << " " << x[k] << endl; } } catch (CanteraError) { showErrors(cout); } return 0; } /***********************************************************/
26.060606
73
0.511628
[ "vector" ]
ca8f8d55ad75d633d3a19944e8ebf34a608ed52a
2,086
cpp
C++
codeforces/1010D - Mars rover.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
1
2018-12-25T23:55:19.000Z
2018-12-25T23:55:19.000Z
codeforces/1010D - Mars rover.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
codeforces/1010D - Mars rover.cpp
Dijkstraido-2/online-judge
31844cd8fbd5038cc5ebc6337d68229cef133a30
[ "MIT" ]
null
null
null
//============================================================================ // Problem : 1010D - Mars rover // Category : DFS //============================================================================ #include <bits/stdc++.h> using namespace std; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<string> vs; vvi g; int n,x,y; vi f,r; vs s; void dfs(int v) { for(int u : g[v]) dfs(u); if(s[v] == "AND") f[v] = f[g[v][0]] & f[g[v][1]]; else if(s[v] == "OR") f[v] = f[g[v][0]] | f[g[v][1]]; else if(s[v] == "XOR") f[v] = f[g[v][0]] ^ f[g[v][1]]; else if(s[v] == "NOT") f[v] = !f[g[v][0]]; } void rev(int v) { if(!r[v]) return; if(s[v] == "AND") { x = (!f[g[v][0]]) & (f[g[v][1]]); if(x != f[v]) r[g[v][0]] = 1; x = (f[g[v][0]]) & (!f[g[v][1]]); if(x != f[v]) r[g[v][1]] = 1; } else if(s[v] == "OR") { x = (!f[g[v][0]]) | (f[g[v][1]]); if(x != f[v]) r[g[v][0]] = 1; x = (f[g[v][0]]) | (!f[g[v][1]]); if(x != f[v]) r[g[v][1]] = 1; } else if(s[v] == "XOR") r[g[v][0]] = r[g[v][1]] = 1; else if(s[v] == "NOT") r[g[v][0]] = 1; for(int u : g[v]) rev(u); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); while(cin >> n) { g = vvi(n); s = vs(n); f = vi(n); r = vi(n,0); for(int i = 0; i < n; i++) { cin >> s[i]; if(s[i] == "IN") cin >> f[i]; else if(s[i] == "NOT") { cin >> x; x--; g[i].push_back(x); } else { cin >> x >> y; x--; y--; g[i].push_back(x); g[i].push_back(y); } } dfs(0); r[0] = 1; rev(0); for(int i = 0; i < n; i++) if(s[i] == "IN") cout << (f[0] ^ r[i]); cout << '\n'; } return 0; }
22.430108
78
0.291467
[ "vector" ]
ca99ac966ade1a7ca1d577f9cf11c3b7bdadfe25
2,586
hh
C++
src/sim/TrackInitializerStore.hh
sethrj/celeritas
44395a039e223604365256a13f96c7742cdf5e09
[ "Apache-2.0", "MIT" ]
null
null
null
src/sim/TrackInitializerStore.hh
sethrj/celeritas
44395a039e223604365256a13f96c7742cdf5e09
[ "Apache-2.0", "MIT" ]
null
null
null
src/sim/TrackInitializerStore.hh
sethrj/celeritas
44395a039e223604365256a13f96c7742cdf5e09
[ "Apache-2.0", "MIT" ]
null
null
null
//----------------------------------*-C++-*----------------------------------// // Copyright 2020 UT-Battelle, LLC, and other Celeritas developers. // See the top-level COPYRIGHT file for details. // SPDX-License-Identifier: (Apache-2.0 OR MIT) //---------------------------------------------------------------------------// //! \file TrackInitializerStore.hh //---------------------------------------------------------------------------// #pragma once #include "base/DeviceVector.hh" #include "ParamStore.hh" #include "StateStore.hh" #include "TrackInitializerInterface.hh" namespace celeritas { //---------------------------------------------------------------------------// /*! * Manage device data for track initializers. */ class TrackInitializerStore { public: // Construct with the number of tracks, the maximum number of track // initializers to store on device, and the primary particles explicit TrackInitializerStore(size_type num_tracks, size_type capacity, std::vector<Primary> primaries); // Get a view to the managed data TrackInitializerPointers device_pointers(); //! Number of track initializers size_type size() const { return initializers_.size(); } //! Number of empty track slots on device size_type num_vacancies() const { return vacancies_.size(); } //! Number of primary particles left to be initialized on device size_type num_primaries() const { return primaries_.size(); } // Create track initializers on device from primary particles void extend_from_primaries(); // Create track initializers on device from secondary particles. void extend_from_secondaries(StateStore* states, ParamStore* params); // Initialize track states on device. void initialize_tracks(StateStore* states, ParamStore* params); private: // Track initializers created from primaries or secondaries DeviceVector<TrackInitializer> initializers_; // Thread ID of the secondary's parent DeviceVector<size_type> parent_; // Index of empty slots in track vector DeviceVector<size_type> vacancies_; // Number of surviving secondaries produced in each interaction DeviceVector<size_type> secondary_counts_; // Track ID counter for each event DeviceVector<TrackId::size_type> track_counter_; // Host-side primary particles std::vector<Primary> primaries_; }; //---------------------------------------------------------------------------// } // namespace celeritas
35.424658
79
0.601315
[ "vector" ]
ca9c0ce750071b31dfddbc0295c12ab10eabcb6c
6,407
cpp
C++
wingchun/tool/DataConsumer.cpp
dfhljf/kungfu
ebbc9e21f3b2efad743c402f453d7487d8d3f961
[ "Apache-2.0" ]
3
2020-01-15T10:37:51.000Z
2021-12-14T15:35:48.000Z
wingchun/tool/DataConsumer.cpp
dfhljf/kungfu
ebbc9e21f3b2efad743c402f453d7487d8d3f961
[ "Apache-2.0" ]
null
null
null
wingchun/tool/DataConsumer.cpp
dfhljf/kungfu
ebbc9e21f3b2efad743c402f453d7487d8d3f961
[ "Apache-2.0" ]
3
2020-01-24T02:09:00.000Z
2022-02-18T06:29:17.000Z
/***************************************************************************** * Copyright [2017] [taurus.ai] * * 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. *****************************************************************************/ /** * DataConsumer: consume journal data. * @Author cjiang (changhao.jiang@taurus.ai) * @since Oct, 2017 */ #include "DataConsumer.h" #include "Timer.h" #include "longfist/sys_messages.h" #include <iostream> #include <sstream> #include <math.h> USING_WC_NAMESPACE using namespace std; using namespace kungfu::yijinjing; DataConsumer::DataConsumer(): start_nano(-1), end_nano(-1), cur_time(-1) { } void DataConsumer::init(long start_nano, long end_nano) { this->start_nano = start_nano; this->end_nano = end_nano; string reader_name = "Consumer_" + parseNano(getNanoTime(), "%H%M%S"); vector<string> empty; reader = JournalReader::createReaderWithSys(empty, empty, start_nano, reader_name); cur_time = start_nano; } void DataConsumer::run() { yijinjing::FramePtr frame; while (end_nano < 0 || cur_time < end_nano) { frame = reader->getNextFrame(); if (frame.get() != nullptr) { short msg_type = frame->getMsgType(); short msg_source = frame->getSource(); int request_id = frame->getRequestId(); string name = reader->getFrameName(); void* data = frame->getData(); cur_time = frame->getNano(); long extra_nano = frame->getExtraNano(); if (msg_type == MSG_TYPE_LF_MD) // md { LFMarketDataField* md = (LFMarketDataField*)data; on_market_data(md); } else if (msg_type == MSG_TYPE_STRATEGY_START) // system { try { string content((char *) frame->getData()); json j_start = json::parse(content); on_strategy_start(j_start, cur_time, j_start["name"].get<string>()); } catch (...) { cout << " --- ERROR: cannot parse MSG_TYPE_STRATEGY_START --- " << endl; cout << (char *)frame->getData() << endl; cout << " --- " << endl; } } else if (msg_type == MSG_TYPE_STRATEGY_END) // system { try { string content((char *) frame->getData()); json j_end = json::parse(content); on_strategy_end(j_end, cur_time, j_end["name"].get<string>()); } catch (...) { cout << " --- ERROR: cannot parse MSG_TYPE_STRATEGY_END --- " << endl; cout << (char *)frame->getData() << endl; cout << " --- " << endl; } } else if (msg_type == MSG_TYPE_TRADE_ENGINE_LOGIN) { try { string content((char *) frame->getData()); json j_request = json::parse(content); on_td_connect(j_request, msg_source, cur_time, j_request["name"].get<string>()); } catch (...) { cout << " --- ERROR: cannot parse MSG_TYPE_TRADE_ENGINE_LOGIN --- " << endl; cout << (char *)frame->getData() << endl; cout << " --- " << endl; } } else if (msg_type == MSG_TYPE_TRADE_ENGINE_ACK) // td { try { string content((char *) frame->getData()); json j_ack = json::parse(content); on_td_ack(j_ack, msg_source, cur_time, j_ack["name"].get<string>()); } catch (...) { cout << " --- ERROR: cannot parse MSG_TYPE_TRADE_ENGINE_LOGIN --- " << endl; cout << (char *)frame->getData() << endl; cout << " --- " << endl; } } else if (msg_type == MSG_TYPE_STRATEGY_POS_SET) // oe { try { string content((char *) frame->getData()); json j_request = json::parse(content); on_pos_set(j_request, msg_source, cur_time, j_request["name"].get<string>()); } catch (...) { cout << " --- ERROR: cannot parse MSG_TYPE_STRATEGY_POS_SET --- " << endl; cout << (char *)frame->getData() << endl; cout << " --- " << endl; } } else if (msg_type == MSG_TYPE_LF_ORDER) // oe / td_send { LFInputOrderField* order = (LFInputOrderField*)data; if (!name.compare(0, 8, "TD_SEND_")) { on_order_send(order, msg_source, request_id, cur_time, extra_nano); } else { on_order_origin(order, msg_source, request_id, cur_time, extra_nano, name); } } else if (msg_type == MSG_TYPE_LF_RTN_ORDER) // td { LFRtnOrderField* order = (LFRtnOrderField*)data; on_rtn_order(order, msg_source, request_id, cur_time); } else if (msg_type == MSG_TYPE_LF_RTN_TRADE) // td { LFRtnTradeField* trade = (LFRtnTradeField*)data; on_rtn_trade(trade, msg_source, request_id, cur_time); } } else { if (end_nano > 0) return; } } }
36.821839
100
0.474949
[ "vector" ]
ca9f2e9025f2fd71f386d6bb861b5b4f8db58e2c
3,863
cpp
C++
test/test_environment.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
37
2019-10-13T12:23:32.000Z
2022-03-19T10:40:29.000Z
test/test_environment.cpp
rht/ESL
f883155a167d3c48e5ecdca91c8302fefc901c22
[ "Apache-2.0" ]
3
2020-03-20T04:44:06.000Z
2021-01-12T06:18:33.000Z
test/test_environment.cpp
vishalbelsare/ESL
cea6feda1e588d5f441742dbb1e4c5479b47d357
[ "Apache-2.0" ]
10
2019-11-06T15:59:06.000Z
2021-08-09T17:28:24.000Z
/// \file test_environment.cpp /// /// \brief /// /// \authors Maarten P. Scholl /// \date 2019-09-22 /// \copyright Copyright 2017-2019 The Institute for New Economic Thinking, /// Oxford Martin School, University of Oxford /// /// 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. /// /// You may obtain instructions to fulfill the attribution /// requirements in CITATION.cff /// #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE environment #include <boost/test/included/unit_test.hpp> #include <esl/computation/environment.hpp> #include <esl/simulation/model.hpp> #include <esl/agent.hpp> using namespace esl; using namespace esl::simulation; struct test_agent : public agent { using agent::agent; unsigned int delay = 0; time_point act(time_interval step, std::seed_seq &seed) override { (void) seed; return step.lower + delay; } }; struct test_model : public model { using model::model; int initialize_called = 0; int terminate_called = 0; void initialize() override { auto ta = this->template create<test_agent>(); ++initialize_called; } void terminate() override { ++terminate_called; } }; BOOST_AUTO_TEST_SUITE(ESL) BOOST_AUTO_TEST_CASE(environment_constructor) { computation::environment e; test_model tm(e, parameter::parametrization(0, 1, 100)); BOOST_CHECK_EQUAL(tm.start, 1); BOOST_CHECK_EQUAL(tm.time, 1); BOOST_CHECK_EQUAL(tm.end, 100); } BOOST_AUTO_TEST_CASE(environment_basic_time_stepping) { computation::environment e; test_model tm(e, parameter::parametrization(0, 0, 100)); auto next_ = tm.step( {0, 3}); std::cout << next_ << std::endl; BOOST_CHECK_EQUAL(next_, 3); } BOOST_AUTO_TEST_CASE(environment_time_step_with_agents) { computation::environment e; test_model tm(e, parameter::parametrization(0, 0, 100)); auto a1 = tm.create<test_agent>(); a1->delay = 5; auto next_ = tm.step( {0, 3}); BOOST_CHECK_EQUAL(next_, 3); next_ = tm.step( {3, 5}); BOOST_CHECK_EQUAL(next_, 5); } /// /// \brief /// BOOST_AUTO_TEST_CASE(environment_run_agents_parallel) { computation::environment e; unsigned int threads = 8; test_model tm(e, parameter::parametrization(0, 0, 100, 0, threads)); // We create one agent with delay 5, and other agents have more. // If the parallelisation fails, we might miss that particular agent // and end with a higher time point although this is nondeterministic // and we are thus not guaranteed to catch it. auto test_agents = 100'000; for(auto i = 0; i < test_agents; ++i){ auto a1 = tm.create<test_agent>(); a1->delay = 4 + test_agents - i; } auto next_ = tm.step( {0, 3}); BOOST_CHECK_EQUAL(next_, 3); // agents will delay again next_ = tm.step( {3, 1234}); BOOST_CHECK_EQUAL(next_, 8); } BOOST_AUTO_TEST_SUITE_END() // ESL
25.926174
80
0.610924
[ "model" ]
caa115390bfaafaad9757743a143ec9e85e0a5a0
2,548
cpp
C++
cannon/ml/piecewise_recursive_lstd.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
cannon/ml/piecewise_recursive_lstd.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
cannon/ml/piecewise_recursive_lstd.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <cannon/ml/piecewise_recursive_lstd.hpp> #include <cassert> #include <cannon/log/registry.hpp> using namespace cannon::ml; using namespace cannon::log; // Public void PiecewiseRecursiveLSTDFilter::process_datum(const VectorXd& in_vec, const VectorXd& next_in_vec, unsigned int idx, unsigned int next_idx, double reward) { auto feat = make_feature_vec_(in_vec, idx); auto next_feat = make_feature_vec_(next_in_vec, next_idx); SparseMatrix<double> diff = feat - (discount_factor_ * next_feat); auto v = a_inv_ * feat.transpose(); MatrixXd tmp = diff * v; //MatrixXd tmp = g * feat.transpose(); assert(tmp.size() == 1); double a = tmp(0, 0) + 1.0; double inv_a = 1.0 / a; MatrixXd tmp2 = diff * theta_; assert(tmp2.size() == 1); double e_t = reward - tmp2(0, 0); theta_ += inv_a * (e_t * v); update_a_inv_(v, diff, inv_a); } VectorXd PiecewiseRecursiveLSTDFilter::get_mat(unsigned int idx) const { unsigned int start_coord = idx * in_dim_; VectorXd ret_vec = theta_.segment(start_coord, in_dim_ - 1); return ret_vec; } double PiecewiseRecursiveLSTDFilter::predict(const VectorXd& in_vec, unsigned int idx) const { RowVectorXd feat = make_feature_vec_(in_vec, idx); return feat * theta_; } void PiecewiseRecursiveLSTDFilter::reset() { a_inv_ = MatrixXd::Identity(param_dim_, param_dim_) * alpha_; theta_ = VectorXd::Zero(param_dim_); } // Private SparseMatrix<double> PiecewiseRecursiveLSTDFilter::make_feature_vec_(VectorXd in_vec, unsigned int idx) const { assert(in_vec.size() == in_dim_ - 1); assert(idx < num_refs_); SparseMatrix<double> feat(1, param_dim_); unsigned int start_coord = idx * in_dim_; unsigned int end_coord = idx * in_dim_ + in_dim_ - 1; std::vector<Triplet<double>> triplets; triplets.reserve(in_vec.size()); for (unsigned int i = 0; i < in_vec.size(); ++i) { triplets.push_back(Triplet<double>(0, start_coord+i, in_vec[i])); } triplets.push_back(Triplet<double>(0, end_coord, 1.0)); feat.setFromTriplets(triplets.begin(), triplets.end()); return feat; } void PiecewiseRecursiveLSTDFilter::update_a_inv_( const Ref<const VectorXd> &a_inv_feat_t, const Ref<const SparseMatrix<double>> &diff, double inv_denom) { // Numerator = a_inv_ * feat.transpose() * diff * a_inv_ auto numerator = a_inv_feat_t * (diff * a_inv_); assert(numerator.rows() == param_dim_); assert(numerator.cols() == param_dim_); auto update = numerator * inv_denom; a_inv_ -= update; }
29.976471
101
0.699372
[ "vector" ]
caa3dd189e1e996f712ae2c1f8620f77858f808f
6,803
cpp
C++
example/main.cpp
JimmyDdotEXE/jui
08277e58a71d1102210228bbb8a4e481966b4980
[ "MIT" ]
null
null
null
example/main.cpp
JimmyDdotEXE/jui
08277e58a71d1102210228bbb8a4e481966b4980
[ "MIT" ]
null
null
null
example/main.cpp
JimmyDdotEXE/jui
08277e58a71d1102210228bbb8a4e481966b4980
[ "MIT" ]
1
2022-02-25T11:34:58.000Z
2022-02-25T11:34:58.000Z
#include <iostream> #include <fstream> #include <vector> #include <string> #include <cstdlib> #include <iomanip> #include "General.h" #include "Window.h" #include "Controls.h" /*tell JUI where to find the font and icon files*/ std::string fontLocation = "SourceCodePro-Regular.ttf"; std::string iconLocation = "Untitled.png"; /*derived button class to change the title of the window*/ class TitleButton : public Button{ public: TitleButton(int x, int y, Window *win, TextBox *text) : Button(x, y, "Set Title"){ window = win; textBox = text; hasLeftClick = true; } bool leftClick(){ window->setTitle(textBox->getText()); return window->getTitle() == textBox->getText(); } protected: Window *window; TextBox *textBox; }; /*entry point of the function*/ int main(int argc, char *argv[]){ /*load the color scheme of the program*/ loadPalette(); /*start the JUI backend*/ start(); /*creat the window*/ Window win(480, 360, "Test Window"); /*define all the needed controls*/ View *v = new View(0, 0, 480, 360); v->setLeftLock(true); v->setRightLock(true); v->setTopLock(true); v->setBottomLock(true); v->setLockResize(true); double sliderDouble = 0; Slider *slider = new Slider(10, 10, 360 - 36, 0, 100, &sliderDouble, HORIZONTAL); slider->setTopLock(true); slider->setBottomLock(true); Label *label = new Label(slider->getX() + slider->getWidth() + 10, 10, 20, numString(0)); TextBox *tex = new TextBox(label->getX(), label->getY() + label->getHeight() + 10, 120, 24, "Window Title"); tex->setText(win.getTitle()); TitleButton *button = new TitleButton(tex->getX(), tex->getY() + tex->getHeight() + 10, &win, tex); button->setX(tex->getX() + (tex->getWidth() - button->getWidth())/2); CheckBoxGroup *visibleControls = new CheckBoxGroup(tex->getX() + tex->getWidth() + 10, 10, "Visible Controls", {"Label", "Slider", "Button", "TextBox", "RadioButtonGroup", "ComboBox", "Toggle"}); visibleControls->setSelection({"Label", "Slider", "Button", "TextBox", "RadioButtonGroup", "ComboBox", "Toggle"}); RadioButtonGroup *rad = new RadioButtonGroup(slider->getX() + slider->getWidth() + 10, 0, "Accent Color", {"Yellow", "Orange", "Red", "Magenta", "Violet", "Blue", "Cyan", "Green"}); rad->setY(win.getHeight() - 10 - rad->getHeight()); rad->setBottomLock(true); rad->setSelection("Cyan"); ComboBox *combo = new ComboBox(rad->getX(), 0); combo->setY(rad->getY() - 10 - combo->getHeight()); combo->setBottomLock(true); combo->setList({"Yellow", "Orange", "Red", "Magenta", "Violet", "Blue", "Cyan", "Green"}); combo->setSelection({"Cyan"}); Toggle *darkToggle = new Toggle(0, 10, &darkMode); darkToggle->setX(v->getWidth() - darkToggle->getWidth() - 10); darkToggle->setRightLock(true); /*add the view to the window*/ win.addControl(v); /*add all the controls to the view*/ v->addControl(tex); v->addControl(slider); v->addControl(label); v->addControl(rad); v->addControl(combo); v->addControl(darkToggle); v->addControl(button); v->addControl(visibleControls); /*run the program as long as the window is open*/ while(win.isReady()){ /*handle the window events*/ win.handleEvents(); /*clear the window and view based on the darkmode setting*/ if(darkMode){ win.clear(*darkTheme[0]); v->clear(*darkTheme[0]); }else{ win.clear(*lightTheme[0]); v->clear(*lightTheme[0]); } /*set highlight color based on changes to the RadioButtons and ComboBox*/ if((rad->getSelection() == "Yellow" || combo->getSelection().at(0) == "Yellow") && accent != &highlightColor[0]){ accent = &highlightColor[0]; win.updateTheme(); rad->setSelection("Yellow"); combo->setSelection({"Yellow"}); }else if((rad->getSelection() == "Orange" || combo->getSelection().at(0) == "Orange") && accent != &highlightColor[1]){ accent = &highlightColor[1]; win.updateTheme(); rad->setSelection("Orange"); combo->setSelection({"Orange"}); }else if((rad->getSelection() == "Red" || combo->getSelection().at(0) == "Red") && accent != &highlightColor[2]){ accent = &highlightColor[2]; win.updateTheme(); rad->setSelection("Red"); combo->setSelection({"Red"}); }else if((rad->getSelection() == "Magenta" || combo->getSelection().at(0) == "Magenta") && accent != &highlightColor[3]){ accent = &highlightColor[3]; win.updateTheme(); rad->setSelection("Magenta"); combo->setSelection({"Magenta"}); }else if((rad->getSelection() == "Violet" || combo->getSelection().at(0) == "Violet") && accent != &highlightColor[4]){ accent = &highlightColor[4]; win.updateTheme(); rad->setSelection("Violet"); combo->setSelection({"Violet"}); }else if((rad->getSelection() == "Blue" || combo->getSelection().at(0) == "Blue") && accent != &highlightColor[5]){ accent = &highlightColor[5]; win.updateTheme(); rad->setSelection("Blue"); combo->setSelection({"Blue"}); }else if((rad->getSelection() == "Cyan" || combo->getSelection().at(0) == "Cyan") && accent != &highlightColor[6]){ accent = &highlightColor[6]; win.updateTheme(); rad->setSelection("Cyan"); combo->setSelection({"Cyan"}); }else if((rad->getSelection() == "Green" || combo->getSelection().at(0) == "Green") && accent != &highlightColor[7]){ accent = &highlightColor[7]; win.updateTheme(); rad->setSelection("Green"); combo->setSelection({"Green"}); } /*hide all controls*/ tex->setVisible(false); slider->setVisible(false); label->setVisible(false); rad->setVisible(false); combo->setVisible(false); darkToggle->setVisible(false); button->setVisible(false); /*show controls based on which CheckBoxes are selected*/ std::vector<std::string> selected = visibleControls->getSelection(); for(int i=0;i<selected.size();i++){ if(selected.at(i) == "Label"){ label->setVisible(true); }else if(selected.at(i) == "Slider"){ slider->setVisible(true); }else if(selected.at(i) == "Button"){ button->setVisible(true); }else if(selected.at(i) == "TextBox"){ tex->setVisible(true); }else if(selected.at(i) == "RadioButtonGroup"){ rad->setVisible(true); }else if(selected.at(i) == "ComboBox"){ combo->setVisible(true); }else if(selected.at(i) == "Toggle"){ darkToggle->setVisible(true); } } /*set the label text based on the value of the slider*/ std::ostringstream stream; stream << std::fixed; stream << std::setprecision(2); stream << sliderDouble; label->setText(stream.str()); /*draw all controls*/ win.drawControls(); /*post the current frame to the window*/ win.postFrame(); } /*stop the JUI backend*/ stop(); return 0; }
28.11157
123
0.637219
[ "vector" ]
caa403336dfc57c311bbdc87535db0821c6e7369
20,768
cpp
C++
Vocodec/Source/PluginEditor.cpp
spiricom/Vocodec_JUCE
4368c9bd7cfdead0ad898cebd6a8a7c8119d48a7
[ "MIT" ]
null
null
null
Vocodec/Source/PluginEditor.cpp
spiricom/Vocodec_JUCE
4368c9bd7cfdead0ad898cebd6a8a7c8119d48a7
[ "MIT" ]
9
2020-08-17T16:38:10.000Z
2020-09-03T17:23:32.000Z
Vocodec/Source/PluginEditor.cpp
spiricom/Vocodec_JUCE
4368c9bd7cfdead0ad898cebd6a8a7c8119d48a7
[ "MIT" ]
null
null
null
/* ============================================================================== This file was auto-generated! It contains the basic framework code for a JUCE plugin editor. ============================================================================== */ #include "PluginProcessor.h" #include "PluginEditor.h" #include "oled.h" #include "ui.h" #include <iostream> //============================================================================== VocodecAudioProcessorEditor::VocodecAudioProcessorEditor (VocodecAudioProcessor& p) : AudioProcessorEditor (&p), processor (p), constrain(new ComponentBoundsConstrainer()), resizer(new ResizableCornerComponent (this, constrain.get())), screen(p), chooser("Select a .wav file to load...", {}, "*.wav") { panel = Drawable::createFromImageData(BinaryData::panel_svg, BinaryData::panel_svgSize); setWantsKeyboardFocus(true); addAndMakeVisible(oversamplingMenu); oversamplingMenu.setLookAndFeel(&vocodecLAF); oversamplingMenu.addItem("1", 1); oversamplingMenu.addItem("2", 2); oversamplingMenu.addItem("4", 3); oversamplingMenu.addItem("8", 4); oversamplingMenu.addItem("16", 5); // oversamplingMenu.addItem("32", 6); // oversamplingMenu.addItem("64", 7); oversamplingMenu.setJustificationType(Justification::centred); oversamplingMenu.setSelectedId(1, dontSendNotification); oversamplingMenu.onChange = [this] { processor.oversamplingRatio = exp2(oversamplingMenu.getSelectedId()-1); }; Typeface::Ptr tp = Typeface::createSystemTypefaceFor(BinaryData::EuphemiaCAS_ttf, BinaryData::EuphemiaCAS_ttfSize); euphemia = Font(tp); euphemia.setItalic(true); oversamplingLabel.setText("OVERSAMPLING", dontSendNotification); oversamplingLabel.setFont(euphemia); oversamplingLabel.setJustificationType(Justification::centredTop); oversamplingLabel.setLookAndFeel(&vocodecLAF); addAndMakeVisible(oversamplingLabel); addAndMakeVisible(screen); screen.setOpaque(true); screen.onChange = [this] { presetChanged(); }; for (int i = 0; i < NUM_KNOBS; i++) { // knobs.add(new DrawableImage()); dials.add(new Slider()); addAndMakeVisible(dials[i]); // addAndMakeVisible(knobs[i]); dials[i]->setLookAndFeel(&vocodecLAF); dials[i]->setSliderStyle(Slider::RotaryHorizontalVerticalDrag); dials[i]->setTextBoxStyle(Slider::NoTextBox, false, 0, 0); dials[i]->addListener(this); dials[i]->setRange(0., 1.); dials[i]->setOpaque(true); dialLabels.add(new Label()); // dialLabels[i]->setMultiLine(true); // dialLabels[i]->setReadOnly(true); dialLabels[i]->setFont(euphemia); // dialLabels[i]->setInterceptsMouseClicks(false, false); dialLabels[i]->setJustificationType(Justification::centredTop); // dialLabels[i]->setBorder(BorderSize<int>(-3, 0, 0, 0)); dialLabels[i]->setLookAndFeel(&vocodecLAF); addAndMakeVisible(dialLabels[i]); } dials[0]->setRange(0., 4.); dials[0]->setSkewFactorFromMidPoint(1.0f); dials[0]->setDoubleClickReturnValue(true, 1.0f); dialLabels[0]->setJustificationType(Justification::topLeft); dialLabels[0]->setText("INPUT\nGAIN", dontSendNotification); dialLabels[4]->setJustificationType(Justification::topRight); gainLabel.setText(String(processor.inputGain->get(), 2, false), dontSendNotification); addAndMakeVisible(gainLabel); Path path; path.addEllipse(0, 0, 30, 30); for (int i = 0; i < NUM_BUTTONS; i++) { buttons.add(new VocodecButton("", Colours::white, Colours::grey.brighter(), Colours::darkgrey)); buttons[i]->setShape(path, true, true, true); addAndMakeVisible(buttons[i]); buttons[i]->addListener(this); buttons[i]->setOpaque(true); } buttons[0]->setClickingTogglesState(true); for (int i = 0; i < (int) vocodec::VocodecLightNil; i++) { lights.add(new VocodecLight("", darkergrey, cLightColours[i])); addAndMakeVisible(lights[i]); lights[i]->setOpaque(true); } processor.vcd.lightStates[vocodec::VocodecLightIn1Meter] = true; processor.vcd.lightStates[vocodec::VocodecLightIn2Meter] = true; processor.vcd.lightStates[vocodec::VocodecLightOut1Meter] = true; processor.vcd.lightStates[vocodec::VocodecLightOut2Meter] = true; setSize(600 * processor.editorScale, 716 * processor.editorScale); constrain->setFixedAspectRatio(600.0f / 716.0f); addAndMakeVisible(*resizer); resizer->setAlwaysOnTop(true); versionLabel.setText("v" + String(ProjectInfo::versionString), dontSendNotification); versionLabel.setColour(Label::ColourIds::textColourId, Colours::lightgrey); addAndMakeVisible(versionLabel); vocodec::OLED_writePreset(&processor.vcd); currentKnobPreset = processor.vcd.currentPreset; startTimerHz(30); } VocodecAudioProcessorEditor::~VocodecAudioProcessorEditor() { for (int i = 0; i < NUM_KNOBS; i++) { dials[i]->setLookAndFeel(nullptr); dialLabels[i]->setLookAndFeel(nullptr); } oversamplingMenu.setLookAndFeel(nullptr); oversamplingLabel.setLookAndFeel(nullptr); } //============================================================================== void VocodecAudioProcessorEditor::paint (Graphics& g) { // (Our component is opaque, so we must completely fill the background with a solid colour) g.setGradientFill(ColourGradient(Colour(25, 25, 25), juce::Point<float>(0,0), Colour(10, 10, 10), juce::Point<float>(0, getHeight()), false)); g.fillRect(0, 0, getWidth(), getHeight()); Rectangle<float> panelArea = getLocalBounds().toFloat(); panelArea.reduce(getWidth()*0.025f, getHeight()*0.01f); panelArea.removeFromBottom(getHeight()*0.03f); panel->drawWithin(g, panelArea, RectanglePlacement::centred, 1.0f); g.fillRect(getWidth() * 0.25f, getHeight() * 0.25f, getWidth() * 0.6f, getHeight() * 0.5f); g.fillRect(getWidth() * 0.25f, getHeight() * 0.75f, getWidth() * 0.2f, getHeight() * 0.15f); } void VocodecAudioProcessorEditor::resized() { int width = getWidth(); int height = getHeight(); screen.setBounds(width*0.347f, height*0.096f, width*0.306f, height*0.105f); float s = width / 600.0f; processor.editorScale = s; const float buttonSize = 24.0f*s; const float knobSize = 57.0f*s; const float bigLightSize = 23.0f*s; const float smallLightSize = 15.0f*s; const float labelWidth = 130.0f*s; const float labelHeight = 20.0f*s; oversamplingMenu.setBounds(378*s, 621*s, 72.0f*s, 24.0f*s); oversamplingLabel.setBounds(332*s, 656*s, 164.0f*s, 50.0f*s); oversamplingLabel.setFont(euphemia.withHeight(height * 0.025f)); buttons[vocodec::ButtonA] ->setBounds(543*s, 356*s, buttonSize, buttonSize); buttons[vocodec::ButtonB] ->setBounds(543*s, 415*s, buttonSize, buttonSize); buttons[vocodec::ButtonC] ->setBounds(303*s, 526*s, buttonSize, buttonSize); buttons[vocodec::ButtonD] ->setBounds(184*s, 621*s, buttonSize, buttonSize); buttons[vocodec::ButtonE] ->setBounds(241*s, 621*s, buttonSize, buttonSize); buttons[vocodec::ButtonEdit] ->setBounds(422*s, 91*s, buttonSize, buttonSize); buttons[vocodec::ButtonLeft] ->setBounds(441*s, 145*s, buttonSize, buttonSize); buttons[vocodec::ButtonRight] ->setBounds(531*s, 145*s, buttonSize, buttonSize); buttons[vocodec::ButtonUp] ->setBounds(485*s, 121*s, buttonSize, buttonSize); buttons[vocodec::ButtonDown] ->setBounds(485*s, 177*s, buttonSize, buttonSize); lights[vocodec::VocodecLightUSB] ->setBounds(493*s, 252*s, bigLightSize); lights[vocodec::VocodecLight1] ->setBounds(502*s, 296*s, bigLightSize); lights[vocodec::VocodecLight2] ->setBounds(539*s, 296*s, bigLightSize); lights[vocodec::VocodecLightA] ->setBounds(510*s, 356*s, bigLightSize); lights[vocodec::VocodecLightB] ->setBounds(510*s, 415*s, bigLightSize); lights[vocodec::VocodecLightC] ->setBounds(303*s, 493*s, bigLightSize); lights[vocodec::VocodecLightEdit] ->setBounds(422*s, 50*s, bigLightSize); lights[vocodec::VocodecLightIn1Meter] ->setBounds(25*s, 398*s, smallLightSize); lights[vocodec::VocodecLightIn1Clip] ->setBounds(45*s, 398*s, smallLightSize); lights[vocodec::VocodecLightIn2Meter] ->setBounds(25*s, 530*s, smallLightSize); lights[vocodec::VocodecLightIn2Clip] ->setBounds(45*s, 530*s, smallLightSize); lights[vocodec::VocodecLightOut1Meter] ->setBounds(538*s, 620*s, smallLightSize); lights[vocodec::VocodecLightOut1Clip] ->setBounds(558*s, 620*s, smallLightSize); lights[vocodec::VocodecLightOut2Meter] ->setBounds(538*s, 503*s, smallLightSize); lights[vocodec::VocodecLightOut2Clip] ->setBounds(558*s, 503*s, smallLightSize); dials[0] ->setBounds(85*s, 60*s, knobSize, knobSize); dials[1] ->setBounds(175*s, 205*s, knobSize, knobSize); dials[2] ->setBounds(385*s, 205*s, knobSize, knobSize); dials[3] ->setBounds(250*s, 345*s, knobSize, knobSize); dials[4] ->setBounds(445*s, 345*s, knobSize, knobSize); dials[5] ->setBounds(175*s, 500*s, knobSize, knobSize); dials[6] ->setBounds(380*s, 500*s, knobSize, knobSize); dialLabels[0] ->setBounds(40*s, 110*s, 100*s, 50*s); // dialLabels[1] ->setBounds(138*s, 185*s, labelWidth, labelHeight); // dialLabels[2] ->setBounds(348*s, 185*s, labelWidth, labelHeight); // dialLabels[3] ->setBounds(213*s, 325*s, labelWidth, labelHeight); // dialLabels[4] ->setBounds(408*s, 325*s, labelWidth, labelHeight); // dialLabels[5] ->setBounds(138*s, 480*s, labelWidth, labelHeight); // dialLabels[6] ->setBounds(343*s, 480*s, labelWidth, labelHeight); dialLabels[1] ->setBounds(138*s, 270*s, labelWidth, labelHeight); dialLabels[2] ->setBounds(348*s, 270*s, labelWidth, labelHeight); dialLabels[3] ->setBounds(213*s, 410*s, labelWidth, labelHeight); dialLabels[4] ->setBounds(373*s, 410*s, labelWidth, labelHeight); dialLabels[5] ->setBounds(138*s, 570*s, labelWidth, labelHeight); dialLabels[6] ->setBounds(343*s, 570*s, labelWidth, labelHeight); for (auto label : dialLabels) label->setFont(euphemia.withHeight(height * 0.027f)); gainLabel.setBounds(95*s, 120*s, 80*s, 25*s); gainLabel.setFont(euphemia.withHeight(height * 0.025f)); versionLabel.setBounds(0, height * 0.97f, width * 0.2f, height * 0.03f); versionLabel.setFont(euphemia.withHeight(height * 0.025f)); float r = 600.0f / 716.0f; constrain->setSizeLimits(200, 200/r, 800*r, 800); resizer->setBounds(getWidth()-16, getHeight()-16, 16, 16); } void VocodecAudioProcessorEditor::sliderValueChanged(Slider* slider) { if (slider == nullptr) return; float sliderValue; sliderValue = slider->getValue(); int whichKnob = dials.indexOf(slider) - 1; if (whichKnob < 0) { *processor.inputGain = sliderValue; return; } // Set ADC_values so that we can take advantage of hardware UI internals (*processor.vcd.ADC_values)[whichKnob] = (uint16_t) (sliderValue * TWO_TO_10) << 6; sliderActive[whichKnob] = true; if (whichKnob == 5) { *processor.dryWetMix = sliderValue; } else { int whichParam = (processor.vcd.knobPage * KNOB_PAGE_SIZE) + whichKnob; processor.vcd.presetKnobValues[processor.vcd.currentPreset][whichParam] = sliderValue; int paramId = (processor.vcd.currentPreset * NUM_PRESET_KNOB_VALUES) + whichParam; if (processor.pluginParams.contains(paramId)) *processor.pluginParams[paramId] = sliderValue; } } void VocodecAudioProcessorEditor::buttonClicked(Button*button) { } void VocodecAudioProcessorEditor::buttonStateChanged(Button *button) { if (button == nullptr) return; // Set the button values to be checked in the audio frame (same as hardware Vocodec) int whichButton = buttons.indexOf(static_cast<VocodecButton*>(button)); if (whichButton == 0) // The edit button, do toggle behavior { processor.vcd.buttonValues[whichButton] = button->getToggleState(); } else if (button->getState() == Button::ButtonState::buttonDown) { processor.vcd.buttonValues[whichButton] = 1; } else processor.vcd.buttonValues[whichButton] = 0; } void VocodecAudioProcessorEditor::presetChanged() { processor.vcd.loadingPreset = 1; int id = screen.getMenu()->getSelectedId(); processor.vcd.currentPreset = vocodec::VocodecPresetType(id > 0 ? id - 1 : 0); processor.vcd.knobPage = 0; vocodec::OLED_writePreset(&processor.vcd); vocodec::clearButtonActions(&processor.vcd); } void VocodecAudioProcessorEditor::timerCallback() { screen.getMenu()->setSelectedId(processor.vcd.currentPreset + 1, dontSendNotification); oversamplingMenu.setSelectedId(log2(processor.oversamplingRatio)+1); processor.vcd.lightStates[vocodec::VocodecLightIn1Clip] = processor.audioInput[0] >= 0.999f; processor.vcd.lightStates[vocodec::VocodecLightIn2Clip] = processor.audioInput[1] >= 0.999f; processor.vcd.lightStates[vocodec::VocodecLightOut1Clip] = processor.audioOutput[0] >= 0.999f; processor.vcd.lightStates[vocodec::VocodecLightOut2Clip] = processor.audioOutput[1] >= 0.999f; for (int i = 0; i < vocodec::VocodecLightNil; i++) { lights[i]->setState(processor.vcd.lightStates[i]); } float b = atodb(processor.audioInput[0]); b = LEAF_clip(MIN_METER_VOL, b, 0.0f); b = (b - MIN_METER_VOL) * -INV_MIN_METER_VOL; lights[vocodec::VocodecLightIn1Meter]->setBrightness(b); b = atodb(processor.audioInput[1]); b = LEAF_clip(MIN_METER_VOL, b, 0.0f); b = (b - MIN_METER_VOL) * -INV_MIN_METER_VOL; lights[vocodec::VocodecLightIn2Meter]->setBrightness(b); b = atodb(processor.audioOutput[0]); b = LEAF_clip(MIN_METER_VOL, b, 0.0f); b = (b - MIN_METER_VOL) * -INV_MIN_METER_VOL; lights[vocodec::VocodecLightOut1Meter]->setBrightness(b); b = atodb(processor.audioOutput[1]); b = LEAF_clip(MIN_METER_VOL, b, 0.0f); b = (b - MIN_METER_VOL) * -INV_MIN_METER_VOL; lights[vocodec::VocodecLightOut2Meter]->setBrightness(b); updateKnobs(); if (currentKnobPreset != processor.vcd.currentPreset) { for (int i = 0; i < NUM_ADC_CHANNELS; i++) sliderActive[i] = false; currentKnobPreset = processor.vcd.currentPreset; } for (int i = 0; i < NUM_ADC_CHANNELS; i++) { if (sliderActive[i]) { // Set ADC_values so that we can take advantage of hardware UI internals (*processor.vcd.ADC_values)[i] = (uint16_t) (dials[i+1]->getValue() * TWO_TO_10) << 6; } if (i < 5) { int whichParam = (processor.vcd.knobPage * KNOB_PAGE_SIZE) + i; int paramId = (processor.vcd.currentPreset * NUM_PRESET_KNOB_VALUES) + whichParam; if (processor.pluginParams.contains(paramId)) { String name = processor.pluginParams[paramId]->getName(50).fromFirstOccurrenceOf("_", false, false).replace("_", " "); dialLabels[i+1]->setText(name, dontSendNotification); } else dialLabels[i+1]->setText("", dontSendNotification); } } gainLabel.setText(String(processor.inputGain->get(), 2, false), dontSendNotification); screen.timerCallback(); if (processor.vcd.attemptFileLoad) { processor.vcd.attemptFileLoad = 0; loadWav(); } } void VocodecAudioProcessorEditor::updateKnobs() { for (int i = 1; i < NUM_KNOBS - 1; ++i) { int whichParam = (processor.vcd.knobPage * KNOB_PAGE_SIZE) + (i - 1); int paramId = (processor.vcd.currentPreset * NUM_PRESET_KNOB_VALUES) + whichParam; if (processor.pluginParams.contains(paramId)) { dials[i]->setAlpha(1.0f); dials[i]->setEnabled(true); if (dials[i]->getValue() != processor.pluginParams[paramId]->get()) dials[i]->setValue(processor.pluginParams[paramId]->get(), dontSendNotification); } else { dials[i]->setAlpha(0.4f); dials[i]->setEnabled(false); } } if (dials[0]->getValue() != processor.inputGain->get()) dials[0]->setValue(processor.inputGain->get(), dontSendNotification); if (dials[6]->getValue() != processor.dryWetMix->get()) dials[6]->setValue(processor.dryWetMix->get(), dontSendNotification); } void VocodecAudioProcessorEditor::loadWav() { chooser.launchAsync (FileBrowserComponent::canSelectMultipleItems | FileBrowserComponent::openMode | FileBrowserComponent::canSelectFiles, [this] (const FileChooser& chooser) { int idx = processor.vcd.wavetableSynthParams.loadIndex; auto results = chooser.getResults(); int n = 0; for (auto result : results) { auto* reader = processor.formatManager.createReaderFor (result); if (reader != nullptr) { std::unique_ptr<juce::AudioFormatReaderSource> newSource (new juce::AudioFormatReaderSource (reader, true)); AudioBuffer<float> buffer = AudioBuffer<float>(reader->numChannels, int(reader->lengthInSamples)); reader->read(&buffer, 0, buffer.getNumSamples(), 0, true, true); if (processor.vcd.loadedTableSizes[idx] > 0) { mpool_free((char*)processor.vcd.loadedTables[idx], processor.vcd.largePool); } processor.vcd.loadedTables[idx] = (float*) mpool_alloc(sizeof(float) * buffer.getNumSamples(), processor.vcd.largePool); processor.vcd.loadedTableSizes[idx] = buffer.getNumSamples(); for (int i = 0; i < processor.vcd.loadedTableSizes[idx]; ++i) { processor.vcd.loadedTables[idx][i] = buffer.getSample(0, i); } processor.readerSource.reset(newSource.release()); processor.wavetablePaths.set(idx, result.getFullPathName()); processor.vcd.loadedFilePaths[idx] = (char*) processor.wavetablePaths[idx].toRawUTF8(); } idx++; n++; if (idx >= 4) idx = 0; // Only load the first 4 files if (n >= 4) break; } processor.vcd.newWavLoaded = 1; }); } namespace vocodec { void setLED_A(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLightA] = (bool) onOFF; } void setLED_B(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLightB] = (bool) onOFF; } void setLED_C(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLightC] = (bool) onOFF; } void setLED_1(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLight1] = (bool) onOFF; } void setLED_2(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLight2] = (bool) onOFF; } void setLED_Edit(Vocodec* vcd, int onOFF) { vcd->lightStates[VocodecLightEdit] = (bool) onOFF; } void OLED_draw(Vocodec* vcd) { ; } }
43.630252
147
0.607088
[ "solid" ]
caa4fb65798e42e2c6e07088605e2d230a73d7a5
503
cpp
C++
Dataset/Leetcode/train/75/488.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/75/488.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/train/75/488.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: void XXX(vector<int>& nums) { for(int i = 0, n = 0; n < nums.size(); n++, i++) { if(nums[i] == 0) { nums.insert(nums.begin(), nums[i]); nums.erase(nums.begin() + i + 1); } if(nums[i] == 2) { nums.insert(nums.end(), nums[i]); nums.erase(nums.begin() + i); i = i - 1; } } return ; } };
22.863636
56
0.337972
[ "vector" ]
caa5e50f497876235a0ca027ec4021e6a5567663
22,090
cpp
C++
WarningList old versions/WarningList 0.4.9/WarningList 0.4.9.cpp
AMProgramms/Test2
82a0fc370c13c4b941214a7db747c7e2624e0837
[ "Apache-2.0" ]
2
2021-05-29T18:47:00.000Z
2021-05-29T18:47:07.000Z
WarningList old versions/WarningList 0.4.9/WarningList 0.4.9.cpp
AMProgramsc/WarningList
82a0fc370c13c4b941214a7db747c7e2624e0837
[ "Apache-2.0" ]
null
null
null
WarningList old versions/WarningList 0.4.9/WarningList 0.4.9.cpp
AMProgramsc/WarningList
82a0fc370c13c4b941214a7db747c7e2624e0837
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <string> #include <Windows.h> #include <time.h> #include <conio.h> #include <vector> #include <fstream> #include "Translite.h" #pragma warning(disable : 4996); using namespace std; enum ConsoleColor { Black = 0, Blue = 1, Green = 2, Cyan = 3, Red = 4, Magneta = 5, Brown = 6, LightGray = 7, DarkGray = 8, LightBlue = 9, LightGreen = 10, LightCyan = 11, LightRed = 12, LightMagneta = 13, Yellow = 14, White = 15 }; void SetColor(int text, int bg) { HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hStdOut, (WORD)((bg << 4) | text)); } enum class score { two = 2, three, four, five }; void intro(string logo,string f,int cF,int cW) { SetColor(cF,cW); system("mode con cols=140 lines=31"); fstream lg; lg.open(logo, fstream::in | fstream::out | fstream::app); while (!lg.eof()) { getline(lg, f); cout << f << endl; } } void Transelete(int h) { if (h == 1) { Translite(); } } void BackEvent(int d,string f,string g,int CF,int CW) { cout << "<------" << endl; cout << "1) Back" << endl; cin >> d; if (d == 1) { system("cls"); intro(f,g,CF,CW); } else { cin >> d; } } class User //User Information { public: User(string g, int y,string jh) : name(g) , ID(y) , family(jh) { } void SetID(int id) { this->ID = id; } int GetID() { return ID; } private: int ID; string name; string family; }; int main() { string bd = "BD.txt"; string logos = "Logo.txt"; string info = "Information.txt"; string options = "Options.txt"; string files = "Files.txt"; fstream fs; fstream fe; fstream le; fstream ne; fstream me; fstream ke; string str,msg,ftr,ltr,ntr,mtr,ktr; char ch,ce; string ster,sty; srand(time(NULL)); int totalScore, totalResult, CorrectResult; int y = 0,x,selectdata,savedata,loaddata,save = 0,i = 0, deletedata , e = 0; bool exit = false; string name, family; string newname, addname; const int size = 10; int colorW = 0, colorF = 7; int arrx = 0; int correct; int hit, hit2; int fix; int Delete,deletef; int enter1 = 0, enter2, enter3 = 0 ,enter4 , enter5 = 0,enter6 = 0,enter7 = 0; double warning = 0; double Count = 0; // Сумма оценок полученная вводом double result; // Общий результат(средний балл) vector<string> data = {""}; vector<string> mylist = { "Match: ", "Rus.Iaz: ", "Physics: ", "History: ","Eng.Iaz: ","Chemistry: ","Literature: ","Socialscience: ","Biology: ","Geography: ","LSF: ","PE: ","PD: ","Informatics: " }; vector<double> ryr = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0 }; int id = (rand() % 10000); intro(logos,ftr,colorF,colorW); fs.open(bd, fstream::in | fstream::out | fstream::app); cin >> enter1; while (enter1 != 1) { if (enter1 == 2) { cout << "Exit..." << endl; return 0; } else if (enter1 == 3) { system("cls"); le.open(options, fstream::in | fstream::out | fstream::app); while (!le.eof()) { getline(le, ltr); cout << ltr << endl; } cin >> enter4; if (enter4 == 1) { Transelete(enter4); } else if (enter4 == 2) { cout << "Select window color: " << endl; SetColor(8, colorW); cout << "0.Black" << endl; SetColor(1, colorW); cout << "1.Blue" << endl; SetColor(2, colorW); cout << "2.Green" << endl; SetColor(3, colorW); cout << "3.Cyan" << endl; SetColor(4, colorW); cout << "4.Red" << endl; SetColor(5, colorW); cout << "5.Magneta" << endl; SetColor(6, colorW); cout << "6.Brown" << endl; SetColor(7, colorW); cout << "7.LightGray" << endl; SetColor(8, colorW); cout << "8.DarkGray" << endl; SetColor(9, colorW); cout << "9.LightBlue" << endl; SetColor(10, colorW); cout << "10.LightGreen" << endl; SetColor(11, colorW); cout << "11.LightCyan" << endl; SetColor(12, colorW); cout << "12.LightRed" << endl; SetColor(13, colorW); cout << "13.LightMagneta" << endl; SetColor(14, colorW); cout << "14.Yellow" << endl; SetColor(15, colorW); cout << "15.White" << endl; SetColor(7, colorW); cin >> colorW; switch (colorW) { case 0: SetColor(colorF, 0); break; case 1: SetColor(colorF, 1); break; case 2: SetColor(colorF, 2); break; case 3: SetColor(colorF, 3); break; case 4: SetColor(colorF, 4); break; case 5: SetColor(colorF, 5); break; case 6: SetColor(colorF, 6); break; case 7: SetColor(colorF, 7); break; case 8: SetColor(colorF, 8); break; case 9: SetColor(colorF, 9); break; case 10: SetColor(colorF, 10); break; case 11: SetColor(colorF, 11); break; case 12: SetColor(colorF, 12); break; case 13: SetColor(colorF, 13); break; case 14: SetColor(colorF, 14); break; case 15: SetColor(colorF, 15); break; } if (colorF == colorW) { SetColor(7, 0); cout << "Error! Font color equal window color! " << endl; } BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; le.close(); } else if (enter4 == 3) { cout << "Select font color: " << endl; cout << "0.Black" << endl; SetColor(1, colorW); cout << "1.Blue" << endl; SetColor(2, colorW); cout << "2.Green" << endl; SetColor(3, colorW); cout << "3.Cyan" << endl; SetColor(4, colorW); cout << "4.Red" << endl; SetColor(5, colorW); cout << "5.Magneta" << endl; SetColor(6, colorW); cout << "6.Brown" << endl; SetColor(7, colorW); cout << "7.LightGray" << endl; SetColor(8, colorW); cout << "8.DarkGray" << endl; SetColor(9, colorW); cout << "9.LightBlue" << endl; SetColor(10, colorW); cout << "10.LightGreen" << endl; SetColor(11, colorW); cout << "11.LightCyan" << endl; SetColor(12, colorW); cout << "12.LightRed" << endl; SetColor(13, colorW); cout << "13.LightMagneta" << endl; SetColor(14, colorW); cout << "14.Yellow" << endl; SetColor(15, colorW); cout << "15.White" << endl; SetColor(7, colorW); cin >> colorF; switch (colorF) { case 0: SetColor(0, colorW); break; case 1: SetColor(1, colorW); break; case 2: SetColor(2, colorW); break; case 3: SetColor(3, colorW); break; case 4: SetColor(4, colorW); break; case 5: SetColor(5, colorW); break; case 6: SetColor(6, colorW); break; case 7: SetColor(7, colorW); break; case 8: SetColor(8, colorW); break; case 9: SetColor(9, colorW); break; case 10: SetColor(10, colorW); break; case 11: SetColor(11, colorW); break; case 12: SetColor(12, colorW); break; case 13: SetColor(13, colorW); break; case 14: SetColor(14, colorW); break; case 15: SetColor(15, colorW); break; } if (colorF == colorW) { SetColor(7, 0); cout << "Error! Font color equal window color! " << endl; } BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; le.close(); } } else if (enter1 == 4) { system("cls"); ne.open(info, fstream::in | fstream::out | fstream::app); while (!ne.eof()) { getline(ne, ntr); cout << ntr << endl; } cin >> enter2; switch (enter2) { case 1: cout << ".---------------------------------------------------." << endl; cout << "|Name - WarningList |" << endl; cout << "|Version - 0.4.9 Basic |" << endl; cout << "|id - 18062021 |" << endl; cout << "|Information: |" << endl; cout << "|Added - Set color for font and window |" << endl; cout << "|Updated - Russian version |" << endl; cout << "|*Note - Last version Basic |" << endl; cout << ".---------------------------------------------------." << endl; BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; ne.close(); break; case 2: cout << ".-----------------------------------------------------------." << endl; cout << "|Hello! My name Alexander! It's my three project. |" << endl; cout << "|You probably know me from two other projects, namely |" << endl; cout << "|RPG BASIC and Snake. I've been programmimg for 2 years now |" << endl; cout << "|and 3 mounts. My main classification is C++, C(Newble),and |" << endl; cout << "|C#(3 - 6 mounts). The development of the program is onging |" << endl; cout << "|to this day... |" << endl; cout << ".-----------------------------------------------------------." << endl; BackEvent(enter3,logos,ftr, colorF, colorW); cin >> enter1; ne.close(); break; case 3: cout << ".------------------------------------------------------." << endl; cout << "|WarningList - this is a program |" << endl; cout << "|that calculates your GPA by entering several values. |" << endl; cout << "|This program is very suitable for both schoolchildrens|" << endl; cout << "|and students |" << endl; cout << ".------------------------------------------------------." << endl; BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; ne.close(); break; default: cin >> enter2; ne.close(); break; } } else if (enter1 == 5) { system("cls"); me.open(files, fstream::in | fstream::out | fstream::app); while (!me.eof()) { getline(me, mtr); cout << mtr << endl; } cout << "Select further action with the file:" << endl; cout << "1) Load " << endl; cout << "2) Delete " << endl; cin >> deletef; if (deletef == 1) { while (fs.peek() == EOF) { cout << "File BD empty" << endl; fs.close(); BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; } while (!fs.eof()) { data[i] = (char*)malloc(sizeof(char) * size); fs >> data[i] >> ch; if (i > 0) { ster = ch + data[i]; data[i] = ster; } ce = ch; cout << data[i] << "\0" << endl; i++; if (i > 0) { data.push_back(""); } } cin >> loaddata; fe.open(data[loaddata]); while (fe.peek() == EOF) { cout << "File "<< data[i] << "empty or does not exist!" << endl; BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; } while (!fe.eof()) { msg = ""; getline(fe, msg); cout << msg << endl; } BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; fe.close(); fs.close(); me.close(); } else if (deletef == 2) { while (fs.peek() == EOF) { cout << "File BD empty" << endl; fs.close(); BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; } cout << "Change your savedata file for delete: " << endl; while (!fs.eof()) { data[i] = (char*)malloc(sizeof(char) * save); fs >> data[i] >> ch; if (i > 0) { str = ce + data[i]; data[i] = str; } ce = ch; cout << data[i] << endl; i++; if (i > 0) { data.push_back(""); } } cin >> deletedata; if (remove(data[deletedata].c_str()) != -1) { cout << "File " << data[deletedata] << " Deleted" << endl; data.erase(data.begin() + deletedata); fs.close(); if (remove(bd.c_str()) != -1) { fs.open(bd, fstream::in | fstream::out | fstream::app); for (; e < i; e++) { fs << data[e] << endl; } } } else { cout << "Error!" << endl; } fs.close(); BackEvent(enter3, logos, ftr, colorF, colorW); cin >> enter1; me.close(); } } } if (enter1 == 1) { system("cls"); cout << "\t\t\t\tLoading..." << endl; cout << "\t\t\t\t._________________________________________________." << endl; cout << "\t\t\t\t"; for (int f = 0; f < 50; f++) { SetColor(colorF, 15); cout << " "; SetColor(colorF, colorW); Sleep(100); } cout << endl; cout << "\t\t\t\t.-------------------------------------------------." << endl; system("cls"); } cout << "WarningList 0.4.9 BASIC" << endl; cout << ".__________________________." << endl; cout << "|Enter name student: "; cin >> name; cout << "|Enter Sername student: "; cin >> family; while (name == family) { cout << "Error! Name and Family equal!" << endl; cout << "|Enter name student: "; cin >> name; cout << "|Enter family student: "; cin >> family; } cout << "|Your ID: " << "#" << id << "|" << endl; cout << ".--------------------------." << endl; User user(name, id , family); Sleep(300); system("cls"); vector<int> d_syze = {}; // Количество вводимых оценок /*for (int i = 0; i < size; i++) { cout << arr[i] << endl; } */ cout << "Entering score subjects: " << endl; for (int c = 0; c < mylist.size(); c++) { cout << "._____________________________." << endl; cout << "|Your name: " << name << endl; cout << "|Your family: " << family << endl; cout << "|Your ID - " << id << endl; cout << "._____________________________." << endl; cout << "Do you fixed or add and delete element in list?" << endl; cout << "1)Yes" << endl; cout << "2)Delete " << endl; cout << "3)No" << endl; cin >> enter5; if (enter5 == 1) { while (exit != 1) { if (enter5 == 1) { cout << "Change element to fix or add element in list" << endl; cin >> fix; if (fix > mylist.size()) { cout << "Enter name added element: " << endl; cin >> addname; mylist.push_back(addname); ryr.push_back(0); } else { cout << "Enter new name element: " << endl; cin >> newname; mylist[fix] = newname; } } if (enter5 == 2) { cout << "Enter index for delete element: " << endl; cin >> Delete; while (Delete > mylist.size()) { SetColor(4, colorW); cout << ".________________________________." << endl; cout << "|Error! Index not found! |" << endl; cout << "|Please, enter the number again: |" << endl; cin >> Delete; cout << ".--------------------------------." << endl; SetColor(colorF, colorW); } mylist.erase(mylist.begin() + Delete); ryr.erase(ryr.begin() + Delete); } cout << "Exit?" << endl; cout << "1)Yes" << endl; cout << "0)No" << endl; cin >> exit; if (exit == 0) { cout << "1)Fix element" << endl; cout << "2)Delete " << endl; cout << "3)No" << endl; cin >> enter5; } } } cout << "._____________________________." << endl; for (int h = 0; h < mylist.size(); h++) { cout << "|" << mylist[h] << " = " << ryr[h] << "\t|" << endl; } cout << ".------------------------------" << endl; cout << "Enter element array: " << endl; cin >> x; cout << mylist[x] << endl; cout << "--------------------" << endl; cout << "|Enter quantity array: " << endl; cin >> arrx; d_syze.resize(arrx); while (arrx < 3) { SetColor(4, colorW); cout << ".________________________________." << endl; cout << "|Error! Your array is very low! |" << endl; cout << "|Please, enter the number again: |" << endl; cin >> arrx; cout << ".--------------------------------." << endl; SetColor(colorF, colorW); } cout << "--------------------" << endl; for (int i = 0;i < arrx; i++) { cout << "Enter score: " << endl; cin >> d_syze[i]; switch (d_syze[i]) { case 2: 2; break; case 3: 3; break; case 4: 4; break; case 5: 5; break; } while (d_syze[i] <= 1 || d_syze[i] > 5) { cout << "Error! Wrong number! " << endl; d_syze[i] = NULL; cin >> d_syze[i]; } Count += d_syze[i]; } cout << "Do you want correct result? " << endl; cout << "1) Yes " << endl; cout << "2) No " << endl; cin >> CorrectResult; if (CorrectResult == 1) { Count = NULL; for (int i = 0;i < arrx; i++) { cout << "Enter score: " << endl; cin >> d_syze[i]; switch (d_syze[i]) { case 2: 2; break; case 3: 3; break; case 4: 4; break; case 5: 5; break; } if (d_syze[i] == 1 || d_syze[i] > 5) { cout << "Error! Wrong number! " << endl; d_syze[i] = NULL; cin >> d_syze[i]; } Count += d_syze[i]; } } // Count = d_syze[0] + d_syze[1] + d_syze[2] + d_syze[3] + d_syze[4]; result = Count / arrx; ryr[x] = result; if (ryr[x] <= 2.5) { SetColor(4, colorW); cout << "Your middle score = " << result << endl; cout << "WARNING!!! Low-score! " << endl; for (; warning < 2.6; ) { warning = (Count + 3) / (arrx + 1); Count += 3; arrx += 1; cout << "You need: " << 3 << " for " << warning << endl; } warning = NULL; SetColor(colorF, colorW); getch(); } else if (ryr[x] <= 3.5) { SetColor(14, colorW); cout << "Your middle score = " << result << endl; cout << "Warning! Score equal 3!" << endl; for (; warning < 3.6; ) { warning = (Count + 4) / (arrx + 1); Count += 4; arrx += 1; cout << "You need: " << 4 << " for " << warning << endl; } warning = NULL; SetColor(colorF, colorW); getch(); } else if (ryr[x] <= 4.5) { SetColor(10, colorW); cout << "Your middle score = " << result << endl; cout << "Warning! Score equal 4!" << endl; for (; warning < 4.6; ) { warning = (Count + 5) / (arrx + 1); Count += 5; arrx += 1; cout << "You need: " << 5 << " for " << warning << endl; } warning = NULL; SetColor(colorF, colorW); getch(); } else { SetColor(3, colorW); cout << "Your middle score = " << result << endl; cout << "Total score is normal! ;) " << endl; SetColor(colorF, colorW); getch(); } exit = false; Count = NULL; system("cls"); } cout << endl; totalScore = ryr[0] + ryr[1] + ryr[2] + ryr[3] + ryr[4] + ryr[5] + ryr[6] + ryr[7] + ryr[8] + ryr[9] + ryr[10] + ryr[11] + ryr[12] + ryr[13]; // Общая сумма всех предметов totalResult = totalScore / 14; // Общий средний балл switch (totalResult) { case 2: SetColor(4, colorW); cout << "Your Total Score " << totalResult << endl; SetColor(colorF, colorW); break; case 3: SetColor(14, colorW); cout << "Your Total Score " << totalResult << endl; SetColor(colorF, colorW); break; case 4: SetColor(2, colorW); cout << "Your Total Score " << totalResult << endl; SetColor(colorF, colorW); break; case 5: SetColor(3, colorW); cout << "Your Total Score " << totalResult << endl; SetColor(colorF, colorW); break; } cout << "End Statistics: " << endl; cout << ".____________________________." << endl; cout << "|Your name: " << name << "\t|" << endl; cout << "|Your family: " << family << "\t|" << endl; cout << "|Your ID: " << user.GetID() << "\t|" << endl; cout << "|Your total score: " << totalResult << "\t|" << endl; cout << "|Your recomend: " << "\t|" << endl; cout << ".----------------------------." << endl; cout << "Save?: " << endl; cout << "1) Yes " << endl; cout << "2) No " << endl; cin >> savedata; if (savedata == 1) { cout << "Enter name your save: " << endl; cin >> sty; fs << sty << "\n"; fs.open(sty, fstream::in | fstream::out | fstream::app); fe.open(sty, fstream::in | fstream::out | fstream::app); try { cout << "File is open!" << endl; fs << sty << "\n"; } catch(exception er) { cout << "File is don't open " << endl; cout << er.what() << endl; } try { cout << "File is open!" << endl; fe << "End Statistics: " << endl; fe << ".____________________________." << endl; fe << "|Your name: " << name << "\t|" << endl; fe << "|Your family: " << family << "\t|" << endl; fe << "|Your ID: " << user.GetID() << "\t|" << endl; fe << "|Your total score: " << totalResult << "\t|" << endl; fe << "|Your recomend: " << "\t|" << endl; fe << ".----------------------------." << endl; fe << "._____________________________." << endl; for (int h = 0; h < mylist.size(); h++) { fe << "|" << mylist[h] << " = " << ryr[h] << "\t|" << endl; } fe << ".------------------------------" << endl; fe << "Version: " << "0.4.9 BASIC" << endl; fe << "Programm running time: " << clock() / 1000000.0 << "/sec" << endl; } catch(exception ses) { cout << "File is don't open " << endl; cout << ses.what() << endl; } fs.close(); fe.close(); } /*else { } */ return 0; } //(c)AMProgramms, 2021
23.13089
202
0.471752
[ "vector" ]
caa61c55e5650224de51e0fb004e9483168ec621
1,908
cpp
C++
example/convolve2d.cpp
Paul92/gil
da0655fb66dd161a643e1ca0ed51937548465d18
[ "BSL-1.0" ]
null
null
null
example/convolve2d.cpp
Paul92/gil
da0655fb66dd161a643e1ca0ed51937548465d18
[ "BSL-1.0" ]
null
null
null
example/convolve2d.cpp
Paul92/gil
da0655fb66dd161a643e1ca0ed51937548465d18
[ "BSL-1.0" ]
null
null
null
// // Copyright 2019 Miral Shah <miralshah2211@gmail.com> // Copyright 2019 Mateusz Loskot <mateusz at loskot dot net> // Copyright 2021 Pranam Lashkari <plashkari628@gmail.com> // // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <vector> #include <iostream> #include <boost/gil/image_processing/kernel.hpp> #include <boost/gil/image_processing/convolve.hpp> #include <boost/gil/extension/io/png.hpp> #include <boost/gil/extension/io/jpeg.hpp> using namespace boost::gil; using namespace std; // Convolves the image with a 2d kernel. // Note that the kernel can be fixed or resizable: // kernel_2d_fixed<float, N> k(elements, centre_y, centre_x) produces a fixed kernel // kernel_2d<float> k(elements, size, centre_y, centre_x) produces a resizable kernel // The size of the kernel matrix is deduced as the square root of the number of the elements (9 elements yield a 3x3 matrix) // See also: // convolution.cpp - Convolution with 2d kernels int main() { gray8_image_t img; read_image("src_view.png", img, png_tag{}); gray8_image_t img_out(img.dimensions()), img_out1(img.dimensions()); std::vector<float> v(9, 1.0f / 9.0f); detail::kernel_2d<float> kernel(v.begin(), v.size(), 1, 1); detail::convolve_2d(view(img), kernel, view(img_out1)); write_view("out-convolve2d.png", view(img_out1), png_tag{}); std::vector<float> v1(3, 1.0f / 3.0f); kernel_1d<float> kernel1(v1.begin(), v1.size(), 1); detail::convolve_1d<gray32f_pixel_t>(const_view(img), kernel1, view(img_out), boundary_option::extend_zero); write_view("out-convolve_option_extend_zero.png", view(img_out), png_tag{}); if (equal_pixels(view(img_out1), view(img_out))) cout << "convolve_option_extend_zero" << endl; return 0; }
34.690909
124
0.72327
[ "vector" ]
caa79782b6d0c16e908ee2d2e878566c53f83680
9,269
cpp
C++
review/Advanced_lighting/Parallax_Mapping/main.cpp
yuyuyu223/opengl-learning
c69679c1a42971d814eb3d4115caef63899ac463
[ "MulanPSL-1.0" ]
null
null
null
review/Advanced_lighting/Parallax_Mapping/main.cpp
yuyuyu223/opengl-learning
c69679c1a42971d814eb3d4115caef63899ac463
[ "MulanPSL-1.0" ]
null
null
null
review/Advanced_lighting/Parallax_Mapping/main.cpp
yuyuyu223/opengl-learning
c69679c1a42971d814eb3d4115caef63899ac463
[ "MulanPSL-1.0" ]
null
null
null
#include <glad/glad.h> #include <GLFW/glfw3.h> #include <cmath> #include <Texture.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <Camera.h> #include <Shader.h> float screenWidth = 800; float screenHeight = 600; //初始化相机 Camera *camera = new Camera(glm::vec3(0.0f, 0.0f, 3.0f), //相机位置 glm::vec3(0.0f, 0.0f, 0.0f), //观察位置 glm::vec3(0.0f, 1.0f, 0.0f)); //上向量 #include <EventListener.h> void renderQuad(); GLboolean parallax_mapping = true; GLfloat height_scale = 0.1; int main() { /* GLFW配置 */ ////////////////////////////////////////////////////////////////////////////// //初始化GLFW glfwInit(); //设置OpenGL版本为3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //使用OpenGL-core模式 glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_SAMPLES, 1920); //创建窗体指针,窗体大小800*600,标题LearnOpenGL GLFWwindow *window = glfwCreateWindow(screenWidth, screenHeight, "LearnOpenGL", NULL, NULL); //若创建窗体失败 if (window == NULL) { //打印错误信息 std::cout << "Failed to create GLFW window" << std::endl; //结束GLFW glfwTerminate(); return -1; } //通知GLFW将我们窗口的上下文设置为当前线程的主上下文 glfwMakeContextCurrent(window); //隐藏光标,并捕捉(Capture)它 glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); //设置回调函数,触发器为窗体 glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); //绑定鼠标回调 glfwSetCursorPosCallback(window, mouse_callback); //绑定滚动事件 glfwSetScrollCallback(window, scroll_callback); //传入GLFW的进程地址来初始化GLAD if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { //初始化失败报错 std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // 启用深度测试 glEnable(GL_DEPTH_TEST); // glEnable(GL_MULTISAMPLE); /////////////////////////////////////////////////////////////////////////////////// /* 着色器配置 */ /////////////////////////////////////////////////////////////////////////////////// Shader *shader = new Shader("../review/Advanced_lighting/Parallax_Mapping/parallax_mapping.vs", "../review/Advanced_lighting/Parallax_Mapping/parallax_mapping.frag"); /////////////////////////////////////////////////////////////////////////////////// // 木地板纹理 Texture *diffuseMap = new Texture("../texture/bricks2.jpg", GL_TEXTURE0); Texture *normalMap = new Texture("../texture/bricks2_normal.jpg", GL_TEXTURE1); Texture *heightMap = new Texture("../texture/bricks2_disp.jpg", GL_TEXTURE2); shader->setInt("diffuseMap",0); shader->setInt("normalMap",1); shader->setInt("depthMap",2); // 光照位置 glm::vec3 lightPos(0.5f, 1.0f, 0.3f); ////////////////////////////////////////////////////////////////////////////////// /* 渲染部分 */ /////////////////////////////////////////////////////////////////////////////////// // 渲染循环 while (!glfwWindowShouldClose(window)) { //检测键盘输入 processInput(window, camera, 0.05); //清除颜色缓冲之后,整个颜色缓冲都会被填充为glClearColor里所设置的颜色 glClearColor(0.1f, 0.1f, 0.1f, 1.0f); //清除颜色缓冲和深度缓冲 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Configure view/projection matrices shader->use(); glm::mat4 view = camera->get_view_matrix(); glm::mat4 projection = glm::perspective(camera->get_fov(), (GLfloat)screenWidth / (GLfloat)screenHeight, 0.1f, 100.0f); shader->setMat4("view",view); shader->setMat4("projection",projection); // Render normal-mapped quad glm::mat4 model; model = glm::rotate(model, (GLfloat)glfwGetTime() * -10, glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // Rotates the quad to show parallax mapping works in all directions shader->setMat4("model",model); shader->setVec3("lightPos", lightPos); shader->setVec3("viewPos", camera->get_camera_pos()); shader->setFloat("height_scale", height_scale); shader->setInt("parallax", parallax_mapping); diffuseMap->bind(); normalMap->bind(); heightMap->bind(); renderQuad(); // render light source (simply renders a smaller plane at the light's position for debugging/visualization) model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.1f)); shader->setMat4("model", model); renderQuad(); //交换缓冲 glfwSwapBuffers(window); //检查有没有触发什么事件(比如键盘输入、鼠标移动等)、更新窗口状态, //并调用对应的回调函数(可以通过回调方法手动设置) glfwPollEvents(); } ////////////////////////////////////////////////////////////////////////////////////// glfwTerminate(); return 0; } // RenderQuad() Renders a 1x1 quad in NDC GLuint quadVAO = 0; GLuint quadVBO; void renderQuad() { if (quadVAO == 0) { // positions glm::vec3 pos1(-1.0, 1.0, 0.0); glm::vec3 pos2(-1.0, -1.0, 0.0); glm::vec3 pos3(1.0, -1.0, 0.0); glm::vec3 pos4(1.0, 1.0, 0.0); // texture coordinates glm::vec2 uv1(0.0, 1.0); glm::vec2 uv2(0.0, 0.0); glm::vec2 uv3(1.0, 0.0); glm::vec2 uv4(1.0, 1.0); // normal vector glm::vec3 nm(0.0, 0.0, 1.0); // calculate tangent/bitangent vectors of both triangles glm::vec3 tangent1, bitangent1; glm::vec3 tangent2, bitangent2; // - triangle 1 glm::vec3 edge1 = pos2 - pos1; glm::vec3 edge2 = pos3 - pos1; glm::vec2 deltaUV1 = uv2 - uv1; glm::vec2 deltaUV2 = uv3 - uv1; GLfloat f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); tangent1.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x); tangent1.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y); tangent1.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z); tangent1 = glm::normalize(tangent1); bitangent1.x = f * (-deltaUV2.x * edge1.x + deltaUV1.x * edge2.x); bitangent1.y = f * (-deltaUV2.x * edge1.y + deltaUV1.x * edge2.y); bitangent1.z = f * (-deltaUV2.x * edge1.z + deltaUV1.x * edge2.z); bitangent1 = glm::normalize(bitangent1); // - triangle 2 edge1 = pos3 - pos1; edge2 = pos4 - pos1; deltaUV1 = uv3 - uv1; deltaUV2 = uv4 - uv1; f = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV2.x * deltaUV1.y); tangent2.x = f * (deltaUV2.y * edge1.x - deltaUV1.y * edge2.x); tangent2.y = f * (deltaUV2.y * edge1.y - deltaUV1.y * edge2.y); tangent2.z = f * (deltaUV2.y * edge1.z - deltaUV1.y * edge2.z); tangent2 = glm::normalize(tangent2); bitangent2.x = f * (-deltaUV2.x * edge1.x + deltaUV1.x * edge2.x); bitangent2.y = f * (-deltaUV2.x * edge1.y + deltaUV1.x * edge2.y); bitangent2.z = f * (-deltaUV2.x * edge1.z + deltaUV1.x * edge2.z); bitangent2 = glm::normalize(bitangent2); GLfloat quadVertices[] = { // Positions // normal // TexCoords // Tangent // Bitangent pos1.x, pos1.y, pos1.z, nm.x, nm.y, nm.z, uv1.x, uv1.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos2.x, pos2.y, pos2.z, nm.x, nm.y, nm.z, uv2.x, uv2.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos3.x, pos3.y, pos3.z, nm.x, nm.y, nm.z, uv3.x, uv3.y, tangent1.x, tangent1.y, tangent1.z, bitangent1.x, bitangent1.y, bitangent1.z, pos1.x, pos1.y, pos1.z, nm.x, nm.y, nm.z, uv1.x, uv1.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z, pos3.x, pos3.y, pos3.z, nm.x, nm.y, nm.z, uv3.x, uv3.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z, pos4.x, pos4.y, pos4.z, nm.x, nm.y, nm.z, uv4.x, uv4.y, tangent2.x, tangent2.y, tangent2.z, bitangent2.x, bitangent2.y, bitangent2.z }; // Setup plane VAO glGenVertexArrays(1, &quadVAO); glGenBuffers(1, &quadVBO); glBindVertexArray(quadVAO); glBindBuffer(GL_ARRAY_BUFFER, quadVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), &quadVertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat))); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat))); glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(8 * sizeof(GLfloat))); glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 14 * sizeof(GLfloat), (GLvoid*)(11 * sizeof(GLfloat))); } glBindVertexArray(quadVAO); glDrawArrays(GL_TRIANGLES, 0, 6); glBindVertexArray(0); }
38.945378
176
0.571475
[ "render", "vector", "model" ]
caabddd268462ec158a70bdc5d52dd8119dc4b3b
2,217
cpp
C++
nclgl/SceneNode.cpp
BertTDev/Graphics-Island
ce7c15cba8ad86df658c35b3bb37d63ef12bc985
[ "MIT" ]
null
null
null
nclgl/SceneNode.cpp
BertTDev/Graphics-Island
ce7c15cba8ad86df658c35b3bb37d63ef12bc985
[ "MIT" ]
null
null
null
nclgl/SceneNode.cpp
BertTDev/Graphics-Island
ce7c15cba8ad86df658c35b3bb37d63ef12bc985
[ "MIT" ]
null
null
null
#include "SceneNode.h" Shader* SceneNode::defaultShader = NULL; SceneNode::SceneNode(Mesh* mesh, Vector4 colour, Shader* s, Vector4 p) { this->mesh = mesh; this->colour = colour; if (s == NULL) { if (SceneNode::defaultShader == NULL) SceneNode::defaultShader = new Shader("SceneVertex.glsl", "SceneFragment.glsl"); s = SceneNode::defaultShader; } this->shader = s; this->waterPlane = p; progNum = shader->GetProgram(); parent = NULL; modelScale = Vector3(1, 1, 1); boundingRadius = 1.0f; distanceFromCamera = 0.0f; texture = 0; updateMats = true; updateLights = false; } SceneNode::~SceneNode(void) { for (unsigned int i = 0; i < children.size(); ++i) { delete children[i]; } } void SceneNode::SetUniforms(const OGLRenderer& r) { Matrix4 model = this->GetWorldTransform() * Matrix4::Scale(this->GetModelScale()); glUniformMatrix4fv(glGetUniformLocation(shader->GetProgram(), "modelMatrix"), 1, false, model.values); glUniform4fv(glGetUniformLocation(shader->GetProgram(), "nodeColour"), 1, (float*)& this->GetColour()); texture = this->GetTexture(); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glUniform1i(glGetUniformLocation(shader->GetProgram(), "useTexture"), 0); glUniform4fv(glGetUniformLocation(shader->GetProgram(), "plane"), 1, (float*)& waterPlane); } void SceneNode::AddChild(SceneNode* s) { children.push_back(s); s->parent = this; } void SceneNode::Draw(const OGLRenderer& r) { SetUniforms(r); if (mesh) mesh->Draw(); } void SceneNode::SetTextureRepeating(GLuint target, bool state) { glBindTexture(GL_TEXTURE_2D, target); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, state ? GL_REPEAT : GL_CLAMP); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, state ? GL_REPEAT : GL_CLAMP); glBindTexture(GL_TEXTURE_2D, 0); } void SceneNode::SetAllPlanes(Vector4 p) { this->waterPlane = p; for (vector<SceneNode*>::iterator i = children.begin(); i != children.end(); ++i) { (*i)->SetAllPlanes(p); } } void SceneNode::Update(float dt) { if (parent) worldTransform = parent->worldTransform * transform; else worldTransform = transform; for (vector<SceneNode*>::iterator i = children.begin(); i != children.end(); ++i) (*i)->Update(dt); }
33.590909
121
0.717636
[ "mesh", "vector", "model", "transform" ]
caac680ae4f07e681c4e28127a0797a102562744
3,526
hpp
C++
PSME/common/agent-framework/include/agent-framework/command-ref/pnc_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
5
2021-10-07T15:36:37.000Z
2022-03-01T07:21:49.000Z
PSME/common/agent-framework/include/agent-framework/command-ref/pnc_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
null
null
null
PSME/common/agent-framework/include/agent-framework/command-ref/pnc_commands.hpp
opencomputeproject/HWMgmt-DeviceMgr-PSME
2a00188aab6f4bef3776987f0842ef8a8ea972ac
[ "Apache-2.0" ]
1
2022-03-01T07:21:51.000Z
2022-03-01T07:21:51.000Z
/*! * @section LICENSE * * @copyright * Copyright (c) 2016-2017 Intel Corporation * * @copyright * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @section DESCRIPTION * * @file pnc_commands.cpp * * @brief Declarations of all pnc commands * */ #pragma once #include "agent-framework/command-ref/command.hpp" #include "agent-framework/module/model/model_pnc.hpp" #include "agent-framework/module/requests/common.hpp" #include "agent-framework/module/requests/pnc.hpp" #include "agent-framework/module/responses/common.hpp" #include "agent-framework/module/responses/pnc.hpp" namespace agent_framework { namespace command_ref { // declarations of get collection methods using GetCollection = Command<model::requests::GetCollection, model::attribute::Array<model::attribute::SubcomponentEntry>>; using GetManagersCollection = Command<model::requests::GetManagersCollection, model::attribute::Array<model::attribute::ManagerEntry>>; using GetTasksCollection = Command<model::requests::GetTasksCollection, model::attribute::Array<model::attribute::TaskEntry>>; // declarations of all get info methods using GetChassisInfo = Command<model::requests::GetChassisInfo, model::Chassis>; using GetDriveInfo = Command<model::requests::GetDriveInfo, model::Drive>; using GetManagerInfo = Command<model::requests::GetManagerInfo, model::Manager>; using GetSystemInfo = Command<model::requests::GetSystemInfo, model::System>; using GetStorageSubsystemInfo = Command<model::requests::GetStorageSubsystemInfo, model::StorageSubsystem>; using GetFabricInfo = Command<model::requests::GetFabricInfo, model::Fabric>; using GetPcieDeviceInfo = Command<model::requests::GetPcieDeviceInfo, model::PcieDevice>; using GetPcieFunctionInfo = Command<model::requests::GetPcieFunctionInfo, model::PcieFunction>; using GetEndpointInfo = Command<model::requests::GetEndpointInfo, model::Endpoint>; using GetPortInfo = Command<model::requests::GetPortInfo, model::Port>; using GetSwitchInfo = Command<model::requests::GetSwitchInfo, model::Switch>; using GetZoneInfo = Command<model::requests::GetZoneInfo, model::Zone>; using GetTaskInfo = Command<model::requests::GetTaskInfo, model::Task>; using GetTaskResultInfo = Command<model::requests::GetTaskResultInfo, model::responses::GetTaskResultInfo>; // declarations of all add methods using AddZone = Command<model::requests::AddZone, model::responses::AddZone>; using AddZoneEndpoint = Command<model::requests::AddZoneEndpoint, model::responses::AddZoneEndpoint>; // declarations of all delete methods using DeleteZone = Command<model::requests::DeleteZone, model::responses::DeleteZone>; using DeleteZoneEndpoint = Command<model::requests::DeleteZoneEndpoint, model::responses::DeleteZoneEndpoint>; using DeleteTask = Command<model::requests::DeleteTask, model::responses::DeleteTask>; // declarations of all set methods using SetComponentAttributes = Command<model::requests::SetComponentAttributes, model::responses::SetComponentAttributes>; } }
47.013333
135
0.786444
[ "model" ]
caaff2b0c301b0b83eca8ace12bbb7411f13c742
3,910
cpp
C++
MP-APS/Camera.cpp
htmlboss/OpenGL-Shader-Viewer
9a6c5fbeb10a45303198cb1918a549ab90de0a6c
[ "MIT" ]
235
2017-06-27T18:38:41.000Z
2022-03-31T09:42:38.000Z
MP-APS/Camera.cpp
MaximumProgrammer/OpenGL-Renderer
018211ff3bd559d6912784d3dfdec97f03838e35
[ "MIT" ]
10
2017-01-17T14:57:25.000Z
2021-12-04T04:01:26.000Z
MP-APS/Camera.cpp
htmlboss/OpenGL-Shader-Viewer
9a6c5fbeb10a45303198cb1918a549ab90de0a6c
[ "MIT" ]
17
2017-04-30T11:37:26.000Z
2022-03-15T03:23:21.000Z
#include "Camera.h" #include "Input.h" #include <GLFW/glfw3.h> /***********************************************************************************/ Camera::Camera() noexcept { updateVectors(); } /***********************************************************************************/ void Camera::SetNear(const float near) { m_near = near; } /***********************************************************************************/ void Camera::SetFar(const float far) { m_far = far; } /***********************************************************************************/ void Camera::SetSpeed(const float speed) { m_speed = speed; } /***********************************************************************************/ void Camera::Update(const double deltaTime) { if (Input::GetInstance().IsKeyPressed(GLFW_KEY_TAB)) { m_dirty = !m_dirty; } if (m_dirty) { // Update view from mouse movement updateView(); // Update Keyboard if (Input::GetInstance().IsKeyHeld(GLFW_KEY_W)) { processKeyboard(Direction::FORWARD, deltaTime); } if (Input::GetInstance().IsKeyHeld(GLFW_KEY_S)) { processKeyboard(Direction::BACKWARD, deltaTime); } if (Input::GetInstance().IsKeyHeld(GLFW_KEY_A)) { processKeyboard(Direction::LEFT, deltaTime); } if (Input::GetInstance().IsKeyHeld(GLFW_KEY_D)) { processKeyboard(Direction::RIGHT, deltaTime); } if (Input::GetInstance().IsKeyHeld(GLFW_KEY_SPACE)) { processKeyboard(Direction::UP, deltaTime); } if (Input::GetInstance().IsKeyHeld(GLFW_KEY_LEFT_CONTROL)) { processKeyboard(Direction::DOWN, deltaTime); } } } /***********************************************************************************/ void Camera::processKeyboard(const Direction direction, const double deltaTime) noexcept { const float velocity = m_speed * static_cast<float>(deltaTime); switch (direction) { case Direction::FORWARD: m_position += m_front * velocity; break; case Direction::BACKWARD: m_position -= m_front * velocity; break; case Direction::LEFT: m_position -= m_right * velocity; break; case Direction::RIGHT: m_position += m_right * velocity; break; case Direction::UP: m_position += m_worldUp * velocity; break; case Direction::DOWN: m_position -= m_worldUp * velocity; break; } } /***********************************************************************************/ void Camera::updateView(const bool constrainPitch /*= true*/) { // If the mouse position has changed, recalculate vectors if (Input::GetInstance().MouseMoved()) { const auto xPos = Input::GetInstance().GetMouseX(); const auto yPos = Input::GetInstance().GetMouseY(); if (m_firstMouse) { m_prevX = xPos; m_prevY = yPos; m_firstMouse = false; } const auto xOffset = (xPos - m_prevX) * m_sensitivity; const auto yOffset = (m_prevY - yPos) * m_sensitivity; // Reversed since y-coordinates go from bottom to top m_prevX = xPos; m_prevY = yPos; m_yaw += xOffset; m_pitch += yOffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (m_pitch > 89.0) { m_pitch = 89.0; } if (m_pitch < -89.0) { m_pitch = -89.0; } } // Update Front, Right and Up Vectors using the updated Eular angles updateVectors(); } } /***********************************************************************************/ void Camera::updateVectors() { // Calculate the new Front vector glm::vec3 front{ front.x = glm::cos(glm::radians(m_yaw)) * glm::cos(glm::radians(m_pitch)), front.y = glm::sin(glm::radians(m_pitch)), front.z = glm::sin(glm::radians(m_yaw)) * glm::cos(glm::radians(m_pitch)) }; m_front = glm::normalize(front); m_right = glm::normalize(glm::cross(m_front, m_worldUp)); // Normalize the vectors, because their length gets closer to 0 the more you look up or down which results in slower movement. m_up = glm::normalize(glm::cross(m_right, m_front)); }
32.583333
185
0.574936
[ "vector" ]
cab18f9598c5058cd3eef49aac154af0c3a317f7
716
cpp
C++
code/477.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
23
2020-03-30T05:44:56.000Z
2021-09-04T16:00:57.000Z
code/477.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
1
2020-05-10T15:04:05.000Z
2020-06-14T01:21:44.000Z
code/477.cpp
Nightwish-cn/my_leetcode
40f206e346f3f734fb28f52b9cde0e0041436973
[ "MIT" ]
6
2020-03-30T05:45:04.000Z
2020-08-13T10:01:39.000Z
#include <bits/stdc++.h> #define INF 2000000000 using namespace std; typedef long long ll; int read(){ int f = 1, x = 0; char c = getchar(); while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();} while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar(); return f * x; } class Solution { public: int totalHammingDistance(vector<int>& nums) { int ans = 0, n = nums.size(); for (int i = (1 << 30); i; i >>= 1){ int m = 0; for (int j: nums) if(j & i) ++m; ans += m * (n - m); } return ans; } }; Solution sol; void init(){ } void solve(){ // sol.convert(); } int main(){ init(); solve(); return 0; }
19.351351
64
0.459497
[ "vector" ]
cab1c6145428e32ffa25bbec07ef69ee9779c1d6
817
hpp
C++
deps/bc-ur-arduino/src/random-sampler.hpp
ksedgwic/bc-lethe-kit
c40f3c0220d91f0ad95054937f99165245372c91
[ "BSD-2-Clause-Patent" ]
34
2020-04-02T06:58:45.000Z
2021-04-09T08:07:46.000Z
deps/bc-ur-arduino/src/random-sampler.hpp
ksedgwic/bc-lethe-kit
c40f3c0220d91f0ad95054937f99165245372c91
[ "BSD-2-Clause-Patent" ]
28
2020-04-02T04:33:17.000Z
2021-04-23T22:00:48.000Z
deps/bc-ur-arduino/src/random-sampler.hpp
ksedgwic/bc-lethe-kit
c40f3c0220d91f0ad95054937f99165245372c91
[ "BSD-2-Clause-Patent" ]
8
2020-04-02T04:29:08.000Z
2020-09-30T22:12:58.000Z
// // random-sampler.hpp // // Copyright © 2020 by Blockchain Commons, LLC // Licensed under the "BSD-2-Clause Plus Patent License" // #ifndef BC_UR_RANDOM_SAMPLER22_HPP #define BC_UR_RANDOM_SAMPLER22_HPP #include <ArduinoSTL.h> #include <vector> #include <functional> #include <Arduino.h> // Random-number sampling using the Walker-Vose alias method, // as described by Keith Schwarz (2011) // http://www.keithschwarz.com/darts-dice-coins // Based on C implementation: // https://jugit.fz-juelich.de/mlz/ransampl // Translated to C++ by Wolf McNally namespace ur_arduino { class RandomSampler final { public: RandomSampler(std::vector<double> probs); int next(double r1, double r2); private: std::vector<double> probs_; std::vector<int> aliases_; }; } #endif // BC_UR_RANDOM_SAMPLER_HPP
20.425
61
0.729498
[ "vector" ]
cababe42f08992dfe8f96e1b9f8305b91d0ba8ff
10,572
cc
C++
chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
leiferikb/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-11-15T15:17:43.000Z
2021-11-15T15:17:43.000Z
chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
houseoflifeproperty/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/extensions/api/browsing_data/browsing_data_api.cc
houseoflifeproperty/bitpop-private
4c967307d228e86f07f2576068a169e846c833ca
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:02.000Z
2020-11-04T07:24:02.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Defines the Chrome Extensions BrowsingData API functions, which entail // clearing browsing data, and clearing the browser's cache (which, let's be // honest, are the same thing), as specified in the extension API JSON. #include "chrome/browser/extensions/api/browsing_data/browsing_data_api.h" #include <string> #include "base/values.h" #include "chrome/browser/browsing_data/browsing_data_helper.h" #include "chrome/browser/browsing_data/browsing_data_remover.h" #include "chrome/browser/plugins/plugin_data_remover_helper.h" #include "chrome/browser/plugins/plugin_prefs.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/ui/browser.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/browser_thread.h" #include "extensions/common/error_utils.h" using content::BrowserThread; namespace extension_browsing_data_api_constants { // Type Keys. const char kAppCacheKey[] = "appcache"; const char kCacheKey[] = "cache"; const char kCookiesKey[] = "cookies"; const char kDownloadsKey[] = "downloads"; const char kFileSystemsKey[] = "fileSystems"; const char kFormDataKey[] = "formData"; const char kHistoryKey[] = "history"; const char kIndexedDBKey[] = "indexedDB"; const char kLocalStorageKey[] = "localStorage"; const char kServerBoundCertsKey[] = "serverBoundCertificates"; const char kPasswordsKey[] = "passwords"; const char kPluginDataKey[] = "pluginData"; const char kWebSQLKey[] = "webSQL"; // Option Keys. const char kExtensionsKey[] = "extension"; const char kOriginTypesKey[] = "originTypes"; const char kProtectedWebKey[] = "protectedWeb"; const char kSinceKey[] = "since"; const char kUnprotectedWebKey[] = "unprotectedWeb"; // Errors! const char kOneAtATimeError[] = "Only one 'browsingData' API call can run at " "a time."; } // namespace extension_browsing_data_api_constants namespace { // Given a DictionaryValue |dict|, returns either the value stored as |key|, or // false, if the given key doesn't exist in the dictionary. bool RemoveType(base::DictionaryValue* dict, const std::string& key) { bool value = false; if (!dict->GetBoolean(key, &value)) return false; else return value; } // Convert the JavaScript API's object input ({ cookies: true }) into the // appropriate removal mask for the BrowsingDataRemover object. int ParseRemovalMask(base::DictionaryValue* value) { int GetRemovalMask = 0; if (RemoveType(value, extension_browsing_data_api_constants::kAppCacheKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_APPCACHE; if (RemoveType(value, extension_browsing_data_api_constants::kCacheKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_CACHE; if (RemoveType(value, extension_browsing_data_api_constants::kCookiesKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_COOKIES; if (RemoveType(value, extension_browsing_data_api_constants::kDownloadsKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_DOWNLOADS; if (RemoveType(value, extension_browsing_data_api_constants::kFileSystemsKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_FILE_SYSTEMS; if (RemoveType(value, extension_browsing_data_api_constants::kFormDataKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_FORM_DATA; if (RemoveType(value, extension_browsing_data_api_constants::kHistoryKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_HISTORY; if (RemoveType(value, extension_browsing_data_api_constants::kIndexedDBKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_INDEXEDDB; if (RemoveType(value, extension_browsing_data_api_constants::kLocalStorageKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_LOCAL_STORAGE; if (RemoveType(value, extension_browsing_data_api_constants::kServerBoundCertsKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS; if (RemoveType(value, extension_browsing_data_api_constants::kPasswordsKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_PASSWORDS; if (RemoveType(value, extension_browsing_data_api_constants::kPluginDataKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_PLUGIN_DATA; if (RemoveType(value, extension_browsing_data_api_constants::kWebSQLKey)) GetRemovalMask |= BrowsingDataRemover::REMOVE_WEBSQL; return GetRemovalMask; } } // namespace void BrowsingDataExtensionFunction::OnBrowsingDataRemoverDone() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); this->SendResponse(true); Release(); // Balanced in RunImpl. } bool BrowsingDataExtensionFunction::RunImpl() { // If we don't have a profile, something's pretty wrong. DCHECK(profile()); // Grab the initial |options| parameter, and parse out the arguments. DictionaryValue* options; EXTENSION_FUNCTION_VALIDATE(args_->GetDictionary(0, &options)); DCHECK(options); origin_set_mask_ = ParseOriginSetMask(*options); // If |ms_since_epoch| isn't set, default it to 0. double ms_since_epoch; if (!options->GetDouble(extension_browsing_data_api_constants::kSinceKey, &ms_since_epoch)) ms_since_epoch = 0; // base::Time takes a double that represents seconds since epoch. JavaScript // gives developers milliseconds, so do a quick conversion before populating // the object. Also, Time::FromDoubleT converts double time 0 to empty Time // object. So we need to do special handling here. remove_since_ = (ms_since_epoch == 0) ? base::Time::UnixEpoch() : base::Time::FromDoubleT(ms_since_epoch / 1000.0); removal_mask_ = GetRemovalMask(); if (removal_mask_ & BrowsingDataRemover::REMOVE_PLUGIN_DATA) { // If we're being asked to remove plugin data, check whether it's actually // supported. BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind( &BrowsingDataExtensionFunction::CheckRemovingPluginDataSupported, this, PluginPrefs::GetForProfile(profile()))); } else { StartRemoving(); } // Will finish asynchronously. return true; } void BrowsingDataExtensionFunction::CheckRemovingPluginDataSupported( scoped_refptr<PluginPrefs> plugin_prefs) { if (!PluginDataRemoverHelper::IsSupported(plugin_prefs)) removal_mask_ &= ~BrowsingDataRemover::REMOVE_PLUGIN_DATA; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&BrowsingDataExtensionFunction::StartRemoving, this)); } void BrowsingDataExtensionFunction::StartRemoving() { if (BrowsingDataRemover::is_removing()) { error_ = extension_browsing_data_api_constants::kOneAtATimeError; SendResponse(false); return; } // If we're good to go, add a ref (Balanced in OnBrowsingDataRemoverDone) AddRef(); // Create a BrowsingDataRemover, set the current object as an observer (so // that we're notified after removal) and call remove() with the arguments // we've generated above. We can use a raw pointer here, as the browsing data // remover is responsible for deleting itself once data removal is complete. BrowsingDataRemover* remover = BrowsingDataRemover::CreateForRange(profile(), remove_since_, base::Time::Max()); remover->AddObserver(this); remover->Remove(removal_mask_, origin_set_mask_); } int BrowsingDataExtensionFunction::ParseOriginSetMask( const base::DictionaryValue& options) { // Parse the |options| dictionary to generate the origin set mask. Default to // UNPROTECTED_WEB if the developer doesn't specify anything. int mask = BrowsingDataHelper::UNPROTECTED_WEB; const DictionaryValue* d = NULL; if (options.HasKey(extension_browsing_data_api_constants::kOriginTypesKey)) { EXTENSION_FUNCTION_VALIDATE(options.GetDictionary( extension_browsing_data_api_constants::kOriginTypesKey, &d)); bool value; // The developer specified something! Reset to 0 and parse the dictionary. mask = 0; // Unprotected web. if (d->HasKey(extension_browsing_data_api_constants::kUnprotectedWebKey)) { EXTENSION_FUNCTION_VALIDATE(d->GetBoolean( extension_browsing_data_api_constants::kUnprotectedWebKey, &value)); mask |= value ? BrowsingDataHelper::UNPROTECTED_WEB : 0; } // Protected web. if (d->HasKey(extension_browsing_data_api_constants::kProtectedWebKey)) { EXTENSION_FUNCTION_VALIDATE(d->GetBoolean( extension_browsing_data_api_constants::kProtectedWebKey, &value)); mask |= value ? BrowsingDataHelper::PROTECTED_WEB : 0; } // Extensions. if (d->HasKey(extension_browsing_data_api_constants::kExtensionsKey)) { EXTENSION_FUNCTION_VALIDATE(d->GetBoolean( extension_browsing_data_api_constants::kExtensionsKey, &value)); mask |= value ? BrowsingDataHelper::EXTENSION : 0; } } return mask; } int RemoveBrowsingDataFunction::GetRemovalMask() const { // Parse the |dataToRemove| argument to generate the removal mask. base::DictionaryValue* data_to_remove; if (args_->GetDictionary(1, &data_to_remove)) return ParseRemovalMask(data_to_remove); else return 0; } int RemoveAppCacheFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_APPCACHE; } int RemoveCacheFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_CACHE; } int RemoveCookiesFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_COOKIES | BrowsingDataRemover::REMOVE_SERVER_BOUND_CERTS; } int RemoveDownloadsFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_DOWNLOADS; } int RemoveFileSystemsFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_FILE_SYSTEMS; } int RemoveFormDataFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_FORM_DATA; } int RemoveHistoryFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_HISTORY; } int RemoveIndexedDBFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_INDEXEDDB; } int RemoveLocalStorageFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_LOCAL_STORAGE; } int RemovePluginDataFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_PLUGIN_DATA; } int RemovePasswordsFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_PASSWORDS; } int RemoveWebSQLFunction::GetRemovalMask() const { return BrowsingDataRemover::REMOVE_WEBSQL; }
37.35689
80
0.761351
[ "object" ]
cabb08676e5b86f8cb7c8aeadb10347ef7343d5e
31,669
cpp
C++
fallen/DDEngine/Source/fastprim.cpp
jordandavidson/MuckyFoot-UrbanChaos
00f7bda3f061bff9ecbb611d430f8f71bd557d14
[ "MIT" ]
188
2017-05-20T03:26:33.000Z
2022-03-10T16:58:39.000Z
fallen/DDEngine/Source/fastprim.cpp
jordandavidson/MuckyFoot-UrbanChaos
00f7bda3f061bff9ecbb611d430f8f71bd557d14
[ "MIT" ]
7
2017-05-28T14:28:13.000Z
2022-01-09T01:47:38.000Z
fallen/DDEngine/Source/fastprim.cpp
inco1/MuckyFoot-UrbanChaos
81aa5cfe18ef7fe2d1b1f9911bd33a47c22d5390
[ "MIT" ]
43
2017-05-20T07:31:32.000Z
2022-03-09T18:39:35.000Z
// // Draws prims super-fast! // #include "game.h" #include "ddlib.h" #include "poly.h" #include "polypoint.h" #include "polypage.h" #include "fastprim.h" #include "memory.h" #include "texture.h" #include "matrix.h" //#define FASTPRIM_PERFORMANCE #ifdef FASTPRIM_PERFORMANCE FILE *FASTPRIM_handle; SLONG FASTPRIM_num_freed; SLONG FASTPRIM_num_cached; SLONG FASTPRIM_num_already_cached; SLONG FASTPRIM_num_drawn; #endif // // The D3D vertices and indices passed to DrawIndexedPrimitive // D3DLVERTEX *FASTPRIM_lvert_buffer; D3DLVERTEX *FASTPRIM_lvert; SLONG FASTPRIM_lvert_max; SLONG FASTPRIM_lvert_upto; SLONG FASTPRIM_lvert_free_end; // The end of the free range of lverts. SLONG FASTPRIM_lvert_free_unused; // From this lvert to the end of the array is unused. UWORD *FASTPRIM_index; SLONG FASTPRIM_index_max; SLONG FASTPRIM_index_upto; SLONG FASTPRIM_index_free_end; // The end of the free range of indices SLONG FASTPRIM_index_free_unused; // From this index to the end of the array is unused. // // A 32-byte aligned matrix. // UBYTE FASTPRIM_matrix_buffer[sizeof(D3DMATRIX) + 32]; D3DMATRIX *FASTPRIM_matrix; // // Each DrawIndexedPrim call has one of these structures. // #define FASTPRIM_CALL_TYPE_NORMAL 0 // Uses DrawIndMM - no alpha, no MESH_colour_and, no envmapping... #define FASTPRIM_CALL_TYPE_COLOURAND 1 // Uses DrawIndMM. The colours for this call should be AND'ed with MESH_colour_and #define FASTPRIM_CALL_TYPE_INDEXED 2 // Uses DrawIndexedPrimitive and the texture is an alpha texture #define FASTPRIM_CALL_TYPE_ENVMAP 3 // This is an an environment mapping call - uses DrawIndexedPrimitive and the (u,v) must be set each frame. #define FASTPRIM_CALL_FLAG_SELF_ILLUM (1 << 0) typedef struct { UWORD flag; UWORD type; UWORD lvert; UWORD lvertcount; UWORD index; UWORD indexcount; LPDIRECT3DTEXTURE2 texture; } FASTPRIM_Call; #define FASTPRIM_MAX_CALLS 512 FASTPRIM_Call FASTPRIM_call[FASTPRIM_MAX_CALLS]; SLONG FASTPRIM_call_upto; // // Each prim... // #define FASTPRIM_PRIM_FLAG_CACHED (1 << 0) #define FASTPRIM_PRIM_FLAG_INVALID (1 << 1) // This prim cannot be converted for some reason. typedef struct { UWORD flag; UWORD call_index; UWORD call_count; } FASTPRIM_Prim; #define FASTPRIM_MAX_PRIMS 256 FASTPRIM_Prim FASTPRIM_prim[FASTPRIM_MAX_PRIMS]; // // Circular queue of prims we have cached. // #define FASTPRIM_MAX_QUEUE 128 UBYTE FASTPRIM_queue[FASTPRIM_MAX_QUEUE]; SLONG FASTPRIM_queue_start; SLONG FASTPRIM_queue_end; // // Returns the actual page used. // LPDIRECT3DTEXTURE2 FASTPRIM_find_texture_from_page(SLONG page) { SLONG i; PolyPage *pp = &POLY_Page[page]; return pp->RS.GetTexture(); } #ifdef DEBUG void *pvJustChecking1 = NULL; void *pvJustChecking2 = NULL; #endif void FASTPRIM_init() { // // Allocate memory. // FASTPRIM_lvert_max = 4096; //FASTPRIM_lvert_max = 256; #ifdef DEBUG FASTPRIM_lvert_buffer = (D3DLVERTEX *) MemAlloc(sizeof(D3DLVERTEX) * FASTPRIM_lvert_max + 31 + 32); FASTPRIM_lvert = (D3DLVERTEX *) ((((SLONG) FASTPRIM_lvert_buffer) + 31) & ~0x1f); // And write magic numbers just afterwards to check for scribbles. char *pcTemp = (char *)( (SLONG)FASTPRIM_lvert + sizeof(D3DLVERTEX) * FASTPRIM_lvert_max ); strcpy ( pcTemp, "ThisIsAMagicString901234567890" ); #else FASTPRIM_lvert_buffer = (D3DLVERTEX *) MemAlloc(sizeof(D3DLVERTEX) * FASTPRIM_lvert_max + 31); FASTPRIM_lvert = (D3DLVERTEX *) ((((SLONG) FASTPRIM_lvert_buffer) + 31) & ~0x1f); #endif FASTPRIM_lvert_upto = 0; FASTPRIM_lvert_free_end = FASTPRIM_lvert_max; FASTPRIM_lvert_free_unused = FASTPRIM_lvert_max; FASTPRIM_index_max = FASTPRIM_lvert_max * 3; // Not * 5 / 4 because we may have some extra sharing... FASTPRIM_index = (UWORD *) MemAlloc(sizeof(UWORD) * FASTPRIM_index_max); FASTPRIM_index_upto = 0; FASTPRIM_index_free_end = FASTPRIM_index_max; FASTPRIM_index_free_unused = FASTPRIM_index_max; #ifdef DEBUG pvJustChecking1 = (void *)FASTPRIM_lvert_buffer; pvJustChecking2 = (void *)FASTPRIM_index; #endif FASTPRIM_call_upto = 0; FASTPRIM_queue_start = 0; FASTPRIM_queue_end = 0; memset(FASTPRIM_lvert, 0, sizeof(D3DLVERTEX) * FASTPRIM_lvert_max); memset(FASTPRIM_index, 0, sizeof(UWORD ) * FASTPRIM_index_max); memset(FASTPRIM_call, 0, sizeof(FASTPRIM_call)); memset(FASTPRIM_prim, 0, sizeof(FASTPRIM_prim)); memset(FASTPRIM_queue, 0, sizeof(FASTPRIM_queue)); FASTPRIM_matrix = (D3DMATRIX *) ((SLONG(FASTPRIM_matrix_buffer) + 31) & ~0x1f); // // Don't convert car wheels because their texture coordinates rotate! // FASTPRIM_prim[PRIM_OBJ_CAR_WHEEL].flag = FASTPRIM_PRIM_FLAG_INVALID; #ifdef FASTPRIM_PERFORMANCE if (!FASTPRIM_handle){FASTPRIM_handle = fopen("c:\\fastprim.txt", "wb");} FASTPRIM_num_freed = 0; FASTPRIM_num_cached = 0; FASTPRIM_num_already_cached = 0; FASTPRIM_num_drawn = 0; #endif } // // Frees up the given cached prim. // void FASTPRIM_free_cached_prim(SLONG prim) { SLONG i; FASTPRIM_Call *fc; FASTPRIM_Prim *fp; ASSERT(WITHIN(prim, 0, FASTPRIM_MAX_PRIMS - 1)); fp = &FASTPRIM_prim[prim]; for (i = 0; i < fp->call_count; i++) { ASSERT(WITHIN(fp->call_index, 0, FASTPRIM_MAX_CALLS - 1)); fc = &FASTPRIM_call[fp->call_index + i]; // // Free up the verts and indices used by this call. // FASTPRIM_lvert_free_end = fc->lvert + fc->lvertcount; FASTPRIM_index_free_end = fc->index + fc->indexcount; if (FASTPRIM_lvert_free_end >= FASTPRIM_lvert_free_unused || FASTPRIM_index_free_end >= FASTPRIM_index_free_unused) { FASTPRIM_lvert_free_end = FASTPRIM_lvert_max; FASTPRIM_index_free_end = FASTPRIM_index_max; FASTPRIM_lvert_free_unused = FASTPRIM_lvert_max; FASTPRIM_index_free_unused = FASTPRIM_index_max; break; } } fp->flag &= ~FASTPRIM_PRIM_FLAG_CACHED; fp->call_count = 0; fp->call_index = 0; #ifdef FASTPRIM_PERFORMANCE fprintf(FASTPRIM_handle, "Gameturn %5d free prim %3d\n", GAME_TURN, prim); fflush(FASTPRIM_handle); FASTPRIM_num_freed += 1; #endif } // // Frees up the oldest cached prim to make room for the given call // to grow. It may move all the data in the call! // void FASTPRIM_free_queue_for_call(FASTPRIM_Call *fc) { SLONG duplicates = 0; SLONG old_lvert_free_end; SLONG old_index_free_end; SLONG copy_to_beginning = FALSE; while(1) { old_lvert_free_end = FASTPRIM_lvert_free_end; old_index_free_end = FASTPRIM_index_free_end; // // Free up the last cached prim. // ASSERT(FASTPRIM_queue_end < FASTPRIM_queue_start); FASTPRIM_free_cached_prim(FASTPRIM_queue[FASTPRIM_queue_end++ & (FASTPRIM_MAX_QUEUE - 1)]); if (FASTPRIM_lvert_free_end < old_lvert_free_end || FASTPRIM_index_free_end < old_index_free_end) { // // The lverts have wrapped around. We must copy all the lverts // in the call to the beginning of the array (when we have enough room). // FASTPRIM_lvert_upto = fc->lvertcount; FASTPRIM_index_upto = fc->indexcount; copy_to_beginning = TRUE; #ifdef FASTPRIM_PERFORMANCE fprintf(FASTPRIM_handle, "Wrap...\n"); fflush(FASTPRIM_handle); #endif } if (FASTPRIM_index_upto + 16 < FASTPRIM_index_free_end && FASTPRIM_lvert_upto + 16 < FASTPRIM_lvert_free_end) { // // Enough room! Do we have to copy the lverts or indices to the // beginning of the array? // if (copy_to_beginning) { memcpy(FASTPRIM_lvert, FASTPRIM_lvert + fc->lvert, sizeof(D3DLVERTEX) * fc->lvertcount); memcpy(FASTPRIM_index, FASTPRIM_index + fc->index, sizeof(UWORD ) * fc->indexcount); FASTPRIM_lvert_free_unused = fc->lvert; FASTPRIM_index_free_unused = fc->index; fc->lvert = 0; fc->index = 0; } return; } else { duplicates += 1; } } } // // Makes sure the given FASTPRIM_Prim has a call structure for // the given texture. // void FASTPRIM_create_call(FASTPRIM_Prim *fp, LPDIRECT3DTEXTURE2 texture, UWORD type) { SLONG i; FASTPRIM_Call *fc; // // Do we already have a call structure for this texture? // for (i = 0; i < fp->call_count; i++) { ASSERT(WITHIN(fp->call_index + i, 0, FASTPRIM_call_upto - 1)); fc = &FASTPRIM_call[fp->call_index + i]; if (fc->texture == texture && fc->type == type) { return; } } // // Create a new call structure. // ASSERT(WITHIN(FASTPRIM_call_upto, 0, FASTPRIM_MAX_CALLS - 1)); ASSERT(fp->call_index + fp->call_count == FASTPRIM_call_upto); fc = &FASTPRIM_call[fp->call_index + fp->call_count]; fc->type = type; fc->lvert = 0; fc->lvertcount = 0; fc->index = 0; fc->indexcount = 0; fc->texture = texture; fp->call_count += 1; FASTPRIM_call_upto += 1; return; } // // Adds a point to the given call structure. If the point already // exists then it returns the old point. // UWORD FASTPRIM_add_point_to_call( FASTPRIM_Call *fc, float x, float y, float z, float u, float v, ULONG colour, ULONG specular) { SLONG i; D3DLVERTEX *lv; // // Does this point already exist? // for (i = fc->lvertcount - 1; i >= 0; i--) { ASSERT(WITHIN(fc->lvert + i, 0, FASTPRIM_lvert_max - 1)); lv = &FASTPRIM_lvert[fc->lvert + i]; if (lv->x == x && lv->y == y && lv->z == z && lv->tu == u && lv->tv == v && lv->color == colour && lv->specular == specular) { return i; } } // // Create a new point. // if (FASTPRIM_lvert_upto >= FASTPRIM_lvert_free_end) { // // Need more room! // #ifdef FASTPRIM_PERFORMANCE fprintf(FASTPRIM_handle, "No lverts...\n"); fflush(FASTPRIM_handle); #endif FASTPRIM_free_queue_for_call(fc); } ASSERT(WITHIN(FASTPRIM_lvert_upto, 0, FASTPRIM_lvert_max - 1)); ASSERT(fc->lvert + fc->lvertcount == FASTPRIM_lvert_upto); lv = &FASTPRIM_lvert[fc->lvert + fc->lvertcount]; lv->x = x; lv->y = y; lv->z = z; lv->tu = u; lv->tv = v; lv->color = colour; lv->specular = specular; FASTPRIM_lvert_upto += 1; return fc->lvertcount++; } void FASTPRIM_ensure_room_for_indices(FASTPRIM_Call *fc) { if (FASTPRIM_index_upto + 8 >= FASTPRIM_index_free_end) { #ifdef FASTPRIM_PERFORMANCE fprintf(FASTPRIM_handle, "No indices...\n"); fflush(FASTPRIM_handle); #endif FASTPRIM_free_queue_for_call(fc); } } SLONG FASTPRIM_draw( SLONG prim, float x, float y, float z, float matrix[9], NIGHT_Colour *lpc) { #ifndef TARGET_DC if (!Keys[KB_R]) { return FALSE; } #endif SLONG i; SLONG j; SLONG k; SLONG page; SLONG type; SLONG index[4]; float px; float py; float pz; float pu; float pv; ULONG pcolour; ULONG pspecular; FASTPRIM_Prim *fp; PrimObject *po; PrimFace4 *f4; PrimFace3 *f3; FASTPRIM_Call *fc; PolyPage *pp; LPDIRECT3DTEXTURE2 texture; ASSERT(WITHIN(prim, 0, FASTPRIM_MAX_PRIMS - 1)); // // Is this prim too close to the camera in (x,z)? Ignore y // because lamposts and trees have a huge y! // { PrimInfo *pi = get_prim_info(prim); extern float AENG_cam_x; extern float AENG_cam_z; float dx = x - AENG_cam_x; float dz = z - AENG_cam_z; float dist = dx*dx + dz*dz; float radius = float(MAX(pi->maxx-pi->minx,pi->maxz-pi->minz)) + 16.0f; if (dist < radius*radius) { // // Less than 1 mapsquare distant... drawn the old way! // return FALSE; } } fp = &FASTPRIM_prim[prim]; #ifndef TARGET_DC if (!Keys[KB_R]) { return FALSE; } #endif #ifdef FASTPRIM_PERFORMANCE FASTPRIM_num_drawn += 1; #endif if (fp->flag & FASTPRIM_PRIM_FLAG_CACHED) { #ifdef FASTPRIM_PERFORMANCE FASTPRIM_num_already_cached += 1; #endif } else { // // We've come across a new prim. // if (FASTPRIM_call_upto + 32 >= FASTPRIM_MAX_CALLS) { // // Assume max of 32 calls per prim? And pray to god // that there is enough room! // FASTPRIM_call_upto = 0; } fp->call_count = 0; fp->call_index = FASTPRIM_call_upto; // // Go through all the faces and create a new call // structure for each new texture/type we come across. // po = &prim_objects[prim]; for (i = po->StartFace3; i < po->EndFace3; i++) { ASSERT(WITHIN(i, 0, next_prim_face3 - 1)); f3 = &prim_faces3[i]; page = f3->UV[0][0] & 0xc0; page <<= 2; page |= f3->TexturePage; page += FACE_PAGE_OFFSET; texture = FASTPRIM_find_texture_from_page(page); if (POLY_Page[page].RS.IsAlphaBlendEnabled()) { type = FASTPRIM_CALL_TYPE_INDEXED; } else if (f3->FaceFlags & FACE_FLAG_TINT) { type = FASTPRIM_CALL_TYPE_COLOURAND; } else { type = FASTPRIM_CALL_TYPE_NORMAL; } FASTPRIM_create_call(fp, texture, type); } for (i = po->StartFace4; i < po->EndFace4; i++) { ASSERT(WITHIN(i, 0, next_prim_face4 - 1)); f4 = &prim_faces4[i]; page = f4->UV[0][0] & 0xc0; page <<= 2; page |= f4->TexturePage; page += FACE_PAGE_OFFSET; texture = FASTPRIM_find_texture_from_page(page); if (POLY_Page[page].RS.IsAlphaBlendEnabled()) { type = FASTPRIM_CALL_TYPE_INDEXED; } else if (f4->FaceFlags & FACE_FLAG_TINT) { type = FASTPRIM_CALL_TYPE_COLOURAND; } else { type = FASTPRIM_CALL_TYPE_NORMAL; } FASTPRIM_create_call(fp, texture, type); } // // Now go through each texture and add the faces // that use that texture. // for (i = 0; i < fp->call_count; i++) { ASSERT(WITHIN(fp->call_index + i, 0, FASTPRIM_call_upto - 1)); fc = &FASTPRIM_call[fp->call_index + i]; fc->flag = 0; fc->lvert = FASTPRIM_lvert_upto; fc->index = FASTPRIM_index_upto; fc->lvertcount = 0; fc->indexcount = 0; for (j = po->StartFace3; j < po->EndFace3; j++) { ASSERT(WITHIN(j, 0, next_prim_face3 - 1)); f3 = &prim_faces3[j]; page = f3->UV[0][0] & 0xc0; page <<= 2; page |= f3->TexturePage; page += FACE_PAGE_OFFSET; texture = FASTPRIM_find_texture_from_page(page); if (POLY_Page[page].RS.IsAlphaBlendEnabled()) { type = FASTPRIM_CALL_TYPE_INDEXED; } else if (f3->FaceFlags & FACE_FLAG_TINT) { type = FASTPRIM_CALL_TYPE_COLOURAND; } else { type = FASTPRIM_CALL_TYPE_NORMAL; } if (texture == fc->texture && type == fc->type) { // // Add the three points of this face. // pp = &POLY_Page[page]; for (k = 0; k < 3; k++) { ASSERT(WITHIN(f3->Points[k], 0, next_prim_point - 1)); px = AENG_dx_prim_points[f3->Points[k]].X; py = AENG_dx_prim_points[f3->Points[k]].Y; pz = AENG_dx_prim_points[f3->Points[k]].Z; pu = (f3->UV[k][0] & 0x3f) * (1.0F / 32.0F); pv = (f3->UV[k][1] ) * (1.0F / 32.0F); #ifdef TEX_EMBED pu = pu * pp->m_UScale + pp->m_UOffset; pv = pv * pp->m_VScale + pp->m_VOffset; #endif if (lpc) { NIGHT_get_d3d_colour( lpc[f3->Points[k] - po->StartPoint], &pcolour, &pspecular); } else { // // Light this point badly... // pcolour = NIGHT_amb_d3d_colour; pspecular = NIGHT_amb_d3d_specular; } if (POLY_page_flag[page] & POLY_PAGE_FLAG_SELF_ILLUM) { pcolour = 0xffffff; pspecular = 0xff000000; fc->flag |= FASTPRIM_CALL_FLAG_SELF_ILLUM; } index[k] = FASTPRIM_add_point_to_call(fc, px,py,pz, pu,pv, pcolour, pspecular); if (type == FASTPRIM_CALL_TYPE_COLOURAND) { // // Put the 'y' component of the normal into the // top byte of dwReserved- we cheekily use just this // value to do the lighting... // ASSERT(WITHIN(fc->lvert + index[k], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[k]].dwReserved = prim_normal[f3->Points[k]].Y << 24; } else { // // Put the point index into the top UWORD of the dwReserved field. // ASSERT(WITHIN(fc->lvert + index[k], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[k]].dwReserved = (f3->Points[k] - po->StartPoint) << 16; } } // // Now add the face. // FASTPRIM_ensure_room_for_indices(fc); ASSERT(WITHIN(FASTPRIM_index_upto + 3, 0, FASTPRIM_index_max)); ASSERT(fc->index + fc->indexcount == FASTPRIM_index_upto); if (type != FASTPRIM_CALL_TYPE_INDEXED) { FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = -1; fc->indexcount += 4; } else { FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; fc->indexcount += 3; } } } for (j = po->StartFace4; j < po->EndFace4; j++) { ASSERT(WITHIN(j, 0, next_prim_face4 - 1)); f4 = &prim_faces4[j]; page = f4->UV[0][0] & 0xc0; page <<= 2; page |= f4->TexturePage; page += FACE_PAGE_OFFSET; texture = FASTPRIM_find_texture_from_page(page); if (POLY_Page[page].RS.IsAlphaBlendEnabled()) { type = FASTPRIM_CALL_TYPE_INDEXED; } else if (f4->FaceFlags & FACE_FLAG_TINT) { type = FASTPRIM_CALL_TYPE_COLOURAND; } else { type = FASTPRIM_CALL_TYPE_NORMAL; } if (texture == fc->texture && type == fc->type) { // // Add the four points of this face. // pp = &POLY_Page[page]; for (k = 0; k < 4; k++) { ASSERT(WITHIN(f4->Points[k], 0, next_prim_point - 1)); px = AENG_dx_prim_points[f4->Points[k]].X; py = AENG_dx_prim_points[f4->Points[k]].Y; pz = AENG_dx_prim_points[f4->Points[k]].Z; pu = (f4->UV[k][0] & 0x3f) * (1.0F / 32.0F); pv = (f4->UV[k][1] ) * (1.0F / 32.0F); #ifdef TEX_EMBED pu = pu * pp->m_UScale + pp->m_UOffset; pv = pv * pp->m_VScale + pp->m_VOffset; #endif if (lpc) { NIGHT_get_d3d_colour( lpc[f4->Points[k] - po->StartPoint], &pcolour, &pspecular); } else { // // Light this point badly... // pcolour = NIGHT_amb_d3d_colour; pspecular = NIGHT_amb_d3d_specular; } if (POLY_page_flag[page] & POLY_PAGE_FLAG_SELF_ILLUM) { pcolour = 0xffffff; pspecular = 0xff000000; } index[k] = FASTPRIM_add_point_to_call(fc, px,py,pz, pu,pv, pcolour, pspecular); if (type == FASTPRIM_CALL_TYPE_COLOURAND) { // // Put the 'y' component of the normal into the // top byte of dwReserved- we cheekily use just this // value to do the lighting... // ASSERT(WITHIN(fc->lvert + index[k], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[k]].dwReserved = prim_normal[f4->Points[k]].Y << 24; } else { // // Put the point index into the top UWORD of the dwReserved field. // ASSERT(WITHIN(fc->lvert + index[k], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[k]].dwReserved = (f4->Points[k] - po->StartPoint) << 16; } } // // Now add the face. // FASTPRIM_ensure_room_for_indices(fc); ASSERT(WITHIN(FASTPRIM_index_upto + 6, 0, FASTPRIM_index_max)); ASSERT(fc->index + fc->indexcount == FASTPRIM_index_upto); if (type != FASTPRIM_CALL_TYPE_INDEXED) { FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = index[3]; FASTPRIM_index[FASTPRIM_index_upto++] = -1; fc->indexcount += 5; } else { FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = index[3]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; fc->indexcount += 6; } } } } if (po->flag & PRIM_FLAG_ENVMAPPED) { // // Create another call for the environment mapped faces. // LPDIRECT3DTEXTURE2 envtexture = FASTPRIM_find_texture_from_page(POLY_PAGE_ENVMAP); FASTPRIM_create_call(fp, envtexture, FASTPRIM_CALL_TYPE_ENVMAP); // // Find the newly-created call structure- should be the last one in the array. // ASSERT(WITHIN(fp->call_index + fp->call_count - 1, 0, FASTPRIM_call_upto - 1)); fc = &FASTPRIM_call[fp->call_index + fp->call_count - 1]; ASSERT(fc->texture == envtexture && fc->type == FASTPRIM_CALL_TYPE_ENVMAP); fc->flag = 0; fc->lvert = FASTPRIM_lvert_upto; fc->index = FASTPRIM_index_upto; fc->lvertcount = 0; fc->indexcount = 0; // // Add all the environment mapped faces. // for (i = po->StartFace3; i < po->EndFace3; i++) { ASSERT(WITHIN(i, 0, next_prim_face3 - 1)); f3 = &prim_faces3[i]; if (f3->FaceFlags & FACE_FLAG_ENVMAP) { for (j = 0; j < 3; j++) { ASSERT(WITHIN(f3->Points[j], 0, next_prim_point - 1)); px = AENG_dx_prim_points[f3->Points[j]].X; py = AENG_dx_prim_points[f3->Points[j]].Y; pz = AENG_dx_prim_points[f3->Points[j]].Z; pu = 0.0F; pv = 0.0F; pcolour = 0xff888888; pspecular = 0x00000000; index[j] = FASTPRIM_add_point_to_call(fc, px,py,pz, pu,pv, pcolour, pspecular); // // Put the point index into the top UWORD of 'dwReserved' so we know // which normal to use. // ASSERT(WITHIN(fc->lvert + index[j], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[j]].dwReserved = f3->Points[j] << 16; } // // Now add the face. // FASTPRIM_ensure_room_for_indices(fc); ASSERT(WITHIN(FASTPRIM_index_upto + 4, 0, FASTPRIM_index_max)); ASSERT(fc->index + fc->indexcount == FASTPRIM_index_upto); FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; fc->indexcount += 3; } } for (i = po->StartFace4; i < po->EndFace4; i++) { ASSERT(WITHIN(i, 0, next_prim_face4 - 1)); f4 = &prim_faces4[i]; if (f4->FaceFlags & FACE_FLAG_ENVMAP) { for (j = 0; j < 4; j++) { ASSERT(WITHIN(f4->Points[j], 0, next_prim_point - 1)); px = AENG_dx_prim_points[f4->Points[j]].X; py = AENG_dx_prim_points[f4->Points[j]].Y; pz = AENG_dx_prim_points[f4->Points[j]].Z; pu = 0.0F; pv = 0.0F; pcolour = 0xff888888; pspecular = 0x00000000; index[j] = FASTPRIM_add_point_to_call(fc, px,py,pz, pu,pv, pcolour, pspecular); // // Put the point index into the top UWORD of 'dwReserved' so we know // which normal to use. // ASSERT(WITHIN(fc->lvert + index[j], 0, FASTPRIM_lvert_max - 1)); FASTPRIM_lvert[fc->lvert + index[j]].dwReserved = f4->Points[j] << 16; } // // Now add the face. // FASTPRIM_ensure_room_for_indices(fc); ASSERT(WITHIN(FASTPRIM_index_upto + 5, 0, FASTPRIM_index_max)); ASSERT(fc->index + fc->indexcount == FASTPRIM_index_upto); FASTPRIM_index[FASTPRIM_index_upto++] = index[0]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = index[3]; FASTPRIM_index[FASTPRIM_index_upto++] = index[2]; FASTPRIM_index[FASTPRIM_index_upto++] = index[1]; fc->indexcount += 6; } } } // // We've cached it now! // fp->flag |= FASTPRIM_PRIM_FLAG_CACHED; FASTPRIM_queue[FASTPRIM_queue_start++ & (FASTPRIM_MAX_QUEUE - 1)] = prim; #ifdef FASTPRIM_PERFORMANCE fprintf(FASTPRIM_handle, "Gameturn %5d cache prim %3d\n", GAME_TURN, prim); fflush(FASTPRIM_handle); FASTPRIM_num_cached += 1; #endif } // // Are we strinking this prim? // extern UBYTE kludge_shrink; if (kludge_shrink) { float fstretch; fstretch = (prim == PRIM_OBJ_ITEM_AMMO_SHOTGUN) ? 0.15F : 0.7F; matrix[0] *= fstretch; matrix[1] *= fstretch; matrix[2] *= fstretch; matrix[3] *= fstretch; matrix[4] *= fstretch; matrix[5] *= fstretch; matrix[6] *= fstretch; matrix[7] *= fstretch; matrix[8] *= fstretch; } // // Are we strinking this prim? // extern UBYTE kludge_shrink; if (kludge_shrink) { float fstretch; fstretch = (prim == PRIM_OBJ_ITEM_AMMO_SHOTGUN) ? 0.15F : 0.7F; matrix[0] *= fstretch; matrix[1] *= fstretch; matrix[2] *= fstretch; matrix[3] *= fstretch; matrix[4] *= fstretch; matrix[5] *= fstretch; matrix[6] *= fstretch; matrix[7] *= fstretch; matrix[8] *= fstretch; } // // Draw the cached version. Set up the matrix for this object's rotation. // POLY_set_local_rotation( x,y,z, matrix); GenerateMMMatrixFromStandardD3DOnes( FASTPRIM_matrix, &g_matProjection, &g_matWorld, &g_viewData); for (i = 0; i < fp->call_count; i++) { ASSERT(WITHIN(fp->call_index + i, 0, FASTPRIM_MAX_CALLS - 1)); fc = &FASTPRIM_call[fp->call_index + i]; if (fc->type == FASTPRIM_CALL_TYPE_ENVMAP) { // // Work out the environment mapping. Calculate the rotation // matrix combined with the camera. // float nx; float ny; float nz; float comb[9]; float cam_matrix[9]; extern float AENG_cam_yaw; extern float AENG_cam_pitch; extern float AENG_cam_roll; D3DLVERTEX *lv; MATRIX_calc(cam_matrix, AENG_cam_yaw, AENG_cam_pitch, AENG_cam_roll); MATRIX_3x3mul(comb, cam_matrix, matrix); for (j = 0; j < fc->lvertcount; j++) { ASSERT(WITHIN(fc->lvert + j, 0, FASTPRIM_lvert_max - 1)); lv = &FASTPRIM_lvert[fc->lvert + j]; ASSERT(WITHIN(lv->dwReserved >> 16, 0, (unsigned)( next_prim_point - 1 ))); nx = prim_normal[lv->dwReserved >> 16].X * (2.0F / 256.0F); ny = prim_normal[lv->dwReserved >> 16].Y * (2.0F / 256.0F); nz = prim_normal[lv->dwReserved >> 16].Z * (2.0F / 256.0F); MATRIX_MUL( comb, nx, ny, nz); lv->tu = (nx * 0.5F) + 0.5F; lv->tv = (ny * 0.5F) + 0.5F; } } else if (fc->type == FASTPRIM_CALL_TYPE_COLOURAND) { ULONG default_colour; ULONG default_specular; NIGHT_get_d3d_colour( NIGHT_get_light_at(x,y,z), &default_colour, &default_specular); extern ULONG MESH_colour_and; default_colour &= MESH_colour_and; // // Relight then AND out the colours... // D3DLVERTEX *lv; for (j = 0; j < fc->lvertcount; j++) { ASSERT(WITHIN(fc->lvert + j, 0, FASTPRIM_lvert_max - 1)); lv = &FASTPRIM_lvert[fc->lvert + j]; lv->color = default_colour; lv->specular = default_specular; } } else if (fc->type == FASTPRIM_CALL_TYPE_NORMAL) { if (lpc) { // // Relight from the cached lighting. // D3DLVERTEX *lv; for (j = 0; j < fc->lvertcount; j++) { ASSERT(WITHIN(fc->lvert + j, 0, FASTPRIM_lvert_max - 1)); lv = &FASTPRIM_lvert[fc->lvert + j]; NIGHT_get_d3d_colour( lpc[lv->dwReserved >> 16], &lv->color, &lv->specular); } } else { // // Relight using local light... // ULONG default_colour; ULONG default_specular; NIGHT_get_d3d_colour( NIGHT_get_light_at(x,y,z), &default_colour, &default_specular); D3DLVERTEX *lv; for (j = 0; j < fc->lvertcount; j++) { ASSERT(WITHIN(fc->lvert + j, 0, FASTPRIM_lvert_max - 1)); lv = &FASTPRIM_lvert[fc->lvert + j]; lv->color = default_colour; lv->specular = default_specular; } } } if (fc->type == FASTPRIM_CALL_TYPE_INDEXED || fc->type == FASTPRIM_CALL_TYPE_ENVMAP) { // // Standard D3D DrawIndexedPrimitive() call... // if (fc->type == FASTPRIM_CALL_TYPE_INDEXED) { // // Setup alphablend renderstates... // the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_SRCALPHA ); the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_INVSRCALPHA); the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE, TRUE ); } else { // // Setup additive renderstates... // the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_SRCBLEND, D3DBLEND_ONE); the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_DESTBLEND, D3DBLEND_ONE); the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE, TRUE ); } the_display.lp_D3D_Device->SetTexture(0, fc->texture); the_display.lp_D3D_Device->DrawIndexedPrimitive( D3DPT_TRIANGLELIST, D3DFVF_LVERTEX, FASTPRIM_lvert + fc->lvert, fc->lvertcount, FASTPRIM_index + fc->index, fc->indexcount, 0); the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_ALPHABLENDENABLE, FALSE); } else { // // Tom's DrawIndMM() call... // D3DMULTIMATRIX d3dmm = { FASTPRIM_lvert + fc->lvert, FASTPRIM_matrix, NULL, NULL }; the_display.lp_D3D_Device->SetTexture(0, fc->texture); if (fc->flag & FASTPRIM_CALL_FLAG_SELF_ILLUM) { the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_TEXTUREMAPBLEND,D3DTBLEND_DECAL); } //TRACE ( "S3" ); DrawIndPrimMM( the_display.lp_D3D_Device, D3DFVF_LVERTEX, &d3dmm, fc->lvertcount, FASTPRIM_index + fc->index, fc->indexcount); //TRACE ( "F3" ); if (fc->flag & FASTPRIM_CALL_FLAG_SELF_ILLUM) { the_display.lp_D3D_Device->SetRenderState(D3DRENDERSTATE_TEXTUREMAPBLEND,D3DTBLEND_MODULATE); } } } return TRUE; } void FASTPRIM_fini() { #ifdef DEBUG ASSERT ( FASTPRIM_lvert_buffer != NULL ); ASSERT ( FASTPRIM_index != NULL ); ASSERT ( FASTPRIM_lvert_buffer == (void *)pvJustChecking1 ); ASSERT ( FASTPRIM_index == (void *)pvJustChecking2 ); char *pcTemp = (char *)( (SLONG)FASTPRIM_lvert + sizeof(D3DLVERTEX) * FASTPRIM_lvert_max ); ASSERT ( 0 == strcmp ( pcTemp, "ThisIsAMagicString901234567890" ) ); #endif TRACE ( "FASTPRIM_fini " ); MemFree(FASTPRIM_lvert_buffer); TRACE ( "1 " ); MemFree(FASTPRIM_index); TRACE ( "2\n" ); FASTPRIM_lvert_buffer = NULL; FASTPRIM_index = NULL; #ifdef FASTPRIM_PERFORMANCE float av_freed_per_turn = float(FASTPRIM_num_freed ) / float(GAME_TURN); float av_cached_per_turn = float(FASTPRIM_num_cached) / float(GAME_TURN); float av_in_cache_per_turn = float(FASTPRIM_num_already_cached) / float(GAME_TURN); float av_drawn_per_turn = float(FASTPRIM_num_drawn) / float(GAME_TURN); fprintf(FASTPRIM_handle, "Average freed per gameturn = %f\n", av_freed_per_turn ); fprintf(FASTPRIM_handle, "Average cached per gameturn = %f\n", av_cached_per_turn ); fprintf(FASTPRIM_handle, "Average in cache per gameturn = %f\n", av_in_cache_per_turn); fprintf(FASTPRIM_handle, "Average drawn per gameturn = %f\n", av_drawn_per_turn ); fflush(FASTPRIM_handle); #endif }
22.34933
147
0.640848
[ "object", "3d" ]
cabd10379f9b4b6ed76e464f5810ed6e095bcf28
2,743
cpp
C++
initial_project/src/main.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
1
2018-01-07T03:57:27.000Z
2018-01-07T03:57:27.000Z
initial_project/src/main.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
10
2016-03-22T16:02:45.000Z
2016-05-12T21:06:34.000Z
initial_project/src/main.cpp
HeroesOfSecurity/SecureSender
33e44d474c2bc6f4e80c3bb1860a6d08afda4dd6
[ "MIT" ]
null
null
null
/* * File: main.cpp * Author: pedro1 * * Created on February 26, 2016, 12:50 PM */ #include "crypto.h" #include "string.h" #include "stdio.h" using namespace std; int main(int argc, char** argv) { //AES key - 16 bytes unsigned char key[16] = { 0xa5, 0x84, 0x99, 0x8d, 0x0d, 0xbd, 0xb1, 0x54, 0xbb, 0xc5, 0x4f, 0xed, 0x86, 0x9a, 0x66, 0x11 }; //Initialization Vector unsigned char iv[16] = { 0x6c, 0x70, 0xed, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x51, 0xa3, 0x40, 0xbd, 0x92, 0x9d, 0x38, 0x9d }; //iv for encryption and decryption unsigned char encryptIv[16]; unsigned char decryptIv[16]; memcpy(encryptIv, iv, 16); memcpy(decryptIv, iv, 16); unsigned char *fileInput; int outSize; Crypto::readFile("../input.txt", &fileInput); // SHA2-512 unsigned char shaResult1[64] = { 0 }; unsigned char shaResult2[64] = { 0 }; Crypto::hashFile((unsigned char*)fileInput, shaResult1); unsigned int length = strlen((const char *)fileInput); unsigned char encryptedOutput[length]; unsigned char decryptedOutput[length]; memset( encryptedOutput, 0, length*sizeof(char) ); memset( decryptedOutput, 0, length*sizeof(char) ); printf("Povodny subor: %s\n", fileInput); printf("Dlzka povodneho subora: %lu\n", strlen((const char *)fileInput)); Crypto::encrypt(key, fileInput, strlen((const char *)fileInput), encryptedOutput, outSize, encryptIv); printf("Zasifrovany subor: %s\n", encryptedOutput); printf("Dlzka zasifrovaneho subora: %lu\n", strlen((const char *)encryptedOutput)); Crypto::writeToFile("../encrypt_output.txt", encryptedOutput); // printf("outSize -> %d, strlen -> %d", outSize, strlen((const char*)encryptedOutput)); Crypto::decrypt(key, (const unsigned char*)encryptedOutput, outSize, decryptedOutput, decryptIv); printf("Desifrovany subor: %s\n", decryptedOutput); printf("Dlzka desifrovaneho subora: %lu\n", strlen((const char *)decryptedOutput)); Crypto::writeToFile("../decrypt_output.txt", decryptedOutput); Crypto::hashFile((unsigned char*)decryptedOutput, shaResult2); printf("Hash1 -> "); for (const unsigned char* p = shaResult1; *p; ++p) { printf("%02x", *p); ++p; } printf("\n"); printf("Hash2 -> "); for (const unsigned char* p = shaResult2; *p; ++p) { printf("%02x", *p); } printf("\n"); if(memcmp(shaResult1, shaResult2, strlen((const char*)fileInput))) { printf("Hashes are the same.\n"); } else { printf("Hashes are different.\n"); } delete[] fileInput; return 0; }
29.180851
106
0.614655
[ "vector" ]
cabff92b5a51687025b2bfd2b14ff563375b4b29
951
cc
C++
cc/trees/target_property.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
cc/trees/target_property.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
cc/trees/target_property.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright (c) 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 "cc/trees/target_property.h" #include "base/macros.h" namespace cc { namespace { static_assert(TargetProperty::FIRST_TARGET_PROPERTY == 0, "TargetProperty must be 0-based enum"); // This should match the TargetProperty enum. static const char* const s_targetPropertyNames[] = { "TRANSFORM", "OPACITY", "FILTER", "SCROLL_OFFSET", "BACKGROUND_COLOR"}; static_assert(static_cast<int>(TargetProperty::LAST_TARGET_PROPERTY) + 1 == arraysize(s_targetPropertyNames), "TargetPropertyEnumSize should equal the number of elements in " "s_targetPropertyNames"); } // namespace const char* TargetProperty::GetName(TargetProperty::Type property) { return s_targetPropertyNames[property]; } } // namespace cc
29.71875
78
0.713985
[ "transform" ]
cac6627ea9b656a1e7a996e1bddbd9ee5a2d1589
2,437
cc
C++
bankocr/line_test.cc
horance-liu/bankocr
ce1c0575eb4bd0b91991bc01b497f01af2e926a7
[ "Apache-2.0" ]
1
2018-10-30T11:11:59.000Z
2018-10-30T11:11:59.000Z
bankocr/line_test.cc
horance-liu/bankocr
ce1c0575eb4bd0b91991bc01b497f01af2e926a7
[ "Apache-2.0" ]
null
null
null
bankocr/line_test.cc
horance-liu/bankocr
ce1c0575eb4bd0b91991bc01b497f01af2e926a7
[ "Apache-2.0" ]
null
null
null
#include "bankocr/line.h" #include "cut/cut.hpp" USING_CUT_NS USING_CUM_NS FIXTURE(LineTest) { using Lines = std::vector<std::string>; static Line line(const Lines& lines) { Line merged; for (auto& line : lines) { merged.merge(line); } return merged; } static void expect(const Lines& lines, const std::string& value) { ASSERT_THAT(line(lines).value(), eq(value)); } TEST("single digit") { expect({ " ", " |", " |", }, "1"); } TEST("| is not !") { expect({ " ", " !", " |", }, "?"); } TEST("| is not 1") { expect({ " ", " 1", " |", }, "?"); } TEST("| is not l") { expect({ " ", " l", " |", }, "?"); } TEST("is not 1") { expect({ " |", " |", " |", }, "?"); expect({ " ", "| ", "| ", }, "?"); expect({ " |", " |", " ", }, "?"); expect({ " ", " | ", " | ", }, "?"); } TEST("is not 2: - is not _") { expect({ " - ", " _|", "|_ ", }, "?"); } TEST("all blank") { expect({ " ", " ", " ", }, "?"); } TEST("1024: programmer's lucky number") { expect({ " _ _ ", " || | _||_|", " ||_||_ |", }, "1024"); } TEST("contains illegible digit: x") { expect({ " _ _ ", " | _| _|", " ||_ x_|", }, "12?"); } TEST("all digits") { expect({ " _ _ _ _ _ _ _ _ ", "| | | _| _||_||_ |_ ||_||_|", "|_| ||_ _| | _||_| ||_| _|", }, "0123456789"); } struct Collector : Alternative { void matches(const std::vector<std::string>& expected) const { ASSERT_THAT(alts, eq(expected)); } private: void accept(const std::string& alt) override { alts.emplace_back(alt); } private: std::vector<std::string> alts; }; TEST("alternatives") { Collector collector; line({ " ", " | | | | | | | | |", " | | | | | | | | |", }).alternatives(collector); collector.matches({ "711111111", "171111111", "117111111", "111711111", "111171111", "111117111", "111111711", "111111171", "111111117", }); } };
15.722581
68
0.367665
[ "vector" ]
cad2eeaf11da6a9d9cd593adcd38a1fa82d6c69f
811
cc
C++
src/filters/oidc/state_cookie_codec.cc
blockspacer/authservice
b40e1763a20e0a0aab73f4ec0f2cf6e477e855af
[ "Apache-2.0" ]
null
null
null
src/filters/oidc/state_cookie_codec.cc
blockspacer/authservice
b40e1763a20e0a0aab73f4ec0f2cf6e477e855af
[ "Apache-2.0" ]
null
null
null
src/filters/oidc/state_cookie_codec.cc
blockspacer/authservice
b40e1763a20e0a0aab73f4ec0f2cf6e477e855af
[ "Apache-2.0" ]
null
null
null
#include "state_cookie_codec.h" #include <sstream> #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" namespace authservice { namespace filters { namespace oidc { namespace { const char *separator = ";"; } std::string StateCookieCodec::Encode(absl::string_view state, absl::string_view nonce) { return absl::StrJoin({state, nonce}, separator); } absl::optional<std::pair<absl::string_view, absl::string_view>> StateCookieCodec::Decode(absl::string_view value) { std::vector<absl::string_view> values = absl::StrSplit(value, separator); if (values.size() != 2) { return absl::nullopt; } return std::pair<absl::string_view, absl::string_view>(values[0], values[1]); } } // namespace oidc } // namespace filters } // namespace authservice
30.037037
79
0.691739
[ "vector" ]
cad4622dd5769a96cf0592d43a0769d4aa095fee
5,981
cxx
C++
Modules/Filtering/DisplacementField/test/itkDisplacementFieldToBSplineImageFilterTest.cxx
hendradarwin/ITK
12f11d1f408680d24b6380856dd28dbe43582285
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/DisplacementField/test/itkDisplacementFieldToBSplineImageFilterTest.cxx
hendradarwin/ITK
12f11d1f408680d24b6380856dd28dbe43582285
[ "Apache-2.0" ]
null
null
null
Modules/Filtering/DisplacementField/test/itkDisplacementFieldToBSplineImageFilterTest.cxx
hendradarwin/ITK
12f11d1f408680d24b6380856dd28dbe43582285
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkDisplacementFieldToBSplineImageFilter.h" int itkDisplacementFieldToBSplineImageFilterTest( int, char * [] ) { const unsigned int ImageDimension = 2; typedef itk::Vector<float, ImageDimension> VectorType; typedef itk::Image<VectorType, ImageDimension> DisplacementFieldType; typedef itk::PointSet<VectorType, ImageDimension> PointSetType; // Create a displacement field DisplacementFieldType::PointType origin; DisplacementFieldType::SpacingType spacing; DisplacementFieldType::SizeType size; DisplacementFieldType::DirectionType direction; direction.SetIdentity(); origin.Fill( 0.0 ); spacing.Fill( 0.5 ); size.Fill( 100 ); VectorType ones( 1 ); DisplacementFieldType::Pointer field = DisplacementFieldType::New(); field->SetOrigin( origin ); field->SetSpacing( spacing ); field->SetRegions( size ); field->SetDirection( direction ); field->Allocate(); field->FillBuffer( ones ); typedef itk::DisplacementFieldToBSplineImageFilter <DisplacementFieldType, PointSetType> BSplineFilterType; typedef BSplineFilterType::RealImageType RealImageType; RealImageType::Pointer confidenceImage = RealImageType::New(); confidenceImage->CopyInformation( field ); confidenceImage->SetRegions( size ); confidenceImage->Allocate(); confidenceImage->FillBuffer( 1.0 ); PointSetType::Pointer pointSet = PointSetType::New(); pointSet->Initialize(); // Assign some random points within the b-spline domain PointSetType::PointType point1; point1[0] = 23.75; point1[1] = 5.125; pointSet->SetPoint( 0, point1 ); pointSet->SetPointData( 0, ones ); PointSetType::PointType point2; point2[0] = 1.75; point2[1] = 45.125; pointSet->SetPoint( 1, point2 ); pointSet->SetPointData( 1, ones ); PointSetType::PointType point3; point3[0] = 45.75; point3[1] = 2.125; pointSet->SetPoint( 2, point3 ); pointSet->SetPointData( 2, ones ); BSplineFilterType::ArrayType numberOfControlPoints; numberOfControlPoints.Fill( 4 ); BSplineFilterType::Pointer bspliner = BSplineFilterType::New(); bspliner->SetDisplacementField( field ); bspliner->SetConfidenceImage( confidenceImage ); bspliner->SetPointSet( pointSet ); bspliner->SetUseInputFieldToDefineTheBSplineDomain( true ); bspliner->SetNumberOfControlPoints( numberOfControlPoints ); bspliner->SetSplineOrder( 3 ); bspliner->SetNumberOfFittingLevels( 8 ); bspliner->EnforceStationaryBoundaryOff(); bspliner->EnforceStationaryBoundaryOn(); bspliner->SetEnforceStationaryBoundary( false ); bspliner->EstimateInverseOff(); bspliner->EstimateInverseOn(); bspliner->SetEstimateInverse( false ); bspliner->Update(); std::cout << "spline order: " << bspliner->GetSplineOrder() << std::endl; std::cout << "number of control points: " << bspliner->GetNumberOfControlPoints() << std::endl; std::cout << "number of fitting levels: " << bspliner->GetNumberOfFittingLevels() << std::endl; std::cout << "enforce stationary boundary: " << bspliner->GetEnforceStationaryBoundary() << std::endl; std::cout << "estimate inverse: " << bspliner->GetEstimateInverse() << std::endl; try { bspliner->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << std::endl; std::cerr << excp << std::endl; } DisplacementFieldType::IndexType index; index[0] = 50; index[1] = 50; VectorType v = bspliner->GetOutput()->GetPixel( index ); if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 ) { std::cerr << "Failed to find the correct forward displacement vector." << std::endl; return EXIT_FAILURE; } bspliner->SetNumberOfControlPoints( numberOfControlPoints ); bspliner->SetSplineOrder( 3 ); bspliner->SetNumberOfFittingLevels( 5 ); bspliner->EnforceStationaryBoundaryOff(); bspliner->EnforceStationaryBoundaryOn(); bspliner->SetEnforceStationaryBoundary( false ); bspliner->SetEstimateInverse( true ); bspliner->Update(); v = bspliner->GetOutput()->GetPixel( index ); if( vnl_math_abs( v.GetNorm() - 1.414214 ) >= 0.01 ) { std::cerr << "Failed to find the correct inverse displacement vector." << std::endl; return EXIT_FAILURE; } bspliner->Print( std::cout, 3 ); /** do a second run using only the point set. */ BSplineFilterType::Pointer bspliner2 = BSplineFilterType::New(); bspliner2->SetPointSet( pointSet ); bspliner2->SetUseInputFieldToDefineTheBSplineDomain( false ); bspliner2->SetBSplineDomainFromImage( field ); bspliner2->SetNumberOfControlPoints( numberOfControlPoints ); bspliner2->SetSplineOrder( 3 ); bspliner2->SetNumberOfFittingLevels( 8 ); bspliner2->EnforceStationaryBoundaryOff(); bspliner2->EnforceStationaryBoundaryOn(); bspliner2->SetEnforceStationaryBoundary( false ); bspliner2->EstimateInverseOff(); bspliner2->EstimateInverseOn(); bspliner2->SetEstimateInverse( false ); bspliner2->Update(); try { bspliner2->Update(); } catch( itk::ExceptionObject & excp ) { std::cerr << "Exception thrown " << std::endl; std::cerr << excp << std::endl; } return EXIT_SUCCESS; }
33.79096
104
0.693028
[ "vector" ]
cae535919f8e094ee6e9b281d2fdb099a7f85ac8
2,492
cpp
C++
police.cpp
Redoblue/find-the-bombs
9f87abdd895c81acfb24bb697bcfd226004d95dd
[ "MIT" ]
null
null
null
police.cpp
Redoblue/find-the-bombs
9f87abdd895c81acfb24bb697bcfd226004d95dd
[ "MIT" ]
null
null
null
police.cpp
Redoblue/find-the-bombs
9f87abdd895c81acfb24bb697bcfd226004d95dd
[ "MIT" ]
null
null
null
#include "police.h" /* from stl */ #include <iostream> Police::Police(const cv::Mat &frame, const cv::Rect &rect, const int num_dogs) { ColorHistogram ch; cv::Mat imgROI = frame(rect); cv::Mat *hist = ch.getHueHistogram(imgROI, 40); for (int i = 0; i < num_dogs; i++) { Dog *pd = new Dog(frame.cols, frame.rows, rect, hist); _dogs.push_back(pd); _num_dogs = num_dogs; } } void Police::find(cv::Mat &frame, gsl_rng *rng) { std::vector<Dog *>::iterator it; for (it = _dogs.begin(); it != _dogs.end(); it++) { (*it)->run(frame, rng); } } void Police::normalize() { float sum = 0.0f; std::vector<Dog *>::iterator it; for (it = _dogs.begin(); it != _dogs.end(); it++) { sum += (*it)->weight; } for (it = _dogs.begin(); it != _dogs.end(); it++) { (*it)->weight /= sum; } } void Police::reassign() { std::vector<Dog *> tmp_dogs(_dogs); int k = 0; /* clear _polices */ std::vector<Dog *>().swap(_dogs); std::vector<Dog *>::iterator it; for (it = tmp_dogs.begin(); it != tmp_dogs.end(); it++) { int np = cvRound((*it)->weight * _num_dogs); for (int i = 0; i < np; i++) { Dog *pd = new Dog(**it); pd->weight = 0.0f; _dogs.push_back(pd); k++; if (k == _num_dogs) { return; } } } while (k < _num_dogs) { Dog *pd = new Dog(*tmp_dogs.front()); pd->weight = 0.0f; _dogs.push_back(pd); k++; } } void Police::sort_dogs() { std::sort(_dogs.begin(), _dogs.end(), [](Dog *const d1, Dog *const d2) -> bool { return d1->weight > d2->weight; }); } void Police::report_best(cv::Mat &frame, const cv::Scalar color) { Dog *bd = _dogs.front(); int x1 = cvRound(bd->x - 0.5 * bd->s * bd->width); int y1 = cvRound(bd->y - 0.5 * bd->s * bd->height); int x2 = cvRound(bd->s * bd->width) + x1; int y2 = cvRound(bd->s * bd->height) + y1; cv::rectangle(frame, cv::Point(x1, y1), cv::Point(x2, y2), color, 1, 8, 0); } void Police::report_all(cv::Mat &frame, const cv::Scalar color) { cv::Point center; std::vector<Dog *>::iterator it; for (it = _dogs.begin(); it != _dogs.end(); it++) { center.x = cvRound((*it)->x); center.y = cvRound((*it)->y); cv::circle(frame, center, 2, color, -1); } }
25.428571
80
0.50321
[ "vector" ]
caf17b218ed1c226aaa3f19ddcdb9f99829c3e13
2,628
cpp
C++
leetcode/problems/medium/1409-queries-on-a-permutation-with-key.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/medium/1409-queries-on-a-permutation-with-key.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/medium/1409-queries-on-a-permutation-with-key.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Queries on a Permutation With Key https://leetcode.com/problems/queries-on-a-permutation-with-key/ Given the array queries of positive integers between 1 and m, you have to process all queries[i] (from i=0 to i=queries.length-1) according to the following rules: In the beginning, you have the permutation P=[1,2,3,...,m]. For the current i, find the position of queries[i] in the permutation P (indexing from 0) and then move this at the beginning of the permutation P. Notice that the position of queries[i] in P is the result for queries[i]. Return an array containing the result for the given queries. Example 1: Input: queries = [3,1,2,1], m = 5 Output: [2,1,2,1] Explanation: The queries are processed as follow: For i=0: queries[i]=3, P=[1,2,3,4,5], position of 3 in P is 2, then we move 3 to the beginning of P resulting in P=[3,1,2,4,5]. For i=1: queries[i]=1, P=[3,1,2,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,3,2,4,5]. For i=2: queries[i]=2, P=[1,3,2,4,5], position of 2 in P is 2, then we move 2 to the beginning of P resulting in P=[2,1,3,4,5]. For i=3: queries[i]=1, P=[2,1,3,4,5], position of 1 in P is 1, then we move 1 to the beginning of P resulting in P=[1,2,3,4,5]. Therefore, the array containing the result is [2,1,2,1]. Example 2: Input: queries = [4,1,2,2], m = 4 Output: [3,1,2,0] Example 3: Input: queries = [7,5,5,8,3], m = 8 Output: [6,5,0,7,5] Constraints: 1 <= m <= 10^3 1 <= queries.length <= m 1 <= queries[i] <= m */ class Solution { public: template <class T> struct BIT { //1-indexed int n; vector<T> t; BIT() {} BIT(int _n) { n = _n; t.assign(n + 1, 0); } T query(int i) { T ans = 0; for (; i >= 1; i -= (i & -i)) ans += t[i]; return ans; } void upd(int i, T val) { if (i <= 0) return; for (; i <= n; i += (i & -i)) t[i] += val; } void upd(int l, int r, T val) { upd(l, val); upd(r + 1, -val); } T query(int l, int r) { return query(r) - query(l - 1); } }; vector<int> processQueries(vector<int>& queries, int m) { vector<int> ans; // [1 .. m] -> [m + 1 .. 2 * m] BIT bit = BIT<int>(2 * m + 1); unordered_map<int, int> mp; for(int i = 1; i <= m; i++) { mp[i] = i + m; bit.upd(i + m, 1); } for(auto x : queries) { ans.push_back(bit.query(mp[x]) - 1); bit.upd(mp[x], -1); bit.upd(m, 1); mp[x] = m--; } return ans; } };
32.04878
221
0.552131
[ "vector" ]
caf966caca187724b5d30a89871879396a5e6322
686
hpp
C++
teas/teaport_utils/environ.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/environ.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
teas/teaport_utils/environ.hpp
benman64/buildhl
137f53d3817928d67b898653b612bbaa669d0112
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #ifdef _WIN32 #define PATH_DELIMITER ';' #else #define PATH_DELIMITER ':' #endif namespace tea { class EnvironSetter { public: EnvironSetter(const std::string& name); operator std::string() { return to_string(); } std::string to_string(); EnvironSetter &operator=(const std::string &str); EnvironSetter &operator=(int value); EnvironSetter &operator=(bool value); EnvironSetter &operator=(float value); private: std::string mName; }; class Environ { public: EnvironSetter operator[](const std::string&); }; extern Environ cenv; }
22.129032
57
0.629738
[ "vector" ]
1b03d09f95623d3094be710d801e47afeed9e32a
5,234
cpp
C++
Code/Tools/AssetProcessor/native/AssetManager/ControlRequestHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Tools/AssetProcessor/native/AssetManager/ControlRequestHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Tools/AssetProcessor/native/AssetManager/ControlRequestHandler.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <native/AssetManager/ControlRequestHandler.h> #if !defined(Q_MOC_RUN) #include <QHostAddress> #include <QTcpSocket> #include <QTcpServer> #endif #include <native/assetprocessor.h> #include <native/utilities/ApplicationManagerBase.h> #include <AzCore/Casting/numeric_cast.h> #include <AzCore/Debug/Trace.h> ControlRequestHandler::ControlRequestHandler(ApplicationManagerBase* parent) : QObject(parent), m_applicationManager(parent) { connect(m_applicationManager, &ApplicationManagerBase::FullIdle, this, &ControlRequestHandler::AssetManagerIdleStateChange); StartListening(0); } ControlRequestHandler::~ControlRequestHandler() { } bool ControlRequestHandler::StartListening(unsigned short port) { if (!m_tcpServer) { m_tcpServer = new QTcpServer(this); } if (!m_tcpServer->isListening()) { if (!m_tcpServer->listen(QHostAddress::LocalHost, port)) { AZ_Error(AssetProcessor::ConsoleChannel, false, "Control Request Handler couldn't listen on requested port %d", port); return false; } port = m_tcpServer->serverPort(); AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control Port: %d\n", port); connect(m_tcpServer, &QTcpServer::newConnection, this, &ControlRequestHandler::GotConnection); AZ_TracePrintf(AssetProcessor::DebugChannel, "Asset Processor Control Request Handler listening on port %d\n", port); } return true; } void ControlRequestHandler::GotConnection() { if (m_tcpServer->hasPendingConnections()) { QTcpSocket* newSocket = m_tcpServer->nextPendingConnection(); connect(newSocket, &QTcpSocket::stateChanged, this, &ControlRequestHandler::SocketStateUpdate); connect(newSocket, &QTcpSocket::readyRead, this, &ControlRequestHandler::DataReceived); connect(newSocket, &QTcpSocket::disconnected, this, &ControlRequestHandler::Disconnected); m_listenSockets.push_back(newSocket); AZ_TracePrintf(AssetProcessor::DebugChannel, "Asset Processor Control Request Handler got new connection\n"); if (newSocket->bytesAvailable()) { AZ_TracePrintf(AssetProcessor::DebugChannel, "Asset Processor Control Request Handler socket had data available\n"); ReadData(newSocket); } } } void ControlRequestHandler::SocketStateUpdate(QAbstractSocket::SocketState newState) { if (newState == QAbstractSocket::UnconnectedState) { m_listenSockets.removeOne(static_cast<QTcpSocket*>(QObject::sender())); } } void ControlRequestHandler::DataReceived() { QTcpSocket* incoming = static_cast<QTcpSocket*>(QObject::sender()); ReadData(incoming); } void ControlRequestHandler::ReadData(QTcpSocket* incoming) { if (!incoming) { AZ_Error(AssetProcessor::DebugChannel, false, "Attempting to read from null QTcpSocket in ControlRequestHandler"); return; } auto sentMessage = incoming->readAll().toStdString(); AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Got Control request %s\n", sentMessage.c_str()); if (sentMessage == "quit") { QMetaObject::invokeMethod(parent(), "QuitRequested", Qt::QueuedConnection); } else if (sentMessage == "ping") { incoming->write("pong"); } else if (sentMessage == "isidle") { bool isIdle = m_applicationManager->IsAssetProcessorManagerIdle(); incoming->write(isIdle ? "true" : "false"); } else if (sentMessage == "waitforidle") { bool isIdle = m_applicationManager->CheckFullIdle(); if (isIdle) { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control request responding idle\n"); incoming->write("idle"); } else { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control request adding wait idle waiter\n"); m_idleWaitSockets.push_back(incoming); } } else if (sentMessage == "signalidle") { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control request adding signal idle waiter\n"); m_idleWaitSockets.push_back(incoming); } } void ControlRequestHandler::Disconnected() { QTcpSocket* incoming = static_cast<QTcpSocket*>(QObject::sender()); m_listenSockets.removeOne(incoming); incoming->deleteLater(); } void ControlRequestHandler::AssetManagerIdleStateChange(bool isIdle) { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control Request Got idle state %d with %d waiters\n", isIdle, m_idleWaitSockets.size()); if (!isIdle) { // We only currently care when transitioning to idle return; } for (auto& thisConnection : m_idleWaitSockets) { if (m_listenSockets.indexOf(thisConnection) != -1) { AZ_TracePrintf(AssetProcessor::ConsoleChannel, "Control request sending idle state to socket\n"); thisConnection->write("idle"); } } m_idleWaitSockets.clear(); }
32.918239
158
0.691632
[ "3d" ]
db61d963bd57cbf127999b7193a28a51c76d71f3
3,079
cpp
C++
src/mattree/NFANode.cpp
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
4
2018-08-23T08:05:33.000Z
2019-06-13T09:23:27.000Z
src/mattree/NFANode.cpp
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
null
null
null
src/mattree/NFANode.cpp
mahmoudimus/flamingo
61b46a9f57c9aa4050b0dd8b95a44e1abef0d006
[ "Unlicense" ]
null
null
null
// // $Id: NFANode.cpp 5027 2010-02-18 19:41:48Z rares $ // // Copyright (C) 2004 - 2007 by The Regents of the University of // California // // Redistribution of this file is permitted under the terms of the // BSD license // // Date: October, 2004 // // Author: // Liang Jin <liangj (at) ics.uci.edu> // #include "stdafx.h" #include "NFANode.h" #include <string> #include <iostream> #include "parameters.h" //#include <vector> NFANode::NFANode (char name, bool finalState, bool initState) { this->name = name; this->finalState = finalState; this->initState = initState; //branches = new vector(); //backBranches = new vector(); //downBranches = new vector(); //upBranches = new vector(); } NFANode::NFANode (char name, bool finalState, bool initState, int level) { this->name = name; this->finalState = finalState; this->initState = initState; this->level = level; //branches = new vector(); //backBranches = new vector(); //downBranches = new vector(); //upBranches = new vector(); } NFANode::~NFANode () { int i; for(i = 0; i < this->branches.size(); i++) delete (NFATransition*)branches[i]; //for(i = 0; i < this->backBranches.size(); i++) // delete (NFATransition*)backBranches[i]; for(i = 0; i < this->upBranches.size(); i++) delete (NFATransition*)upBranches[i]; //for(i = 0; i < this->downBranches.size(); i++) // delete (NFATransition*)downBranches[i]; } void NFANode::printMe() { int i; cout << "**********Node Info********************" << endl; cout << "number\t\t" << nodeNumber << "\t"; if ( initState){ cout << "init state\t"; } if (finalState){ cout << "final state\t"; } cout << endl; cout << "name\t\t"+name << endl; cout << "to edge:\t\t" << endl; for(i=0; i<branches.size(); i++){ ((NFATransition*)branches[i])->printMe(TO); } cout << "back edge:\t\t" << endl; for(i=0; i<backBranches.size(); i++){ ((NFATransition*)backBranches[i])->printMe(BACK); } cout << endl; } void NFANode::printMeAll() { int i; cout << "**********Node Info********************" << endl; cout << "number\t\t" << nodeNumber << "\t"; if ( initState){ cout << "init state\t"; } if (finalState){ cout << "final state\t"; } cout << endl; cout << "name\t\t"+name << endl; cout << "to edge:\t\t" << endl; for(i=0; i<branches.size(); i++){ ((NFATransition*)branches[i])->printMe(TO); } cout << "back edge:\t\t" << endl; for(i=0; i<backBranches.size(); i++){ ((NFATransition*)backBranches[i])->printMe(BACK); } cout << "down edge:\t\t" << endl; for(i=0; i<downBranches.size(); i++){ ((NFATransition*)downBranches[i])->printMe(DOWN); } cout << "up edge:\t\t" << endl; for(i=0; i<upBranches.size(); i++){ ((NFATransition*)upBranches[i])->printMe(UP); } cout << endl; }
24.054688
73
0.538162
[ "vector" ]
db6270b07b4f0b2b3c6647edae95cbe0f8136789
8,105
hpp
C++
src/LogisticRegressionModel.hpp
bw-young/MachineLearning
fd309002d80b20579f595d07263a0ac59d5c3b80
[ "MIT" ]
null
null
null
src/LogisticRegressionModel.hpp
bw-young/MachineLearning
fd309002d80b20579f595d07263a0ac59d5c3b80
[ "MIT" ]
null
null
null
src/LogisticRegressionModel.hpp
bw-young/MachineLearning
fd309002d80b20579f595d07263a0ac59d5c3b80
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////// // Class and methods for developing and evaluating a logistic // // regression model. // // // // Source: Saishruthi Swaminathan (Logistic Regression--Detailed // // Overview, https://towardsdatascience.com/logistic-regression-detailed-overview-46c4da4303bc, // // posted Mar 15, 2018. // ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // -- HISTORY ---------------------------------------------------- // // 04/08/2021 - Brennan Young // // - created. // // 04/13/2021 - Brennan Young // // - significantly simplified and corrected. // // 04/15/2021 - Brennan Young // // - there can be an occasional issue computing cost with zero or // // near-zero inverse predictions. This is avoided by adding a // // very small number to the inverse predictions. // // - corrected an error where forcing binary outputs would go out // // of bounds. // // 05/06/2021 - Brennan Young // // - corrected an occasional issue computing cost with zero or // // near-zero inverse predictions. This is avoided by adding a // // very small number to the inverse predictions. // ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // -- TO-DO ------------------------------------------------------ // // Might be less efficient, but enable each iteration to be called // // independently, and remove all attempts to report during // // iterations (let the calling program handle that -- also permits // // the calling program to terminate if convergence doesn't occur). // ///////////////////////////////////////////////////////////////////// #ifndef YOUNG_LOGISTICREGRESSION_20210408 #define YOUNG_LOGISTICREGRESSION_20210408 #include <iostream> #include "Matrix.hpp" class LogisticRegressionModel { private: // helpers Matrix<double> sigmoid(const Matrix<double>&) const; double costFunc (const Matrix<double>&, const Matrix<double>&, const Matrix<double>&) const; public: double learn_rate; double cost_threshold; int n_iter; int print_output; Matrix<double> weights; double intercept; double cost; double dCost; int iteration; // constructors, destructor LogisticRegressionModel(double, double, int); LogisticRegressionModel(const LogisticRegressionModel&); ~LogisticRegressionModel(); // operators LogisticRegressionModel& operator=( const LogisticRegressionModel&); // operations void train(const Matrix<double>&, const Matrix<double>&); Matrix<double> predict(const Matrix<double>&, bool) const; Matrix<double> predict(const Matrix<double>&) const; }; // Logistic Model // CONSTRUCTORS / DESTRUCTOR //////////////////////////////////////// LogisticRegressionModel::LogisticRegressionModel ( double lrate=0.0001, double threshold=0.0000001, int n=1000000 ) : learn_rate(lrate), cost_threshold(threshold), n_iter(n), print_output(0), intercept(0), cost(0), dCost(0), iteration(0) {} LogisticRegressionModel::LogisticRegressionModel ( const LogisticRegressionModel& model ) : learn_rate(model.learn_rate), cost_threshold(model.cost_threshold), n_iter(model.n_iter), print_output(model.print_output), weights(model.weights), intercept(model.intercept), cost(model.cost), dCost(model.dCost), iteration(model.iteration) {} LogisticRegressionModel::~LogisticRegressionModel () {} // OPERATORS //////////////////////////////////////////////////////// LogisticRegressionModel& LogisticRegressionModel::operator= ( const LogisticRegressionModel& model ) { if ( &model == this ) return *this; learn_rate = model.learn_rate; cost_threshold = model.cost_threshold; n_iter = model.n_iter; print_output = model.print_output; weights = model.weights; intercept = model.intercept; cost = model.cost; dCost = model.dCost; iteration = model.iteration; return *this; } // OPERATIONS /////////////////////////////////////////////////////// // Activate with the sigmoid function. // -- Arguments -- // Y : vector of values to transform. Matrix<double> LogisticRegressionModel::sigmoid ( const Matrix<double>& Y ) const { return 1.0 / (1.0 + elemExp(-Y)); } // Compute the cost of the current model. // -- Arguments -- // X : independent variable matrix. // Y : training outcome vector. // Yp : predicted outcome vector. double LogisticRegressionModel::costFunc ( const Matrix<double>& X, const Matrix<double>& Y, const Matrix<double>& Yp ) const { Matrix<double> Yt = Y.transpose(); Matrix<double> Ypt = Yp.transpose(); return (-1.0 / X.ncols()) * sum((Yt * elemLog(Ypt + 0.0000001)) + ((1.0 - Yt) * (elemLog(1.0 - Ypt + 0.0000001)))); } // Train the logistic regression model. // -- Arguments -- // X : independent variable training samples, with a column for each // predictor variable and a row for each sample. // Y : dependent variable training samples. void LogisticRegressionModel::train ( const Matrix<double>& X, const Matrix<double>& Y ) { // initialize coefficients weights = randMatrix(1, X.ncols()); intercept = 0.0; // perform the regression Matrix<double> Xt = X.transpose(); Matrix<double> dw; double db; double prevCost = 0; dCost = cost_threshold + 1; for ( iteration = 0; iteration < n_iter && dCost > cost_threshold; ++iteration ) { // predict Matrix<double> Y_predicted = sigmoid( (weights * Xt) + intercept); // compute cost cost = costFunc(X, Y, Y_predicted); dCost = fabs(cost - prevCost); prevCost = cost; // compute gradients Matrix<double> gradient = Y_predicted - Y.transpose(); dw = (1.0 / X.nrows()) * (Xt * gradient.transpose()); db = (1.0 / X.nrows()) * sum(gradient); // update weight weights = weights - (learn_rate * dw.transpose()); intercept = intercept - (learn_rate * db); if ( print_output > 0 && iteration % print_output == 0 ) { std::cout << "epoch " << iteration << " cost " << cost << " :" << " " << intercept; for ( int j = 0; j < weights.size(); ++j ) std::cout << " + " << weights[j] << "x" << (j+1); std::cout << "\n"; } } } // Predict the model outcome. // -- Arguments -- // X : independent variable matrix, with a column for each predictor // and a row for each sample. // b : (default=false) true to force all outputs to 0 or 1; false // for real outputs in the interval [0,1]. // -- Returns -- // Solution vector. Matrix<double> LogisticRegressionModel::predict ( const Matrix<double>& X, bool b ) const { Matrix<double> Y = sigmoid( (weights * X.transpose()) + intercept); for ( int i = 0; b && i < Y.size(); ++i ) Y[i] = Y[i] < 0.5 ? 0.0 : 1.0; return Y; } Matrix<double> LogisticRegressionModel::predict ( const Matrix<double>& X ) const { return predict(X, false); } #endif // YOUNG_LOGISTICREGRESSION_20210408
36.674208
101
0.530907
[ "vector", "model", "transform" ]
db67f85ffa31ad72dcf948052cd325096c03429c
1,125
tpp
C++
include/mgcpp/operations/hdmd.tpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
48
2018-01-02T03:47:18.000Z
2021-09-09T05:55:45.000Z
include/mgcpp/operations/hdmd.tpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
24
2017-12-27T18:03:13.000Z
2018-07-02T09:00:30.000Z
include/mgcpp/operations/hdmd.tpp
MGfoundation/mgcpp
66c072191e58871637bcb3b76701a79a4ae89779
[ "BSL-1.0" ]
6
2018-01-14T14:06:10.000Z
2018-10-16T08:43:01.000Z
// Copyright RedPortal, mujjingun 2017 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <mgcpp/kernels/mgblas_lv1.hpp> #include <mgcpp/operations/hdmd.hpp> #include <mgcpp/system/assert.hpp> #include <mgcpp/system/exception.hpp> namespace mgcpp { template <typename LhsDenseVec, typename RhsDenseVec, typename Type> decltype(auto) strict::hdmd(dense_vector<LhsDenseVec, Type> const& lhs, dense_vector<RhsDenseVec, Type> const& rhs) { using allocator_type = typename LhsDenseVec::allocator_type; auto const& lhs_vec = ~lhs; auto const& rhs_vec = ~rhs; MGCPP_ASSERT(lhs_vec.shape() == rhs_vec.shape(), "matrix dimensions didn't match"); size_t size = lhs_vec.size(); auto result = device_vector<Type, allocator_type>(size); auto status = mgblas_vhp(lhs_vec.data(), rhs_vec.data(), result.data_mutable(), size); if (!status) { MGCPP_THROW_SYSTEM_ERROR(status.error()); } return result; } } // namespace mgcpp
31.25
78
0.692444
[ "shape" ]
db689262683d122838e75a13cc517db78c374698
16,048
cpp
C++
samples/gl/MultipleLights.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
6
2019-01-25T08:41:14.000Z
2021-08-22T07:06:11.000Z
samples/gl/MultipleLights.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
null
null
null
samples/gl/MultipleLights.cpp
kunka/SoftRender
8089844e9ab00ab71ef1a820641ec07ae8df248d
[ "MIT" ]
3
2019-01-25T08:41:16.000Z
2020-09-04T06:04:29.000Z
// // Created by huangkun on 04/04/2018. // #include "MultipleLights.h" TEST_NODE_IMP_BEGIN MultipleLights::MultipleLights() { const char *vert = R"( #version 330 core layout (location = 0) in vec3 a_position; layout (location = 1) in vec3 a_normal; layout (location = 2) in vec2 a_texCoords; out vec3 Normal; out vec3 FragPos; out vec2 TexCoords; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { gl_Position = projection * view * model * vec4(a_position, 1.0); FragPos = vec3(model * vec4(a_position, 1.0)); Normal = mat3(transpose(inverse(model))) * a_normal; // should cal on CPU TexCoords = a_texCoords; } )"; const char *light_frag = R"( #version 330 core out vec4 FragColor; uniform vec3 lightColor; void main() { FragColor = vec4(lightColor, 1.0f); } )"; const char *frag = R"( #version 330 core in vec3 Normal; in vec3 FragPos; out vec4 FragColor; uniform vec3 viewPos; struct Material { sampler2D diffuse; sampler2D specular; float shininess; }; uniform Material material; in vec2 TexCoords; struct DirLight { vec3 direction; vec3 ambient; vec3 diffuse; vec3 specular; }; uniform DirLight dirLight; struct PointLight { vec3 position; float constant; float linear; float quadratic; vec3 ambient; vec3 diffuse; vec3 specular; }; #define NR_POINT_LIGHTS 4 uniform PointLight pointLights[NR_POINT_LIGHTS]; struct SpotLight { vec3 position; vec3 direction; float cutOff; float outerCutOff; vec3 ambient; vec3 diffuse; vec3 specular; float constant; float linear; float quadratic; }; #define NR_SPOT_LIGHTS 1 uniform SpotLight spotLights[NR_SPOT_LIGHTS]; vec3 calcDirLight(DirLight light, vec3 normal, vec3 viewDir); vec3 calcPointLight(PointLight light, vec3 normal, vec3 FragPos, vec3 viewDir); vec3 calcSpotLight(SpotLight light, vec3 norm, vec3 FragPos, vec3 viewDir); void main() { vec3 norm = normalize(Normal); vec3 viewDir = normalize(viewPos - FragPos); // // phase 1: Directional lighting vec3 result = calcDirLight(dirLight, norm, viewDir); // phase 2: Point lights for(int i = 0; i < NR_POINT_LIGHTS; i++) result += calcPointLight(pointLights[i], norm, FragPos, viewDir); // phase 3: Spot light for(int i = 0; i < NR_SPOT_LIGHTS; i++) result += calcSpotLight(spotLights[i], norm, FragPos, viewDir); FragColor = vec4(result, 1.0); } vec3 calcDirLight(DirLight light, vec3 norm, vec3 viewDir) { vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); vec3 lightDir = normalize(-light.direction); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords)); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords)); return diffuse + ambient + specular; } vec3 calcPointLight(PointLight light, vec3 norm, vec3 FragPos, vec3 viewDir) { float distance = length(light.position - FragPos); float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance)); vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); vec3 lightDir = normalize(light.position - FragPos); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords)); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords)); return attenuation*(diffuse + ambient + specular); } vec3 calcSpotLight(SpotLight light, vec3 norm, vec3 FragPos, vec3 viewDir) { // check if lighting is inside the spotlight cone vec3 lightDir = normalize(light.position - FragPos); float theta = dot(lightDir, normalize(-light.direction)); if(theta > light.outerCutOff) { // soft edges float intensity = 1.0; if(theta < light.cutOff) { float epsilon = light.outerCutOff - light.cutOff ; intensity = clamp((light.outerCutOff - theta) / epsilon, 0.0, 1.0); } float distance = length(light.position - FragPos); float attenuation = 1.0 / (light.constant + light.linear * distance + light.quadratic * (distance * distance)); vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = light.diffuse * diff * vec3(texture(material.diffuse, TexCoords)); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), material.shininess); vec3 specular = light.specular * spec * vec3(texture(material.specular, TexCoords)); return attenuation*(diffuse + specular) * intensity + ambient; } else { // use ambient light vec3 ambient = light.ambient * vec3(texture(material.diffuse, TexCoords)); return ambient; } } )"; shader.loadStr(vert, frag); lightShader.loadStr(vert, light_frag); float vertices[] = { // positions // normals // texture coords -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f }; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) 0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) (3 * sizeof(float))); glEnableVertexAttribArray(1); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) (6 * sizeof(float))); glEnableVertexAttribArray(2); // texture int width, height, nrChannels; unsigned char *data = stbi_load("../res/container2.png", &width, &height, &nrChannels, 0); if (!data) { log("Failed to load texture"); return; } else { log("Texture width = %d, height = %d", width, height); } glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data); int width2, height2, nrChannels2; unsigned char *data2 = stbi_load("../res/container2_specular.png", &width2, &height2, &nrChannels2, 0); if (!data2) { log("Failed to load texture2"); return; } else { log("Texture2 width = %d, height = %d", width2, height2); } glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width2, height2, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2); glGenerateMipmap(GL_TEXTURE_2D); // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); stbi_image_free(data2); // point light obj glGenVertexArrays(1, &lightVAO); glBindVertexArray(lightVAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void *) 0); glEnableVertexAttribArray(0); // unbind glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); auto &size = Director::getInstance()->getWinSize(); projection = glm::perspective(glm::radians(60.0f), (float) size.width / (float) size.height, 0.1f, 100.0f); shader.use(); shader.setMat4("projection", projection); shader.setInt("material.diffuse", 0); shader.setInt("material.specular", 1); shader.setFloat("material.shininess", 32.0f); // directional light shader.setVec3("dirLight.direction", vec3(-0.2f, -1.0f, -0.3f)); shader.setVec3("dirLight.ambient", vec3(0.05f, 0.05f, 0.05f)); shader.setVec3("dirLight.diffuse", vec3(0.4f, 0.4f, 0.4f)); shader.setVec3("dirLight.specular", vec3(0.5f, 0.5f, 0.5f)); } void MultipleLights::draw(const mat4 &transform) { glEnable(GL_DEPTH_TEST); glClearColor(0.1f, 0.1f, 0.1f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); static glm::vec3 pointLightPositions[] = { glm::vec3(0.7f, 0.2f, 2.0f), glm::vec3(2.3f, -3.3f, -4.0f), glm::vec3(-4.0f, -2.0f, -6.0f), glm::vec3(0.0f, 0.0f, -3.0f) }; static glm::vec3 pointLightColors[] = { glm::vec3(1.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), glm::vec3(0.0f, 0.0f, 1.0f), glm::vec3(0.0f, 1.0f, 1.0f) }; // use WSAD to control view = glm::lookAt(cameraPos, cameraPos + cameraDir, cameraUp); glBindVertexArray(lightVAO); for (int i = 0; i < 4; i++) { // light obj vec3 lightColor = pointLightColors[i]; vec3 lightPos = pointLightPositions[i]; lightShader.use(); model = glm::mat4(); model = glm::translate(model, lightPos); model = glm::scale(model, glm::vec3(0.2, 0.2f, 0.2f)); lightShader.setMat4("projection", projection); lightShader.setMat4("model", model); lightShader.setMat4("view", view); lightShader.setVec3("lightColor", lightColor); glDrawArrays(GL_TRIANGLES, 0, 36); } glBindVertexArray(VAO); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glm::vec3 cubePositions[] = { glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3(2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3(1.3f, -2.0f, -2.5f), glm::vec3(1.5f, 2.0f, -2.5f), glm::vec3(1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; shader.use(); std::string name; for (int i = 0; i < 4; i++) { name = formatString("pointLights[%d].position", i); shader.setVec3(name, pointLightPositions[i]); name = formatString("pointLights[%d].ambient", i); shader.setVec3(name, vec3(0.2f, 0.2f, 0.2f) * pointLightColors[i]); name = formatString("pointLights[%d].diffuse", i); shader.setVec3(name, vec3(0.5f, 0.5f, 0.5f) * pointLightColors[i]); name = formatString("pointLights[%d].specular", i); shader.setVec3(name, vec3(1.0f, 1.0f, 1.0f) * pointLightColors[i]); name = formatString("pointLights[%d].constant", i); shader.setFloat(name, 1.0f); name = formatString("pointLights[%d].linear", i); shader.setFloat(name, 0.09f); name = formatString("pointLights[%d].quadratic", i); shader.setFloat(name, 0.032f); } shader.setVec3("spotLights[0].ambient", vec3(0.0f, 0.0f, 0.0f)); shader.setVec3("spotLights[0].diffuse", vec3(1.0f, 1.0f, 1.0f)); // darken the light a bit to fit the scene shader.setVec3("spotLights[0].specular", vec3(1.0f, 1.0f, 1.0f)); shader.setFloat("spotLights[0].constant", 1.0f); shader.setFloat("spotLights[0].linear", 0.09f); shader.setFloat("spotLights[0].quadratic", 0.032f); shader.setFloat("spotLights[0].cutOff", glm::cos(glm::radians(9.0f))); shader.setFloat("spotLights[0].outerCutOff", glm::cos(glm::radians(12.0f))); shader.setVec3("spotLights[0].position", cameraPos); shader.setVec3("spotLights[0].direction", cameraDir); shader.setMat4("view", view); shader.setVec3("viewPos", cameraPos); for (unsigned int i = 0; i < 10; i++) { model = glm::mat4(); model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); shader.setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } glDisable(GL_DEPTH_TEST); } MultipleLights::~MultipleLights() { glDeleteVertexArrays(1, &VAO); glDeleteVertexArrays(1, &lightVAO); glDeleteBuffers(1, &VBO); } TEST_NODE_IMP_END
37.062356
119
0.581505
[ "object", "model", "transform" ]
db6a22ab40a779cf47c9f95b30a7869eb82b1d1d
19,112
cpp
C++
src/game/shared/swarm/asw_alien_goo_shared.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
3
2015-05-17T02:33:00.000Z
2016-10-08T07:02:40.000Z
src/game/shared/swarm/asw_alien_goo_shared.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
null
null
null
src/game/shared/swarm/asw_alien_goo_shared.cpp
BenLubar/SwarmDirector2
78685d03eaa0d35e87c638ffa78f46f3aa8379a6
[ "Apache-2.0" ]
1
2019-10-16T15:21:56.000Z
2019-10-16T15:21:56.000Z
#include "cbase.h" #ifdef CLIENT_DLL #define CBaseFlex C_BaseFlex #define CASW_Alien_Goo C_ASW_Alien_Goo #define CASW_Grub_Sac C_ASW_Grub_Sac #include "c_asw_generic_emitter_entity.h" #include "c_asw_fx.h" #include "baseparticleentity.h" #include "asw_util_shared.h" #else #include "EntityFlame.h" #include "asw_simple_grub.h" #include "asw_marine.h" #include "asw_player.h" #include "asw_fx_shared.h" #include "asw_util_shared.h" #include "asw_gamerules.h" #include "asw_mission_manager.h" #include "asw_entity_dissolve.h" #include "asw_marine_speech.h" #include "asw_burning.h" #include "te_effect_dispatch.h" #include "cvisibilitymonitor.h" #include "asw_director.h" #endif #include "asw_alien_goo_shared.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #define ASW_GRUB_SAC_BURST_DISTANCE 180.0f #define ACID_BURN_INTERVAL 1.0f #define ASW_ACID_DAMAGE 10.0f IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Alien_Goo, DT_ASW_Alien_Goo ) BEGIN_NETWORK_TABLE( CASW_Alien_Goo, DT_ASW_Alien_Goo ) #ifdef CLIENT_DLL // recvprops RecvPropFloat (RECVINFO(m_fPulseStrength)), RecvPropFloat (RECVINFO(m_fPulseSpeed)), RecvPropBool(RECVINFO(m_bOnFire)), #else // sendprops SendPropExclude( "DT_BaseFlex", "m_flexWeight" ), // don't send the weights from the server, we'll animate them clientside SendPropFloat (SENDINFO(m_fPulseStrength), 10, SPROP_UNSIGNED ), SendPropFloat (SENDINFO(m_fPulseSpeed), 10, SPROP_UNSIGNED ), SendPropBool(SENDINFO(m_bOnFire)), #endif END_NETWORK_TABLE() #ifdef GAME_DLL ConVar asw_goo_volume("asw_goo_volume", "1.0f", FCVAR_CHEAT, "Volume of the alien goo looping sound"); LINK_ENTITY_TO_CLASS( asw_alien_goo, CASW_Alien_Goo ); PRECACHE_WEAPON_REGISTER(asw_alien_goo); #endif #ifndef CLIENT_DLL //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CASW_Alien_Goo ) DEFINE_KEYFIELD( m_fPulseStrength, FIELD_FLOAT, "PulseStrength" ), DEFINE_KEYFIELD( m_fPulseSpeed, FIELD_FLOAT, "PulseSpeed" ), DEFINE_KEYFIELD( m_BurningLinkName, FIELD_STRING, "BurningLinkName" ), DEFINE_KEYFIELD( m_fGrubSpawnAngle, FIELD_FLOAT, "GrubSpawnAngle" ), DEFINE_KEYFIELD( m_bHasAmbientSound, FIELD_BOOLEAN, "HasAmbientSound" ), DEFINE_KEYFIELD( m_bRequiredByObjective, FIELD_BOOLEAN, "RequiredByObjective" ), DEFINE_FIELD( m_bSpawnedGrubs, FIELD_BOOLEAN ), DEFINE_FIELD( m_bHasGrubs, FIELD_BOOLEAN ), DEFINE_FIELD( m_bOnFire, FIELD_BOOLEAN ), DEFINE_THINKFUNC(BurningLinkThink), DEFINE_THINKFUNC(InitThink), DEFINE_THINKFUNC(GrubSacThink), DEFINE_FUNCTION( GooTouch ), DEFINE_FUNCTION( GooAcidTouch ), DEFINE_INPUTFUNC( FIELD_VOID, "Burst", InputBurst ), DEFINE_OUTPUT( m_OnGooDestroyed, "OnGooDestroyed" ), END_DATADESC() float CASW_Alien_Goo::s_fNextSpottedChatterTime = 0; CUtlVector<CASW_Alien_Goo*> g_AlienGoo; #endif // not client CASW_Alien_Goo::CASW_Alien_Goo() { #ifdef CLIENT_DLL m_fPulseCycle = 0; m_bClientOnFire = false; m_pBurningEffect = NULL; #else m_bPlayingAmbientSound = false; m_bPlayingGooScream = false; m_fNextAcidBurnTime = 0; #endif m_fPulseStrength = 1.0f; m_fPulseSpeed = 1.0f; #ifndef CLIENT_DLL g_AlienGoo.AddToTail( this ); #endif } CASW_Alien_Goo::~CASW_Alien_Goo() { #ifdef CLIENT_DLL m_bOnFire = false; UpdateFireEmitters(); #endif #ifndef CLIENT_DLL g_AlienGoo.FindAndRemove( this ); #endif } #ifndef CLIENT_DLL void CASW_Alien_Goo::Spawn() { BaseClass::Spawn(); char *szModel = (char *)STRING( GetModelName() ); if (!szModel || !*szModel) { Warning( "%s at %.0f %.0f %0.f missing modelname\n", GetClassname(), GetAbsOrigin().x, GetAbsOrigin().y, GetAbsOrigin().z ); UTIL_Remove( this ); return; } if (FClassnameIs(this, "asw_grub_sac")) { m_bHasGrubs = true; m_fPulseStrength = 1.0f; m_fPulseSpeed = random->RandomFloat(1.5f, 3.0f); SetBlocksLOS(false); } PrecacheModel( szModel ); Precache(); SetModel( szModel ); SetMoveType( MOVETYPE_NONE ); SetSolid(SOLID_VPHYSICS); SetCollisionGroup( COLLISION_GROUP_NONE ); //COLLISION_GROUP_DEBRIS ); m_takedamage = DAMAGE_YES; m_iHealth = 100; m_iMaxHealth = m_iHealth; AddFlag( FL_STATICPROP ); VPhysicsInitStatic(); SetThink( &CASW_Alien_Goo::InitThink ); SetNextThink( gpGlobals->curtime + random->RandomFloat(5.0f, 10.0f)); if ( m_bRequiredByObjective ) { VisibilityMonitor_AddEntity( this, asw_visrange_generic.GetFloat() * 0.9f, NULL, NULL ); } } void CASW_Alien_Goo::InitThink() { if (m_bHasAmbientSound && !m_bPlayingAmbientSound) { if (!UTIL_ASW_MissionHasBriefing(STRING(gpGlobals->mapname))) { StartGooSound(); } } // if spawns grubs if (m_bHasGrubs) { SetTouch( &CASW_Alien_Goo::GooTouch ); } else { SetTouch( &CASW_Alien_Goo::GooAcidTouch ); } // all goo needs to think periodically, so marines can shout about it // check if we need to burst open thanks to nearby marines SetThink( &CASW_Alien_Goo::GrubSacThink ); SetNextThink( gpGlobals->curtime + 1.0f ); } void CASW_Alien_Goo::Event_Killed( const CTakeDamageInfo &info ) { m_OnGooDestroyed.FireOutput( this, this ); if (!m_bHasGrubs) { if (ASWGameRules() && ASWGameRules()->GetMissionManager()) ASWGameRules()->GetMissionManager()->GooKilled(this); } StopGooSound(); BaseClass::Event_Killed(info); } void CASW_Alien_Goo::Precache() { PrecacheModel( "models/aliens/biomass/biomasshelix.mdl" ); PrecacheModel( "models/aliens/biomass/biomassl.mdl" ); PrecacheModel( "models/aliens/biomass/biomasss.mdl" ); PrecacheModel( "models/aliens/biomass/biomassu.mdl" ); PrecacheScriptSound("ASWGoo.GooLoop"); PrecacheScriptSound("ASWGoo.GooScream"); PrecacheScriptSound("ASWGoo.GooDissolve"); PrecacheScriptSound("ASWFire.AcidBurn"); PrecacheParticleSystem( "biomass_dissolve" ); PrecacheParticleSystem( "acid_touch" ); PrecacheParticleSystem( "grubsack_death" ); UTIL_PrecacheOther( "asw_grub" ); BaseClass::Precache(); } int CASW_Alien_Goo::OnTakeDamage( const CTakeDamageInfo &info ) { CASW_Marine* pMarine = dynamic_cast<CASW_Marine*>(info.GetAttacker()); // if has grubs if ( m_bHasGrubs && HasSpawnFlags( ASW_SF_BURST_WHEN_DAMAGED ) ) { SpawnGrubs(); if ( pMarine) pMarine->HurtAlien(this, info); } // goo is only damaged by fire! if ( !( info.GetDamageType() & DMG_BURN ) && !( info.GetDamageType() & DMG_ENERGYBEAM ) ) return 0; // notify the marine that he's hurting this, so his accuracy doesn't drop if (info.GetAttacker() && info.GetAttacker()->Classify() == CLASS_ASW_MARINE) { if ( pMarine ) { pMarine->HurtJunkItem( this, info ); } } // if this damage would make us close to dying, then make us dissolve instead if ( m_iHealth - info.GetDamage() < 10.0f ) { if ( !IsDissolving() ) { //bool bRagdollCreated = Dissolve( NULL, gpGlobals->curtime, false, ENTITY_DISSOLVE_NORMAL ); //Msg("Dissolved = %d\n", bRagdollCreated); return 0; } else if ( info.GetDamage() != 10000.0 ) // when dissolving, only the dissolve damage will kill us { return 0; } } int result = BaseClass::OnTakeDamage( info ); if ( result > 0 ) { if ( info.GetDamageType() & DMG_BURN ) { Ignite( 30.0f ); if (ASWDirector()) { ASWDirector()->OnMarineBurnedBiomass( pMarine, this ); } CASW_Player *pPlayerAttacker = NULL; if ( pMarine ) { pPlayerAttacker = pMarine->GetCommander(); } IGameEvent * event = gameeventmanager->CreateEvent( "alien_ignited" ); if ( event ) { event->SetInt( "userid", ( pPlayerAttacker ? pPlayerAttacker->GetUserID() : 0 ) ); event->SetInt( "entindex", entindex() ); gameeventmanager->FireEventClientSide( event ); } } } return result; } void CASW_Alien_Goo::Ignite( float flFlameLifetime, bool bNPCOnly, float flSize, bool bCalledByLevelDesigner ) { if ( IsOnFire() || m_bHasGrubs ) { return; } AddFlag( FL_ONFIRE ); m_bOnFire = true; if ( ASWBurning() ) { ASWBurning()->BurnEntity(this, NULL, flFlameLifetime, 0.4f, 5.0f * 0.4f); // 5 dps, applied every 0.4 seconds } m_OnIgnite.FireOutput( this, this ); // wail StartScreaming(); // set up a delay to burn our linked entities SetThink( &CASW_Alien_Goo::BurningLinkThink ); SetNextThink( gpGlobals->curtime + 2.0f ); } void CASW_Alien_Goo::Extinguish() { m_bOnFire = false; if (ASWBurning()) ASWBurning()->Extinguish(this); RemoveFlag( FL_ONFIRE ); } // periodically find the nearest marine and check if we should burst open void CASW_Alien_Goo::GrubSacThink() { if (m_bHasAmbientSound && !m_bPlayingAmbientSound) { if (UTIL_ASW_MissionHasBriefing(STRING(gpGlobals->mapname)) && ASWGameRules() && ASWGameRules()->GetGameState() == ASW_GS_INGAME) StartGooSound(); } if (m_bHasGrubs) { float marine_distance = -1; if (UTIL_ASW_NearestMarine(GetAbsOrigin(), marine_distance )) // returns the nearest marine to this point { if (m_bHasGrubs && HasSpawnFlags(ASW_SF_BURST_WHEN_NEAR)) { if (marine_distance <= ASW_GRUB_SAC_BURST_DISTANCE) { SpawnGrubs(); return; } } // NOTE: Marines chattering about alien good disabled, as it sounded bad /* else if (marine_distance < 300 && gpGlobals->curtime > s_fNextSpottedChatterTime) { CASW_Marine *pSpottedMarine = UTIL_ASW_Marine_Can_Chatter_Spot(this, 300); if (pSpottedMarine) { pSpottedMarine->GetMarineSpeech()->Chatter(CHATTER_BIOMASS); s_fNextSpottedChatterTime = gpGlobals->curtime + 30.0f; } else s_fNextSpottedChatterTime = gpGlobals->curtime + 1.0f; }*/ } // rethink interval based on how near the marines are if (marine_distance == -1 || marine_distance > 4096) { SetNextThink( gpGlobals->curtime + 5.0f ); } else if (marine_distance > 1024) { SetNextThink( gpGlobals->curtime + 2.0f ); } else { SetNextThink( gpGlobals->curtime + 1.0f ); } } else { if (m_bHasAmbientSound && !m_bPlayingAmbientSound) { SetNextThink( gpGlobals->curtime + random->RandomFloat(2.0f, 5.0f) ); } } } void CASW_Alien_Goo::BurningLinkThink() { CBaseEntity *ent = NULL; while ( (ent = gEntList.NextEnt(ent)) != NULL ) { CASW_Alien_Goo *pGoo = dynamic_cast<CASW_Alien_Goo*>(ent); if (pGoo) { if ( (pGoo->GetBurningLinkName() != NULL_STRING && FStrEq(STRING(m_BurningLinkName), STRING(pGoo->GetBurningLinkName()))) && (ent->GetClassname()!=NULL && (FStrEq("asw_alien_goo", ent->GetClassname()) || FStrEq("asw_grub_sac", ent->GetClassname()) ))) { pGoo->Ignite(30.0f); } } } } void CASW_Alien_Goo::GooAcidTouch(CBaseEntity* pOther) { // if touched by a marine, acid burn him! if (pOther && pOther->Classify() == CLASS_ASW_MARINE) { if (m_fNextAcidBurnTime == 0 || gpGlobals->curtime > m_fNextAcidBurnTime) { m_fNextAcidBurnTime = gpGlobals->curtime + ACID_BURN_INTERVAL; CTakeDamageInfo info( this, this, ASW_ACID_DAMAGE, DMG_ACID ); Vector killDir = pOther->GetAbsOrigin() - GetAbsOrigin(); VectorNormalize( killDir ); info.SetDamageForce( killDir ); Vector vecDamagePos = pOther->GetAbsOrigin() -killDir * 32.0f; info.SetDamagePosition( vecDamagePos ); pOther->TakeDamage(info); EmitSound("ASWFire.AcidBurn"); CEffectData data; data.m_vOrigin = vecDamagePos; data.m_nOtherEntIndex = pOther->entindex(); DispatchEffect( "ASWAcidBurn", data ); } } } void CASW_Alien_Goo::GooTouch(CBaseEntity* pOther) { // egg will open if touched by a marine CASW_Marine* pMarine = CASW_Marine::AsMarine( pOther ); if (pMarine && m_bHasGrubs && HasSpawnFlags(ASW_SF_BURST_WHEN_TOUCHED)) { SetTouch( NULL ); SpawnGrubs(); } } bool CASW_Alien_Goo::RoomToSpawnGrub(const Vector& pos) { // Check to see if there's enough room to spawn trace_t tr; UTIL_TraceHull( pos, pos, Vector(-12,-12,0),Vector(12,12,0), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr ); if ( tr.m_pEnt || tr.startsolid ) { return false; } return true; } // makes this bit of goo burst and spawn some grubs void CASW_Alien_Goo::SpawnGrubs() { if (m_bSpawnedGrubs) return; m_bSpawnedGrubs = true; AddSolidFlags( FSOLID_NOT_SOLID ); int num_grubs = random->RandomInt(4,5); if (m_fGrubSpawnAngle <= 0) m_fGrubSpawnAngle = 180.0f; //Vector mins = WorldAlignMins() + GetAbsOrigin(); //Vector maxs = WorldAlignMaxs() + GetAbsOrigin(); if (!CollisionProp()) return; // for some reason if we calculate these inside the loop, the random numbers all come out the same. Worrying. QAngle angGrubFacing[5]; angGrubFacing[0] = GetAbsAngles(); angGrubFacing[0].y += RandomFloat(-m_fGrubSpawnAngle, m_fGrubSpawnAngle); angGrubFacing[1] = GetAbsAngles(); angGrubFacing[1].y += RandomFloat(-m_fGrubSpawnAngle, m_fGrubSpawnAngle); angGrubFacing[2] = GetAbsAngles(); angGrubFacing[2].y += RandomFloat(-m_fGrubSpawnAngle, m_fGrubSpawnAngle); angGrubFacing[3] = GetAbsAngles(); angGrubFacing[3].y += RandomFloat(-m_fGrubSpawnAngle, m_fGrubSpawnAngle); angGrubFacing[4] = GetAbsAngles(); angGrubFacing[4].y += RandomFloat(-m_fGrubSpawnAngle, m_fGrubSpawnAngle); Vector vecSpawnPos[5]; CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[0] ); CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[1] ); CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[2] ); CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[3] ); CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[4] ); Vector mins, maxs; CollisionProp()->WorldSpaceAABB( &mins, &mins ); for (int i=0;i<num_grubs;i++) { angGrubFacing[i].x = 0; vecSpawnPos[i].z += 1.0f; int count = 0; while (!RoomToSpawnGrub(vecSpawnPos[i]) && count < 5) { CollisionProp()->RandomPointInBounds( Vector(0.1f, 0.1f, 0.1f), Vector( 0.9f, 0.9f, 0.9f ), &vecSpawnPos[i] ); count++; } if (count >= 5) continue; UTIL_ASW_DroneBleed( vecSpawnPos[i], Vector(0,0,1), 4 ); CASW_Simple_Grub* pGrub = dynamic_cast<CASW_Simple_Grub*>(CreateNoSpawn("asw_grub", vecSpawnPos[i], angGrubFacing[i], this)); if (pGrub) { ASWGameRules()->GrubSpawned(pGrub); pGrub->AddSpawnFlags(SF_NPC_FALL_TO_GROUND); // stop it teleporting to the ground pGrub->Spawn(); pGrub->m_fFallSpeed = 250; pGrub->PlayFallingAnimation(); } } EmitSound("ASW_Parasite.EggBurst"); UTIL_ASW_EggGibs( WorldSpaceCenter(), EGG_FLAG_GRUBSACK_DIE, entindex() ); trace_t ptr; Vector vecDir( 0, 0, -1.0f ); ptr.endpos = GetLocalOrigin(); ptr.endpos[2] += 8.0f; // make blood decal on the floor trace_t Bloodtr; Vector vecTraceDir; int k; for ( k = 0 ; k < 4 ; k++ ) { vecTraceDir = vecDir; vecTraceDir.x += random->RandomFloat( -0.8f, 0.8f ); vecTraceDir.y += random->RandomFloat( -0.8f, 0.8f ); vecTraceDir.z += random->RandomFloat( -0.8f, 0.8f ); AI_TraceLine( ptr.endpos, ptr.endpos + vecTraceDir * 172, MASK_SOLID_BRUSHONLY, this, COLLISION_GROUP_NONE, &Bloodtr); if ( Bloodtr.fraction != 1.0 ) { UTIL_BloodDecalTrace( &Bloodtr, BLOOD_COLOR_BRIGHTGREEN ); } } UTIL_Remove( this ); } // make this goo sac burst open and spit out grubs void CASW_Alien_Goo::InputBurst( inputdata_t &inputdata ) { if (m_bHasGrubs && HasSpawnFlags(ASW_SF_BURST_ON_INPUT)) SpawnGrubs(); } void CASW_Alien_Goo::StartGooSound() { m_bPlayingAmbientSound = true; UTIL_EmitAmbientSound(GetSoundSourceIndex(), GetAbsOrigin(), "ASWGoo.GooLoop", random->RandomFloat(0.9f, 1.0f) * asw_goo_volume.GetFloat(), SNDLVL_85dB, SND_CHANGE_VOL, random->RandomInt( 95, 105 )); } void CASW_Alien_Goo::StartScreaming() { if (!m_bPlayingGooScream) { StopGooSound(); m_bPlayingGooScream = true; UTIL_EmitAmbientSound(GetSoundSourceIndex(), GetAbsOrigin(), "ASWGoo.GooScream", random->RandomFloat(0.9f, 1.0f) * asw_goo_volume.GetFloat(), SNDLVL_95dB, SND_CHANGE_VOL, random->RandomInt( 95, 105 )); } } void CASW_Alien_Goo::StopLoopingSounds() { StopGooSound(); } void CASW_Alien_Goo::StopGooSound() { if (m_bPlayingGooScream) UTIL_EmitAmbientSound(GetSoundSourceIndex(), GetAbsOrigin(), "ASWGoo.GooLoop", 0, SNDLVL_NONE, SND_STOP, 0); else UTIL_EmitAmbientSound(GetSoundSourceIndex(), GetAbsOrigin(), "ASWGoo.GooLoop", 0, SNDLVL_NONE, SND_STOP, 0); } bool CASW_Alien_Goo::Dissolve( const char *pMaterialName, float flStartTime, bool bNPCOnly, int nDissolveType ) { // Right now this prevents stuff we don't want to catch on fire from catching on fire. if( bNPCOnly && !(GetFlags() & FL_NPC) ) return false; // Can't dissolve twice if ( IsDissolving() ) return false; bool bRagdollCreated = false; CASW_Entity_Dissolve *pDissolve = CASW_Entity_Dissolve::Create( this, pMaterialName, flStartTime, nDissolveType, &bRagdollCreated ); if (pDissolve) { SetEffectEntity( pDissolve ); AddFlag( FL_DISSOLVING ); // m_flDissolveStartTime = flStartTime; EmitSound( "ASWGoo.GooDissolve" ); } return bRagdollCreated; } #else // make all our flex controllers sine in and out, each one time offset a bit to // create a rippling pulse in the mesh void CASW_Alien_Goo::SetupWeights( const matrix3x4_t *pBoneToWorld, int nFlexWeightCount, float *pFlexWeights, float *pFlexDelayedWeights ) { m_fPulseCycle += gpGlobals->frametime * m_fPulseSpeed; float interval = 1.5f / nFlexWeightCount; for (int i = 0; i < nFlexWeightCount; i++) { pFlexWeights[i] = sin(m_fPulseCycle + i * interval); if (pFlexWeights[i] < 0) pFlexWeights[i] = -pFlexWeights[i]; pFlexWeights[i] *= m_fPulseStrength; } if ( pFlexDelayedWeights ) { memset( pFlexDelayedWeights, 0, nFlexWeightCount * sizeof(float) ); } } void CASW_Alien_Goo::OnDataChanged( DataUpdateType_t type ) { BaseClass::OnDataChanged( type ); UpdateFireEmitters(); } void CASW_Alien_Goo::UpdateFireEmitters() { bool bOnFire = (m_bOnFire && !IsEffectActive(EF_NODRAW)); if (bOnFire != m_bClientOnFire) { m_bClientOnFire = bOnFire; if (m_bClientOnFire) { if ( !m_pBurningEffect ) { m_pBurningEffect = UTIL_ASW_CreateFireEffect( this ); } EmitSound( "ASWFire.BurningFlesh" ); } else { if ( m_pBurningEffect ) { ParticleProp()->StopEmission( m_pBurningEffect ); m_pBurningEffect = NULL; } StopSound("ASWFire.BurningFlesh"); if ( C_BaseEntity::IsAbsQueriesValid() ) EmitSound("ASWFire.StopBurning"); } } } void CASW_Alien_Goo::UpdateOnRemove() { BaseClass::UpdateOnRemove(); m_bOnFire = false; UpdateFireEmitters(); } #endif // not client /// ========================== grub sac version ======================= #ifndef CLIENT_DLL LINK_ENTITY_TO_CLASS( asw_grub_sac, CASW_Grub_Sac ); #endif IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Grub_Sac, DT_ASW_Grub_Sac ) BEGIN_NETWORK_TABLE( CASW_Grub_Sac, DT_ASW_Grub_Sac ) #ifdef CLIENT_DLL // recvprops #else // sendprops #endif END_NETWORK_TABLE() CASW_Grub_Sac::CASW_Grub_Sac() { } CASW_Grub_Sac::~CASW_Grub_Sac() { }
27.45977
139
0.71081
[ "mesh", "vector" ]
db6bed2044ed827ce79ab22887f9f000cb44b235
21,438
cpp
C++
lib/cpp-test/hawkes/model/hawkes_models_gtest.cpp
sumau/tick
1b56924a35463e12f7775bc0aec182364f26f2c6
[ "BSD-3-Clause" ]
411
2017-03-30T15:22:05.000Z
2022-03-27T01:58:34.000Z
lib/cpp-test/hawkes/model/hawkes_models_gtest.cpp
saurabhdash/tick
bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48
[ "BSD-3-Clause" ]
345
2017-04-13T14:53:20.000Z
2022-03-26T00:46:22.000Z
lib/cpp-test/hawkes/model/hawkes_models_gtest.cpp
saurabhdash/tick
bbc561804eb1fdcb4c71b9e3e2d83a66e7b13a48
[ "BSD-3-Clause" ]
102
2017-04-25T11:47:53.000Z
2022-02-15T11:45:49.000Z
// License: BSD 3 clause #include <algorithm> #include <complex> #include <numeric> #define DEBUG_COSTLY_THROW 1 #include <gtest/gtest.h> #include "tick/hawkes/model/model_hawkes_sumexpkern_loglik_single.h" #include <cereal/archives/portable_binary.hpp> #include <cereal/types/unordered_map.hpp> #include <fstream> #include "tick/hawkes/model/model_hawkes_expkern_leastsq_single.h" #include "tick/hawkes/model/model_hawkes_expkern_loglik_single.h" #include "tick/hawkes/model/model_hawkes_sumexpkern_leastsq_single.h" #include "tick/hawkes/model/list_of_realizations/model_hawkes_expkern_leastsq.h" #include "tick/hawkes/model/list_of_realizations/model_hawkes_expkern_loglik.h" #include "tick/hawkes/model/list_of_realizations/model_hawkes_sumexpkern_leastsq.h" #include "tick/hawkes/model/list_of_realizations/model_hawkes_sumexpkern_loglik.h" class HawkesModelTest : public ::testing::Test { protected: SArrayDoublePtrList1D timestamps; void SetUp() override { timestamps = SArrayDoublePtrList1D(0); // Test will fail if process array is not sorted ArrayDouble timestamps_0 = ArrayDouble{0.31, 0.93, 1.29, 2.32, 4.25}; timestamps.push_back(timestamps_0.as_sarray_ptr()); ArrayDouble timestamps_1 = ArrayDouble{0.12, 1.19, 2.12, 2.41, 3.35, 4.21}; timestamps.push_back(timestamps_1.as_sarray_ptr()); } }; TEST_F(HawkesModelTest, hawkes_loglik_serialization) { ModelHawkesLogLik model; auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesLogLik restored_model(0); inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ((*restored_model.get_end_times())[1], 5.87); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, hawkes_loglik_single_serialization) { ModelHawkesLogLikSingle model; model.set_data(timestamps, 5.65); std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesLogLikSingle restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ(restored_model.get_end_time(), 5.65); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, hawkes_sum_exp_loglik_serialization) { ArrayDouble decays{2., 3.}; ModelHawkesSumExpKernLogLik model(decays, 2); auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesSumExpKernLogLik restored_model(ArrayDouble(), 0); inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ((*restored_model.get_end_times())[1], 5.87); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); auto why = (model == restored_model); if(!why) std::cerr << why.why() << std::endl; ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, hawkes_exp_loglik_serialization) { double decay = 2.; ModelHawkesExpKernLogLik model(decay, 2); auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesExpKernLogLik restored_model(0, 0); inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ((*restored_model.get_end_times())[1], 5.87); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, hawkes_exp_loglik_single_serialization) { double decay = 2.; ModelHawkesExpKernLogLikSingle model(decay); model.set_data(timestamps, 5.65); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesExpKernLogLikSingle restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ(restored_model.get_end_time(), 5.65); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, hawkes_sum_exp_loglik_single_serialization) { ArrayDouble decays{2., 3.}; ModelHawkesSumExpKernLogLikSingle model(decays); model.set_data(timestamps, 5.65); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesSumExpKernLogLikSingle restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2); EXPECT_EQ(restored_model.get_end_time(), 5.65); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, compute_weights_loglikelihood) { ModelHawkesExpKernLogLikSingle model(2); model.set_data(timestamps, 4.25); model.compute_weights(); } TEST_F(HawkesModelTest, compute_loss_loglikelihood) { ModelHawkesExpKernLogLikSingle model(2); model.set_data(timestamps, 4.25); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; const double loss = model.loss(coeffs); ArrayDouble grad(model.get_n_coeffs()); model.grad(coeffs, grad); EXPECT_DOUBLE_EQ(loss, 2.9434509731246283); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 6); } TEST_F(HawkesModelTest, compute_loss_loglikelihood_sparse) { ModelHawkesExpKernLogLikSingle model(2); auto sparse_timestamps = SArrayDoublePtrList1D(0); // Test will fail if process array is not sorted ArrayDouble timestamps_0 = ArrayDouble{0.31, 0.93, 1.29, 2.32, 4.25}; sparse_timestamps.push_back(timestamps_0.as_sarray_ptr()); ArrayDouble timestamps_1 = ArrayDouble(0); sparse_timestamps.push_back(timestamps_1.as_sarray_ptr()); model.set_data(sparse_timestamps, 4.25); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; const double loss = model.loss(coeffs); ArrayDouble grad(model.get_n_coeffs()); model.grad(coeffs, grad); EXPECT_DOUBLE_EQ(loss, 5.9243119662517856); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 6); } TEST_F(HawkesModelTest, check_sto_loglikelihood) { ModelHawkesExpKernLogLikSingle model(2); model.set_data(timestamps, 6.); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; const double loss = model.loss(coeffs); ArrayDouble grad(model.get_n_coeffs()); model.grad(coeffs, grad); double sum_sto_loss = 0; ArrayDouble sto_grad(model.get_n_coeffs()); sto_grad.init_to_zero(); ArrayDouble tmp_sto_grad(model.get_n_coeffs()); for (ulong i = 0; i < model.get_rand_max(); ++i) { sum_sto_loss += model.loss_i(i, coeffs) / model.get_rand_max(); tmp_sto_grad.init_to_zero(); model.grad_i(i, coeffs, tmp_sto_grad); sto_grad.mult_incr(tmp_sto_grad, 1. / model.get_rand_max()); } EXPECT_DOUBLE_EQ(loss, sum_sto_loss); for (ulong i = 0; i < model.get_n_coeffs(); ++i) { SCOPED_TRACE(i); EXPECT_DOUBLE_EQ(grad[i], sto_grad[i]); } } TEST_F(HawkesModelTest, compute_loss_loglikelihood_sum_exp_kern) { ArrayDouble decays{1., 2., 3.}; const double end_time = 5.65; ModelHawkesSumExpKernLogLikSingle model(decays, 1); model.set_data(timestamps, end_time); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4., 2., 3., 4., 5.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 0.43573314143220188); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 8.4919969312665398); EXPECT_DOUBLE_EQ(model.loss(coeffs), 17.202925821121468); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 14); } TEST_F(HawkesModelTest, compute_loss_least_squares) { ArrayDouble2d decays(2, 2); decays.fill(2); ModelHawkesExpKernLeastSqSingle model(decays.as_sarray2d_ptr(), 2); model.set_data(timestamps, 5.65); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 177.74263433770577); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 300.36718283368231); EXPECT_DOUBLE_EQ(model.loss(coeffs), 43.46452883376255); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 6); } TEST_F(HawkesModelTest, hawkes_least_squares_serialization) { ArrayDouble2d decays(2, 2); decays.fill(2); auto sdecays = decays.as_sarray2d_ptr(); ModelHawkesExpKernLeastSqSingle model(sdecays, 2); model.set_data(timestamps, 5.65); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesExpKernLeastSqSingle restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2u); EXPECT_EQ(restored_model.get_end_time(), 5.65); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, compute_loss_least_square_sum_exp_kern) { ArrayDouble decays(2); decays.fill(2); const double end_time = 5.65; ModelHawkesSumExpKernLeastSqSingle model(decays, 1, end_time, 2); model.set_data(timestamps, end_time); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 709.43688360602232); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 1717.7627409202796); EXPECT_DOUBLE_EQ(model.loss(coeffs), 220.65451132057288); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 10); } TEST_F(HawkesModelTest, compute_loss_least_square_sum_exp_varying_baseline) { ArrayDouble decays(2); decays.fill(2); const double end_time = 5.87; ModelHawkesSumExpKernLeastSqSingle model(decays, 3, 2., 1); model.set_data(timestamps, end_time); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 754.50509295231836); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 1488.8712825118096); EXPECT_DOUBLE_EQ(model.loss(coeffs), 203.94330686037526); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 14); } TEST_F(HawkesModelTest, hawkes_least_squares_sum_exp_serialization) { ArrayDouble decays{2., 3.}; ModelHawkesSumExpKernLeastSqSingle model(decays, 2, 3.); model.set_data(timestamps, 5.65); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesSumExpKernLeastSqSingle restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2u); EXPECT_EQ(restored_model.get_end_time(), 5.65); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, compute_loss_least_square_list) { ArrayDouble2d decays(2, 2); decays.fill(2); ModelHawkesExpKernLeastSq model(decays.as_sarray2d_ptr(), 2); auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 356.00492335074784); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 603.45311621338624); EXPECT_DOUBLE_EQ(model.loss(coeffs), 43.611729071097002); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 6u); } TEST_F(HawkesModelTest, least_square_list_serialization) { ArrayDouble2d decays(2, 2); decays.fill(2); ModelHawkesExpKernLeastSq model(decays.as_sarray2d_ptr(), 2); auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesExpKernLeastSq restored_model(nullptr, 0); inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2u); EXPECT_EQ((*restored_model.get_end_times())[1], 5.87); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, compute_loss_least_square_sum_exp_list) { ArrayDouble decays(2); decays.fill(2); ArrayDouble end_times{5.65, 5.87}; ModelHawkesSumExpKernLeastSq model(decays, 1, 1e300, 1); model.incremental_set_data(timestamps, end_times[0]); model.incremental_set_data(timestamps, end_times[1]); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 1419.8117850574868); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 3439.937591029975); EXPECT_DOUBLE_EQ(model.loss(coeffs), 220.89769891306648); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 10); } TEST_F(HawkesModelTest, compute_loss_least_square_sum_exp_list_varying_baseline) { ArrayDouble decays(2); decays.fill(2); ArrayDouble end_times{5.65, 5.87}; ModelHawkesSumExpKernLeastSq model(decays, 3, 2., 1); model.incremental_set_data(timestamps, end_times[0]); model.incremental_set_data(timestamps, end_times[1]); ArrayDouble coeffs = ArrayDouble{1., 3., 0., 1., 1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 1508.7587849870356); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 2973.3304558342033); EXPECT_DOUBLE_EQ(model.loss(coeffs), 203.73132912823812); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 14); } TEST_F(HawkesModelTest, hawkes_least_squares_sum_exp_list_serialization) { ArrayDouble decays{0.1, 5.}; ArrayDouble end_times{5.65, 5.87}; ModelHawkesSumExpKernLeastSq model(decays, 1, 1e300, 1); model.incremental_set_data(timestamps, end_times[0]); model.incremental_set_data(timestamps, end_times[1]); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4.}; std::stringstream os; { cereal::PortableBinaryOutputArchive outputArchive(os); outputArchive(model); } { cereal::PortableBinaryInputArchive inputArchive(os); ModelHawkesSumExpKernLeastSq restored_model; inputArchive(restored_model); EXPECT_EQ(restored_model.get_n_nodes(), 2u); EXPECT_EQ((*restored_model.get_end_times())[1], 5.87); EXPECT_EQ(restored_model.get_n_total_jumps(), model.get_n_total_jumps()); EXPECT_DOUBLE_EQ(restored_model.loss(coeffs), model.loss(coeffs)); ASSERT_TRUE(model == restored_model); } } TEST_F(HawkesModelTest, compute_loss_loglik_list) { const double decay = 2.; ModelHawkesExpKernLogLik model(decay, 2); auto timestamps_list = SArrayDoublePtrList2D(0); timestamps_list.push_back(timestamps); timestamps_list.push_back(timestamps); auto end_times = VArrayDouble::new_ptr(2); (*end_times)[0] = 5.65; (*end_times)[1] = 5.87; model.set_data(timestamps_list, end_times); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), -0.68144584020170718); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 1.671674207054755); EXPECT_DOUBLE_EQ(model.loss(coeffs), 4.1398114444887462); ArrayDouble vector = ArrayDouble{1, 3., 3., 7., 8., 1}; EXPECT_DOUBLE_EQ(model.hessian_norm(coeffs, vector), 2.7963385385715074); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 6); } TEST_F(HawkesModelTest, check_sto_loglikelihood_list) { const double decay = 2.; ModelHawkesExpKernLogLik model(decay, 1); model.incremental_set_data(timestamps, 5.65); model.incremental_set_data(timestamps, 5.87); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; double loss = model.loss(coeffs); ArrayDouble grad(model.get_n_coeffs()); model.grad(coeffs, grad); double sum_sto_loss = 0; ArrayDouble sto_grad(model.get_n_coeffs()); sto_grad.init_to_zero(); ArrayDouble tmp_sto_grad(model.get_n_coeffs()); for (ulong i = 0; i < model.get_rand_max(); ++i) { sum_sto_loss += model.loss_i(i, coeffs) / model.get_rand_max(); tmp_sto_grad.init_to_zero(); model.grad_i(i, coeffs, tmp_sto_grad); sto_grad.mult_incr(tmp_sto_grad, 1. / model.get_rand_max()); } EXPECT_DOUBLE_EQ(loss, sum_sto_loss); for (ulong i = 0; i < model.get_n_coeffs(); ++i) { SCOPED_TRACE(i); EXPECT_DOUBLE_EQ(grad[i], sto_grad[i]); } } TEST_F(HawkesModelTest, compute_loss_loglikelihood_list_sum_exp_kern) { ArrayDouble decays{1., 2., 3.}; ModelHawkesSumExpKernLogLik model(decays, 1); model.incremental_set_data(timestamps, 5.65); model.incremental_set_data(timestamps, 5.87); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4., 2., 3., 4., 5.}; EXPECT_DOUBLE_EQ(model.loss_i(0, coeffs), 0.43573314143220188); EXPECT_DOUBLE_EQ(model.loss_i(1, coeffs), 8.4919969312665398); EXPECT_DOUBLE_EQ(model.loss(coeffs), 17.270721554384703); EXPECT_DOUBLE_EQ(model.get_n_coeffs(), 14); } TEST_F(HawkesModelTest, compute_hessian_loglikelihood) { ModelHawkesExpKernLogLikSingle model(2); model.set_data(timestamps, 4.25); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1}; const int n_nodes = 2; ArrayDouble out((1 + n_nodes) * (n_nodes + n_nodes * n_nodes)); out.init_to_zero(); model.hessian(coeffs, out); // test some random indexes... EXPECT_DOUBLE_EQ(out[0], 0.01631907612617749); EXPECT_DOUBLE_EQ(out[4], 0.0060622624486514612); EXPECT_DOUBLE_EQ(out[6], 0.0070643083720372474); EXPECT_DOUBLE_EQ(out[8], 0.0059903489344126197); EXPECT_DOUBLE_EQ(out[9], 0.01668440042028695); } TEST_F(HawkesModelTest, compute_hessian_sumexp_loglikelihood) { ArrayDouble decays{1., 2.}; ModelHawkesSumExpKernLogLikSingle model(decays, 1); model.set_data(timestamps, 4.25); model.compute_weights(); ArrayDouble coeffs = ArrayDouble{1., 3., 2., 3., 4., 1., 5., 3., 2., 4., 2., 3., 4., 5.}; const ulong n_nodes = 2; const ulong n_alpha_i = n_nodes * decays.size(); ArrayDouble out((1 + n_alpha_i) * (n_nodes + n_alpha_i * n_nodes)); out.init_to_zero(); model.hessian(coeffs, out); EXPECT_DOUBLE_EQ(out[0], 0.0074914657915579903); EXPECT_DOUBLE_EQ(out[4], 0.0088873654563159724); EXPECT_DOUBLE_EQ(out[6], 0.0021770298651935666); EXPECT_DOUBLE_EQ(out[8], 0.0024676761791649136); EXPECT_DOUBLE_EQ(out[9], 0.001582373650788027); } #ifdef ADD_MAIN int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); ::testing::FLAGS_gtest_death_test_style = "fast"; return RUN_ALL_TESTS(); } #endif // ADD_MAIN
29.24693
83
0.729639
[ "vector", "model" ]
db6ec8c4b1ee0c70d305ef0871bda69bac6452ce
5,446
cpp
C++
app/gnp_torus.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
22
2020-06-12T07:26:45.000Z
2022-03-03T17:03:08.000Z
app/gnp_torus.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
4
2019-09-04T10:39:39.000Z
2020-05-26T05:25:35.000Z
app/gnp_torus.cpp
vaidehi8913/VieCut
f4bd2b468689cb8e5e11f18f1bb21468a119083d
[ "MIT" ]
3
2020-12-11T13:43:45.000Z
2021-11-09T15:08:58.000Z
/****************************************************************************** * gnp_torus.cpp * * Source of VieCut. * ****************************************************************************** * Copyright (C) 2019 Alexander Noe <alexander.noe@univie.ac.at> * * Published under the MIT license in the LICENSE file. *****************************************************************************/ #include <ext/alloc_traits.h> #include <algorithm> #include <cstdio> #include <map> #include <memory> #include <string> #include <utility> #include <vector> #ifdef PARALLEL #include "parallel/algorithm/parallel_cactus.h" #else #endif #include "common/configuration.h" #include "common/definitions.h" #include "data_structure/graph_access.h" #include "io/graph_io.h" #include "tlx/cmdline_parser.hpp" #include "tlx/logger.hpp" #include "tools/random_functions.h" #include "tools/timer.h" int main(int argn, char** argv) { timer t; tlx::CmdlineParser cmdl; auto cfg = configuration::getConfig(); size_t vertices_per_block = 0; size_t cut = 0; size_t blocks_per_dimension = 0; size_t seed = 0; std::string output_folder = ""; cmdl.add_size_t('n', "vertices", vertices_per_block, "number of vertices in block"); cmdl.add_size_t('c', "cut", cut, "cut edges between gnp blocks"); cmdl.add_size_t('b', "blocks", blocks_per_dimension, "number of blocks per dimension"); cmdl.add_size_t('s', "seed", seed, "random seed"); cmdl.add_string('o', "output", output_folder, "folder to write output to"); if (!cmdl.process(argn, argv)) return -1; random_functions::setSeed(seed); graphAccessPtr G = std::make_shared<graph_access>(); // blocks * blocks gnp graphs with vertices vertices each size_t blocks = blocks_per_dimension * blocks_per_dimension; size_t num_vertices = blocks * vertices_per_block; LOG1 << "Generating inter-block edges..."; std::vector<std::vector<NodeID> > interblockedges(num_vertices); for (size_t i = 0; i < blocks; ++i) { NodeID my_start = vertices_per_block * i; NodeID x = i % blocks_per_dimension; NodeID y = i / blocks_per_dimension; // right for (size_t k = 0; k < cut; ++k) { size_t r1 = random_functions::nextInt(0, vertices_per_block - 1); size_t r2 = random_functions::nextInt(0, vertices_per_block - 1); NodeID v1 = my_start + r1; NodeID v2 = ((y * blocks_per_dimension) + ((x + 1) % blocks_per_dimension)) * vertices_per_block + r2; interblockedges[v1].emplace_back(v2); interblockedges[v2].emplace_back(v1); } // down for (size_t k = 0; k < cut; ++k) { size_t r1 = random_functions::nextInt(0, vertices_per_block - 1); size_t r2 = random_functions::nextInt(0, vertices_per_block - 1); NodeID v1 = my_start + r1; NodeID v2 = ((((y + 1) % blocks_per_dimension) * blocks_per_dimension) + x) * vertices_per_block + r2; interblockedges[v1].emplace_back(v2); interblockedges[v2].emplace_back(v1); } } LOG1 << "...done!"; LOG1 << "Memory allocation..."; G->start_construction(num_vertices, num_vertices * 6 * cut); std::vector<std::vector<EdgeWeight> > inblock(vertices_per_block); for (auto& i : inblock) { i.resize(vertices_per_block, 0); } LOG1 << "...done"; LOG1 << "Setting in-block edges..."; for (size_t b = 0; b < blocks; ++b) { LOG1 << "Generating edges for block " << b << "..."; NodeID my_start = b * vertices_per_block; for (auto& i : inblock) { for (auto& j : i) { j = 0; } } for (size_t i = 0; i < inblock.size(); ++i) { for (size_t m = 0; m < 4 * cut + 1; ++m) { size_t r = random_functions::nextInt(0, vertices_per_block - 1); inblock[i][r] += 1; inblock[r][i] += 1; } } LOG1 << "Writing block " << b << "..."; for (size_t i = 0; i < inblock.size(); ++i) { G->new_node(); for (size_t j = 0; j < inblock[i].size(); ++j) { if (inblock[i][j] > 0) G->new_edge(i + my_start, j + my_start, inblock[i][j]); } if (interblockedges[i + my_start].size() > 0) { std::map<size_t, size_t> intermap; std::for_each(interblockedges[i + my_start].begin(), interblockedges[i + my_start].end(), [&intermap](NodeID val) { intermap[val]++; }); for (const auto& p : intermap) { G->new_edge(i + my_start, p.first, p.second); } } } } G->finish_construction(); std::string name = "gnp_" + std::to_string(vertices_per_block) + "_" + std::to_string(blocks_per_dimension) + "_" + std::to_string(cut) + "_" + std::to_string(seed); if (output_folder != "") { name = output_folder + "/" + name; } LOG1 << "Writing to file " << name << "..."; graph_io::writeGraphWeighted(G, name); LOG1 << "Done!"; }
33.006061
80
0.527176
[ "vector" ]
db7430414e6b6b74c449040b272475199daba0a0
4,496
cpp
C++
libcxx/test/std/utilities/memory/specialized.algorithms/specialized.destroy/ranges_destroy_at.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/std/utilities/memory/specialized.algorithms/specialized.destroy/ranges_destroy_at.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/std/utilities/memory/specialized.algorithms/specialized.destroy/ranges_destroy_at.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++03, c++11, c++14, c++17 // UNSUPPORTED: libcpp-has-no-incomplete-ranges // <memory> // // namespace ranges { // template<destructible T> // constexpr void destroy_at(T* location) noexcept; // since C++20 // } #include <cassert> #include <memory> #include <type_traits> #include "test_macros.h" // TODO(varconst): consolidate the ADL checks into a single file. // Because this is a variable and not a function, it's guaranteed that ADL won't be used. However, // implementations are allowed to use a different mechanism to achieve this effect, so this check is // libc++-specific. LIBCPP_STATIC_ASSERT(std::is_class_v<decltype(std::ranges::destroy_at)>); struct NotNothrowDtrable { ~NotNothrowDtrable() noexcept(false) {} }; static_assert(!std::is_invocable_v<decltype(std::ranges::destroy_at), NotNothrowDtrable*>); struct Counted { int& count; constexpr Counted(int& count_ref) : count(count_ref) { ++count; } constexpr ~Counted() { --count; } friend void operator&(Counted) = delete; }; struct VirtualCountedBase { int& count; constexpr VirtualCountedBase(int& count_ref) : count(count_ref) { ++count; } constexpr virtual ~VirtualCountedBase() { --count; } void operator&() const = delete; }; struct VirtualCountedDerived : VirtualCountedBase { constexpr VirtualCountedDerived(int& count_ref) : VirtualCountedBase(count_ref) {} // Without a definition, GCC gives an error when the destructor is invoked in a constexpr context (see // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=93413). constexpr ~VirtualCountedDerived() override {} }; constexpr bool test() { // Destroying a "trivial" object. { std::allocator<Counted> alloc; using Traits = std::allocator_traits<decltype(alloc)>; int counter = 0; Counted* buffer = Traits::allocate(alloc, 2); Traits::construct(alloc, buffer, counter); Traits::construct(alloc, buffer + 1, counter); assert(counter == 2); std::ranges::destroy_at(buffer); assert(counter == 1); std::ranges::destroy_at(buffer + 1); assert(counter == 0); Traits::deallocate(alloc, buffer, 2); } // Destroying a derived object with a virtual destructor. { std::allocator<VirtualCountedDerived> alloc; using Traits = std::allocator_traits<decltype(alloc)>; int counter = 0; VirtualCountedDerived* buffer = Traits::allocate(alloc, 2); Traits::construct(alloc, buffer, counter); Traits::construct(alloc, buffer + 1, counter); assert(counter == 2); std::ranges::destroy_at(buffer); assert(counter == 1); std::ranges::destroy_at(buffer + 1); assert(counter == 0); Traits::deallocate(alloc, buffer, 2); } return true; } constexpr bool test_arrays() { // Pointer to an array. { using Array = Counted[3]; std::allocator<Array> alloc; using Traits = std::allocator_traits<decltype(alloc)>; int counter = 0; Array* array = Traits::allocate(alloc, 1); Array& array_ref = *array; for (int i = 0; i != 3; ++i) { Traits::construct(alloc, std::addressof(array_ref[i]), counter); } assert(counter == 3); std::ranges::destroy_at(array); assert(counter == 0); Traits::deallocate(alloc, array, 1); } // Pointer to a two-dimensional array. { using Array = Counted[3][2]; std::allocator<Array> alloc; using Traits = std::allocator_traits<decltype(alloc)>; int counter = 0; Array* array = Traits::allocate(alloc, 1); Array& array_ref = *array; for (int i = 0; i != 3; ++i) { for (int j = 0; j != 2; ++j) { Traits::construct(alloc, std::addressof(array_ref[i][j]), counter); } } assert(counter == 3 * 2); std::ranges::destroy_at(array); assert(counter == 0); Traits::deallocate(alloc, array, 1); } return true; } int main(int, char**) { test(); test_arrays(); static_assert(test()); // TODO: Until std::construct_at has support for arrays, it's impossible to test this // in a constexpr context (see https://reviews.llvm.org/D114903). // static_assert(test_arrays()); return 0; }
27.925466
104
0.642571
[ "object" ]
db7487eadbdfdfadd5bcd6bb943875b7fd87b534
1,707
cpp
C++
GEngine/Collision/Geometry/GESphereGeometry.cpp
jsyishan/GomiEngine
7fd4c1ba19a2711373e3c4120427c0b19c869e8b
[ "MIT" ]
null
null
null
GEngine/Collision/Geometry/GESphereGeometry.cpp
jsyishan/GomiEngine
7fd4c1ba19a2711373e3c4120427c0b19c869e8b
[ "MIT" ]
2
2018-03-17T15:46:33.000Z
2018-03-17T15:55:13.000Z
GEngine/Collision/Geometry/GESphereGeometry.cpp
jsyishan/GomiEngine
7fd4c1ba19a2711373e3c4120427c0b19c869e8b
[ "MIT" ]
null
null
null
#include <cmath> #include <new> #include "GESphereGeometry.h" #include "../../Math/GEConstant.h" #include "../../Math/GEMatrix33.h" #include "../../Math/GEVector.h" namespace ge { Geometry* SphereGeometry::clone(SmallObjectAllocator* allocator) const { void* mem = allocator->allocate(sizeof(SphereGeometry)); SphereGeometry* clone = new (mem) SphereGeometry(radius); *clone = *this; return clone; } void SphereGeometry::updateMass() { volume = 4 / 3 * PI * radius * radius * radius; inertiaCoeff = Matrix33().diagonal(2 / 5 * radius * radius, 2 / 5 * radius * radius, 2 / 5 * radius * radius); } void SphereGeometry::computeAabb(Aabb* aabb, const Transform& trans) const { Vector3D rad(radius, radius, radius); aabb->setMin(trans.position - rad); aabb->setMax(trans.position + rad); } void SphereGeometry::computeLocalSupportingVertex(const Vector3D& in, Vector3D* out) const { out->zero(); } bool SphereGeometry::rayCast(const Vector3D& begin, const Vector3D& end, RaycastHit* hit) const { Vector3D offset = end - begin; float x = offset * offset; float y = begin * offset; float z = begin * begin - radius * radius; float w = y * y - x * z; if (w < 0) return false; float t = (-y - std::sqrt(w)) / x; if (t < 0 || t > 1) return false; Vector3D loc_position, loc_normal; loc_position = begin + offset * t; loc_normal = Vector3D(loc_position).normalize(); hit->position = loc_position; hit->normal = loc_normal; hit->fraction = t; return true; } }
31.611111
118
0.59754
[ "geometry", "transform" ]
db798ac3a58d310abbbb98810ca7922579e07d43
15,338
cpp
C++
Source/FileSystem.cpp
MarcArizaAlborni/VeryRealEngine
bc666f29e336c461d1a9a348623e7d5d1a2be9e3
[ "MIT" ]
null
null
null
Source/FileSystem.cpp
MarcArizaAlborni/VeryRealEngine
bc666f29e336c461d1a9a348623e7d5d1a2be9e3
[ "MIT" ]
null
null
null
Source/FileSystem.cpp
MarcArizaAlborni/VeryRealEngine
bc666f29e336c461d1a9a348623e7d5d1a2be9e3
[ "MIT" ]
null
null
null
#include "Globals.h" #include "Application.h" #include "Definitions.h" #include "FileSystem.h" #include "Component.h" #include "ComponentTexture.h" #include "ComponentMesh.h" #include "ComponentTransform.h" #include "ModuleMeshImporter.h" #include "ModuleTextureImporter.h" #include "GameObject.h" #include "libraries/PhysFS/include/physfs.h" #include "libraries/Assimp/Assimp/include/cfileio.h" #include "libraries/Assimp/Assimp/include/types.h" #include "libraries/Assimp/Assimp/include/cimport.h" #include "libraries/Assimp/Assimp/include/scene.h" #include "libraries/Assimp/Assimp/include/postprocess.h" #pragma comment (lib, "libraries/Assimp/Assimp/libx86/assimp.lib") #pragma comment( lib, "libraries/PhysFS/libx86/physfs.lib" ) ModuleFileSystem::ModuleFileSystem(Application* app, const char* name, bool start_enabled) : Module(app, "FileSystem", start_enabled) { // Init PhysFS char* base_path = SDL_GetBasePath(); PHYSFS_init(base_path); SDL_free(base_path); // Default Path AddPath("."); if (0 && name != nullptr) { AddPath(name); } // Creates an empty file if the dir is not found if (PHYSFS_setWriteDir(".") == 0) { LOG("File System error while creating write dir: %s\n", PHYSFS_getLastError()); } CreateLibraryDirectories(); } // Destructor ModuleFileSystem::~ModuleFileSystem() { PHYSFS_deinit(); } // Called before quitting bool ModuleFileSystem::CleanUp() { LOG("Freeing File System subsystem"); return true; } bool ModuleFileSystem::AddPath(const char* path_or_zip) { bool ret = false; //Add an archive or directory to the search path. if (PHYSFS_mount(path_or_zip, nullptr, 1) == 0) { LOG("File System error while adding a path or zip: %s\n", PHYSFS_getLastError()); } else { ret = true; } return ret; } // Checks if a file exists bool ModuleFileSystem::Exists(const char* file) const { return PHYSFS_exists(file) != 0; } bool ModuleFileSystem::CreateDir(const char* dir) { if (IsDirectory(dir) == false) { PHYSFS_mkdir(dir); return true; } return false; } // Checks if a file is inside a directory bool ModuleFileSystem::IsDirectory(const char* file) const { return PHYSFS_isDirectory(file) != 0; } // Adds a directory void ModuleFileSystem::CreateDirectory(const char* directory) { PHYSFS_mkdir(directory); } //Gets a file listing of a search path's directory. void ModuleFileSystem::DiscoverFiles(const char* directory, std::vector<std::string>& file_list, std::vector<std::string>& direction_list) const { char** rc = PHYSFS_enumerateFiles(directory); std::string dir(directory); for (char** i = rc; *i != nullptr; i++) { if (PHYSFS_isDirectory((dir + *i).c_str())) { direction_list.push_back(*i); } else { file_list.push_back(*i); } } PHYSFS_freeList(rc); } bool ModuleFileSystem::CopyFromOutsideFS(const char* full_path, const char* destination) { // Only place we acces non virtual filesystem (defined functions) bool ret = false; char buf[8192]; size_t size; FILE* source = nullptr; fopen_s(&source, full_path, "rb"); PHYSFS_file* dest = PHYSFS_openWrite(destination); if (source && dest) { while (size = fread_s(buf, 8192, 1, 8192, source)) { PHYSFS_write(dest, buf, 1, size); } fclose(source); PHYSFS_close(dest); ret = true; LOG("File System copied from [%s] to [%s]", full_path, destination); } else { LOG("File System error while copying from [%s] to [%s]", full_path, destination); } return ret; } bool ModuleFileSystem::Copy(const char* source, const char* destination) { bool ret = false; char buf[8192]; PHYSFS_file* src = PHYSFS_openRead(source); PHYSFS_file* dst = PHYSFS_openWrite(destination); PHYSFS_sint32 size; if (src && dst) { while (size = (PHYSFS_sint32)PHYSFS_read(src, buf, 1, 8192)) { PHYSFS_write(dst, buf, 1, size); } PHYSFS_close(src); PHYSFS_close(dst); ret = true; LOG("File System copied form [%s] to [%s]", source, destination); } else { LOG("File System error while copy from [%s] to [%s]", source, destination); } return ret; } // Force to always use lowercase and / as folder separator char normalize_char(char c) { if (c == '\\') { return '/'; } return tolower(c); } std::string ModuleFileSystem::NormalizeNodePath(const char* full_path) { std::string normalized_path(full_path); for (uint i = 0; i < normalized_path.size(); ++i) { if (normalized_path[i] == '\\') { normalized_path[i] = '/'; } } return normalized_path; } void ModuleFileSystem::NormalizePath(std::string& full_path) const { for (std::string::iterator it = full_path.begin(); it != full_path.end(); ++it) { if (*it == '\\') { *it = '/'; } else { //*it = tolower(*it); } } } void ModuleFileSystem::SplitFilePath(const char* full_path, std::string* path, std::string* file, std::string* extension) const { if (full_path != nullptr) { std::string full(full_path); NormalizePath(full); size_t pos_separator = full.find_last_of("\\/"); size_t pos_dot = full.find_last_of("."); if (path != nullptr) { if (pos_separator < full.length()) *path = full.substr(0, pos_separator + 1); else path->clear(); } if (file != nullptr) { if (pos_separator < full.length()) *file = full.substr(pos_separator + 1); else *file = full; } if (extension != nullptr) { if (pos_dot < full.length()) { *extension = full.substr(pos_dot + 1); if (file != nullptr) file->resize(file->length() - extension->length() - 1); } else extension->clear(); } } } bool ModuleFileSystem::IsInDirectory(const char* directory, const char* p) { bool ret = true; std::string dir = directory; std::string path = p; std::size_t found = path.find(dir); if (found != std::string::npos) { ret = true; } else { ret = false; } return ret; } void ModuleFileSystem::CreateLibraryDirectories() { CreateDir(LIBRARY_FOLDER); CreateDir(LIBRARY_TEXTURES_FOLDER); CreateDir(LIBRARY_MESH_FOLDER); CreateDir(LIBRARY_MODELS_FOLDER); CreateDir(LIBRARY_SCENE_FOLDER); } bool ModuleFileSystem::RemovePath(std::string* directory, const char* p) { bool ret = true; std::size_t found = directory->find(p); if (found != std::string::npos) { directory->erase(found, 6); ret = true; } else { ret = false; } return ret; } void ModuleFileSystem::DeleteExtension(std::string& Path) { std::size_t pos = Path.find("."); Path = Path.substr(0, pos); } unsigned int ModuleFileSystem::Load(const char* path, const char* file, char** buffer) const { std::string full_path(path); full_path += file; return Load(full_path.c_str(), buffer); } // Read a file and writes it on a buffer uint ModuleFileSystem::Load(const char* file, char** buffer) const { uint ret = 0; PHYSFS_file* fs_file = PHYSFS_openRead(file); if (fs_file != nullptr) { PHYSFS_sint32 size = (PHYSFS_sint32)PHYSFS_fileLength(fs_file); if (size > 0) { *buffer = new char[size]; uint readed = (uint)PHYSFS_read(fs_file, *buffer, 1, size); if (readed != size) { LOG("File System error while reading %s: %s\n", file, PHYSFS_getLastError()); RELEASE(buffer); } else { ret = readed; } } if (PHYSFS_close(fs_file) == 0) { LOG("File System error while closing %s: %s\n", file, PHYSFS_getLastError()); } } else { LOG("File System error while opening %s: %s\n", file, PHYSFS_getLastError()); } return ret; } SDL_RWops* ModuleFileSystem::Load(const char* file) const { char* buffer; int size = Load(file, &buffer); if (size > 0) { SDL_RWops* r = SDL_RWFromConstMem(buffer, size); if (r != nullptr) { r->close = close_sdl_rwops; } return r; } else { return nullptr; } } int close_sdl_rwops(SDL_RWops* rw) { RELEASE_ARRAY(rw->hidden.mem.base); SDL_FreeRW(rw); return 0; } // Saves all buffers to disk uint ModuleFileSystem::Save(const char* file, const void* buffer, unsigned int size, bool append) const { unsigned int ret = 0; bool overwrite = PHYSFS_exists(file) != 0; PHYSFS_file* fs_file = (append) ? PHYSFS_openAppend(file) : PHYSFS_openWrite(file); if (fs_file != nullptr) { uint written = (uint)PHYSFS_write(fs_file, (const void*)buffer, 1, size); if (written != size) { LOG("File System error while writing to file %s: %s", file, PHYSFS_getLastError()); } else { if (append == true) { LOG("Added %u data to [%s%s]", size, PHYSFS_getWriteDir(), file); } else if (overwrite == false) { LOG("New file created [%s%s] of %u bytes", PHYSFS_getWriteDir(), file, size); } ret = written; } if (PHYSFS_close(fs_file) == 0) { LOG("File System error while closing file %s: %s", file, PHYSFS_getLastError()); } } else { LOG("File System error while opening file %s: %s", file, PHYSFS_getLastError()); } return ret; } bool ModuleFileSystem::Remove(const char* file) { bool ret = false; if (file != nullptr) { if (PHYSFS_delete(file) == 0) { LOG("File deleted: [%s]", file); ret = true; } else LOG("File System error while trying to delete [%s]: ", file, PHYSFS_getLastError()); } return ret; } std::string ModuleFileSystem::GetFileAndExtension(const char* path) { std::string full_path = path; std::string file = ""; std::string extension = ""; // Just for safety check purposes. full_path = NormalizeNodePath(full_path.c_str()); // Will swap all '\\' for '/'. size_t file_start = full_path.find_last_of("/"); // Gets the position of the last '/' of the string. Returns npos if none was found. size_t extension_start = full_path.find_last_of("."); // Gets the position of the last '.' of the string. Returns npos if none was found. if (file_start != std::string::npos) { file = full_path.substr(file_start + 1, full_path.size()); // Will get the string past the last slash } else { LOG("[WARNING] Path %s does not have any file!", path); } if (extension_start != std::string::npos) { extension = full_path.substr(extension_start + 1, full_path.size()); // Will get the string past the last dot of the path string. Ex: File.ext --> ext if (extension == "") { LOG("[WARNING] Path %s does not have any file extension!", path); } } return full_path; } void ModuleFileSystem::SaveMeshInto_WAF(MeshInfo* Mesh, aiMesh* RawMesh) { //ORDER OF WRITING!!!!!! //Mesh //Mesh->num_index; //Mesh->num_vertex; //Mesh->num_texcoords; Mesh->vertex; Mesh->texcoords; Mesh->normals; Mesh->index; Mesh->Name; Mesh->TextureName; //Generate Random Value int NewId = App->GiveRandomNum_Undefined(); StoreMetaIDs_List.push_back(NewId); // ID's To create Meta file to write //Generate Path std::string NewId_C = std::to_string(NewId); std::string Extension = ".waf"; std::string GeneralPath = "Library/Meshes/"; std::string FinalPath = GeneralPath + NewId_C + Extension; //num index, num vertex uint ranges[3] = { Mesh->num_index,Mesh->num_vertex, Mesh->num_texcoords }; uint size = sizeof(ranges) + sizeof(uint) * Mesh->num_index + sizeof(float) * Mesh->num_vertex * 3 + sizeof(float)*Mesh->num_texcoords*2; char* buffer = new char[size]; char* cursor = buffer; uint bytes = sizeof(ranges); memcpy(cursor, ranges, bytes); cursor += bytes; //index bytes = sizeof(uint) * Mesh->num_index; memcpy(cursor, Mesh->index, bytes); cursor += bytes; //vertex bytes = sizeof(float) * Mesh->num_vertex*3; memcpy(cursor, Mesh->vertex, bytes); cursor += bytes; //texcoords bytes = sizeof(float) * Mesh->num_texcoords * 2; memcpy(cursor, Mesh->texcoords, bytes); cursor += bytes; // WRITING THE INFO INTO THE FILE PHYSFS_File* WFile = PHYSFS_openWrite(FinalPath.c_str()); PHYSFS_sint64 AmountWritten = PHYSFS_write(WFile, (const void*)buffer, 1, size); PHYSFS_close(WFile); /////////////////// //READING FROM THE FILE PHYSFS_File* RFile = PHYSFS_openRead(FinalPath.c_str()); PHYSFS_sint32 Rsize = (PHYSFS_sint32)PHYSFS_fileLength(RFile); char* Rbuffer = new char[Rsize]; char* Rcursor = Rbuffer; PHYSFS_sint64 AmountRead = PHYSFS_read(RFile, Rbuffer, 1, Rsize); uint Rranges[3]; uint Rbytes = sizeof(Rranges); memcpy(Rranges, Rcursor, Rbytes); Rcursor += Rbytes; uint NumIndex = Rranges[0]; uint NumVertex = Rranges[1]; uint NumTexCoords = Rranges[2]; //Index reading Rbytes = sizeof(uint) * Mesh->num_index; uint* Indexes = new uint[Mesh->num_index]; memcpy(Indexes, Rcursor, Rbytes); Rcursor += Rbytes; //Vertex Rbytes = sizeof(float) * Mesh->num_vertex*3; float* Vertexes = new float[Mesh->num_vertex*3]; memcpy(Vertexes, Rcursor, Rbytes); Rcursor += Rbytes; //Texcoords Rbytes = sizeof(float) * Mesh->num_texcoords*2; float* Texcoordses = new float[Mesh->num_texcoords*2]; memcpy(Texcoordses, Rcursor, Rbytes); Rcursor += Rbytes; } MeshInfo* ModuleFileSystem::LoadMeshFrom_WAF(int FileId) { MeshInfo* LoadedItem; //KEEP THIS ORDER OF OPERATIONS!! std::string NewId_C = std::to_string(FileId); std::string Extension = ".waf"; std::string GeneralPath = "Library/Meshes/"; std::string FinalPath = GeneralPath + NewId_C + Extension; PHYSFS_File* RFile = PHYSFS_openRead(FinalPath.c_str()); PHYSFS_sint32 Rsize = (PHYSFS_sint32)PHYSFS_fileLength(RFile); char* Rbuffer = new char[Rsize]; char* Rcursor = Rbuffer; PHYSFS_sint64 AmountRead = PHYSFS_read(RFile, Rbuffer, 1, Rsize); uint Rranges[2]; uint Rbytes = sizeof(Rranges); memcpy(Rranges, Rcursor, Rbytes); Rcursor += Rbytes; uint NumIndex = Rranges[0]; uint NumVertex = Rranges[1]; uint Rranges2[1]; uint Rbytes2 = sizeof(Rranges2); memcpy(Rranges2, Rcursor, Rbytes2); Rcursor += Rbytes2; uint NumTexcoord = Rranges2[0]; return LoadedItem; } uint ModuleFileSystem::GenerateSafeBuffer_Mesh(MeshInfo* Mesh) { return uint(); } void ModuleFileSystem::CreateMesh_META(int id, std::string FilePath) { PHYSFS_File* MetaFile = PHYSFS_openWrite(CurrentlyDetectedMETA.c_str()); uint value=StoreMetaIDs_List[0]; uint size = sizeof(value) + sizeof(uint) * value; char* buffer = new char[size]; char* cursor = buffer; uint bytes = sizeof(value); int ToPasteSize = StoreMetaIDs_List.size(); std::reverse(StoreMetaIDs_List.begin(), StoreMetaIDs_List.end()); StoreMetaIDs_List.push_back(ToPasteSize); std::reverse(StoreMetaIDs_List.begin(), StoreMetaIDs_List.end()); std::vector<int>::iterator It = StoreMetaIDs_List.begin(); for (int i = 0; i < StoreMetaIDs_List.size(); ++i) { int ID = *It; memcpy(cursor, &ID, bytes); cursor += bytes; ++It; } PHYSFS_sint64 AmountWritten = PHYSFS_write(MetaFile, (const void*)buffer, 1, size); PHYSFS_close(MetaFile); LoadMesh_META(); } void ModuleFileSystem::LoadMesh_META() { PHYSFS_File* RFile = PHYSFS_openRead(CurrentlyDetectedMETA.c_str()); PHYSFS_sint32 Rsize = (PHYSFS_sint32)PHYSFS_fileLength(RFile); char* Rbuffer = new char[Rsize]; char* Rcursor = Rbuffer; PHYSFS_sint64 AmountRead = PHYSFS_read(RFile, Rbuffer, 1, Rsize); uint Values[MAX_SIZE_ARRAY_META_FILE]; uint Rbytes = sizeof(Values); memcpy(&Values, Rcursor, Rbytes); Rcursor += Rbytes; for (int o = 0; o < Values[0]+1; ++o) { LoadMetaIDs_List.push_back(Values[o]); } PHYSFS_close(RFile); }
20.505348
155
0.677468
[ "mesh", "vector" ]
db86c57fb47b4475cff17dd3498f0d21cb0f9e81
3,666
cpp
C++
src/cast_ray.cpp
AnttiVainio/Ray-tracer
0843aeb490b14417d47b844ebaa4174617833568
[ "Unlicense" ]
null
null
null
src/cast_ray.cpp
AnttiVainio/Ray-tracer
0843aeb490b14417d47b844ebaa4174617833568
[ "Unlicense" ]
null
null
null
src/cast_ray.cpp
AnttiVainio/Ray-tracer
0843aeb490b14417d47b844ebaa4174617833568
[ "Unlicense" ]
null
null
null
/** cast_ray.cpp **/ #include "global.hpp" #include "polygon.hpp" #include "math.hpp" //Makes the ray collision calculation //Returns false for cast_ray function to try to calculate with different values if something is about to be divided by zero bool cast_ray2(float &a, float &b, float &c, float &rx, float &ry, float &rz, cfloat A, cfloat B, cfloat C, cfloat D, cfloat E, cfloat F, cfloat G, cfloat H, cfloat I, cfloat J, cfloat K, cfloat L, cfloat M, cfloat N, cfloat O) { //This formula was not actually copied from anywhere, it's all made by me :) if(D == 0) return false; cfloat four = H * D - G * E; if(four == 0) return false; cfloat one = N * D - M * E; cfloat two = I * D - G * F; cfloat three = O * D - M * F; cfloat temp = one * two - three * four; if(temp == 0) return false; cfloat JA = J - A; cfloat five = D * (K - B) - E * JA; cfloat six = D * (L - C) - F * JA; c = (four * six - two * five) / temp; rx = J + c * M; ry = K + c * N; rz = L + c * O; b = (one * c + five) / four; a = (rx - A - b * G) / D; return true; } //#define DRAW_CUBE //This function calls a function that calculates if a ray hits a polygon //a, b, c, rx, ry and rz are returned //a and b represent the values in where the ray hits the plane where the polygon lies //a is the multiplier for vector vertex1 -> vertex2 and b is multiplier for vector vertex1 -> vertex3 of the polygon //So, if a < 0 || b < 0 || a + b > 1 the ray does not hit the polygon //rx, ry, rz is the location of the collision in the 3D space //J, K and L are the position of the viewer (x, y, z) //x, y and z are the position of the target (x, y, z) the viewer is looking at //c is the multiplier of the viewer vector for the collision (kind of like the distance from the viewer) //c is used for depth testing and testing if something is between a light and a position in 3D space //returns false if the ray doesn't hit the cube around the polygon bool cast_ray(polygon_c &polygon, float &a, float &b, float &c, float &rx, float &ry, float &rz, cfloat J, cfloat K, cfloat L, cfloat x, cfloat y, cfloat z) { cfloat M = x - J; cfloat N = y - K; cfloat O = z - L; //Check the cube collision cfloat x1 = (polygon.minx - J) / M; cfloat x2 = (polygon.maxx - J) / M; cfloat y1 = (polygon.miny - K) / N; cfloat y2 = (polygon.maxy - K) / N; float minv = max(min(x1, x2), min(y1, y2)); float maxv = min(max(x1, x2), max(y1, y2)); if(minv > maxv) return false; cfloat z1 = (polygon.minz - L) / O; cfloat z2 = (polygon.maxz - L) / O; minv = max(minv, min(z1, z2)); maxv = min(maxv, max(z1, z2)); if(minv > maxv) return false; #ifdef DRAW_CUBE a = 0.25; b = 0.25; c = (minv + maxv) / 2.0; rx = J + c * M; ry = K + c * N; rz = L + c * O; return true; #endif //Try to make the calculation three times and swap the polygon if it failed //Only swap 3 times at max because after 3 swaps the order of the vertexes in the polygon is the same as it originally was for(uchar t=0;t<3;t++) { cfloat A = polygon.x1; cfloat B = polygon.y1; cfloat C = polygon.z1; cfloat D = polygon.x2 - A; cfloat E = polygon.y2 - B; cfloat F = polygon.z2 - C; cfloat G = polygon.x3 - A; cfloat H = polygon.y3 - B; cfloat I = polygon.z3 - C; //Try with different orders of the values if(cast_ray2(a, b, c, rx, ry, rz, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O)) return true; if(cast_ray2(a, b, c, rz, rx, ry, C, A, B, F, D, E, I, G, H, L, J, K, O, M, N)) return true; if(cast_ray2(a, b, c, ry, rz, rx, B, C, A, E, F, D, H, I, G, K, L, J, N, O, M)) return true; polygon.swap(); } return false; //It should be impossible to ever get this far }
35.941176
123
0.626568
[ "vector", "3d" ]
db8c6139bfa484ddbf1b10ba3e485c8ced05adb7
14,831
cpp
C++
third_party/skia_m79/third_party/externals/angle2/src/tests/gl_tests/WebGLReadOutsideFramebufferTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
6
2018-10-20T10:53:55.000Z
2021-12-25T07:58:57.000Z
third_party/skia_m79/third_party/externals/angle2/src/tests/gl_tests/WebGLReadOutsideFramebufferTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
null
null
null
third_party/skia_m79/third_party/externals/angle2/src/tests/gl_tests/WebGLReadOutsideFramebufferTest.cpp
kniefliu/WindowsSamples
c841268ef4a0f1c6f89b8e95bf68058ea2548394
[ "MIT" ]
9
2018-10-31T03:07:11.000Z
2021-08-06T08:53:21.000Z
// // Copyright 2017 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // WebGLReadOutsideFramebufferTest.cpp : Test functions which read the framebuffer (readPixels, // copyTexSubImage2D, copyTexImage2D) on areas outside the framebuffer. #include "test_utils/ANGLETest.h" #include "test_utils/gl_raii.h" namespace { class PixelRect { public: PixelRect(int width, int height) : mWidth(width), mHeight(height), mData(width * height) {} // Set each pixel to a different color consisting of the x,y position and a given tag. // Making each pixel a different means any misplaced pixel will cause a failure. // Encoding the position proved valuable in debugging. void fill(unsigned tag) { for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { mData[x + y * mWidth] = angle::GLColor(x + (y << 8) + (tag << 16)); } } } void toTexture2D(GLuint target, GLuint texid) const { glBindTexture(target, texid); if (target == GL_TEXTURE_CUBE_MAP) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } else { ASSERT_GLENUM_EQ(GL_TEXTURE_2D, target); glTexImage2D(target, 0, GL_RGBA, mWidth, mHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } void toTexture3D(GLuint texid, GLint depth) const { glBindTexture(GL_TEXTURE_3D, texid); glTexImage3D(GL_TEXTURE_3D, 0, GL_RGBA, mWidth, mHeight, depth, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); for (GLint z = 0; z < depth; z++) { glTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, mWidth, mHeight, 1, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); } void readFB(int x, int y) { glReadPixels(x, y, mWidth, mHeight, GL_RGBA, GL_UNSIGNED_BYTE, mData.data()); } // Read pixels from 'other' into 'this' from position (x,y). // Pixels outside 'other' are untouched or zeroed according to 'zeroOutside.' void readPixelRect(const PixelRect &other, int x, int y, bool zeroOutside) { for (int i = 0; i < mWidth; ++i) { for (int j = 0; j < mHeight; ++j) { angle::GLColor *dest = &mData[i + j * mWidth]; if (!other.getPixel(x + i, y + j, dest) && zeroOutside) { *dest = angle::GLColor(0); } } } } bool getPixel(int x, int y, angle::GLColor *colorOut) const { if (0 <= x && x < mWidth && 0 <= y && y < mHeight) { *colorOut = mData[x + y * mWidth]; return true; } return false; } void compare(const PixelRect &expected) const { ASSERT_EQ(mWidth, expected.mWidth); ASSERT_EQ(mHeight, expected.mHeight); for (int x = 0; x < mWidth; ++x) { for (int y = 0; y < mHeight; ++y) { ASSERT_EQ(expected.mData[x + y * mWidth], mData[x + y * mWidth]) << "at (" << x << ", " << y << ")"; } } } private: int mWidth, mHeight; std::vector<angle::GLColor> mData; }; } // namespace namespace angle { class WebGLReadOutsideFramebufferTest : public ANGLETest { public: // Read framebuffer to 'pixelsOut' via glReadPixels. void TestReadPixels(int x, int y, int, PixelRect *pixelsOut) { pixelsOut->readFB(x, y); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D and GL_TEXTURE_2D. void TestCopyTexSubImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_2D, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, x, y, kReadWidth, kReadHeight); readTexture2D(GL_TEXTURE_2D, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage2D and cube map. void TestCopyTexSubImageCube(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_CUBE_MAP, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, 0, 0, x, y, kReadWidth, kReadHeight); readTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexSubImage3D. void TestCopyTexSubImage3D(int x, int y, int z, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture3D(destTexture.get(), kTextureDepth); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexSubImage3D(GL_TEXTURE_3D, 0, 0, 0, z, x, y, kReadWidth, kReadHeight); readTexture3D(destTexture, kReadWidth, kReadHeight, z, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexImage2D and GL_TEXTURE_2D. void TestCopyTexImage2D(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_2D, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0); readTexture2D(GL_TEXTURE_2D, destTexture.get(), kReadWidth, kReadHeight, pixelsOut); } // Read framebuffer to 'pixelsOut' via glCopyTexImage2D and cube map. void TestCopyTexImageCube(int x, int y, int, PixelRect *pixelsOut) { // Init texture with given pixels. GLTexture destTexture; pixelsOut->toTexture2D(GL_TEXTURE_CUBE_MAP, destTexture.get()); // Read framebuffer -> texture -> 'pixelsOut' glCopyTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, x, y, kReadWidth, kReadHeight, 0); readTexture2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, destTexture, kReadWidth, kReadHeight, pixelsOut); } protected: static constexpr int kFbWidth = 128; static constexpr int kFbHeight = 128; static constexpr int kTextureDepth = 16; static constexpr int kReadWidth = 4; static constexpr int kReadHeight = 4; static constexpr int kReadLayer = 2; // Tag the framebuffer pixels differently than the initial read buffer pixels, so we know for // sure which pixels are changed by reading. static constexpr GLuint fbTag = 0x1122; static constexpr GLuint readTag = 0xaabb; WebGLReadOutsideFramebufferTest() : mFBData(kFbWidth, kFbHeight) { setWindowWidth(kFbWidth); setWindowHeight(kFbHeight); setConfigRedBits(8); setConfigGreenBits(8); setConfigBlueBits(8); setConfigAlphaBits(8); setWebGLCompatibilityEnabled(true); } void testSetUp() override { constexpr char kVS[] = R"( attribute vec3 a_position; varying vec2 v_texCoord; void main() { v_texCoord = a_position.xy * 0.5 + 0.5; gl_Position = vec4(a_position, 1); })"; constexpr char kFS[] = R"( precision mediump float; varying vec2 v_texCoord; uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, v_texCoord); })"; mProgram = CompileProgram(kVS, kFS); glUseProgram(mProgram); GLint uniformLoc = glGetUniformLocation(mProgram, "u_texture"); ASSERT_NE(-1, uniformLoc); glUniform1i(uniformLoc, 0); glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // fill framebuffer with unique pixels mFBData.fill(fbTag); GLTexture fbTexture; mFBData.toTexture2D(GL_TEXTURE_2D, fbTexture); drawQuad(mProgram, "a_position", 0.0f, 1.0f, true); } void testTearDown() override { glDeleteProgram(mProgram); } using TestFunc = void (WebGLReadOutsideFramebufferTest::*)(int x, int y, int z, PixelRect *dest); void Main2D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, 0); } void Main3D(TestFunc testFunc, bool zeroOutside) { mainImpl(testFunc, zeroOutside, kReadLayer); } void mainImpl(TestFunc testFunc, bool zeroOutside, int readLayer) { PixelRect actual(kReadWidth, kReadHeight); PixelRect expected(kReadWidth, kReadHeight); // Read a kReadWidth*kReadHeight rectangle of pixels from places that include: // - completely outside framebuffer, on all sides of it (i,j < 0 or > 2) // - completely inside framebuffer (i,j == 1) // - straddling framebuffer boundary, at each corner and side for (int i = -1; i < 4; ++i) { for (int j = -1; j < 4; ++j) { int x = i * kFbWidth / 2 - kReadWidth / 2; int y = j * kFbHeight / 2 - kReadHeight / 2; // Put unique pixel values into the read destinations. actual.fill(readTag); expected.readPixelRect(actual, 0, 0, false); // Read from framebuffer into 'actual.' glBindFramebuffer(GL_FRAMEBUFFER, 0); (this->*testFunc)(x, y, readLayer, &actual); glBindFramebuffer(GL_FRAMEBUFFER, 0); // Simulate framebuffer read, into 'expected.' expected.readPixelRect(mFBData, x, y, zeroOutside); // See if they are the same. actual.compare(expected); } } } // Get contents of given texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture2D(GLuint target, GLuint texture, GLsizei width, GLsizei height, PixelRect *out) { GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, texture, 0); out->readFB(0, 0); } // Get contents of current texture by drawing it into a framebuffer then reading with // glReadPixels(). void readTexture3D(GLuint texture, GLsizei width, GLsizei height, int zSlice, PixelRect *out) { GLFramebuffer fbo; glBindFramebuffer(GL_FRAMEBUFFER, fbo); glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, texture, 0, zSlice); out->readFB(0, 0); } PixelRect mFBData; GLuint mProgram; }; class WebGL2ReadOutsideFramebufferTest : public WebGLReadOutsideFramebufferTest {}; // Check that readPixels does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, ReadPixels) { Main2D(&WebGLReadOutsideFramebufferTest::TestReadPixels, false); } // Check that copyTexSubImage2D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexSubImage2D) { Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage2D, false); // TODO(fjhenigman): Figure out this failure. // Cube map skipped on 64-bit Windows with D3D FL 9.3 ANGLE_SKIP_TEST_IF(GetParam() == ES2_D3D11_FL9_3()); Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImageCube, false); } // Check that copyTexImage2D sets (0,0,0,0) for pixels outside the framebuffer. TEST_P(WebGLReadOutsideFramebufferTest, CopyTexImage2D) { Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexImage2D, true); // TODO(fjhenigman): Figure out this failure. // Cube map skipped on 64-bit Windows with D3D FL 9.3 ANGLE_SKIP_TEST_IF(GetParam() == ES2_D3D11_FL9_3()); Main2D(&WebGLReadOutsideFramebufferTest::TestCopyTexImageCube, true); } // Check that copyTexSubImage3D does not set a destination pixel when // the corresponding source pixel is outside the framebuffer. TEST_P(WebGL2ReadOutsideFramebufferTest, CopyTexSubImage3D) { // Robust CopyTexSubImage3D behaviour is not implemented on OpenGL. ANGLE_SKIP_TEST_IF(IsDesktopOpenGL() || IsOpenGLES()); Main3D(&WebGLReadOutsideFramebufferTest::TestCopyTexSubImage3D, false); } ANGLE_INSTANTIATE_TEST(WebGLReadOutsideFramebufferTest, ES2_D3D9(), ES2_D3D11(), ES3_D3D11(), ES2_OPENGL(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); ANGLE_INSTANTIATE_TEST(WebGL2ReadOutsideFramebufferTest, ES3_D3D11(), ES3_OPENGL(), ES2_OPENGLES(), ES3_OPENGLES()); } // namespace angle
37.0775
100
0.628616
[ "vector" ]
db91510649651c7236f0a3efa4822bf0bb7ef699
10,021
hpp
C++
luapp/VarBridgeExtra.hpp
ToyAuthor/luapp
080ebe9b1f547db118934f01b423f5ccb21907e4
[ "MIT" ]
9
2016-05-13T10:58:07.000Z
2022-03-02T20:35:24.000Z
extlibs/lua/luapp/VarBridgeExtra.hpp
ToyAuthor/ToyBox
f517a64d00e00ccaedd76e33ed5897edc6fde55e
[ "Unlicense" ]
2
2018-09-19T03:32:28.000Z
2020-03-30T05:39:46.000Z
luapp/VarBridgeExtra.hpp
ToyAuthor/luapp
080ebe9b1f547db118934f01b423f5ccb21907e4
[ "MIT" ]
7
2016-05-13T10:58:32.000Z
2021-05-10T02:11:23.000Z
#pragma once #include <cstring> #include "luapp/LuaAPI.hpp" #include "luapp/TypeString.hpp" namespace lua{ //------------------------------------------------------------------------------ template<typename T> class _ClassZone { public: _ClassZone(){} ~_ClassZone(){} static int destructor(lua::NativeState L) { T* obj = static_cast<T*>(lua::CheckUserData(L, -1, lua::CreateBindingCoreName<T>())); obj->~T(); return 0; } static void registerType(lua::NativeState hLua,lua::Str &userType) { lua::GetMetaTable(hLua,userType); // ... [?] if ( lua::IsType<lua::Nil>(hLua,-1) ) { lua::NewMetaTable(hLua, userType); // ... [nil] [T] lua::PushString(hLua, "__gc"); // ... [nil] [T] ["__gc"] lua::PushFunction(hLua, &lua::_ClassZone<T>::destructor); // ... [nil] [T] ["__gc"] [F] lua::SetTable(hLua, -3); // ... [nil] [T] lua::Pop(hLua,2); // ... } else { lua::Pop(hLua,1); // ... } } }; inline void _PushCoreKey(lua::NativeState L) { lua::PushInteger(L, 0); // lua::PushInteger(L, 1000); // lua::PushNumber(L, 0.0001f); // lua::PushString(L, "__object_from_cpp"); } template<typename T> inline void PushClassToLua(lua::NativeState hLua) { lua::Str userType = lua::CreateBindingCoreName<T>(); lua::NewTable(hLua); // ... [T] lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } template<typename T,typename A1> inline void PushClassToLua(lua::NativeState hLua,A1 a1) { lua::Str userType = lua::CreateBindingCoreName<T>(); lua::NewTable(hLua); // ... [T] lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(a1); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } template<typename T,typename A1,typename A2> inline void PushClassToLua(lua::NativeState hLua,A1 a1,A2 a2) { lua::Str userType = lua::CreateBindingCoreName<T>(); lua::NewTable(hLua); // ... [T] lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(a1,a2); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } template<typename T,typename A1,typename A2,typename A3> inline void PushClassToLua(lua::NativeState hLua,A1 a1,A2 a2,A3 a3) { lua::Str userType = lua::CreateBindingCoreName<T>(); lua::NewTable(hLua); // ... [T] lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(a1,a2,a3); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } template<typename T,typename A1,typename A2,typename A3,typename A4> inline void PushClassToLua(lua::NativeState hLua,A1 a1,A2 a2,A3 a3,A4 a4) { lua::Str userType = lua::CreateBindingCoreName<T>(); lua::NewTable(hLua); // ... [T] lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(a1,a2,a3,a4); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } // Not every class could copy new one. It's why output pointer here. template<typename T> inline void CheckClassFromLua(lua::NativeState hLua,T **t,int i) { // ... [var] ... lua::_PushCoreKey(hLua); // ... [var] ... [key] if (i<0) { lua::GetTable(hLua, i-1); // ... [var] ... [UD] } else { lua::GetTable(hLua, i); // ... [var] ... [UD] } T* obj = static_cast<T*>(lua::CheckUserData(hLua, -1, lua::CreateBindingCoreName<T>())); *t = obj; lua::Pop(hLua, 1); // ... [var] ... } //------------------------------------------------------------------------------ template<typename T> inline void PushStructToLua(lua::NativeState hLua,const T &t) { lua::Str userType = lua::CreateUserType<T>(); lua::GetMetaTable(hLua,userType); // ... [?] if ( lua::IsType<lua::Nil>(hLua,-1) ) { lua::NewMetaTable(hLua, userType); // ... [nil] [T] lua::Pop(hLua,2); // ... } else { lua::Pop(hLua,1); // ... } T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [UD] *ptr = t; lua::GetMetaTable(hLua, userType); // ... [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [UD] } template<typename T> inline void CheckStructFromLua(lua::NativeState hLua,T *t,int i) { T* obj = static_cast<T*>(lua::CheckUserData(hLua, i, lua::CreateUserType<T>())); *t = *obj; } //------------------------------------------------------------------------------ inline void PushUserDataToLua(lua::NativeState hLua,void *input,size_t size,lua::Str userType) { lua::GetMetaTable(hLua,userType); // ... [?] if ( lua::IsType<lua::Nil>(hLua,-1) ) { lua::NewMetaTable(hLua, userType); // ... [nil] [T] lua::Pop(hLua,2); // ... } else { lua::Pop(hLua,1); // ... } void* ptr = lua::NewUserData(hLua, size); // ... [UD] std::memcpy(ptr,input,size); lua::GetMetaTable(hLua, userType); // ... [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [UD] } inline void CheckUserDataFromLua(lua::NativeState hLua,void *output,size_t size,int i,lua::Str userType) { void* obj = lua::CheckUserData(hLua, i, userType); std::memcpy(output,obj,size); } //------------------------------------------------------------------------------ // Type T must be able to copied by operator "=". template<typename T> class Type { public: Type(){} ~Type(){} T data; }; template<typename T> inline void PushVarToLua(lua::NativeState hLua,lua::Type<T> t) { lua::PushStructToLua(hLua,t.data); } template<typename T> inline void CheckVarFromLua(lua::NativeState hLua,lua::Type<T> *t, int i) { lua::CheckStructFromLua(hLua,&(t->data),i); } //------------------------------------------------------------------------------ template<typename T> class Obj { public: ~Obj(){} Obj():_ptr((T*)0),_isComeFromLua(true) { ; } Obj(T *pointerFromCppSide):_ptr(pointerFromCppSide),_isComeFromLua(false) { if ( _ptr==(T*)0 ) { lua::Log<<"Error:the C++ object pull from lua can't push back to lua."<<lua::End; } } T* ptr() { return _ptr; } T* operator ->() { return _ptr; } T& ref() { return *_ptr; } bool isComeFromLua() { return _isComeFromLua; } private: T* _ptr; bool _isComeFromLua; public: T** _getPointerAddress() { return &_ptr; } }; template<typename T> inline void PushVarToLua(lua::NativeState hLua,lua::Obj<T> t) { if (t.isComeFromLua()) { lua::Log<<"Error:the C++ object pull from lua can't push back to lua."<<lua::End; } lua::NewTable(hLua); // ... [T] lua::GetMetaTable(hLua, lua::CreateBindingMethodName<T>()); // ... [T] [?] if ( lua::IsType<lua::Nil>(hLua,-1) ) { lua::Pop(hLua,1); } else { lua::SetMetaTable(hLua, -2); } lua::_PushCoreKey(hLua); // ... [T] [key] T* ptr = static_cast<T*>(lua::NewUserData(hLua, sizeof(T))); // ... [T] [key] [UD] new (ptr) T(); *ptr = t.ref(); delete (t.ptr()); lua::Str userType = lua::CreateBindingCoreName<T>(); lua::_ClassZone<T>::registerType(hLua,userType); lua::GetMetaTable(hLua, userType); // ... [T] [key] [UD] [MT] lua::SetMetaTable(hLua, -2); // ... [T] [key] [UD] lua::SetTable(hLua, -3); // ... [T] } template<typename C> inline void CheckVarFromLua(lua::NativeState hLua,lua::Obj<C> *obj, int i) { lua::CheckClassFromLua(hLua,obj->_getPointerAddress(),i); } //------------------------------------------------------------------------------ }//namespace lua
26.938172
104
0.470512
[ "object" ]
db9584580307e3eecf12ce48dd31f43c343244fc
14,441
hpp
C++
Includes/Rosetta/PlayMode/Tasks/ComplexTask.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
62
2017-08-21T14:11:00.000Z
2018-04-23T16:09:02.000Z
Includes/Rosetta/PlayMode/Tasks/ComplexTask.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
37
2017-08-21T11:13:07.000Z
2018-04-30T08:58:41.000Z
Includes/Rosetta/PlayMode/Tasks/ComplexTask.hpp
Hearthstonepp/Hearthstonepp
ee17ae6de1ee0078dab29d75c0fbe727a14e850e
[ "MIT" ]
10
2017-08-21T03:44:12.000Z
2018-01-10T22:29:10.000Z
// This code is based on Sabberstone project. // Copyright (c) 2017-2019 SabberStone Team, darkfriend77 & rnilva // RosettaStone is hearthstone simulator using C++ with reinforcement learning. // Copyright (c) 2019 Chris Ohk, Youngjoong Kim, SeungHyun Jeon #ifndef ROSETTASTONE_PLAYMODE_COMPLEX_TASK_HPP #define ROSETTASTONE_PLAYMODE_COMPLEX_TASK_HPP #include <Rosetta/PlayMode/Actions/Generic.hpp> #include <Rosetta/PlayMode/Games/Game.hpp> #include <Rosetta/PlayMode/Tasks/SimpleTasks.hpp> #include <Rosetta/PlayMode/Zones/DeckZone.hpp> #include <Rosetta/PlayMode/Zones/FieldZone.hpp> #include <Rosetta/PlayMode/Zones/GraveyardZone.hpp> #include <Rosetta/PlayMode/Zones/HandZone.hpp> #include <effolkronium/random.hpp> #include <utility> using Random = effolkronium::random_static; namespace RosettaStone::PlayMode { using SelfCondList = std::vector<std::shared_ptr<SelfCondition>>; using TaskList = std::vector<std::shared_ptr<ITask>>; //! //! \brief ComplexTask class. //! //! This class lists complex tasks such as "Summon a minion from your deck.". //! class ComplexTask { public: //! Returns a list of task for drawing card(s) from your deck. //! \param amount The amount to draw card. //! \param list A list of self conditions to filter card(s). //! \param addToStack A flag to store card to stack. static TaskList DrawCardFromDeck(int amount, const SelfCondList& list, bool addToStack = false) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(list), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, amount), std::make_shared<SimpleTasks::DrawStackTask>(addToStack) }; } //! Returns a list of task for summoning a minion from your deck. static TaskList SummonMinionFromDeck() { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::SummonStackTask>(true) }; } //! Returns a list of task for summoning a opponent minion from your deck. static TaskList SummonOpMinionFromDeck() { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::ENEMY_DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::SummonStackTask>(true) }; } //! Returns a list of task for summoning a \p race minion from your deck. //! \param race The race of minion(s) to summon. static TaskList SummonRaceMinionFromDeck(Race race) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()), std::make_shared<SelfCondition>(SelfCondition::IsRace(race)) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::SummonStackTask>(true) }; } //! Returns a list of task for summoning a \p cost minion from your deck. //! \param cost The cost of minion(s) to summon. static TaskList SummonCostMinionFromDeck(int cost) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()), std::make_shared<SelfCondition>( SelfCondition::IsCost(cost, RelaSign::EQ)) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::SummonStackTask>(true) }; } //! Returns a list of task for summoning a \p race and \p cost minion //! from your deck according to \p relaSign. //! \param race The race of minion(s) to summon. //! \param cost The cost of minion(s) to summon. //! \param relaSign The comparer to check condition. static TaskList SummonRaceCostMinionFromDeck(Race race, int cost, RelaSign relaSign) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()), std::make_shared<SelfCondition>(SelfCondition::IsRace(race)), std::make_shared<SelfCondition>( SelfCondition::IsCost(cost, relaSign)) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::SummonStackTask>(true) }; } //! Returns a list of task for summoning friendly minions //! that died this turn. static TaskList SummonAllFriendlyDiedThisTurn() { return TaskList{ std::make_shared<SimpleTasks::CustomTask>( [](Player* player, [[maybe_unused]] Entity* source, [[maybe_unused]] Playable* target) { const auto field = player->GetFieldZone(); if (field->IsFull()) { return; } const int num = player->GetNumFriendlyMinionsDiedThisTurn(); auto& graveyard = *(player->GetGraveyardZone()); std::vector<int> minions; minions.reserve(num); for (int i = graveyard.GetCount() - 1, idx = 0; idx < num; --i) { if (!graveyard[i]->isDestroyed) { continue; } if (graveyard[i]->card->GetCardType() != CardType::MINION) { continue; } ++idx; minions.emplace_back(i); } for (int i = static_cast<int>(minions.size()) - 1; i >= 0; --i) { const auto revivedMinion = Entity::GetFromCard(player, graveyard[minions[i]]->card, std::nullopt, field); field->Add(dynamic_cast<Minion*>(revivedMinion)); if (field->IsFull()) { return; } } }) }; } //! Returns a list of task for casting a secret from your deck. static TaskList CastSecretFromDeck() { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsSecret()), std::make_shared<SelfCondition>( SelfCondition::NotExistInSecretZone()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::CastSpellStackTask>(true) }; } //! Returns a list of task for equipping a weapon from your deck. static TaskList EquipWeaponFromDeck() { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::DECK), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsWeapon()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::WeaponStackTask>(true) }; } //! Returns a list of task for destroying random enemy minion(s). //! \param num The number of minion(s) to destroy. static TaskList DestroyRandomEnemyMinion(int num) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>( EntityType::ENEMY_MINIONS), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsNotDead()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, num), std::make_shared<SimpleTasks::DestroyTask>(EntityType::STACK) }; } //! Returns a list of task for giving buff to a random minion in hand. //! \param enchantmentCardID The ID of enchantment card to give buff. static TaskList GiveBuffToRandomMinionInHand( std::string_view enchantmentCardID) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::HAND), std::make_shared<SimpleTasks::FilterStackTask>(SelfCondList{ std::make_shared<SelfCondition>(SelfCondition::IsMinion()) }), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::AddEnchantmentTask>(enchantmentCardID, EntityType::STACK) }; } //! Returns a list of task for giving buff to a random minion in field. //! \param enchantmentCardID The ID of enchantment card to give buff. static TaskList GiveBuffToRandomMinionInField( std::string_view enchantmentCardID) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>(EntityType::MINIONS), std::make_shared<SimpleTasks::RandomTask>(EntityType::STACK, 1), std::make_shared<SimpleTasks::AddEnchantmentTask>(enchantmentCardID, EntityType::STACK) }; } //! Returns a list of task for giving buff to another random minion //! in field. //! \param enchantmentCardID The ID of enchantment card to give buff. static TaskList GiveBuffToAnotherRandomMinionInField( std::string_view enchantmentCardID) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>( EntityType::MINIONS_NOSOURCE), std::make_shared<SimpleTasks::RandomTask>( EntityType::STACK, 1), std::make_shared<SimpleTasks::AddEnchantmentTask>( enchantmentCardID, EntityType::STACK) }; } //! Returns a list of task for activating a secret card. //! \param tasks A list of task of secret card. static TaskList ActivateSecret(TaskList tasks) { TaskList ret{ std::move(tasks) }; ret.emplace_back(std::make_shared<SimpleTasks::SetGameTagTask>( EntityType::SOURCE, GameTag::REVEALED, 1)); ret.emplace_back(std::make_shared<SimpleTasks::MoveToGraveyardTask>( EntityType::SOURCE)); return ret; } //! Returns a list of task for processing the keyword 'Dormant'. //! \param awakenTasks A list of task to execute when the minion awakens. static TaskList ProcessDormant(TaskList awakenTasks) { TaskList ret; ret.emplace_back(std::make_shared<SimpleTasks::CustomTask>( []([[maybe_unused]] Player* player, Entity* source, [[maybe_unused]] Playable* target) { const int value = source->GetGameTag(GameTag::TAG_SCRIPT_DATA_NUM_2); if (value <= source->GetGameTag(GameTag::TAG_SCRIPT_DATA_NUM_1)) { source->SetGameTag(GameTag::TAG_SCRIPT_DATA_NUM_2, value + 1); } if (value + 1 == source->GetGameTag(GameTag::TAG_SCRIPT_DATA_NUM_1)) { source->SetGameTag(GameTag::UNTOUCHABLE, 0); source->SetGameTag(GameTag::EXHAUSTED, 1); } })); ret.emplace_back(std::make_shared<SimpleTasks::ConditionTask>( EntityType::SOURCE, SelfCondList{ std::make_shared<SelfCondition>( SelfCondition::IsAwaken()) })); ret.emplace_back(std::make_shared<SimpleTasks::FlagTask>( true, std::move(awakenTasks))); return ret; } //! Returns a list of task for processing the text "Repeatable this turn". static TaskList RepeatableThisTurn() { TaskList ret; ret.emplace_back(std::make_shared<SimpleTasks::CustomTask>( [](Player* player, Entity* source, [[maybe_unused]] Playable* target) { std::map<GameTag, int> tags; tags.emplace(GameTag::GHOSTLY, 1); Playable* playable = Entity::GetFromCard( player, source->card, tags, player->GetHandZone()); Generic::AddCardToHand(player, playable); player->game->UpdateAura(); player->game->ghostlyCards.emplace_back( playable->GetGameTag(GameTag::ENTITY_ID)); })); return ret; } //! Returns a list of task for copying a random card(s) in your hand. //! \param amount The amount to copy card(s). //! \param list A list of self conditions to filter card(s). static TaskList CopyCardInHand(int amount, const SelfCondList& list) { return TaskList{ std::make_shared<SimpleTasks::IncludeTask>( EntityType::HAND), std::make_shared<SimpleTasks::FilterStackTask>(list), std::make_shared<SimpleTasks::RandomTask>( EntityType::STACK, amount), std::make_shared<SimpleTasks::CopyTask>( EntityType::STACK, ZoneType::HAND) }; } }; } // namespace RosettaStone::PlayMode #endif // ROSETTASTONE_PLAYMODE_COMPLEX_TASK_HPP
42.225146
80
0.596011
[ "vector" ]
db973455e3cc472bc77b1b8982c28d541ffca835
18,585
cc
C++
src/profile-handler.cc
ncopa/gperftools
c69721b2b2ceae426c36de191dd0a6fa443c5c7a
[ "BSD-3-Clause" ]
null
null
null
src/profile-handler.cc
ncopa/gperftools
c69721b2b2ceae426c36de191dd0a6fa443c5c7a
[ "BSD-3-Clause" ]
null
null
null
src/profile-handler.cc
ncopa/gperftools
c69721b2b2ceae426c36de191dd0a6fa443c5c7a
[ "BSD-3-Clause" ]
1
2021-11-24T05:40:35.000Z
2021-11-24T05:40:35.000Z
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2009, Google Inc. // 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 Google Inc. 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. // --- // Author: Sanjay Ghemawat // Nabeel Mian // // Implements management of profile timers and the corresponding signal handler. #include "config.h" #include "profile-handler.h" #if !(defined(__CYGWIN__) || defined(__CYGWIN32__)) #include <stdio.h> #include <errno.h> #include <sys/time.h> #include <list> #include <string> #if HAVE_LINUX_SIGEV_THREAD_ID // for timer_{create,settime} and associated typedefs & constants #include <time.h> // for sys_gettid #include "base/linux_syscall_support.h" // for perftools_pthread_key_create #include "maybe_threads.h" #endif #include "base/dynamic_annotations.h" #include "base/googleinit.h" #include "base/logging.h" #include "base/spinlock.h" #include "maybe_threads.h" using std::list; using std::string; // This structure is used by ProfileHandlerRegisterCallback and // ProfileHandlerUnregisterCallback as a handle to a registered callback. struct ProfileHandlerToken { // Sets the callback and associated arg. ProfileHandlerToken(ProfileHandlerCallback cb, void* cb_arg) : callback(cb), callback_arg(cb_arg) { } // Callback function to be invoked on receiving a profile timer interrupt. ProfileHandlerCallback callback; // Argument for the callback function. void* callback_arg; }; // Blocks a signal from being delivered to the current thread while the object // is alive. Unblocks it upon destruction. class ScopedSignalBlocker { public: ScopedSignalBlocker(int signo) { sigemptyset(&sig_set_); sigaddset(&sig_set_, signo); RAW_CHECK(sigprocmask(SIG_BLOCK, &sig_set_, NULL) == 0, "sigprocmask (block)"); } ~ScopedSignalBlocker() { RAW_CHECK(sigprocmask(SIG_UNBLOCK, &sig_set_, NULL) == 0, "sigprocmask (unblock)"); } private: sigset_t sig_set_; }; // This class manages profile timers and associated signal handler. This is a // a singleton. class ProfileHandler { public: // Registers the current thread with the profile handler. void RegisterThread(); // Registers a callback routine to receive profile timer ticks. The returned // token is to be used when unregistering this callback and must not be // deleted by the caller. ProfileHandlerToken* RegisterCallback(ProfileHandlerCallback callback, void* callback_arg); // Unregisters a previously registered callback. Expects the token returned // by the corresponding RegisterCallback routine. void UnregisterCallback(ProfileHandlerToken* token) NO_THREAD_SAFETY_ANALYSIS; // Unregisters all the callbacks and stops the timer(s). void Reset(); // Gets the current state of profile handler. void GetState(ProfileHandlerState* state); // Initializes and returns the ProfileHandler singleton. static ProfileHandler* Instance(); private: ProfileHandler(); ~ProfileHandler(); // Largest allowed frequency. static const int32 kMaxFrequency = 4000; // Default frequency. static const int32 kDefaultFrequency = 100; // ProfileHandler singleton. static ProfileHandler* instance_; // pthread_once_t for one time initialization of ProfileHandler singleton. static pthread_once_t once_; // Initializes the ProfileHandler singleton via GoogleOnceInit. static void Init(); // Timer state as configured previously. bool timer_running_; // The number of profiling signal interrupts received. int64 interrupts_ GUARDED_BY(signal_lock_); // Profiling signal interrupt frequency, read-only after construction. int32 frequency_; // ITIMER_PROF (which uses SIGPROF), or ITIMER_REAL (which uses SIGALRM). // Translated into an equivalent choice of clock if per_thread_timer_enabled_ // is true. int timer_type_; // Signal number for timer signal. int signal_number_; // Counts the number of callbacks registered. int32 callback_count_ GUARDED_BY(control_lock_); // Is profiling allowed at all? bool allowed_; // Must be false if HAVE_LINUX_SIGEV_THREAD_ID is not defined. bool per_thread_timer_enabled_; #ifdef HAVE_LINUX_SIGEV_THREAD_ID // this is used to destroy per-thread profiling timers on thread // termination pthread_key_t thread_timer_key; #endif // This lock serializes the registration of threads and protects the // callbacks_ list below. // Locking order: // In the context of a signal handler, acquire signal_lock_ to walk the // callback list. Otherwise, acquire control_lock_, disable the signal // handler and then acquire signal_lock_. SpinLock control_lock_ ACQUIRED_BEFORE(signal_lock_); SpinLock signal_lock_; // Holds the list of registered callbacks. We expect the list to be pretty // small. Currently, the cpu profiler (base/profiler) and thread module // (base/thread.h) are the only two components registering callbacks. // Following are the locking requirements for callbacks_: // For read-write access outside the SIGPROF handler: // - Acquire control_lock_ // - Disable SIGPROF handler. // - Acquire signal_lock_ // For read-only access in the context of SIGPROF handler // (Read-write access is *not allowed* in the SIGPROF handler) // - Acquire signal_lock_ // For read-only access outside SIGPROF handler: // - Acquire control_lock_ typedef list<ProfileHandlerToken*> CallbackList; typedef CallbackList::iterator CallbackIterator; CallbackList callbacks_ GUARDED_BY(signal_lock_); // Starts or stops the interval timer. // Will ignore any requests to enable or disable when // per_thread_timer_enabled_ is true. void UpdateTimer(bool enable) EXCLUSIVE_LOCKS_REQUIRED(signal_lock_); // Returns true if the handler is not being used by something else. // This checks the kernel's signal handler table. bool IsSignalHandlerAvailable(); // Signal handler. Iterates over and calls all the registered callbacks. static void SignalHandler(int sig, siginfo_t* sinfo, void* ucontext); DISALLOW_COPY_AND_ASSIGN(ProfileHandler); }; ProfileHandler* ProfileHandler::instance_ = NULL; pthread_once_t ProfileHandler::once_ = PTHREAD_ONCE_INIT; const int32 ProfileHandler::kMaxFrequency; const int32 ProfileHandler::kDefaultFrequency; // If we are LD_PRELOAD-ed against a non-pthreads app, then these functions // won't be defined. We declare them here, for that case (with weak linkage) // which will cause the non-definition to resolve to NULL. We can then check // for NULL or not in Instance. extern "C" { int pthread_once(pthread_once_t *, void (*)(void)) ATTRIBUTE_WEAK; int pthread_kill(pthread_t thread_id, int signo) ATTRIBUTE_WEAK; #if HAVE_LINUX_SIGEV_THREAD_ID int timer_create(clockid_t clockid, struct sigevent* evp, timer_t* timerid) ATTRIBUTE_WEAK; int timer_delete(timer_t timerid) ATTRIBUTE_WEAK; int timer_settime(timer_t timerid, int flags, const struct itimerspec* value, struct itimerspec* ovalue) ATTRIBUTE_WEAK; #endif } #if HAVE_LINUX_SIGEV_THREAD_ID struct timer_id_holder { timer_t timerid; timer_id_holder(timer_t _timerid) : timerid(_timerid) {} }; extern "C" { static void ThreadTimerDestructor(void *arg) { if (!arg) { return; } timer_id_holder *holder = static_cast<timer_id_holder *>(arg); timer_delete(holder->timerid); delete holder; } } static void CreateThreadTimerKey(pthread_key_t *pkey) { int rv = perftools_pthread_key_create(pkey, ThreadTimerDestructor); if (rv) { RAW_LOG(FATAL, "aborting due to pthread_key_create error: %s", strerror(rv)); } } static void StartLinuxThreadTimer(int timer_type, int signal_number, int32 frequency, pthread_key_t timer_key) { int rv; struct sigevent sevp; timer_t timerid; struct itimerspec its; memset(&sevp, 0, sizeof(sevp)); sevp.sigev_notify = SIGEV_THREAD_ID; sevp._sigev_un._tid = sys_gettid(); sevp.sigev_signo = signal_number; clockid_t clock = CLOCK_THREAD_CPUTIME_ID; if (timer_type == ITIMER_REAL) { clock = CLOCK_MONOTONIC; } rv = timer_create(clock, &sevp, &timerid); if (rv) { RAW_LOG(FATAL, "aborting due to timer_create error: %s", strerror(errno)); } timer_id_holder *holder = new timer_id_holder(timerid); rv = perftools_pthread_setspecific(timer_key, holder); if (rv) { RAW_LOG(FATAL, "aborting due to pthread_setspecific error: %s", strerror(rv)); } its.it_interval.tv_sec = 0; its.it_interval.tv_nsec = 1000000000 / frequency; its.it_value = its.it_interval; rv = timer_settime(timerid, 0, &its, 0); if (rv) { RAW_LOG(FATAL, "aborting due to timer_settime error: %s", strerror(errno)); } } #endif void ProfileHandler::Init() { instance_ = new ProfileHandler(); } ProfileHandler* ProfileHandler::Instance() { if (pthread_once) { pthread_once(&once_, Init); } if (instance_ == NULL) { // This will be true on systems that don't link in pthreads, // including on FreeBSD where pthread_once has a non-zero address // (but doesn't do anything) even when pthreads isn't linked in. Init(); assert(instance_ != NULL); } return instance_; } ProfileHandler::ProfileHandler() : timer_running_(false), interrupts_(0), callback_count_(0), allowed_(true), per_thread_timer_enabled_(false) { SpinLockHolder cl(&control_lock_); timer_type_ = (getenv("CPUPROFILE_REALTIME") ? ITIMER_REAL : ITIMER_PROF); signal_number_ = (timer_type_ == ITIMER_PROF ? SIGPROF : SIGALRM); // Get frequency of interrupts (if specified) char junk; const char* fr = getenv("CPUPROFILE_FREQUENCY"); if (fr != NULL && (sscanf(fr, "%u%c", &frequency_, &junk) == 1) && (frequency_ > 0)) { // Limit to kMaxFrequency frequency_ = (frequency_ > kMaxFrequency) ? kMaxFrequency : frequency_; } else { frequency_ = kDefaultFrequency; } if (!allowed_) { return; } #if HAVE_LINUX_SIGEV_THREAD_ID // Do this early because we might be overriding signal number. const char *per_thread = getenv("CPUPROFILE_PER_THREAD_TIMERS"); const char *signal_number = getenv("CPUPROFILE_TIMER_SIGNAL"); if (per_thread || signal_number) { if (timer_create && pthread_once) { CreateThreadTimerKey(&thread_timer_key); per_thread_timer_enabled_ = true; // Override signal number if requested. if (signal_number) { signal_number_ = strtol(signal_number, NULL, 0); } } else { RAW_LOG(INFO, "Ignoring CPUPROFILE_PER_THREAD_TIMERS and\n" " CPUPROFILE_TIMER_SIGNAL due to lack of timer_create().\n" " Preload or link to librt.so for this to work"); } } #endif // If something else is using the signal handler, // assume it has priority over us and stop. if (!IsSignalHandlerAvailable()) { RAW_LOG(INFO, "Disabling profiler because signal %d handler is already in use.", signal_number_); allowed_ = false; return; } // Install the signal handler. struct sigaction sa; sa.sa_sigaction = SignalHandler; sa.sa_flags = SA_RESTART | SA_SIGINFO; sigemptyset(&sa.sa_mask); RAW_CHECK(sigaction(signal_number_, &sa, NULL) == 0, "sigprof (enable)"); } ProfileHandler::~ProfileHandler() { Reset(); #ifdef HAVE_LINUX_SIGEV_THREAD_ID if (per_thread_timer_enabled_) { perftools_pthread_key_delete(thread_timer_key); } #endif } void ProfileHandler::RegisterThread() { SpinLockHolder cl(&control_lock_); if (!allowed_) { return; } // Record the thread identifier and start the timer if profiling is on. ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); #if HAVE_LINUX_SIGEV_THREAD_ID if (per_thread_timer_enabled_) { StartLinuxThreadTimer(timer_type_, signal_number_, frequency_, thread_timer_key); return; } #endif UpdateTimer(callback_count_ > 0); } ProfileHandlerToken* ProfileHandler::RegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { ProfileHandlerToken* token = new ProfileHandlerToken(callback, callback_arg); SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); callbacks_.push_back(token); ++callback_count_; UpdateTimer(true); } return token; } void ProfileHandler::UnregisterCallback(ProfileHandlerToken* token) { SpinLockHolder cl(&control_lock_); for (CallbackIterator it = callbacks_.begin(); it != callbacks_.end(); ++it) { if ((*it) == token) { RAW_CHECK(callback_count_ > 0, "Invalid callback count"); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); delete *it; callbacks_.erase(it); --callback_count_; if (callback_count_ == 0) UpdateTimer(false); } return; } } // Unknown token. RAW_LOG(FATAL, "Invalid token"); } void ProfileHandler::Reset() { SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); CallbackIterator it = callbacks_.begin(); while (it != callbacks_.end()) { CallbackIterator tmp = it; ++it; delete *tmp; callbacks_.erase(tmp); } callback_count_ = 0; UpdateTimer(false); } } void ProfileHandler::GetState(ProfileHandlerState* state) { SpinLockHolder cl(&control_lock_); { ScopedSignalBlocker block(signal_number_); SpinLockHolder sl(&signal_lock_); // Protects interrupts_. state->interrupts = interrupts_; } state->frequency = frequency_; state->callback_count = callback_count_; state->allowed = allowed_; } void ProfileHandler::UpdateTimer(bool enable) { if (per_thread_timer_enabled_) { // Ignore any attempts to disable it because that's not supported, and it's // always enabled so enabling is always a NOP. return; } if (enable == timer_running_) { return; } timer_running_ = enable; struct itimerval timer; timer.it_interval.tv_sec = 0; timer.it_interval.tv_usec = (enable ? (1000000 / frequency_) : 0); timer.it_value = timer.it_interval; setitimer(timer_type_, &timer, 0); } bool ProfileHandler::IsSignalHandlerAvailable() { struct sigaction sa; RAW_CHECK(sigaction(signal_number_, NULL, &sa) == 0, "is-signal-handler avail"); // We only take over the handler if the current one is unset. // It must be SIG_IGN or SIG_DFL, not some other function. // SIG_IGN must be allowed because when profiling is allowed but // not actively in use, this code keeps the handler set to SIG_IGN. // That setting will be inherited across fork+exec. In order for // any child to be able to use profiling, SIG_IGN must be treated // as available. return sa.sa_handler == SIG_IGN || sa.sa_handler == SIG_DFL; } void ProfileHandler::SignalHandler(int sig, siginfo_t* sinfo, void* ucontext) { int saved_errno = errno; // At this moment, instance_ must be initialized because the handler is // enabled in RegisterThread or RegisterCallback only after // ProfileHandler::Instance runs. ProfileHandler* instance = ANNOTATE_UNPROTECTED_READ(instance_); RAW_CHECK(instance != NULL, "ProfileHandler is not initialized"); { SpinLockHolder sl(&instance->signal_lock_); ++instance->interrupts_; for (CallbackIterator it = instance->callbacks_.begin(); it != instance->callbacks_.end(); ++it) { (*it)->callback(sig, sinfo, ucontext, (*it)->callback_arg); } } errno = saved_errno; } // This module initializer registers the main thread, so it must be // executed in the context of the main thread. REGISTER_MODULE_INITIALIZER(profile_main, ProfileHandlerRegisterThread()); void ProfileHandlerRegisterThread() { ProfileHandler::Instance()->RegisterThread(); } ProfileHandlerToken* ProfileHandlerRegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { return ProfileHandler::Instance()->RegisterCallback(callback, callback_arg); } void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) { ProfileHandler::Instance()->UnregisterCallback(token); } void ProfileHandlerReset() { return ProfileHandler::Instance()->Reset(); } void ProfileHandlerGetState(ProfileHandlerState* state) { ProfileHandler::Instance()->GetState(state); } #else // OS_CYGWIN // ITIMER_PROF doesn't work under cygwin. ITIMER_REAL is available, but doesn't // work as well for profiling, and also interferes with alarm(). Because of // these issues, unless a specific need is identified, profiler support is // disabled under Cygwin. void ProfileHandlerRegisterThread() { } ProfileHandlerToken* ProfileHandlerRegisterCallback( ProfileHandlerCallback callback, void* callback_arg) { return NULL; } void ProfileHandlerUnregisterCallback(ProfileHandlerToken* token) { } void ProfileHandlerReset() { } void ProfileHandlerGetState(ProfileHandlerState* state) { } #endif // OS_CYGWIN
31.878216
84
0.726016
[ "object" ]
db9d92d8b0984f65c97e293acc7c80d28bdd90ea
362
hpp
C++
Model.hpp
aprithul/CPP-Software-Renderer
9ee00b28c140287ed3773fe9f941e55797879bd5
[ "MIT" ]
null
null
null
Model.hpp
aprithul/CPP-Software-Renderer
9ee00b28c140287ed3773fe9f941e55797879bd5
[ "MIT" ]
null
null
null
Model.hpp
aprithul/CPP-Software-Renderer
9ee00b28c140287ed3773fe9f941e55797879bd5
[ "MIT" ]
null
null
null
#ifndef MODEL_HPP #define MODEL_HPP #include "Utils.hpp" #include "Transform.hpp" #include "Mesh.hpp" namespace rendering { class Model { public: Model(rendering::Mesh* mesh, double scaling_factor); rendering::Mesh* mesh; rendering::Transform transform; double scaling_factor; }; } #endif
15.73913
64
0.616022
[ "mesh", "model", "transform" ]
dba426ea42123117106729a2963c439c5f9f0160
4,626
cpp
C++
src/server/cpp/server.cpp
YuriySavchenko/Messenger
ee515765f3654e7d8db4556bdd393077558c70df
[ "Apache-2.0" ]
3
2018-12-02T14:15:37.000Z
2019-12-09T10:08:00.000Z
src/server/cpp/server.cpp
YuriySavchenko/Messenger
ee515765f3654e7d8db4556bdd393077558c70df
[ "Apache-2.0" ]
null
null
null
src/server/cpp/server.cpp
YuriySavchenko/Messenger
ee515765f3654e7d8db4556bdd393077558c70df
[ "Apache-2.0" ]
null
null
null
#include "../headers/server.h" /* implementation explicit constructor */ Server::Server() { this->server_sock = -1; this->client_sock = -1; this->port = 1234; this->ip = "127.0.0.1"; this->count = 0; } /* implementation particular constructor */ Server::Server(std::string ip, int port) { this->server_sock = -1; this->client_sock = -1; this->port = port; this->ip = ip; } /* procedure for connecting to server */ void Server::Connect() { std::cout << "[+] Running server..." << std::endl; server_sock = socket(AF_INET, SOCK_STREAM, 0); if (server_sock == -1) { exit(EXIT_FAILURE); return; } int length_server_addr = sizeof(server_addr); int length_client_addr = sizeof(client_addr); memset(&server_addr, 0, (size_t) length_server_addr); memset(&client_addr, 0, (size_t) length_client_addr); server_addr.sin_family = PF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); bind(server_sock, (struct sockaddr*) &server_addr, (size_t) length_server_addr); listen(server_sock, 5); getsockname(server_sock, (struct sockaddr*) &server_addr, (socklen_t *) &length_server_addr); std::cout << "Server started on: " << inet_ntoa(server_addr.sin_addr) << ":" << ntohs(server_addr.sin_port) << std::endl; std::cout << "Listening port: " << port << "..." << std::endl; } /* procedure for sending messages */ void Server::Send(std::string message) { std::cout << "[+] Sending message..." << std::endl; std::string msg = ""; std::string receiver = ""; int index = 0; // cutting name of receiver for (index; this->buffer[index] != '|'; index++) receiver += this->buffer[index]; index += 1; // cutting text of message for (index; this->buffer[index] != '\0'; index++) msg += this->buffer[index]; // looking for receiver in list of Users and send to him message for (int i=0; i < users.size(); i++) { if (users[i].name == receiver) send(users[i].data, msg.c_str(), msg.length(), 0); } std::cout << "[-] Message was sending!" << std::endl; } /* procedure for receiving messages */ void Server::Receive(int socket) { char buff[1024] = {}; memset(&buff, '\0', sizeof(buff)); int receive = recv(socket, buff, 1024, 0); if (receive != 0) { std::string sender; std::string ip; // looking for name of sender for (int i=0; i < users.size(); i++) { if (users[i].data == socket) { sender = users[i].name; ip = users[i].ip; } } this->buffer = buff; std::cout << "Message from client: " << std::endl; std::cout << "NICKNAME: " << sender << " IP: " << ip << " MESSAGE: " << buff << std::endl; } else if (receive == -1) { std::cout << "[-] Receiving Error!" << std::endl; exit(EXIT_FAILURE); } } /* procedure for closing both sockets */ void Server::Close() { std::cout << "Stop of listening!" << std::endl; std::cout << "[-] Stop of working server!" << std::endl; close(this->client_sock); close(this->server_sock); } /* function for receiving communication on the socket */ void Server::Accept() { // accepting connection of User int length_client_addr = sizeof(client_addr); client_sock = accept(server_sock, (struct sockaddr*) &client_addr, (socklen_t *) &length_client_addr); getpeername(client_sock, (struct sockaddr*) &client_addr, (socklen_t *) &length_client_addr); // print info about connected user std::cout << "Client with IP: "; std::cout << inet_ntoa(client_addr.sin_addr); std::cout << ":" << ntohs(client_addr.sin_port); std::cout << " was connected."; std::cout << std::endl; char buff[1024] = {}; memset(&buff, '\0', sizeof(buff)); // receiving nickname of User int recv_nick = recv(client_sock, buff, 1024, 0); if (recv_nick != 0) { this->buffer = buff; // adding connected User to vector of Users if (this->buffer.length() > 0) users.push_back(User{count, client_sock, "127.0.0.1", buffer}); else std::cout << "[-] Naming Error Nickname!"; this->count++; } else if (recv_nick == -1) { std::cout << "[-] Receiving Error Nickname!"; exit(EXIT_FAILURE); } } /* function for getting value from { client_sock } */ int Server::getSocket() { return this->client_sock; }
26.135593
125
0.57955
[ "vector" ]
dba56c8c0912ccc0c47b43594c865eaabb0f9feb
9,104
cpp
C++
Extensions/TiledSpriteObject/Extension.cpp
nailuj29gaming/GDevelop
e4dff72e74a5050759fc97a67e4c81f47a61b69b
[ "MIT" ]
2
2020-05-23T14:15:30.000Z
2020-06-20T13:23:59.000Z
Extensions/TiledSpriteObject/Extension.cpp
Saurav1905/GDevelop
2811eef4e072ab35cf35ca22562ccd9f854cae9f
[ "MIT" ]
null
null
null
Extensions/TiledSpriteObject/Extension.cpp
Saurav1905/GDevelop
2811eef4e072ab35cf35ca22562ccd9f854cae9f
[ "MIT" ]
null
null
null
/** GDevelop - Tiled Sprite Extension Copyright (c) 2012-2016 Victor Levasseur (victorlevasseur01@orange.fr) Copyright (c) 2014-2016 Florian Rival (Florian.Rival@gmail.com) This project is released under the MIT License. */ #include <iostream> #include "GDCpp/Extensions/ExtensionBase.h" #include "TiledSpriteObject.h" void DeclareTiledSpriteObjectExtension(gd::PlatformExtension& extension) { extension .SetExtensionInformation( "TiledSpriteObject", _("Tiled Sprite Object"), "Displays an image in a repeating pattern over an area. Useful for " "making backgrounds, including background that are scrolling when " "the camera moves. This is more performant than using multiple " "Sprite objects.", "Victor Levasseur and Florian Rival", "Open source (MIT License)") .SetExtensionHelpPath("/objects/tiled_sprite"); gd::ObjectMetadata& obj = extension.AddObject<TiledSpriteObject>( "TiledSprite", _("Tiled Sprite"), _("Displays an image repeated over an area."), "CppPlatform/Extensions/TiledSpriteIcon.png"); #if defined(GD_IDE_ONLY) obj.SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition("Opacity", _("Opacity"), _("Compare the opacity of a Tiled Sprite, between 0 (fully " "transparent) to 255 (opaque)."), _("the opacity"), _("Visibility"), "res/conditions/opacity24.png", "res/conditions/opacity.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number"); obj.AddAction( "SetOpacity", _("Change Tiled Sprite opacity"), _("Change the opacity of a Tiled Sprite. 0 is fully transparent, 255 " "is opaque (default)."), _("the opacity"), _("Visibility"), "res/actions/opacity24.png", "res/actions/opacity.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number"); obj.AddExpression("Opacity", _("Opacity"), _("Opacity"), _("Visibility"), "res/actions/opacity.png") .AddParameter("object", _("Object"), "TiledSprite"); obj.AddAction( "SetColor", _("Tint color"), _("Change the tint of a Tiled Sprite. The default color is white."), _("Change tint of _PARAM0_ to _PARAM1_"), _("Effects"), "res/actions/color24.png", "res/actions/color.png") .AddParameter("object", _("Object"), "TiledSprite") .AddParameter("color", _("Tint")); obj.AddAction("Width", _("Width"), _("Modify the width of a Tiled Sprite."), _("the width"), _("Size and angle"), "res/actions/scaleWidth24.png", "res/actions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number") .SetFunctionName("SetWidth") .SetGetter("GetWidth") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition("Width", _("Width"), _("Test the width of a Tiled Sprite."), _("the width"), _("Size and angle"), "res/conditions/scaleWidth24.png", "res/conditions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("GetWidth") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddAction("Height", _("Height"), _("Modify the height of a Tiled Sprite."), _("the height"), _("Size and angle"), "res/actions/scaleHeight24.png", "res/actions/scaleHeight.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number") .SetFunctionName("SetHeight") .SetGetter("GetHeight") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition("Height", _("Height"), _("Test the height of a Tiled Sprite."), _("the height"), _("Size and angle"), "res/conditions/scaleHeight24.png", "res/conditions/scaleHeight.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("GetHeight") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddAction("Angle", _("Angle"), _("Modify the angle of a Tiled Sprite."), _("the angle"), _("Size and angle"), "res/actions/rotate24.png", "res/actions/rotate.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("SetAngle") .SetGetter("GetAngle") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition("Angle", _("Angle"), _("Test the angle of a Tiled Sprite."), _("the angle"), _("Size and angle"), "res/conditions/rotate24.png", "res/conditions/rotate.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number") .SetHidden() // Now available for all objects .SetFunctionName("GetAngle") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddAction( "XOffset", _("Image X Offset"), _("Modify the offset used on the X axis when displaying the image."), _("the X offset"), _("Image offset"), "res/conditions/scaleWidth24.png", "res/conditions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("SetXOffset") .SetGetter("GetXOffset") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition( "XOffset", _("Image X Offset"), _("Test the offset used on the X axis when displaying the image."), _("the X offset"), _("Image offset"), "res/conditions/scaleWidth24.png", "res/conditions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("GetXOffset") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddAction( "YOffset", _("Image Y Offset"), _("Modify the offset used on the Y axis when displaying the image."), _("the Y offset"), _("Image offset"), "res/conditions/scaleWidth24.png", "res/conditions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("SetYOffset") .SetGetter("GetYOffset") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); obj.AddCondition( "YOffset", _("Image Y Offset"), _("Test the offset used on the Y axis when displaying the image."), _("the Y offset"), _("Image offset"), "res/conditions/scaleWidth24.png", "res/conditions/scaleWidth.png") .AddParameter("object", _("Object"), "TiledSprite") .UseStandardRelationalOperatorParameters("number") .MarkAsAdvanced() .SetFunctionName("GetYOffset") .SetIncludeFile("TiledSpriteObject/TiledSpriteObject.h"); #endif } /** * \brief This class declares information about the extension. */ class TiledSpriteObjectCppExtension : public ExtensionBase { public: /** * Constructor of an extension declares everything the extension contains: * objects, actions, conditions and expressions. */ TiledSpriteObjectCppExtension() { DeclareTiledSpriteObjectExtension(*this); AddRuntimeObject<TiledSpriteObject, RuntimeTiledSpriteObject>( GetObjectMetadata("TiledSpriteObject::TiledSprite"), "RuntimeTiledSpriteObject"); GD_COMPLETE_EXTENSION_COMPILATION_INFORMATION(); }; }; #if defined(ANDROID) extern "C" ExtensionBase* CreateGDCppTiledSpriteObjectExtension() { return new TiledSpriteObjectCppExtension; } #elif !defined(EMSCRIPTEN) /** * Used by GDevelop to create the extension class * -- Do not need to be modified. -- */ extern "C" ExtensionBase* GD_EXTENSION_API CreateGDExtension() { return new TiledSpriteObjectCppExtension; } #endif
35.701961
79
0.607645
[ "object" ]
dba5ea9e064a07c9ef13df93c6ac749e40ab5311
242
cpp
C++
main.cpp
achimett/Qontainer
ad59dbfa32ef3e0e48b6a9564373504b7a9d6fd8
[ "MIT" ]
null
null
null
main.cpp
achimett/Qontainer
ad59dbfa32ef3e0e48b6a9564373504b7a9d6fd8
[ "MIT" ]
null
null
null
main.cpp
achimett/Qontainer
ad59dbfa32ef3e0e48b6a9564373504b7a9d6fd8
[ "MIT" ]
3
2019-10-18T16:33:43.000Z
2021-01-21T12:02:06.000Z
#include <QApplication> #include "MainView.hpp" #include "Model.hpp" int main(int argc, char *argv[]) { QApplication a(argc, argv); Model m(&a); m.newBox(); MainView w; View::initialize(&w, &m); w.show(); return a.exec(); }
13.444444
32
0.619835
[ "model" ]
dba64d03fd73b5c2da8652807e6ac9b4094d736e
10,024
cpp
C++
examples/Mechanics/JointsTests/NE_BouncingBeam.cpp
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
examples/Mechanics/JointsTests/NE_BouncingBeam.cpp
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
examples/Mechanics/JointsTests/NE_BouncingBeam.cpp
stpua/siconos
01cd4a134746b2b22e6473e7a1d8e5bc892cc2a9
[ "Apache-2.0" ]
null
null
null
/* Siconos is a program dedicated to modeling, simulation and control * of non smooth dynamical systems. * * Copyright 2018 INRIA. * * 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. */ /*!\file NE....cpp \brief \ref EMNE_MULTIBODY - C++ input file, Time-Stepping version - O.B. A multibody example. Direct description of the model. Simulation with a Time-Stepping scheme. */ #include "SiconosKernel.hpp" #include "KneeJointR.hpp" #include "PrismaticJointR.hpp" #include <boost/math/quaternion.hpp> using namespace std; /* Given a position of a point in the Inertial Frame and the configuration vector q of a solid * returns a position in the spatial frame. */ void fromInertialToSpatialFrame(double *positionInInertialFrame, double *positionInSpatialFrame, SP::SiconosVector q ) { double q0 = q->getValue(3); double q1 = q->getValue(4); double q2 = q->getValue(5); double q3 = q->getValue(6); ::boost::math::quaternion<double> quatQ(q0, q1, q2, q3); ::boost::math::quaternion<double> quatcQ(q0, -q1, -q2, -q3); ::boost::math::quaternion<double> quatpos(0, positionInInertialFrame[0], positionInInertialFrame[1], positionInInertialFrame[2]); ::boost::math::quaternion<double> quatBuff; //perform the rotation quatBuff = quatQ * quatpos * quatcQ; positionInSpatialFrame[0] = quatBuff.R_component_2()+q->getValue(0); positionInSpatialFrame[1] = quatBuff.R_component_3()+q->getValue(1); positionInSpatialFrame[2] = quatBuff.R_component_4()+q->getValue(2); } void tipTrajectories(SP::SiconosVector q, double * traj, double length) { double positionInInertialFrame[3]; double positionInSpatialFrame[3]; // Output the position of the tip of beam1 positionInInertialFrame[0]=length/2; positionInInertialFrame[1]=0.0; positionInInertialFrame[2]=0.0; fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q ); traj[0] = positionInSpatialFrame[0]; traj[1] = positionInSpatialFrame[1]; traj[2] = positionInSpatialFrame[2]; // std::cout << "positionInSpatialFrame[0]" << positionInSpatialFrame[0]<<std::endl; // std::cout << "positionInSpatialFrame[1]" << positionInSpatialFrame[1]<<std::endl; // std::cout << "positionInSpatialFrame[2]" << positionInSpatialFrame[2]<<std::endl; positionInInertialFrame[0]=-length/2; fromInertialToSpatialFrame(positionInInertialFrame, positionInSpatialFrame, q ); traj[3]= positionInSpatialFrame[0]; traj[4] = positionInSpatialFrame[1]; traj[5] = positionInSpatialFrame[2]; } int main(int argc, char* argv[]) { try { // ================= Creation of the model ======================= // User-defined main parameters unsigned int nDof = 3; unsigned int qDim = 7; unsigned int nDim = 6; double t0 = 0; // initial computation time double T = 10.0; // final computation time double h = 0.01; // time step int N = 1000; double L1 = 1.0; double L2 = 1.0; double L3 = 1.0; double theta = 1.0; // theta for MoreauJeanOSI integrator double g = 9.81; // Gravity double m = 1.; // ------------------------- // --- Dynamical systems --- // ------------------------- FILE * pFile; pFile = fopen("data.h", "w"); if (pFile == NULL) { printf("fopen exampleopen filed!\n"); fclose(pFile); } cout << "====> Model loading ..." << endl << endl; // -- Initial positions and velocities -- SP::SiconosVector q03(new SiconosVector(qDim)); SP::SiconosVector v03(new SiconosVector(nDim)); SP::SimpleMatrix I3(new SimpleMatrix(3, 3)); v03->zero(); I3->eye(); I3->setValue(0, 0, 0.1); q03->zero(); (*q03)(2) = -L1 * sqrt(2.0) - L1 / 2; double angle = M_PI / 2; SiconosVector V1(3); V1.zero(); V1.setValue(0, 0); V1.setValue(1, 1); V1.setValue(2, 0); q03->setValue(3, cos(angle / 2)); q03->setValue(4, V1.getValue(0)*sin(angle / 2)); q03->setValue(5, V1.getValue(1)*sin(angle / 2)); q03->setValue(6, V1.getValue(2)*sin(angle / 2)); SP::NewtonEulerDS bouncingbeam(new NewtonEulerDS(q03, v03, m, I3)); // -- Set external forces (weight) -- SP::SiconosVector weight3(new SiconosVector(nDof)); (*weight3)(2) = -m * g; bouncingbeam->setFExtPtr(weight3); // -------------------- // --- Interactions --- // -------------------- // Interaction with the floor double e = 0.9; SP::SimpleMatrix H(new SimpleMatrix(1, qDim)); SP::SiconosVector eR(new SiconosVector(1)); eR->setValue(0, 2.3); H->zero(); (*H)(0, 2) = 1.0; SP::NonSmoothLaw nslaw0(new NewtonImpactNSL(e)); SP::NewtonEulerR relation0(new NewtonEulerR()); relation0->setJachq(H); relation0->setE(eR); cout << "main jacQH" << endl; relation0->jachq()->display(); // Interactions // Building the prismatic joint for bouncingbeam // input - the first concerned DS : bouncingbeam // - an axis in the spatial frame (absolute frame) // SP::SimpleMatrix H4(new SimpleMatrix(PrismaticJointR::numberOfConstraints(), qDim)); // H4->zero(); SP::SiconosVector axe1(new SiconosVector(3)); axe1->zero(); axe1->setValue(2, 1); SP::PrismaticJointR relation4(new PrismaticJointR(axe1, false, bouncingbeam)); SP::NonSmoothLaw nslaw4(new EqualityConditionNSL(relation4->numberOfConstraints())); SP::Interaction inter4(new Interaction(nslaw4, relation4)); SP::Interaction interFloor(new Interaction(nslaw0, relation0)); // ------------- // --- Model --- // ------------- SP::NonSmoothDynamicalSystem myModel(new NonSmoothDynamicalSystem(t0, T)); // add the dynamical system in the non smooth dynamical system myModel->insertDynamicalSystem(bouncingbeam); // link the interaction and the dynamical system myModel->link(inter4, bouncingbeam); myModel->link(interFloor, bouncingbeam); // ------------------ // --- Simulation --- // ------------------ // -- (1) OneStepIntegrators -- SP::MoreauJeanOSI OSI3(new MoreauJeanOSI(theta)); // -- (2) Time discretisation -- SP::TimeDiscretisation t(new TimeDiscretisation(t0, h)); // -- (3) one step non smooth problem SP::OneStepNSProblem osnspb(new MLCP()); // -- (4) Simulation setup with (1) (2) (3) SP::TimeStepping s(new TimeStepping(myModel, t, OSI3, osnspb)); s->setNewtonTolerance(5e-4); s->setNewtonMaxIteration(50); // =========================== End of model definition =========================== // ================================= Computation ================================= // --- Get the values to be plotted --- // -> saved in a matrix dataPlot unsigned int outputSize = 15 + 7; SimpleMatrix dataPlot(N, outputSize); SimpleMatrix bouncingbeamPlot(2,3*N); SP::SiconosVector q3 = bouncingbeam->q(); SP::SiconosVector y= interFloor->y(0); SP::SiconosVector ydot= interFloor->y(1); // --- Time loop --- cout << "====> Start computation ... " << endl << endl; // ==== Simulation loop - Writing without explicit event handling ===== int k = 0; boost::progress_display show_progress(N); boost::timer time; time.restart(); SP::SiconosVector yAux(new SiconosVector(3)); yAux->setValue(0, 1); SP::SimpleMatrix Jaux(new SimpleMatrix(3, 3)); Index dimIndex(2); Index startIndex(4); fprintf(pFile, "double T[%d*%d]={", N + 1, outputSize); double beamTipTrajectories[6]; for (k = 0; k < N; k++) { // solve ... s->advanceToEvent(); // --- Get values to be plotted --- dataPlot(k, 0) = s->nextTime(); dataPlot(k, 1) = (*q3)(0); dataPlot(k, 2) = (*q3)(1); dataPlot(k, 3) = (*q3)(2); dataPlot(k, 4) = (*q3)(3); dataPlot(k, 5) = (*q3)(4); dataPlot(k, 6) = (*q3)(5); dataPlot(k, 7) = (*q3)(6); dataPlot(k, 8) = y->norm2(); dataPlot(k, 9) = ydot->norm2(); tipTrajectories(q3,beamTipTrajectories,L3); bouncingbeamPlot(0,3*k) = beamTipTrajectories[0]; bouncingbeamPlot(0,3*k+1) = beamTipTrajectories[1]; bouncingbeamPlot(0,3*k+2) = beamTipTrajectories[2]; bouncingbeamPlot(1,3*k) = beamTipTrajectories[3]; bouncingbeamPlot(1,3*k+1) = beamTipTrajectories[4]; bouncingbeamPlot(1,3*k+2) = beamTipTrajectories[5]; //printf("reaction1:%lf \n", interFloor->lambda(1)->getValue(0)); for (unsigned int jj = 0; jj < outputSize; jj++) { if ((k || jj)) fprintf(pFile, ","); fprintf(pFile, "%f", dataPlot(k, jj)); } fprintf(pFile, "\n"); s->nextStep(); ++show_progress; } fprintf(pFile, "};"); cout << endl << "End of computation - Number of iterations done: " << k - 1 << endl; cout << "Computation Time " << time.elapsed() << endl; // --- Output files --- cout << "====> Output file writing ..." << endl; ioMatrix::write("NE_BouncingBeam.dat", "ascii", dataPlot, "noDim"); ioMatrix::write("NE_BouncingBeam_beam.dat", "ascii", bouncingbeamPlot, "noDim"); double error=0.0, eps=1e-12; if ((error=ioMatrix::compareRefFile(dataPlot, "NE_BouncingBeam.ref", eps)) >= 0.0 && error > eps) return 1; fclose(pFile); } catch (SiconosException e) { cout << e.report() << endl; } catch (...) { cout << "Exception caught in NE_...cpp" << endl; } }
31.721519
132
0.612231
[ "vector", "model", "solid" ]
dbaf51fbaeb0cdd577d724351f7da9a6cef51caf
384
cpp
C++
util/vector_reader.cpp
intns/utillib
0cc0fcedb31ec388d44c021f79d80c45cc3e29fb
[ "Unlicense" ]
6
2021-09-18T13:42:28.000Z
2021-09-29T06:25:49.000Z
util/vector_reader.cpp
intns/MODConv
a557e73ffcb18cd1dc6b4e14a8d7e1ef0b4f9e87
[ "Unlicense" ]
null
null
null
util/vector_reader.cpp
intns/MODConv
a557e73ffcb18cd1dc6b4e14a8d7e1ef0b4f9e87
[ "Unlicense" ]
null
null
null
#include <util/vector_reader.hpp> namespace util { vector_reader::vector_reader(Endianness endianness) : m_buffer({ 0 }) , m_position(0) , m_endianness(endianness) { } vector_reader::vector_reader(std::vector<u8> bytes, std::size_t position, Endianness endianness) : m_buffer(bytes) , m_position(position) , m_endianness(endianness) { } } // namespace util
20.210526
96
0.710938
[ "vector" ]
dbaf6dfa21e9f05f9037c6a06a28ec978273a083
3,534
cpp
C++
source/sqlcopy.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
source/sqlcopy.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
source/sqlcopy.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2016, Santili Y-HRAH KRONG * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sqlcopy.hpp> namespace cppsqlx { SQLCopy::SQLCopy(std::string tablename):tablename_(tablename) { delim_ = R"(|)"; esc_ = R"(\\)"; reject_limit_ = 0; } std::string SQLCopy::toString() { std::string query = std::string("COPY ") + tablename_ + "\n"; if(columns_.size() > 0) { int index = 0; query += "("; for(auto v : columns_) { query += v; if( index < columns_.size() - 1) query += ","; else query += ")\n"; index++; } } std::string sdirection = direction_ == COPY_DIRECTION::TO ? "TO" : "FROM"; query += sdirection + " '" + filename_ + "'\n"; query += "WITH DELIMITER '" + delim_ + "'\n"; query += "ESCAPE E'" + esc_ + "'\n"; query += "NULL '" + null_string_ + "'\n"; if(header_) query += "HEADER\n"; if(error_table_ != "") query += "LOG ERRORS INTO " + error_table_ + "\n"; if(csv_) query += "CSV \n"; if(fill_) query += "FILL MISSING FIELDS \n"; if(reject_limit_ > 0) query += "SEGMENT REJECT LIMIT " + std::to_string(reject_limit_) + "\n"; return query; } SQLCopy& SQLCopy::from(std::string filename) { filename_ = filename; return *this; } SQLCopy& SQLCopy::to(std::string filename) { filename_ = filename; return *this; } SQLCopy& SQLCopy::delimiter(std::string delim) { delim_ = delim; return *this; } SQLCopy& SQLCopy::escape(std::string esc) { esc_ = esc; return *this; } SQLCopy& SQLCopy::errorTo(std::string log_table) { error_table_ = log_table; return *this; } SQLCopy& SQLCopy::null(std::string null_string) { null_string_ = null_string; return *this; } SQLCopy& SQLCopy::columns(std::vector<std::string> columnnames) { columns_ = columnnames; return *this; } SQLCopy& SQLCopy::header() { header_ = true; return *this; } SQLCopy& SQLCopy::csv() { csv_ = true; return *this; } SQLCopy& SQLCopy::fillMissingFields() { fill_ = true; return *this; } SQLCopy& SQLCopy::rejectLimit(int limit) { reject_limit_ = limit; return *this; } };/*namespace cppsqlx*/
21.950311
83
0.651952
[ "vector" ]
dbb73cb683622b2aac4831b6855bda15307f2fae
812
cpp
C++
14.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
1
2016-06-21T16:29:37.000Z
2016-06-21T16:29:37.000Z
14.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
null
null
null
14.cpp
jonathanxqs/lintcode
148435aff0a83ac5d77a7ccbd5d0caaea3140a62
[ "MIT" ]
null
null
null
class Solution { public: /** * @param nums: The integer array. * @param target: Target number to find. * @return: The first position of target. Position starts from 0. */ int binarySearch(vector<int> &array, int target) { // write your code here int ar_n=array.size(); int i=0,j,l=0,r=ar_n-1,mid=0; while (l<=r){ mid =(l+r)/2; if (array[mid]>target){ r=mid-1; } else if (array[mid]<target) l=mid+1; else break; } j=mid; if (array[mid+1]==target and mid+1<ar_n) j=mid+1; if (array[mid-1]==target and mid-1>=0) j=mid-1; while (array[j-1]==target and j-1>=0) j--; if (array[j]==target) return j; return -1; } }; // Total Runtime: 156 ms
26.193548
70
0.511084
[ "vector" ]
dbb828597ec3e7a72502225b7c5294861c310181
2,042
cc
C++
elements/ip6/setip6dscp.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
129
2015-10-08T14:38:35.000Z
2022-03-06T14:54:44.000Z
elements/ip6/setip6dscp.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
241
2016-02-17T16:17:58.000Z
2022-03-15T09:08:33.000Z
elements/ip6/setip6dscp.cc
MacWR/Click-changed-for-ParaGraph
18285e5da578fbb7285d10380836146e738dee6e
[ "Apache-2.0" ]
61
2015-12-17T01:46:58.000Z
2022-02-07T22:25:19.000Z
/* * setip6dscp.{cc,hh} -- element sets IP6 header DSCP field * Frederik Scholaert * * Copyright (c) 2002 Massachusetts Institute of Technology * * 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, subject to the conditions * listed in the Click LICENSE file. These conditions include: you must * preserve this copyright notice, and you cannot mention the copyright * holders in advertising related to the Software without their permission. * The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This * notice is a summary of the Click LICENSE file; the license in that file is * legally binding. */ #include <click/config.h> #include "setip6dscp.hh" #include <clicknet/ip6.h> #include <click/args.hh> #include <click/error.hh> CLICK_DECLS SetIP6DSCP::SetIP6DSCP() { } SetIP6DSCP::~SetIP6DSCP() { } int SetIP6DSCP::configure(Vector<String> &conf, ErrorHandler *errh) { unsigned dscp_val; if (Args(conf, this, errh).read_mp("DSCP", dscp_val).complete() < 0) return -1; if (dscp_val > 0x3F) return errh->error("diffserv code point out of range"); // OK: set values _dscp = htonl(dscp_val << IP6_DSCP_SHIFT); return 0; } inline Packet * SetIP6DSCP::smaction(Packet *p_in) { WritablePacket *p = p_in->uniqueify(); assert(p->has_network_header()); click_ip6 *ip6 = p->ip6_header(); ip6->ip6_flow = (ip6->ip6_flow & htonl(~IP6_DSCP_MASK)) | _dscp; return p; } void SetIP6DSCP::push(int, Packet *p) { if ((p = smaction(p)) != 0) output(0).push(p); } Packet * SetIP6DSCP::pull(int) { Packet *p = input(0).pull(); if (p) p = smaction(p); return p; } void SetIP6DSCP::add_handlers() { add_read_handler("dscp", read_keyword_handler, "0 DSCP", Handler::CALM); add_write_handler("dscp", reconfigure_keyword_handler, "0 DSCP"); } CLICK_ENDDECLS EXPORT_ELEMENT(SetIP6DSCP) ELEMENT_MT_SAFE(SetIP6DSCP)
24.309524
77
0.708129
[ "vector" ]
dbb90d8d0398ef46a8b7c8dd0c0d6c166d724735
4,684
cpp
C++
PDS II/VPL 04 - Polígonos/polygon.cpp
nataliaellem/aeds
59b0b5af000baad10f868ed714c43be77f94643b
[ "MIT" ]
4
2020-04-19T15:36:00.000Z
2021-10-21T00:06:21.000Z
PDS II/VPL 04 - Polígonos/polygon.cpp
nataliaellem/aeds
59b0b5af000baad10f868ed714c43be77f94643b
[ "MIT" ]
null
null
null
PDS II/VPL 04 - Polígonos/polygon.cpp
nataliaellem/aeds
59b0b5af000baad10f868ed714c43be77f94643b
[ "MIT" ]
1
2020-04-26T04:13:22.000Z
2020-04-26T04:13:22.000Z
/** * Todas as tarefas deste exercicio devem ser feitas sobre esse arquivo. * Os metodos e operacoes marcados com a tag "TODO" devem ser editados. */ #include <iostream> #include <typeinfo> #include "polygon.h" std::ostream& operator << (std::ostream &out, const Polygon &poly) { for (const Point& p: poly.limits) { out << " " << p; } return out; } bool operator == (const Polygon &lhs, const Polygon &rhs) { // TODO: implement this method. std::vector<Point> limits_lhs = lhs.operator const std::vector<Point, std::allocator<Point>> &(); std::vector<Point> limits_rhs = rhs.operator const std::vector<Point, std::allocator<Point>> &(); bool resp = false; int menor_x, menor_y, maior_x, maior_y; // Se lhs for um quadrado ou um retângulo, // serão adicionados os pontos das outras vértices do quadrado/retângulo. if (typeid(lhs) == typeid(RightRectangle) || typeid(lhs) == typeid(RightSquare)){ if (limits_lhs[0].x > limits_lhs[1].x){ menor_x = limits_lhs[1].x; maior_x = limits_lhs[0].x; } else if (limits_lhs[0].x < limits_lhs[1].x){ menor_x = limits_lhs[0].x; maior_x = limits_lhs[1].x; } if (limits_lhs[0].y > limits_lhs[1].y){ menor_y = limits_lhs[1].y; maior_y = limits_lhs[0].y; } else if (limits_lhs[0].y < limits_lhs[1].y){ menor_y = limits_lhs[0].y; maior_y = limits_lhs[1].y; } Point point1(maior_x, menor_y); Point point2(menor_x, maior_y); Point point3(menor_x, menor_y); Point point4(maior_x, maior_y); limits_lhs.push_back(point1); limits_lhs.push_back(point2); limits_lhs.push_back(point3); limits_lhs.push_back(point4); } // Se rhs for um quadrado ou um retângulo, // serão adicionados os pontos das outras vértices do quadrado/retângulo. if (typeid(rhs) == typeid(RightRectangle) || typeid(rhs) == typeid(RightSquare)){ if (limits_rhs[0].x > limits_rhs[1].x){ menor_x = limits_rhs[1].x; maior_x = limits_rhs[0].x; } else if (limits_rhs[0].x < limits_rhs[1].x){ menor_x = limits_rhs[0].x; maior_x = limits_rhs[1].x; } if (limits_rhs[0].y > limits_rhs[1].y){ menor_y = limits_rhs[1].y; maior_y = limits_rhs[0].y; } else if (limits_rhs[0].y < limits_rhs[1].y){ menor_y = limits_rhs[0].y; maior_y = limits_rhs[1].y; } Point point1(maior_x, menor_y); Point point2(menor_x, maior_y); Point point3(menor_x, menor_y); Point point4(maior_x, maior_y); limits_rhs.push_back(point1); limits_rhs.push_back(point2); limits_rhs.push_back(point3); limits_rhs.push_back(point4); } for (int i = 0; i < limits_lhs.size(); i++){ Point p = limits_lhs[i]; for (int j = 0; j < limits_rhs.size(); j++){ Point p2 = limits_rhs[j]; if (p.contains(p2)){ resp = true; break; } // Se estiver na ultima posição do vetor e não tiver encontrado um dos pontos do polígono lhs em rhs, // significa que os polígonos são diferentes if (j == limits_rhs.size() - 1){ if (!p.contains(p2)){ return false; } } else { resp = false; } } } for (int i = 0; i < limits_rhs.size(); i++){ Point p = limits_lhs[i]; for (int j = 0; j < limits_lhs.size(); j++){ Point p2 = limits_rhs[j]; if (p.contains(p2)){ resp = true; break; } if (j == limits_lhs.size() - 1){ if (!p.contains(p2)){ return false; } } else { resp = false; } } } return resp; } bool Point::contains(const Point& p) const { return p.x == this->x && p.y == this->y; } std::ostream& operator << (std::ostream &out, const Point &p) { out << "(" << p.x << ", " << p.y << ")"; return out; } bool RightRectangle::contains(const Point& p) const { // TODO: implement this method. bool resp; if (this->limits[0].x > this->limits[1].x){ resp = (p.x >= this->limits[1].x && p.x <= this->limits[0].x); } else { resp = (p.x >= this->limits[0].x && p.x <= this->limits[1].x); } if (this->limits[0].y > this->limits[1].y){ resp = (p.y >= this->limits[1].y && p.y <= this->limits[0].y); } else { resp = (p.y >= this->limits[0].y && p.y <= this->limits[1].y); } return resp; } Point::Point(int xx, int yy): x(xx), y(yy) { // TODO: implement this method. this->limits.push_back(*this); } RightRectangle::RightRectangle(int x0, int y0, int x1, int y1) { // TODO: implement this method. Point p1(x0, y0); Point p2(x1, y1); this->limits.push_back(p1); this->limits.push_back(p2); }
27.552941
107
0.588813
[ "vector" ]
dbbb3bb602b0bd70190c7a37572f78c4d7733303
179
cpp
C++
plugins/core/client/src/Madgine/render/rendercontextcollector.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
5
2018-05-16T14:09:34.000Z
2019-10-24T19:01:15.000Z
plugins/core/client/src/Madgine/render/rendercontextcollector.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
71
2017-06-20T06:41:42.000Z
2021-01-11T11:18:53.000Z
plugins/core/client/src/Madgine/render/rendercontextcollector.cpp
MadManRises/Madgine
c9949bc9cf8b30d63db0da2382c9fbc5b60bcd0f
[ "MIT" ]
2
2018-05-16T13:57:25.000Z
2018-05-16T13:57:51.000Z
#include "../clientlib.h" #include "rendercontextcollector.h" #include "Modules/uniquecomponent/uniquecomponentregistry.h" DEFINE_UNIQUE_COMPONENT(Engine::Render, RenderContext)
29.833333
60
0.826816
[ "render" ]
dbbf92b61acf3e200e118142498faa4e1424ade1
611
cpp
C++
Dec2020/5Dec/LastStoneWeight.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
Dec2020/5Dec/LastStoneWeight.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
Dec2020/5Dec/LastStoneWeight.cpp
shivanisbp/2monthsOfCoding
26dc53e3160c7b313dff974b957c81350bf9f1a1
[ "MIT" ]
null
null
null
/* Problem name: 1046. Last Stone Weight Problem link: https://leetcode.com/problems/last-stone-weight/ */ class Solution { public: int lastStoneWeight(vector<int>& stones) { priority_queue <int> pq; for(int i=0;i<stones.size();++i) pq.push(stones[i]); while(pq.size() > 1){ int a = pq.top(); pq.pop(); int b = pq.top(); pq.pop(); if(a == b) continue; else pq.push(a-b); } if(pq.empty()) return 0; else return pq.top(); } };
22.62963
62
0.456628
[ "vector" ]
3a79caef624fd12f1bf3e2397f5fc97cbbb47a9c
1,550
cpp
C++
src/tests/core/Test_Constraint.cpp
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
29
2015-05-19T12:17:16.000Z
2021-03-05T17:53:00.000Z
src/tests/core/Test_Constraint.cpp
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
36
2016-10-26T12:47:11.000Z
2021-03-03T15:19:38.000Z
src/tests/core/Test_Constraint.cpp
sjunges/carl
5013c31c035990d9912a6265944e7d4add4c378b
[ "MIT" ]
16
2015-05-27T07:35:19.000Z
2021-03-05T17:53:08.000Z
#include "gtest/gtest.h" #include <carl-extpolys/ConstraintOperations.h> #include "carl/util/stringparser.h" #include "../Common.h" #include <unordered_set> typedef mpq_class Rational; #if false typedef carl::MultivariatePolynomial<Rational> Pol; typedef carl::Constraint<Pol> PolCon; typedef carl::RationalFunction<Pol> RFunc; typedef carl::Constraint<RFunc> RFuncCon; TEST(Constraint, Operations) { using carl::Relation; carl::StringParser sp; sp.setVariables({"x", "y", "z"}); std::vector<RFuncCon> v1; Pol p1 = sp.parseMultivariatePolynomial<Rational>("3*x"); Pol p2 = sp.parseMultivariatePolynomial<Rational>("1"); RFunc r1(p1,p2); v1.push_back(RFuncCon(r1, Relation::GEQ)); std::unordered_set<PolCon> s1; carl::constraints::toPolynomialConstraints<Pol, false>(v1.begin(), v1.end(), inserter(s1, s1.end())); EXPECT_EQ((size_t)1, s1.size()); v1.clear(); s1.clear(); Pol p3 = sp.parseMultivariatePolynomial<Rational>("z"); RFunc r2(p1,p3); v1.push_back(RFuncCon(r2, Relation::GEQ)); carl::constraints::toPolynomialConstraints<Pol, false>(v1.begin(), v1.end(), inserter(s1, s1.end())); EXPECT_EQ((size_t)2, s1.size()); v1.clear(); s1.clear(); Pol p4 = sp.parseMultivariatePolynomial<Rational>("-2"); RFunc r3(p4); v1.push_back(RFuncCon(r3, Relation::GEQ)); carl::constraints::toPolynomialConstraints<Pol, false>(v1.begin(), v1.end(), inserter(s1, s1.end())); EXPECT_EQ((size_t)1, s1.size()); v1.clear(); s1.clear(); } #endif
26.724138
105
0.674194
[ "vector" ]
3a79d9ea18dafae3e98044dcd97695ff53b045cb
331
cpp
C++
Ch03/Exercises/primer3.17.cpp
Sunrisepeak/gitskills
5f7eba38f114c011e2d1b73bb2be97ba2834c3a4
[ "Apache-2.0" ]
null
null
null
Ch03/Exercises/primer3.17.cpp
Sunrisepeak/gitskills
5f7eba38f114c011e2d1b73bb2be97ba2834c3a4
[ "Apache-2.0" ]
null
null
null
Ch03/Exercises/primer3.17.cpp
Sunrisepeak/gitskills
5f7eba38f114c011e2d1b73bb2be97ba2834c3a4
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<vector> #include<string> using std::cin; using std::cout; int main() { std::vector<std::string> v; std::string word; while(cin >> word) v.push_back(word); for(auto &c : v) { for(decltype(c.size()) i = 0; i < c.size(); i++) c[i] = toupper(c[i]); cout << c; putchar('\n'); } return 0; }
17.421053
50
0.586103
[ "vector" ]
3a79ee42a14d84dc6684be4d65a283f8883b20f6
126,439
cpp
C++
src/newspump.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/newspump.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/newspump.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: newspump.cpp,v $ /* Revision 1.1 2010/07/21 17:14:57 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.4 2009/08/27 15:29:22 richard_wood /* Updates for 2.9.10. /* Fixed : Unable to download a single article (if just one new article in a group) /* Fixed : Crash when trying to close down if a DB compact started (after new version detected) /* /* Revision 1.3 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.2 2009/08/18 22:05:02 richard_wood /* Refactored XOVER and XHDR commands so they fetch item data in batches of 300 (or less) if we want > 300 articles. /* /* Revision 1.1 2009/06/09 13:21:29 richard_wood /* *** empty log message *** /* /* Revision 1.6 2009/04/11 23:55:57 richard_wood /* Updates for bugs 2745988, 2546351, 2622598, 2637852, 2731453, 2674637. /* /* Revision 1.5 2009/03/18 15:08:07 richard_wood /* Added link to SF Gravity web page from Help menu. /* Added "Wrap" command to compose menu. /* Changed version number (dropped minor version, now major, middle, build) /* Fixed bug where app would lock up if downloading & user tried to exit. /* Fixed bozo bin memory leak. /* Fixed "Sort by From" bug. /* Added "sort ascending" and "sort descending" arrows to thread header. /* Fixed width of thread header "threaded" arrow. /* /* Revision 1.4 2009/01/28 14:53:38 richard_wood /* Tidying up formatting /* /* Revision 1.3 2009/01/02 13:34:33 richard_wood /* Build 6 : BETA release /* /* [-] Fixed bug in Follow up dialog - Quoted text should be coloured. /* [-] Fixed bug in New post/Follow up dialog - if more than 1 page of text /* and typing at or near top the text would jump around. /* /* Revision 1.2 2008/09/19 14:51:34 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, Inc. 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. **********************************************************************************/ // newspump.cpp : implementation file // // download headers. WinSock Error - // resubmit job // #include "stdafx.h" #include <tchar.h> #include "News.h" #include "newspump.h" #include "globals.h" #include "server.h" // TNewsServer #include "servcp.h" // TServerCountedPtr #include "tmutex.h" //#include "newsconn.h" #include "tasker.h" #include "tscribe.h" #include "usrdisp.h" #include "custmsg.h" #include "fileutil.h" #include "tglobopt.h" #include "ecpcomm.h" #include "rules.h" #include "fetchart.h" #include "timermgr.h" #include "bits.h" #include "evtlog.h" #include "rgconn.h" #include "enumjob.h" #include "ngutil.h" #include "autoprio.h" #include "timeutil.h" #include "rgswit.h" #include "topexcp.h" // TopLevelException() #include "taglist.h" #include "expire.h" // TExpiryData, TIntVector, #include "tsubjctx.h" // SUBJECT_::CONNECTED #include "nglist.h" #include "memspot.h" #include "utilrout.h" // PostMainWndMsg #include <winperf.h> // PerfMon stuff #include "genutil.h" #include "security.h" #include "superstl.h" // auto_ptr, ... #include "utilerr.h" // TYP_ERROR_ENTERGROUP #include "tscoring.h" // ScoreBody() #include <sstream> #include "utlmacro.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif #define PERFMON_STATS extern TGlobalOptions* gpGlobalOptions; PPERF_COUNTER_BLOCK pCounterBlock; extern LONG gl_Pump_Busy; // in tasker.cpp extern LONG gl_Emergency_Busy; // in tasker.cpp extern BYTE gfGettingNewsgroupList; BOOL FAR WINAPI EmergencyPumpBlockingHook(void); BOOL FAR WINAPI NormalPumpBlockingHook(void); struct PUMPHOOKDATA { HANDLE hKillEvent; TPump * psPump; }; PUMPHOOKDATA gsNormHookData; PUMPHOOKDATA gsPrioHookData; TRETRY vsRetry[2]; // a global , so it can outlive the pump static int FindBlankLineIndex (CString& body, int& iEndHdr, int& iStartBody); static void errorDialog (LPCSTR file, DWORD line, DWORD error, CString & strError); #define ERRDLG(id,desc) errorDialog(__FILE__, __LINE__, id, desc) const static int kiPumpStatusBarRange = 45000; UINT fnProcessNewsgroups (LPVOID pVoid); // thread function TPumpTimeKeeper TPump::m_timeKeeper; // track when to disconnect ///////////////////////////////////////////////////////////////////////////// // C L A S S T P u m p J o b s ///////////////////////////////////////////////////////////////////////////// TPumpJobs::TPumpJobs() { InitializeCriticalSection (&m_csProtect); m_bySacrifice = 0xAC; m_hEventJobReady = CreateEvent ( NULL, // no security TRUE, // we want manual reset FALSE, // start out unsignaled NULL ); // no name } ///////////////////////////////////////////////////////////////////////////// TPumpJobs::~TPumpJobs() { m_bySacrifice = 0x00; cleanup_queue(); CloseHandle (m_hEventJobReady); DeleteCriticalSection (&m_csProtect); } ///////////////////////////////////////////////////////////////////////////// // AddJob - add job to end of the queue. which is the normal case void TPumpJobs::AddJob (TPumpJob * pJob) { TEnterCSection sLock(&m_csProtect); m_Jobs.AddTail ( pJob ); SetEvent ( m_hEventJobReady ); } ///////////////////////////////////////////////////////////////////////////// // put Job at front of queue void TPumpJobs::AddJobToFront (TPumpJob * pJob) { TEnterCSection sLock(&m_csProtect); if (m_Jobs.IsEmpty()) m_Jobs.AddHead ( pJob ); else { // whatever you do, make sure you don't go ahead of the Connect Job! POSITION pos = m_Jobs.GetHeadPosition(); TPumpJob * pHeadJob = m_Jobs.GetAt(pos); if (pHeadJob->GetType() == TPumpJob::kJobConnect) { // TRACE0("Saved by the bell!--->>>\n"); m_Jobs.InsertAfter(pos, pJob); } else m_Jobs.InsertBefore(pos, pJob); } SetEvent ( m_hEventJobReady ); } ///////////////////////////////////////////////////////////////////////////// // erase jobs with flag PJF_TAG_JOB int TPumpJobs::EraseAllTagJobs () { bool fFound = false; TEnterCSection sLock(&m_csProtect); POSITION pos = m_Jobs.GetHeadPosition (); POSITION oldpos ; while (pos) { oldpos = pos; TPumpJob * pJob = m_Jobs.GetNext (pos); if (pJob->GetType() == TPumpJob::kJobArticle) { TPumpJobArticle * pJA = (TPumpJobArticle *) pJob; if (pJA->TestFlag (PJF_TAG_JOB)) { m_Jobs.RemoveAt ( oldpos ); delete pJA; } } } return 0; // success } ///////////////////////////////////////////////////////////////////////////// void TPumpJobs::GetJobCount (int& pumpJobs) { pumpJobs = 0; if (m_bySacrifice != 0xAC) return; TEnterCSection sLock(&m_csProtect); pumpJobs = m_Jobs.GetCount(); #if defined(_DEBUG) if (pumpJobs > 0) { TPumpJob::EPumpJobType type = m_Jobs.GetHead()->GetType (); } #endif } ///////////////////////////////////////////////////////////////////////////// // when we disconnect, we need to weed out certain job types // void TPumpJobs::OnDisconnect () { TEnterCSection sLock(&m_csProtect); POSITION pos = m_Jobs.GetHeadPosition(); POSITION prev; TPumpJob* pPumpJob; while (pos) { prev = pos; pPumpJob = m_Jobs.GetNext ( pos ); if (TPumpJob::kJobBigList == pPumpJob->GetType ()) { m_Jobs.RemoveAt (prev); } } } ///////////////////////////////////////////////////////////////////////////// TPumpJob * TPumpJobs::RemoveJob () { // if TPumpJobs has been deleted, this should throw // // basically, I want to test the waters before trying a fragile KERNEL function // like EnterCriticalSection with an invalid critsect. if (m_bySacrifice != 0xAC) throw 1; TEnterCSection sLock(&m_csProtect); int n = m_Jobs.GetCount(); if (0 == n) { ResetEvent ( m_hEventJobReady ); return NULL; } else if (1 == n) ResetEvent ( m_hEventJobReady ); return m_Jobs.RemoveHead (); } /////////////////////////////////////////////////////////////////////////// // RequestBody (Public) -- called by tasker to DL specific articles // // note: the groupName is passed in as a CString, to take advantage of the // CString reference counting // void TPumpJobs::RequestBody ( const CString & groupName, LONG groupID, int artInt, int iLines, BOOL fFrontOfQueue, DWORD dwFlags ) { CString subject; CPoint ptPartID(0,0); // order the Pump to download this message body TPumpJobArticle * pJob = new TPumpJobArticle( groupName, groupID, subject, ptPartID, artInt, iLines, dwFlags, NULL, NULL); if (fFrontOfQueue) AddJobToFront ( pJob ); else AddJob ( pJob ); } ///////////////////////////////////////////////////////////////////////////// // user is unsubscribing; kill pending jobs int TPumpJobs::CancelNewsgroup(LPCTSTR groupName) { int killCount = 0; TEnterCSection sLock(&m_csProtect); POSITION pos = m_Jobs.GetHeadPosition(); POSITION prev; TPumpJob* pPumpJob; while (pos) { BOOL fKill = FALSE; prev = pos; pPumpJob = m_Jobs.GetNext ( pos ); switch (pPumpJob->GetType()) { case (TPumpJob::kJobGroup): { TPumpJobEnterGroup * pJobGroup = (TPumpJobEnterGroup*) pPumpJob; const CString& rName = pJobGroup->GetGroup(); if (0 == rName.CompareNoCase(groupName)) fKill = TRUE; break; } case (TPumpJob::kJobArticle): { TPumpJobArticle * pJob = (TPumpJobArticle*) pPumpJob; const CString& rName = pJob->GetGroup(); if (0 == rName.CompareNoCase(groupName)) fKill = TRUE; break; } case (TPumpJob::kJobOverview): TPumpJobOverview * pJobOverview = (TPumpJobOverview*) pPumpJob; const CString& rName = pJobOverview->GetGroup(); if (0 == rName.CompareNoCase(groupName)) fKill = TRUE; break; } if (fKill) { delete pPumpJob; m_Jobs.RemoveAt ( prev ); ++killCount; } } // while loop if (0 == m_Jobs.GetCount()) ResetEvent(m_hEventJobReady); return killCount; } // ------------------------------------------------------------------------ // rules analyzes the header, and wants to kill the complete Article // chase down the Body BOOL TPumpJobs::CancelArticleBody ( const CString& groupName, int artInt ) { return cancel_job_in_queue ( groupName, artInt, TPumpJob::kJobArticle ); } // ------------------------------------------------------------------------ // case 2: DEL key applied to tagged article that has been submitted. BOOL TPumpJobs::CancelRetrieveJob ( const CString& groupName, int artInt ) { return cancel_job_in_queue ( groupName, artInt, TPumpJob::kJobArticle ); } // ------------------------------------------------------------------------ // only supports TPumpJob::kJobArticle // BOOL TPumpJobs::cancel_job_in_queue (const CString& groupName, int artInt, TPumpJob::EPumpJobType eType) { ASSERT(TPumpJob::kJobArticle == eType); TEnterCSection sLock(&m_csProtect); POSITION oldPos; POSITION pos = m_Jobs.GetHeadPosition(); TPumpJob* pPumpJob; while (pos) { oldPos = pos; pPumpJob = m_Jobs.GetNext ( pos ); if (eType == pPumpJob->GetType()) { switch (pPumpJob->GetType()) { case (TPumpJob::kJobArticle): { TPumpJobArticle* pParts = (TPumpJobArticle*) pPumpJob; if (artInt == pParts->GetArtInt()) { if (0==groupName.CompareNoCase( pParts->GetGroup() )) { m_Jobs.RemoveAt (oldPos); delete pParts; return TRUE; } } } break; default: ASSERT(FALSE); // unhandled type break; } } } return FALSE; // not found. maybe already downloaded. hmmmm... } // ------------------------------------------------------------------------ // FetchBody -- Retrieve the Body for this Header. Send both into CB function. // NoSave. This is called when a layer wants an article synchronously BOOL TPumpJobs::FetchBody ( const CString& groupName, int groupID, const CString & subject, CPoint & ptPartID, int artInt, int iLines, TFetchArticle* pFetchArticle, BOOL bMarkAsRead /* = TRUE */) { ASSERT(pFetchArticle); ASSERT(groupName); DWORD dwJobFlags = 0; if (bMarkAsRead) dwJobFlags |= PJF_MARK_READ; // order the Pump to download this message body TPumpJobArticle * pJob = new TPumpJobArticle( groupName, groupID, subject, ptPartID, artInt, iLines, dwJobFlags, NULL, // pHeader pFetchArticle); AddJobToFront ( pJob ); return TRUE; } // return True if we moved something BOOL TPumpJobs::QueueReOrder (LPCTSTR groupName) { TEnterCSection sLock(&m_csProtect); if (m_Jobs.IsEmpty()) return FALSE; CTypedPtrList<CObList, TPumpJob*> SubJobs; POSITION oldPos; POSITION pos = m_Jobs.GetTailPosition(); TPumpJob* pPumpJob; while (pos) { oldPos = pos; pPumpJob = m_Jobs.GetPrev ( pos ); switch (pPumpJob->GetType()) { case (TPumpJob::kJobArticle): { TPumpJobArticle* pParts = (TPumpJobArticle*) pPumpJob; if (0 == (pParts->GetGroup()).CompareNoCase(groupName)) { SubJobs.AddHead ( pPumpJob ); m_Jobs.RemoveAt ( oldPos ); } break; } case (TPumpJob::kJobOverview): { TPumpJobOverview* pOver = (TPumpJobOverview*) pPumpJob; if (0 == (pOver->GetGroup()).CompareNoCase(groupName)) { SubJobs.AddHead ( pPumpJob ); m_Jobs.RemoveAt ( oldPos ); } break; } } // switch } // while BOOL fEmpty = SubJobs.IsEmpty(); // move the subgroup to the start m_Jobs.AddHead ( &SubJobs ); return !fEmpty; } ///////////////////////////////////////////////////////////////////////////// // cleanup_queue void TPumpJobs::cleanup_queue() { TPumpJob* pJob; TEnterCSection sLock(&m_csProtect); while (m_Jobs.GetCount() > 0) { pJob = m_Jobs.RemoveHead (); delete pJob; } ResetEvent ( m_hEventJobReady ); } ///////////////////////////////////////////////////////////////////////////// // TPumpExternalLink TPumpExternalLink::TPumpExternalLink (TNewsTasker * pTasker, const CString& strServer, TPumpJobs * pJobs, HANDLE hScribeUnderCapacity, bool fEmergencyPump) : m_pTasker(pTasker), m_pJobs(pJobs), m_strServer(strServer) { // note: send scribe jobs to pTasker m_iSocketError = 0; m_iNNTPError = 0; m_fUserStop = false; // flag used when setting up connection m_fPumpCtorFinished = false; m_hScribeUnderCapacity = hScribeUnderCapacity; m_fEmergencyPump = fEmergencyPump; SetEvent (hScribeUnderCapacity); m_hKillRequest = 0; m_fConnected = false; // set to true after password is accepted } // ------------------------------------------------------------------------ // Flesh out TSubject Interface DWORD TPumpExternalLink::GetSubjectState () { // right now observers only care if we are totally fully connected return m_fConnected ? SUBJECT_CONNECTED : SUBJECT_NO_INFO; } // ------------------------------------------------------------------------ TPumpExternalLink::~TPumpExternalLink() { m_fConnected = false; // let observers know that we are disconnected Update_Observers (); RemoveAllObservers (); } ///////////////////////////////////////////////////////////////////////////// // C L A S S T P u m p ///////////////////////////////////////////////////////////////////////////// UINT TPump::ThreadFunction (LPVOID pParam) { TPump thePump(pParam); UINT ret = thePump.Run (); // kludge : Try to ensure that cleanup happens before the // entire app exits. boost thread priority VERIFY( SetThreadPriority (GetCurrentThread (), THREAD_PRIORITY_ABOVE_NORMAL) ); // automatic call to destructors return ret; } // ------------------------------------------------------------------------ // TPump ctor TPump::TPump(LPVOID pParam) { m_pErrList = &m_sErrorList; m_pLink = (TPumpExternalLink *) pParam; // copy info ptrs m_fEmergencyPump = m_pLink->m_fEmergencyPump; m_pMasterTasker = m_pLink->m_pTasker; // RLWTODO 2 : pump creates the kill request handle TRACE("TPump::TPump : Creating m_KillRequest event\n"); // security, manual, init-state, name m_KillRequest = CreateEvent(NULL, TRUE, FALSE, NULL); // Off by default m_fProcessJobs = true; if (m_fEmergencyPump) { gsPrioHookData.hKillEvent = m_KillRequest; gsPrioHookData.psPump = this; } else { gsNormHookData.hKillEvent = m_KillRequest; gsNormHookData.psPump = this; } // RLWTODO 3 : cpoies it back into the structure m_pLink->m_hKillRequest = m_KillRequest; TServerCountedPtr cpNewsServer; m_pFeeed = new TNewsFeed ( cpNewsServer->GetNewsServerPort (), m_fEmergencyPump ? EmergencyPumpBlockingHook : NormalPumpBlockingHook, m_KillRequest, &m_fProcessJobs, cpNewsServer->GetConnectSecurely()); if ( gpGlobalOptions->GetRegSwitch()->GetLogGroupCmds () ) { m_logFile = cpNewsServer->GetServerDatabasePath(); m_logFile += "\\CMDGRP.TRC"; } else { // m_logFile.Empty(); } m_wServerCap = 0; m_fQuitNNTP = TRUE; // Does Server have XRef info embedded in the XOver info? // this is from registry. if (cpNewsServer->XOverXRef()) m_wServerCap |= kXRefinXOver; m_server = m_pLink->m_strServer; m_pLink->m_fPumpCtorFinished = true; } // ------------------------------------------------------------------------ // You must catch all exceptions in destructors. Otherwise you terminate // TPump::~TPump() { try { CloseHandle (m_KillRequest); FreeConnection (); // created by tasker, but I free the memory if (m_pLink) delete m_pLink; //TRACE0("Pump: destructor is finished\n"); } catch(...) { // catch everything } } // ------------------------------------------------------------------------- // Start normal operation UINT TPump::Run(void) { TRACE("TPump::Run >\n"); DWORD ret; try { for (;;) { ret = CustomizedWait(); if (0 == ret) // kill request break; // Process lots of jobs SingleStep(); } } catch (TSocketException *except) { return run_exception(TRUE, except); } catch (TException *except) { return run_exception(FALSE, except); } catch (CException* pCExc) { pCExc->ReportError(); pCExc->Delete(); // top-level exception handling LINE_TRACE(); TopLevelException (kThreadDownload); pump_lastrites(); throw; } catch(...) { // top-level exception handling LINE_TRACE(); TopLevelException (kThreadDownload); pump_lastrites(); throw; } TRACE("TPump::Run : Thread finished, tidying up before exiting\n"); // This last chunk. Suppose the server disconnected us. Normal pump catches // an exception and dies. But the Emergency pump thinks everything is OK. try { // this is a controlled shutdown. Quit the NNTP session if (m_pFeeed && m_fQuitNNTP) m_pFeeed->Quit( m_pErrList ); // destroy newsfeed before ras-hangup FreeConnection (); } catch (TException *pE) { pE->Delete(); // catch problems with Quit(). LINE_TRACE(); return pump_lastrites(); } catch (CException *pE) { pE->Delete(); // catch problems with Quit(). LINE_TRACE(); return pump_lastrites(); } catch(...) { // top-level exception handling LINE_TRACE(); TopLevelException (kThreadDownload); pump_lastrites(); throw; } // RLWTODO 9 : a flagged killrequest should finally stop the pump thread and end up here // system code will call ExitInstance() && Delete() TRACE("TPump::Run <\n"); return pump_lastrites(); } // ------------------------------------------------------------------------ // ok this is the final gasp BOOL TPump::pump_lastrites() { return FALSE; } //------------------------------------------------------------------------- // process TSocketExceptions & TExceptions here // int TPump::run_exception(BOOL fSocket, TException* pe) { BOOL fKillRequest = (WAIT_OBJECT_0 == WaitForSingleObject(m_KillRequest, 0)); // if the e-pump has a socket problem, let the normal pump continue on. if (fSocket && m_fEmergencyPump) { // if the user did not initiate this problem, display an error if (!fKillRequest) { CString strError; strError.LoadString (IDS_ERR_CONN2); gpEventLog->AddError (TEventEntry::kPump, strError); } // go ahead and call delete return pump_lastrites(); } // what's the matter? if (fKillRequest) { // we are shutting down. We must have done CancelBlockingCall. //TRACE0("TNewsPump::InitInstance shutting down\n"); return pump_lastrites(); // go ahead and call delete } else { // this is a real error pe->Display(); return pump_lastrites(); // go ahead and call delete } } // ------------------------------------------------------------------------ // Wait for // ScribeCanHandleMore && JobReady // Kill Request // int TPump::CustomizedWait() { DWORD dwRet; if (false == m_fProcessJobs) { // since we had an error, we are just waiting around to be killed. dwRet = WaitForSingleObject (m_KillRequest, 60000); // 60 seconds // kill request return 0; } TServerCountedPtr cpNewsServer; HANDLE rSetOne[2]; HANDLE rSetTwo[2]; BOOL fKeepAlive = cpNewsServer->GetSendKeepAliveMsgs(); rSetOne[0] = m_KillRequest; rSetOne[1] = m_pLink->m_hScribeUnderCapacity; rSetTwo[0] = m_KillRequest; rSetTwo[1] = m_pLink->m_pJobs->m_hEventJobReady; dwRet = WaitForMultipleObjects (2, rSetOne, FALSE, INFINITE); if (dwRet - WAIT_OBJECT_0 == 0) { // RLWTODO 6 : a flagged killrequest should end up here TRACE("TPump::CustomizedWait : Received m_KillRequest event (exit 1) <\n"); // kill request return 0; } else { // scribe is ready to handle more data int minutes = 1; const DWORD waitFor = 60000; // one minute // wait for a KillRequest, scribe-trouble or a New Job if (fKeepAlive) { minutes = cpNewsServer->GetKeepAliveMinutes(); } wait_more: dwRet = WaitForMultipleObjects (2, rSetTwo, FALSE, waitFor); if (dwRet - WAIT_OBJECT_0 == 0) { // RLWTODO 7 : or here TRACE("TPump::CustomizedWait : Received m_KillRequest event (exit 2) <\n"); // kill request return 0; } else if (dwRet - WAIT_OBJECT_0 == 1) { // pump job is ready return 1; } else if (WAIT_TIMEOUT != dwRet) { // some error return 0; } else // (WAIT_TIMEOUT == dwRet) { // one minute has passed BOOL fJob = FALSE; // Only the normal pump alone initiates auto-disconnect // - Enough time must have elapsed // - the email thread must be idle if (!m_fEmergencyPump && m_timeKeeper.IsSignaled() && !m_pMasterTasker->IsSendingEmail()) { // start our own demise. fIdleDisconnect, fReconnect PostDisconnectMsg (true, false); } else { if (fKeepAlive && (--minutes <= 0)) { fJob = TRUE; m_pLink->m_pJobs->AddJob (new TPumpJobHelp); minutes = cpNewsServer->GetKeepAliveMinutes(); } } //#if defined(_DEBUG) // TRACE1("%s pump - one minute cycle\n", m_fEmergencyPump ? "E" : "Norm"); //#endif if (fJob) return 2; goto wait_more; } } } // ------------------------------------------------------------------------ void TPump::SingleStep (void) { TPumpJob * pOneJob = NULL; try { pOneJob = m_pLink->m_pJobs->RemoveJob(); } catch (int) { // has m_pJobs been deleted ?? !! pOneJob = NULL; } if (NULL == pOneJob) return; LONG& busy_flag = m_fEmergencyPump ? gl_Emergency_Busy : gl_Pump_Busy; InterlockedIncrement ( &busy_flag ); try { VERIFY(_CrtCheckMemory()); SingleStepDispatch ( pOneJob ); // allow MFC to free Temp maps, DLLS, etc... VERIFY(_CrtCheckMemory()); } catch(...) { InterlockedDecrement ( &busy_flag ); throw; } InterlockedDecrement ( &busy_flag ); } // ------------------------------------------------------------------------ void TPump::SingleStepDispatch (TPumpJob * pOneJob) { BOOL fLogActivity = TRUE; if (TPumpJob::kJobHelp == pOneJob->GetType()) fLogActivity = FALSE; if (fLogActivity) m_timeKeeper.SetActivity (); switch (pOneJob->GetType()) { case (TPumpJob::kJobPingMultiGroup): { // done. PingMultiGroup ( pOneJob ); break; } //case (TPumpJob::kJobPingGroupMode1): case (TPumpJob::kJobPingGroup): case (TPumpJob::kJobGroup): { // done. CheckNewArticles ( pOneJob ); break; } case (TPumpJob::kJobArticle): { //TRACE0("start DownloadArticle\n"); // done. DownloadArticle ( pOneJob ); break; } case (TPumpJob::kJobPost): { // done. PostOneMessage ( pOneJob ); break; } case (TPumpJob::kJobOverview): { // not done! DownloadOverview ( pOneJob ); break; } case (TPumpJob::kJobHelp): { // done. DoHelpCommand ( pOneJob ); break; } case (TPumpJob::kJobConnect): { // not done! DoConnect ( pOneJob ); break; } case (TPumpJob::kJobBigList): { // not done! DoGetNewsgroupList ( pOneJob ); break; } case (TPumpJob::kJobPingArticles): { // done. DoPingArticles ( pOneJob ); break; } } // switch if (fLogActivity) m_timeKeeper.SetActivity (); } // ------------------------------------------------------------------------ // CheckNewArticles - check newsgroup for new articles, send job data // back to tasker. // // Returns 0 for success, 1 for error. (which means stop processing) // Handles // TPumpJob::kJobPingGroupMode1 // TPumpJob::kJobPingGroup // TPumpJob::kJobGroup int TPump::CheckNewArticles (TPumpJob * pBaseJob) { FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); TPumpJobPingGroup * pJob = static_cast<TPumpJobPingGroup*>(pBaseJob); //#ifdef _DEBUG // afxDump << "pump: Checking " << pJob->GetGroup() << "\n"; //#endif sSG.lpszNewsGroup = pJob->GetGroup(); if (0 == m_pFeeed->SetGroup ( m_pErrList, &sSG )) { pJob->SetGroupResults ( sSG.fOK, sSG.iRet, sSG.first, sSG.last ); // $$ reset this pJob->m_NewsGroup = sSG.strGroupName; m_CurrentGroup = pJob->GetGroup(); m_pMasterTasker->AddResult ( pJob ); return 0; // success } DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); if (kClassWinsock == eErrorClass) { // this is not a Job that is important enough to resubmit if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else // disconnect and reconnect PostDisconnectMsg (false, true); return 1; } if (kClassNNTP == eErrorClass) { TCHAR rcNum[10]; _itot(sSG.iRet, rcNum, 10); // no such news group CString desc; AfxFormatString1(desc, IDS_WARN_1NOSUCHNG, sSG.lpszNewsGroup); CString extDesc; sSG.strAck.TrimRight(); AfxFormatString2(extDesc, IDS_WARN_2NOSUCHNGEXT, rcNum, (LPCTSTR) sSG.strAck); gpEventLog->AddWarning (TEventEntry::kPump, desc, extDesc); // present log window to user PostMainWndMsg (WM_COMMAND, ID_VIEW_EVENTLOG); m_CurrentGroup.Empty(); pJob->SetGroupResults ( FALSE, sSG.iRet, 0, 0 ); pJob->m_iRet = sSG.iRet; pJob->m_Ack = sSG.strAck; m_pMasterTasker->AddResult ( pJob ); return 0; // continue processing } ERRDLG(dwErrorID, strError); return 0; } // ------------------------------------------------------------------------ // iSyncGroup -- changes newsgroup. more of a utility function // Returns 0 for success. Caller does the serious error handling // int TPump::iSyncGroup (const CString& rGroup, FEED_SETGROUP * pSG) { // must enter group pSG->fOK = FALSE; pSG->lpszNewsGroup = rGroup; if (0 == m_CurrentGroup.CompareNoCase( rGroup )) return 0; if (0 == m_pFeeed->SetGroup ( m_pErrList, pSG )) { m_CurrentGroup = pSG->strGroupName; return 0; } else return 1; } //////////////////////////////////////////////////////////////////////////// // DownloadArticle -- returns 0 for success // int TPump::DownloadArticle(TPumpJob * pBaseJob) { auto_ptr<CObject> job_deleter(pBaseJob); TPumpJobArticle * pJob = (TPumpJobArticle *) pBaseJob; TArticleText * pText = 0; TUserDisplay_Auto refresher(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); TServerCountedPtr cpNewsServer; TNewsGroup * pNG = 0; BOOL fUseLock; TNewsGroupUseLock useLock (cpNewsServer, pJob->GetGroupID(), &fUseLock, pNG); BOOL fOK = FALSE; if (!fUseLock) { TError sErr (kError, kClassUser, PUMP_GROUP_UNSUBSCRIBED); m_pErrList->PushError (sErr); } else do { // check for unsubscribe // enter Group // setup status line if (0 != dl_body_start( pNG, pJob )) break; pText = new TArticleText; // sub-function for added readability if (download_body_util (pJob, pText)) break; dl_body_success ( pNG, pJob, pText ); pText = 0; return 0; } while (false); // handle errors here DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassWinsock: { bool fResubmit; dl_body_fail_winsock (pJob, dwErrorID, strError, fResubmit); if (fResubmit) job_deleter.release(); break; } case kClassUser: dl_body_fail_user (pJob, dwErrorID, strError); break; case kClassNNTP: dl_body_fail_nntp (pNG, pJob, dwErrorID, strError); break; default: ASSERT(0); break; } delete pText; return 1; } /////////////////////////////////////////////////////////////////////////// // download_body_util // // returns 0 for success // 1 for error // int TPump::download_body_util( TPumpJobArticle * pJob, TArticleText * pText ) { pText->SetNumber ( pJob->GetArtInt() ); BOOL fOK = FALSE; CString& bod = pText->AccessBody(); int iRetryCount = 0; CString ack; int r; ask_utwice: // use the article command to get the Full header and Body simultaneously BOOL fShowREDStatus = m_fEmergencyPump; r = m_pFeeed->Article (m_pErrList, pJob->GetArtInt(), bod, ack, fOK, pJob->GetBodyLines(), fShowREDStatus); if (r) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); if (eErrorClass == kClassNNTP && 412 == dwErrorID && iRetryCount++ == 0) { // special processing for some stupid servers // no newsgroup has been selected m_CurrentGroup.Empty (); m_pErrList->ClearErrors (); FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); r = iSyncGroup (pJob->GetGroup(), &sSG); if (0 == r) goto ask_utwice; return 1; } else { if (FALSE == ack.IsEmpty()) gpEventLog->AddError (TEventEntry::kPump, ack); return 1; } } // chop this article up int iEndHdr = 0; int iStartBody = 0; int ln = bod.GetLength(); // separate the Header from the Body if (0 == FindBlankLineIndex (bod, iEndHdr, iStartBody)) { LPTSTR both = bod.GetBuffer(ln); *(both + iEndHdr) = 0; // cap off the header part pText->SetHeader(both); // set the full header // want to shift the body part up. MoveMemory(both, both + iStartBody, (ln - iStartBody)*sizeof(TCHAR)); bod.ReleaseBuffer( ln - iStartBody ); } else { // Can't find blank line. Treat this as all Header/Zero-Body LPTSTR both = bod.GetBuffer (ln); pText->SetHeader(both); bod.ReleaseBuffer (0); } return 0; } /////////////////////////////////////////////////////////////////////////// // do not delete the PumpJob. The caller will // // // custom errors: kClassUser // PUMP_ARTICLE_INDB // int TPump::dl_body_start (TNewsGroup * pNG, TPumpJobArticle*& pJob) { // check status of article. The emergency pump may have sneaked it in BOOL fHave = pNG->TextRangeHave (pJob->GetArtInt()); // pre-check if other pump got it if (fHave) { TError sErr(kError, kClassUser, PUMP_ARTICLE_INDB); m_pErrList->PushError (sErr); return 1; } FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); if (iSyncGroup ( pJob->GetGroup(), &sSG )) return 1; CString status = pJob->FormatStatusString (); int iLines = pJob->GetBodyLines(); gpUserDisplay->SetText ( status, m_fEmergencyPump ); gpUserDisplay->SetRange( 0, iLines, m_fEmergencyPump ); return 0; } // ------------------------------------------------------------------------ void TPump::dl_body_success (TNewsGroup * pNG, TPumpJobArticle*& pJob, TArticleText* pText) { TPrepBody* pBody = 0; // job for the scribe TFetchArticle * pFetch = pJob->ReleaseFetchObject (); bool fTag = pJob->TestFlag (PJF_TAG_JOB); if (pJob->TestFlag (PJF_MARK_READ)) pNG->StatusMarkRead (pJob->GetArtInt()); if (pJob->TestFlag (PJF_SEND_SCRIBE) && pFetch) { // make a copy for the UI TArticleText * pTxt2 = new TArticleText; *pTxt2 = *pText; // send to the APP. app takes ownership of pFetch pointer pFetch->JobSuccess ( pTxt2 ); pFetch = 0; // pass original off to the scribe pBody = new TPrepBody ( pJob->GetGroup(), pText, pJob->GetArtInt(), fTag ? kJobPartsTag : kJobPartsCache); pText = NULL; // now owned by pBody; ScribeJob ( pBody ); return; } else if (pJob->TestFlag (PJF_SEND_SCRIBE) && NULL == pFetch) { // normal case goes straight to the scribe pBody = new TPrepBody ( pJob->GetGroup(), pText, pJob->GetArtInt(), fTag ? kJobPartsTag : kJobFlagsNone); pText = NULL; // now owned by pBody; ScribeJob ( pBody ); return; } else if (pFetch) { // we are not saving the body. Can give Original back to the UI // - we are skipping the scribe, but we gotta let rules // have a crack at it TArticleHeader * pHeader = pJob->GetArticleHeader(); if (pHeader) { EvalRulesHaveBody (pHeader, pText, pNG); EvalRulesHaveBody_Committed (pHeader, pText, pNG); // also, let the scoring system evaluate the body ScoreBody (pHeader, pText, pNG); } pFetch->JobSuccess ( pText ); } return ; } // ------------------------------------------------------------------------ int TPump::dl_body_fail_winsock ( TPumpJobArticle * pJob, DWORD dwError, CString & strError, bool & fResubmit ) { fResubmit = false; TFetchArticle * pFetch = pJob->ReleaseFetchObject (); if (WSAEINTR == dwError) { // interrupted by user if (pFetch) pFetch->JobFailed (kClassWinsock, dwError, strError); // do no action for // PJF_SEND_UPPERLAYER // PJF_SEND_SCRIBE // PJF_TAG_JOB PostDisconnectMsg (false /* fIdleDisconnect */, false /* fReconnect */ ); } else { TServerCountedPtr cpNewsServer; BOOL fRetry = cpNewsServer->GetRetrying(); int iRetryCount = cpNewsServer->GetRetryCount(); bool fMyReconnect = true; // handles blocking and send_to_ui if (pFetch) pFetch->JobFailed (kClassWinsock, dwError, strError); else { // PJF_TAG_JOB, PJF_SEND_SCRIBE TRETRY * psRetry = &vsRetry[0]; if (m_fEmergencyPump) psRetry = &vsRetry[1]; // see if we can rtry job if ( fRetry && psRetry->CanRetryJob ( (DWORD) pJob, iRetryCount ) ) { // re-do async job resubmit_job ( pJob ); // #1 fResubmit = true; } else fMyReconnect = false; } int iSleepSecs = 0; // disconnect and reconnect PostDisconnectMsg (false, fMyReconnect, iSleepSecs); } return 0; } // ------------------------------------------------------------------------ int TPump::dl_body_fail_user ( TPumpJobArticle * pJob, DWORD dwError, CString & strError) { TServerCountedPtr cpNewsServer; // handle blocking, UI, tscribe TFetchArticle * pFetch = pJob->ReleaseFetchObject (); if (pFetch) pFetch->JobFailed (kClassUser, dwError, strError); // $ ui should ignore // do nothing for PJF_SEND_SCRIBE if (pJob->TestFlag (PJF_TAG_JOB)) { TPersistentTags & rTags = cpNewsServer->GetPersistentTags(); rTags.DeleteTagCancelJob (pJob->GetGroup(), pJob->GetGroupID(), pJob->GetArtInt(), FALSE); cpNewsServer->SavePersistentTags (); } return 0; } // ------------------------------------------------------------------------ int TPump::dl_body_fail_nntp ( TNewsGroup * pNG, TPumpJobArticle * pJob, DWORD dwError, CString & strError) { // handle blocking, UI, tscribe TFetchArticle * pFetch = pJob->ReleaseFetchObject (); // release blocking thread, or // return error to UI if (pFetch) pFetch->JobFailed (kClassNNTP, dwError, strError); if (pJob->TestFlag (PJF_SEND_SCRIBE)) pNG->StatusBitSet (pJob->GetArtInt(), TStatusUnit::kSendErr, TRUE); // pink-X if (pJob->TestFlag (PJF_TAG_JOB)) { TServerCountedPtr cpNewsServer; TPersistentTags & rTags = cpNewsServer->GetPersistentTags(); rTags.DeleteTagCancelJob (pJob->GetGroup(), pJob->GetGroupID(), pJob->GetArtInt(), FALSE); cpNewsServer->SavePersistentTags (); } return 0; } //------------------------------------------------------------------------- int TPump::PostOneMessage(TPumpJob * pBaseJob) { CString post_ack; TPumpJobPost * pJob = (TPumpJobPost *) pBaseJob; BOOL fOK = FALSE; int iMarkRet = 0; int r = m_pFeeed->PostArticle (m_pErrList, pJob->GetFile(), pJob->m_groupName, fOK, post_ack); TServerCountedPtr cpNewsServer; TOutbox* pOutbox = cpNewsServer->GetOutbox (); LONG lArtInt; pJob->GetJobID (lArtInt); pJob->SetPostResult ( fOK ); if (0 == r) { if (pOutbox) iMarkRet = (*pOutbox)->Mark (lArtInt, TStatusUnit::kSent); // save outbox cpNewsServer->SaveOutboxState (); // pass back result, good or bad. m_pMasterTasker->AddResult ( pJob ); return 0; // success } DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassWinsock: if (WSAEINTR == dwErrorID) { if (pOutbox) iMarkRet = (*pOutbox)->Mark (lArtInt, TStatusUnit::kSendErr); PostDisconnectMsg (false, false); } else { // back to waiting if (pOutbox) iMarkRet = (*pOutbox)->Mark (lArtInt, TStatusUnit::kOut); PostDisconnectMsg (false, true); } // save outbox cpNewsServer->SaveOutboxState (); // pass back result, good or bad. m_pMasterTasker->AddResult ( pJob ); break; case kClassNNTP: { CString err; int iPostRet = _ttoi(post_ack); err.Format(IDS_ERR_POSTING_FAILED, (LPCTSTR) pJob->m_groupName, iPostRet); post_ack.TrimRight(); gpEventLog->AddShowError (TEventEntry::kPump, err, post_ack); if (pOutbox) iMarkRet = (*pOutbox)->Mark (lArtInt, TStatusUnit::kSendErr); // save outbox cpNewsServer->SaveOutboxState (); // pass back result, good or bad. m_pMasterTasker->AddResult ( pJob ); } break; default: ASSERT(0); break; } // switch return 0; } /////////////////////////////////////////////////////////////////////////// // DownloadOverview -- download headers, get xpost info, expire articles // // void TPump::DownloadOverview (TPumpJob * pBaseJob) { TServerCountedPtr cpNewsServer; TPumpJobOverview * pJob = static_cast<TPumpJobOverview*>(pBaseJob); auto_ptr<CObject> deleter(pJob); int low, high, i, rangeCount; int grandTotal = 0; TRangeSet * pRangeSet; FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); BOOL fGetBodies = FALSE; DWORD dwErrorID; CString strError; int r; // Sync Group can be sloo-ow, so do status bar immediately // turns on automatic refreshing of statusbar - clear when destruct TUserDisplay_Auto oRefresher(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); // we need more control over that status line for the X-Refs CString mesg1; if (pJob->GetGroup().IsEmpty()) mesg1.Format(IDS_UTIL_ENTERGRP, ""); else mesg1.Format(IDS_UTIL_ENTERGRP, LPCTSTR(pJob->GetGroup())); gpUserDisplay->SetText (mesg1, m_fEmergencyPump); gpUserDisplay->SetRange (0, kiPumpStatusBarRange, m_fEmergencyPump); // must enter group r = iSyncGroup (pJob->GetGroup(), &sSG); if (r) { EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassWinsock: { BOOL fRetry = cpNewsServer->GetRetrying(); int iRetryMax = cpNewsServer->GetRetryCount(); bool fMyReconnect = true; TRETRY * psRetry = &vsRetry[0]; if (m_fEmergencyPump) psRetry = &vsRetry[1]; if ( fRetry && psRetry->CanRetryJob ( (DWORD) pJob, iRetryMax )) { resubmit_job (pJob); // #2 deleter.release(); // we resubmit job, so don't delete ptr } else fMyReconnect = false; if (WSAEINTR==dwErrorID) fMyReconnect = false; int iSleepSecs = 0; PostDisconnectMsg (false, fMyReconnect, iSleepSecs); break; } case kClassNNTP: { // error should have been handled by EnterGroup } default: ASSERT(0); break; } return; } { BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock(cpNewsServer, pJob->GetGroupID(), &fUseLock, pNG); if (!fUseLock) return; // values still not set if (-1 == sSG.first && -1 == sSG.last) { int sblow, sbhi; pNG->GetServerBounds(sblow, sbhi); sSG.first = sblow; sSG.last = sbhi; sSG.est = sbhi - sblow + 1; } // mode 3 newsgroups get the bodies after getting headers fGetBodies = (TNewsGroup::kStoreBodies == UtilGetStorageOption(pNG)); } int iLumpTotal = pJob->GetRangeSet()->CountItems(); int iPingTotal = 0; if (pJob->GetPingRangeSet()) iPingTotal = pJob->GetPingRangeSet()->CountItems(); grandTotal = iLumpTotal + iPingTotal; if (0 == grandTotal) { pJob->Abort(); TExpiryData *pExpiry = new TExpiryData(!pJob->GetExpirePhase(), pJob->GetGroupID(), pJob->GetExpireLow()); ExpireHeadersNotFound (pExpiry); // send back an 'event' for the VCR window PostMainWndMsg (WMU_VCR_GROUPDONE); return ; // avoid divide-by-zero too! } if (pJob->GetGroup().IsEmpty()) AfxFormatString1 (mesg1, IDS_DOWNLOAD_OVERVIEW, _T("")); else AfxFormatString1 (mesg1, IDS_DOWNLOAD_OVERVIEW, (LPCTSTR) pJob->GetGroup()); gpUserDisplay->SetText (mesg1, m_fEmergencyPump); TArtHdrArray * pHdrArray = new TArtHdrArray; try { int iMul = 0; int iLogicalRange; int iLogicalPos = 0; if (0 == iLumpTotal) { iLogicalRange = kiPumpStatusBarRange; POINT ptLogical; ptLogical.x = 0; ptLogical.y = iLogicalRange; ping_articles( pJob->GetPingRangeSet(), pJob->GetExpirePhase(), pJob->GetGroupID(), pJob->GetExpireLow(), grandTotal, &ptLogical, sSG.est, FALSE ); } else if (0 == iPingTotal || pJob->GetExpirePhase()==false) { MPBAR_INFO sBarInfo; sBarInfo.m_iLogPos = 0; sBarInfo.m_iTotalLogRange = iLogicalRange = kiPumpStatusBarRange; sBarInfo.m_nGrandTotal = iLumpTotal; pRangeSet = pJob->GetRangeSet(); int nSubTotal = 0; for (rangeCount = pRangeSet->RangeCount(), i = 0; i < rangeCount; ++i) { pRangeSet->GetRange( i, low, high ); // fill pHdrArray sBarInfo.m_nSubRangeLen = high - low + 1; sBarInfo.m_iLogSubRangeLen = MulDiv (iLogicalRange , sBarInfo.m_nSubRangeLen, iLumpTotal); if (straight_overview( pJob, low, high, &sBarInfo, pHdrArray )) { for (int k = 0; k < pHdrArray->GetSize(); k++) delete pHdrArray->GetAt(k); delete pHdrArray; return; } // track subtotal nSubTotal += sBarInfo.m_nSubRangeLen; // do math, check for overflow iMul = MulDiv (iLogicalRange, nSubTotal, iLumpTotal); // assignment, not increment if (-1 != iMul) sBarInfo.m_iLogPos = iMul; } // even if iPingTotal is zero, we should still call ping_articles. // this takes care of the case when the NewsGroup object has // articles 1-5 and the server now has 7-10. (We must kill 1-5) POINT ptLogical; ptLogical.x = 0; ptLogical.y = 0; ping_articles (pJob->GetPingRangeSet(), pJob->GetExpirePhase(), pJob->GetGroupID(), pJob->GetExpireLow(), grandTotal, &ptLogical, sSG.est, FALSE); } else { POINT ptLogical; MPBAR_INFO sBarInfo; // overview operates on half the range sBarInfo.m_iLogPos = 0; sBarInfo.m_iTotalLogRange = kiPumpStatusBarRange; sBarInfo.m_nGrandTotal = grandTotal; pRangeSet = pJob->GetRangeSet(); rangeCount = pRangeSet->RangeCount(); // grandTotal consists of arbitrary fraction M + N for (i = 0; i < rangeCount; ++i) { pRangeSet->GetRange( i, low, high ); sBarInfo.m_nSubRangeLen = high - low + 1; sBarInfo.m_iLogSubRangeLen = MulDiv (sBarInfo.m_iTotalLogRange , sBarInfo.m_nSubRangeLen, grandTotal); if (straight_overview( pJob, low, high, &sBarInfo, pHdrArray )) { for (int k = 0; k < pHdrArray->GetSize(); k++) delete pHdrArray->GetAt(k); delete pHdrArray; return; } // do math, check for overflow iMul = MulDiv(sBarInfo.m_iTotalLogRange, high - low + 1, grandTotal); if (-1 != iMul) sBarInfo.m_iLogPos += iMul; // StatusBar: M / (M+N) is done } // run the remainder of our work (N) ptLogical.x = sBarInfo.m_iLogPos; ptLogical.y = kiPumpStatusBarRange - sBarInfo.m_iLogPos; ping_articles (pJob->GetPingRangeSet(), pJob->GetExpirePhase(), pJob->GetGroupID(), pJob->GetExpireLow(), grandTotal, &ptLogical, sSG.est, FALSE); } } catch(...) { deliver_headers_to_scribe (pJob, pHdrArray, fGetBodies); throw; } deliver_headers_to_scribe (pJob, pHdrArray, fGetBodies); } typedef struct { CStringArray m_crossPost; CStringArray m_groups; CStringArray m_XIcon; CByteArray m_vbyProtect; } TYP_OVERVIEW_EXTRA, * PTYP_OVERVIEW_EXTRA; /////////////////////////////////////////////////////////////////////////// // straight_overview -- returns 0 for success // // int TPump::straight_overview(TPumpJob * pBaseJob, int low, int high, MPBAR_INFO * psBarInfo, TArtHdrArray* pHdrArray) { psBarInfo->m_nPos = 0; // reset for this subrange BOOL fOK = FALSE; TPumpJobOverview * pParentJob = (TPumpJobOverview*) pBaseJob; int serverRetVal = 0; int r; TServerCountedPtr psServer; BOOL fFullCrossPost = psServer->GetFullCrossPost (); // create a sub-job TPumpJobOverview * pJob; pJob = new TPumpJobOverview( pParentJob->GetGroup(), pParentJob->GetGroupID(), low, high ); auto_ptr<TPumpJobOverview> job_deleter(pJob); // I own this pointer if (m_wServerCap & kMustUseXHDR) return Use_XHDR_Instead (pJob, psBarInfo, fFullCrossPost, pHdrArray); CString followCmd; if (fFullCrossPost) { // Xover is 50% since CP info is 25% + 25% psBarInfo->m_nDivide = 2; } else { // Xover is 100% psBarInfo->m_nDivide = 1; } // use the XOVER command on this range of articles. Ask for everything r = m_pFeeed->Overview (m_pErrList, low, high, pJob->GetList(), fOK, &serverRetVal, m_fEmergencyPump, psBarInfo); if (r) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: if (serverRetVal >= 500) // command unimplemented { m_pErrList->ClearErrors(); return Use_XHDR_Instead (pJob, psBarInfo, fFullCrossPost, pHdrArray); } else log_nntp_error (strError); break; case kClassWinsock: if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else PostDisconnectMsg (false, true); break; } // switch return 1; } // so far so good if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; TYP_OVERVIEW_EXTRA sExtra; sExtra.m_crossPost.SetSize (high - low + 1); sExtra.m_groups.SetSize (high - low + 1); if (!fFullCrossPost) return process_overview_data(pJob, fFullCrossPost, &sExtra, pHdrArray); psBarInfo->m_nPos = 0; // reset for this phase psBarInfo->m_nDivide = 4; r = get_xpost_info(pJob, low, high, &sExtra, psBarInfo); if (r) // cleanup pHdrArray return r; process_overview_data(pJob, fFullCrossPost, &sExtra, pHdrArray); // if this is an OverviewUI job then unblock the UI //pJob->Abort (); return 0; } /////////////////////////////////////////////////////////////////////////// // chop up the overview line. Get the Cross Posting information. // int TPump::process_overview_data(TPumpJobOverview* pBaseJob, BOOL fCrossPost, void * pExtraIn, TArtHdrArray* pHdrArray) { TServerCountedPtr cpNewsServer; TNewsGroup* pNG = 0; BOOL fGroupOpen = FALSE; int bufSz = 8192; LPTSTR pSubj = (LPTSTR) malloc(bufSz); if (0 == pSubj) AfxThrowMemoryException (); THeapBitmap * pAccount = 0; PTYP_OVERVIEW_EXTRA pExtra = (PTYP_OVERVIEW_EXTRA) pExtraIn; try { int req_low, req_hi; pBaseJob->GetGroupRange(req_low, req_hi); pAccount = new THeapBitmap(req_low, req_hi); // bit set to 1 means article OK // tallies expired articles T2StringList & LineList = pBaseJob->GetList(); CString fat; int iArtInt; BOOL fComplete = FALSE; BOOL fUseLock; TNewsGroupUseLock useLock(cpNewsServer, pBaseJob->GetGroup(), &fUseLock, pNG); if (!fUseLock) { // suddenly unsubscribed? //TRACE1("HandleOverview - where is %s\n", LPCTSTR(pBaseJob->GetGroup())); delete pAccount; free (pSubj); return 1; } TArticleHeader * pArtHeader = 0; CString strStatusMsg; int total = LineList.size(); // processing %d headers for %s strStatusMsg.Format (IDS_STATUS_PROCESSING, total, LPCTSTR(pBaseJob->GetGroup())); CString oldStatusTxt; gpUserDisplay->GetText (oldStatusTxt, m_fEmergencyPump); TUserDisplay_Reset sStatusReset(oldStatusTxt, m_fEmergencyPump); gpUserDisplay->SetText (strStatusMsg, m_fEmergencyPump); for (int i = 0; i < total; ++i) { fComplete = overview_to_article ( LineList, fat, pSubj, bufSz, pArtHeader, iArtInt ); if (!fComplete) { delete pArtHeader; pArtHeader = NULL; } else if (iArtInt < req_low || iArtInt > req_hi) { // weirdo case delete pArtHeader; pArtHeader = NULL; } else /* TRUE == fComplete */ { iArtInt = pArtHeader->GetNumber(); pAccount->SetBit( iArtInt ); // article has not expired! // did we retrieve full cross post info if (fCrossPost) add_all_xpost (pExtra->m_crossPost, req_low, iArtInt, fat, pExtra->m_groups, pSubj, bufSz, pArtHeader); catch_header (pNG, pHdrArray, pBaseJob->GetGroup(), iArtInt, pArtHeader); } // fComplete } // for loop, thru all lines TExpiryData * pExpiryData = new TExpiryData(TExpiryData::kMissing, true, // assume all present pNG->m_GroupID, pBaseJob->GetExpireLow()); pExpiryData->m_ArraypBits.Add (pAccount); // sub function ExpireHeadersNotFound (pExpiryData); pAccount = 0; } catch(...) { delete pAccount; free (pSubj); throw; return 1; } delete pAccount; free (pSubj); return 0; } // process_overview_data /////////////////////////////////////////////////////////////////////////// BOOL TPump::overview_to_article (T2StringList & rList, CString & strFat, LPTSTR & pSubj, int & bufSz, TArticleHeader*& rpArtHdr, int & iArtInt) { BOOL fComplete = FALSE; rpArtHdr = NULL; // STL is a little weird.. I admit strFat = *(rList.begin()); rList.pop_front (); int iIndex = strFat.Find ('\t'); if (0 >= iIndex) return FALSE; int iFatLen = strFat.GetLength (); // do we need more room? if (iFatLen > bufSz) size_alloc ( pSubj, bufSz, iFatLen ); LPTSTR fatbuf = strFat.GetBuffer ( iFatLen ); fComplete = overview_make_art ( fatbuf, pSubj, bufSz, rpArtHdr); if (fComplete) { iArtInt = rpArtHdr->GetNumber (); } strFat.ReleaseBuffer ( iFatLen ); return fComplete; } /////////////////////////////////////////////////////////////////////////// void TPump::size_alloc (LPTSTR & pSubj, int & bufSz, int iNewSize) { LPTSTR pNewBuf = (LPTSTR) realloc (pSubj, iNewSize); if (0 == pNewBuf) realloc_error ( bufSz, iNewSize ); else { bufSz = iNewSize; pSubj = pNewBuf; } } /////////////////////////////////////////////////////////////////////////// void TPump::realloc_error (int iOldSize, int iNewSize) { CString final; final.Format (IDS_ERR_REALLOC, iOldSize, iNewSize); throw(new TException (final, kFatal)); } /////////////////////////////////////////////////////////////////////////// // Break this out to profile it // BOOL TPump::overview_make_art (LPTSTR line, LPTSTR pSubj, int bufSz, TArticleHeader*& rpArtHdr) { // Note : get() stops on the delimiter, but doesn't extract it // getline() extracts delimiter, but doesn't store it in result // buffer int iBytes = 0; int iLines = -10; TCHAR rcFrom[4096]; int iArtInt; BOOL fComplete = FALSE; TArticleHeader * pArtHeader = 0; rpArtHdr = NULL; // make a Stream! _tstrstream in(line); // article number Borrow rcFrom as a buffer // these 2 lines handle cases where instead of ArtInt<tab> // we have ArtInt<spaces><tab> // in >> iArtInt; in.getline (rcFrom, sizeof(rcFrom), '\t'); // discard extra junk upto and including Tab // subject in.getline (pSubj, bufSz, '\t'); // from rcFrom[0] = '\0'; in.getline (rcFrom, sizeof(rcFrom), '\t'); if ('\0' == rcFrom[0]) { return FALSE; } pArtHeader = new TArticleHeader; pArtHeader->SetArticleNumber ( iArtInt ); pArtHeader->SetQPFrom ( rcFrom ); #if defined(_DEBUG) pArtHeader->SetQPSubject ( pSubj , rcFrom ); #else pArtHeader->SetQPSubject ( pSubj ); #endif // date in.getline(pSubj, bufSz, '\t'); pArtHeader->SetDate( pSubj ); // msgid in.getline(pSubj, bufSz, '\t'); pArtHeader->SetMessageID(pSubj); // refs in.getline(pSubj, bufSz, '\t'); pArtHeader->SetReferences(pSubj); // skip bytes, get lines in >> iBytes >> iLines; // if lines is not here, then the BYTES token was missing if (iLines < 0) iLines = iBytes; pArtHeader->SetLines( iLines ); // checking for XRef information here at the end in >> ws; in.getline(pSubj, bufSz, _T(' ')); if (0==_tcsicmp(pSubj, _T("Xref:"))) { in >> ws; in.getline(pSubj, bufSz, _T('\r')); // store servername [group:###]+ pArtHeader->SetXRef ( pSubj ); WORD wPrev = m_wServerCap; m_wServerCap |= kXRefinXOver; if (!(wPrev & kXRefinXOver)) { TServerCountedPtr cpNewsServer; cpNewsServer->XOverXRef (true); // saves out to registry cpNewsServer->SaveSettings (); } } fComplete = TRUE; rpArtHdr = pArtHeader; return fComplete; } // ------------------------------------------------------------------------ void TPump::add_all_xpost (CStringArray& crossPost, int iLow, int iArtInt, CString & fat, CStringArray& vNG, LPTSTR & pSubj, int & bufSz, TArticleHeader * pHdr) { int j = iArtInt - iLow; if (!(kXRefinXOver & m_wServerCap)) { fat = crossPost[j]; add_xpost_info ( fat, pSubj, bufSz, pHdr ); } fat = vNG[j]; int iSpace = fat.Find(' '); if (iSpace > 0) process_ng_line (fat, iSpace, pHdr); } // ------------------------------------------------------------------------ // void TPump::add_xpost_info (CString & fat, LPTSTR & pSubj, int & bufSz, TArticleHeader * pHdr) { int index; if (!fat.IsEmpty()) { int iFatLen = fat.GetLength (); if (bufSz < iFatLen) size_alloc (pSubj, bufSz, iFatLen); LPTSTR fatbuf = fat.GetBuffer (iFatLen); _tstrstream in(fatbuf); // discard the article number in >> index; in >> ws; in.getline(pSubj, bufSz, '\r'); // store the servername [group:###]+ pHdr->SetXRef ( pSubj ); fat.ReleaseBuffer (iFatLen); } } /////////////////////////////////////////////////////////////////////////// // take article object and dispatch it somewhere void TPump::catch_header (TNewsGroup* pNG, TArtHdrArray* pHdrArray, LPCTSTR lszGroupName, int iArtInt, TArticleHeader*& rpHdr) { // article is not on disk. But is it already queued up? if (FALSE == pNG->TextRangeHave (iArtInt)) { // scribe will get whole array pHdrArray->Add ( rpHdr ); } else { delete rpHdr; rpHdr = 0; } } /////////////////////////////////////////////////////////////////////////// // This function is called if the server does not support XOVER // // Returns TRUE if a job was queued for the scribe int TPump::Use_XHDR_Instead(TPumpJobOverview*& pBaseJob, MPBAR_INFO * psBarInfo, BOOL fFullCrossPost, TArtHdrArray* pHdrArray) // fill this up with headers { TServerCountedPtr cpNewsServer; ASSERT(0 == m_HeaderMap.GetCount()); TPumpJobOverview * pJob = (TPumpJobOverview*) pBaseJob; int low, high, range; pJob->GetGroupRange ( low, high ); range = high - low + 1; THeapBitmap* pAccount = new THeapBitmap(low, high); int r; int iDenum = (fFullCrossPost) ? 8 : 6; try { do { int iFromCount; int iStatusBarPos = 0; CString output; CString cmdLine; FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); // Request FROM - DATE - REFERENCES - MSGID - SUBJECT - LINECOUNT // XREF // 1 download bunch of FROM lines iFromCount = 0; psBarInfo->m_nDivide = iDenum; psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "from", kXFrom, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // sanity check if (0 == iFromCount) { // there is nothing in this range. don't bother trying // the other fields. jump to the end. break; } // 2 bunch of DATE lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "date", kXDate, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // 3 bunch of REFERENCES lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, _T("references"), kXRefs, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // 4 bunch of MessageID lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "Message-ID", kXMsgID, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // 5 bunch of Subject lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "subject", kXSubject, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // 6 bunch of line-count psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "lines", kXLines, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; if (fFullCrossPost) { // 7 bunch of XREF lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "xref", kXCrossPost, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; // 8 bunch of Newsgroup lines psBarInfo->m_nPos = 0; r = xhdr_command (pJob, low, high, "newsgroups", kXNewsgroups, iFromCount, psBarInfo); if (r) return r; if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; } TArticleHeader* pArtHdr; int artInt; BOOL fUseLock; TNewsGroup* pNG = 0; TNewsGroupUseLock useLock (cpNewsServer, pJob->GetGroup(), &fUseLock, pNG); try { POSITION pos = m_HeaderMap.GetStartPosition(); while (pos) { m_HeaderMap.GetNextAssoc( pos, artInt, pArtHdr ); m_HeaderMap.RemoveKey ( artInt ); // remove from map pAccount->SetBit( artInt ); if (true) { // big package for scribe pHdrArray->Add(pArtHdr); } } } catch(...) { throw; } } while(FALSE); if (true) { TExpiryData * pED = new TExpiryData(TExpiryData::kMissing, !pJob->GetExpirePhase(), pJob->GetGroupID(), pJob->GetExpireLow()); pED->m_ArraypBits.Add (pAccount); pAccount = 0; ExpireHeadersNotFound ( pED ); } } catch (TException *pE) { delete pAccount; // free any remaining items freeHeaderMap(); TException *ex = new TException(*pE); pE->Delete(); throw(ex); return 0; } delete pAccount; m_HeaderMap.RemoveAll(); return 0; } // ------------------------------------------------------------------------ // xhdr_command -- called to get article headers via multiple XHDR commands // int TPump::xhdr_command (TPumpJobOverview * pJob, int low, int high, LPCTSTR token, EHeaderParts ePart, int & total, MPBAR_INFO * psBarInfo) { CString cmd, output; int r; // RLW - Modified so we do not ask for more than 300 articles in one go int nStart = low; total = 0; while (nStart <= high) { cmd.Format("XHDR %s %d-%d", token, nStart, (nStart + 300 < high) ? nStart + 300 : high); //TRACE("%s\n", cmd); if ((r = m_pFeeed->Direct(m_pErrList, cmd)) == 0) { while (true) { if (!m_pFeeed->DirectNext(m_pErrList, output)) { if (output.GetLength() == 3 && output == ".\r\n") break; ++total; StoreHeaderPart(ePart, output, psBarInfo); } else { // returns 0 to continue r = error_xhdr(cmd, pJob); if (r) return r; } } } else { // returns 0 to continue r = error_xhdr(cmd, pJob); if (r) return r; } nStart += 301; } //cmd.Format ("XHDR %s %d-%d", token, low, high); //TRACE("%s\n", cmd); //total = 0; // //if ((r = m_pFeeed->Direct(m_pErrList, cmd)) == 0) //{ // while (true) // { // if (!m_pFeeed->DirectNext(m_pErrList, output)) // { // if (output.GetLength() == 3 && output == ".\r\n") // break; // ++total; // StoreHeaderPart(ePart, output, psBarInfo); // } // else // return error_xhdr(cmd, pJob); // } //} //else //{ // // returns 0 to continue // r = error_xhdr(cmd, pJob); // if (r) // return r; //} return 0; } // ------------------------------------------------------------------------ // Returns 0 to continue with calling function, non-zero to abort caller int TPump::error_xhdr (const CString & cmd, TPumpJobOverview * pJob) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: { CString strMsg; strMsg.Format ("%s returned %s", LPCTSTR(cmd), LPCTSTR(strError)); gpEventLog->AddError (TEventEntry::kPump, strMsg, strError); m_pErrList->ClearErrors(); // caller should continue return 0; } case kClassWinsock: if (WSAEINTR == dwErrorID) { // no reconnect PostDisconnectMsg (false, false); } else { // fIdle, fReconnect PostDisconnectMsg (false, true); } // caller should abort return 1; default: ERRDLG(dwErrorID, strError); // caller should abort return 1; } return 1; } // free any remaining items in the header Map void TPump::freeHeaderMap(void) { //TRACE0("Calling freeHeaderMap for cleanup\n"); TArticleHeader* pArtHdr; int artInt; POSITION pos = m_HeaderMap.GetStartPosition(); while (pos) { pArtHdr = 0; m_HeaderMap.GetNextAssoc ( pos, artInt, pArtHdr ); delete pArtHdr; } m_HeaderMap.RemoveAll(); } /////////////////////////////////////////////////////////////////////////// // StoreHeaderPart // void TPump::StoreHeaderPart (TPump::EHeaderParts ePart, CString& line, MPBAR_INFO * psBarInfo) { ASSERT(line.GetLength() >= 2); static BYTE byDisplay = 0; TArticleHeader* pArtHdr; line.TrimRight(); LPCTSTR ptr = line; int idx = line.Find(' '); int artInt = _ttoi(ptr); if (WAIT_OBJECT_0 == WaitForSingleObject(m_KillRequest, 0)) throw(new TException(IDS_ERR_XHDR_ABORT, kInfo)); psBarInfo->m_nPos++; if (psBarInfo->m_iLogSubRangeLen != -1) { int fraction = MulDiv (psBarInfo->m_iLogSubRangeLen, psBarInfo->m_nPos, psBarInfo->m_nSubRangeLen); if (fraction != -1) fraction /= psBarInfo->m_nDivide; gpUserDisplay->SetPos (psBarInfo->m_iLogPos + fraction, FALSE, m_fEmergencyPump); } if (kXFrom == ePart) { TArticleHeader* pNewHdr = new TArticleHeader; // Take everything after the space if (idx > 0) { pNewHdr->SetQPFrom ( ptr + idx + 1 ); pNewHdr->SetArticleNumber ( artInt ); m_HeaderMap.SetAt ( artInt, pNewHdr ); } return; } if (idx <= 0) return; if (kXRefs == ePart) { if (_tcscmp(ptr + idx + 1, _T("(none)")) && m_HeaderMap.Lookup ( artInt, pArtHdr )) pArtHdr->SetReferences ( ptr + idx + 1 ); return; } if (kXCrossPost == ePart) { if (_tcscmp(ptr + idx + 1, _T("(none)")) && m_HeaderMap.Lookup(artInt, pArtHdr)) pArtHdr->SetXRef( ptr + idx + 1 ); return; } if (kXNewsgroups == ePart) { if (_tcscmp(ptr + idx + 1, _T("(none)")) && m_HeaderMap.Lookup(artInt, pArtHdr)) process_ng_line ( line, idx + 1, pArtHdr ); return; } if (!m_HeaderMap.Lookup ( artInt, pArtHdr )) return; switch (ePart) { case kXDate: pArtHdr->SetDate ( ptr + idx + 1 ); break; case kXMsgID: pArtHdr->SetMessageID ( ptr + idx + 1 ); break; case kXSubject: pArtHdr->SetQPSubject ( ptr + idx + 1 ); break; case kXLines: { int n = _ttoi(ptr + idx + 1); pArtHdr->SetLines ( n ); } break; default: throw(new TException(IDS_ERR_UNKNOWN_TYPE_STOREHEADERPART, kFatal)); } return; } // StoreHeaderPart // ------------------------------------------------------------------------ // Make this job-neutral int TPump::ping_articles ( TRangeSet* prsPing, BOOL fExpirePhase, int iGroupID, int iExpireLow, int grandTotal, LPPOINT pptLogical, int iEstimate, BOOL fRedraw) { int iLogPos = pptLogical->x; int iLogicalRange = pptLogical->y; int r; // Turn bit On if the article is alive if (m_wServerCap & kMustUseXLines) { return ping_articles_lines (prsPing, fExpirePhase, iGroupID, iExpireLow, grandTotal, pptLogical, fRedraw); } // otherwise, we are gonna Try ListGroup command TExpiryData * pExpiryData = new TExpiryData (!fExpirePhase, iGroupID, iExpireLow); if (fRedraw) pExpiryData->m_fRedrawUI = true; TRangeSet* pRange = prsPing; bool fRangeValid = pRange && (pRange->RangeCount() > 0); if (false == fRangeValid) pExpiryData->SetAllPresent (true); // do nothing if nothing to ping if (fRangeValid && fExpirePhase) { // Try LISTGROUP CString cmd = "listgroup"; CString result; r = m_pFeeed->Direct (m_pErrList, cmd); if (r) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: { m_pErrList->ClearErrors (); m_wServerCap |= kMustUseXLines; return ping_articles_lines (prsPing, fExpirePhase, iGroupID, iExpireLow, grandTotal, pptLogical, fRedraw); } break; case kClassWinsock: if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else PostDisconnectMsg (false, true); break; default: break; } // switch } // error from LISTGROUP // real pos = n // real range = pptBound // log pos = iLogPos // log range = iLogicalRange while (true) { r = m_pFeeed->DirectNext (m_pErrList, result); if (r) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: break; case kClassWinsock: if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else PostDisconnectMsg (false, true); break; default: break; } // switch } if (result == ".\r\n") break; int n = _ttoi(result); pExpiryData->Add(n); if (iEstimate > 0) { int iAdvanceLogPos = iLogicalRange * (n - iExpireLow) / iEstimate; gpUserDisplay->SetPos (iLogPos + iAdvanceLogPos, FALSE, m_fEmergencyPump); } } // read data from LISTGROUP } ExpireHeadersNotFound (pExpiryData); return 0; } // ------------------------------------------------------------------------ // check deadwood using 'XHDR LINES' // make this job-neutral int TPump::ping_articles_lines ( TRangeSet * prsPing, BOOL fExpirePhase, int iGroupID, int iExpireLow, int grandTotal, LPPOINT pptLogical, BOOL fRedraw) { int iLogPos = pptLogical->x; int iLogicalRange = pptLogical->y; int i, low, high, r; TExpiryData* pExpiryData = new TExpiryData(TExpiryData::kExpired, !fExpirePhase, iGroupID, iExpireLow); if (fRedraw) pExpiryData->m_fRedrawUI = true; CString cmd, result; TRangeSet* pRange = prsPing; bool fRangeValid = pRange && (pRange->RangeCount() > 0); if (false == fRangeValid) pExpiryData->SetAllPresent (true); if (pRange) { int rangeTot = pRange->RangeCount(); int nPing = 0; #if defined(_DEBUG) { CString strStatus; strStatus.Format("(debug) checking deadwood for NG"); gpUserDisplay->SetText (strStatus, m_fEmergencyPump); } if (false==fExpirePhase) ASSERT(rangeTot==0); #endif for (i = 0; i < rangeTot; ++i) { pRange->GetRange(i, low, high); THeapBitmap* pBits = new THeapBitmap(low, high); int iArtInt, iLineCount; // RLW - Modified so we do not ask for more than 300 items in one go int nStart = low; while (nStart < high) { cmd.Format("XHDR LINES %d-%d", nStart, (nStart + 300 < high) ? nStart + 300 : high); //TRACE("%s\n", cmd); if ((r = m_pFeeed->Direct(m_pErrList, cmd)) == 0) { while (true) { if ((r = m_pFeeed->DirectNext (m_pErrList, result)) == 0) { if (result == ".\r\n") break; int fields = _stscanf(result, _T("%d %d"), &iArtInt, &iLineCount); if ((2 == fields) && (iArtInt >= low && iArtInt <= high)) { pBits->SetBit(iArtInt); } // (high-low+1) // ------------ = % to advance // grandTotal int iLogAdv = iLogicalRange * ++nPing / grandTotal; // this is increment from baseline gpUserDisplay->SetPos(iLogPos + iLogAdv, FALSE, m_fEmergencyPump); } else return r; // $$ } } else return r; // $$ nStart += 301; } //cmd.Format("XHDR LINES %d-%d", low, high); //TRACE("%s\n", cmd); //int iArtInt, iLineCount; //if ((r = m_pFeeed->Direct(m_pErrList, cmd)) == 0) //{ // while (true) // { // if ((r = m_pFeeed->DirectNext (m_pErrList, result)) == 0) // { // if (result == ".\r\n") // break; // int fields = _stscanf(result, _T("%d %d"), &iArtInt, &iLineCount); // if ((2 == fields) && (iArtInt >= low && iArtInt <= high)) // { // pBits->SetBit(iArtInt); // } // // (high-low+1) // // ------------ = % to advance // // grandTotal // int iLogAdv = iLogicalRange * ++nPing / grandTotal; // // this is increment from baseline // gpUserDisplay->SetPos(iLogPos + iLogAdv, FALSE, m_fEmergencyPump); // } // else // return r; // $$ // } //} //else // return r; // $$ pExpiryData->m_ArraypBits.Add (pBits); } // for } // if pRange ExpireHeadersNotFound (pExpiryData); return 0; } ///////////////////////////////////////////////////////////////////////////// void TPump::ScribeJob(TScribePrep * pPrep) { m_pMasterTasker->AddScribeJob ( pPrep ); } /////////////////////////////////////////////////////////////////////////// void TPump::SaveHeader_and_Request( const CString& groupName, LONG groupID, TArticleHeader* pArtHdr, int artInt, BOOL fBody) { // order scribe to write this TPrepHeader * pPrepHeader = new TPrepHeader( groupName, pArtHdr, artInt); ScribeJob ( pPrepHeader ); ASSERT(fBody == TRUE || fBody == FALSE); if (fBody) { m_pLink->m_pJobs->RequestBody ( groupName, groupID, artInt, pArtHdr->GetLines(), false, // front of queue PJF_SEND_SCRIBE); } } // ------------------------------------------------------------------------ // BatchSaveHeader_and_Request -- // void TPump::BatchSaveHeader_and_Request( const CString & groupName, LONG groupID, TArtHdrArray* pHdrArray, BOOL fGetBody, TPumpJob::EPumpJobDone eJobDone) { // the marker helps the TScribe finally bind the Hdr + Body /// we want to send the scribe 1 Big job. CDWordArray ArtInts; CDWordArray Lines; int arraySize = pHdrArray->GetSize(); if (fGetBody) { ArtInts.SetSize(arraySize); Lines.SetSize(arraySize); } int j; int l, artint; for (j = 0; j < arraySize; ++j) { if (fGetBody) { TArticleHeader* pArtHdr = pHdrArray->GetAt(j); artint = pArtHdr->GetArticleNumber(); l = pArtHdr->GetLines(); ArtInts.SetAt(j, artint); Lines.SetAt(j, l); } } TScribePrep::EPrepDone eDone = (TPumpJob::kDoneShow == eJobDone) ? TScribePrep::kDoneDisplay : TScribePrep::kDoneNothing; // send scribe this big job TPrepBatchHeader * pPrepBatchHeader = new TPrepBatchHeader( groupName, groupID, pHdrArray, eDone); ScribeJob ( pPrepBatchHeader ); ASSERT(fGetBody == TRUE || fGetBody == FALSE); if (fGetBody) { for (j = 0; j < arraySize; j++) { m_pLink->m_pJobs->RequestBody ( groupName, groupID, int(ArtInts[j]), int(Lines[j]), false, PJF_SEND_SCRIBE ); } } } /////////////////////////////////////////////////////////////////////////// // This gets called repeatedly when we are blocking on a winsock call // BOOL FAR WINAPI NormalPumpBlockingHook(void) { //#if defined(_DEBUG) && defined(JUNKO) // CTime sNow = CTime::GetCurrentTime(); // // CString str = sNow.Format("%I:%M:%S %p\n"); // //TRACE(LPCTSTR(str)); //#endif if (WAIT_OBJECT_0 == WaitForSingleObject(gsNormHookData.hKillEvent, 0)) { gsNormHookData.psPump->NoSendQuit (); //TRACE("+++++++ called WSACancelBlockingCall ++++\n"); WSACancelBlockingCall(); } return FALSE; } /////////////////////////////////////////////////////////////////////////// BOOL FAR WINAPI EmergencyPumpBlockingHook(void) { if (WAIT_OBJECT_0 == WaitForSingleObject(gsPrioHookData.hKillEvent, 0)) { gsPrioHookData.psPump->NoSendQuit (); WSACancelBlockingCall(); } return FALSE; } //------------------------------------------------------------------------- // Returns 0 for success. caller does major error handling // int TPump::connect (CString & rstrWelcome) { int stat = 0; // clear status line when done TUserDisplay_Auto sAuto(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); CString status_msg; status_msg.Format(IDS_ERR_CONNECTING_TO, m_server); gpUserDisplay->SetText( status_msg, m_fEmergencyPump ); stat = m_pFeeed->Init ( m_pErrList, m_server, rstrWelcome ); if (0 == stat) return 0; DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); if (true) { CString error; error.LoadString(IDS_ERR_CONNECT_TO); error += " " + m_server; CString details; details.Format ("%d %s", dwErrorID, strError); gpEventLog->AddError ( TEventEntry::kPump, error, details ); } return 1; } /////////////////////////////////////////////////////////////////////////// // Returns 0 for success // this used just as a 'keep alive' message. // int TPump::DoHelpCommand (TPumpJob* pBaseJob ) { auto_ptr<CObject> job_deleter(pBaseJob); // clear status line when done TUserDisplay_Auto sAuto(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); CString status_msg; status_msg.LoadString (IDS_HLPCMD_STATUS); gpUserDisplay->SetText( status_msg, m_fEmergencyPump ); int server_code = 999; int iAnswer = 0; CString server_ack; if (m_pFeeed->WriteLine (m_pErrList, _T("help"), 4)) goto help_error; // error if (m_pFeeed->ReadLine (m_pErrList, server_ack)) goto help_error; // error server_code = _ttoi(LPCTSTR(server_ack)); if ((server_code/100) == 1) { // read until .\r\n do { status_msg.Format (IDS_HLPCMD_RESPONSE, ++iAnswer); gpUserDisplay->SetText( status_msg, m_fEmergencyPump ); if (m_pFeeed->ReadLine (m_pErrList, server_ack)) goto help_error; } while (!(3 == server_ack.GetLength() && '.' == server_ack[0])); return 0; } else return 0; help_error: if (true) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassWinsock: if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else // fIdle, fReconnect PostDisconnectMsg (false, true); break; case kClassNNTP: m_pErrList->ClearErrors (); return 0; default: ASSERT(0); ERRDLG(dwErrorID, strError); break; } // switch return 1; } } // ------------------------------------------------------------------------ // CString m_errorMessage; // int m_iNNTPError; void TPump::DoConnect(TPumpJob* pBaseJob) { TServerCountedPtr cpNewsServer; int iWinSockLastError = 0; TPumpJobConnect* pJob = (TPumpJobConnect*) pBaseJob; CString welcome; int srvCode; BOOL fUserCancel = FALSE; int r = 0; CString errorMsg; // holds context "error authorizing passwd" // WinSock connect r = connect ( welcome ); if (r) { connect_fail (pJob, fUserCancel, errorMsg ); return; } // this is a class-wide thing m_timeKeeper.Enable (TRUE); m_timeKeeper.SetActivity (); // analyze the welcome message _tstrstream iss((LPTSTR)(LPCTSTR)welcome); iss >> srvCode; switch (srvCode/100) { case 1: // help text break; case 2: // server ready { // set things up with the Mode Reader command int r; // some servers don't like it, so Gravity has option to turn it off if (cpNewsServer->GetModeReader()) { CString strMode = "mode reader"; CString strModeAck; r = m_pFeeed->WriteLine (m_pErrList, strMode, strMode.GetLength()); if (r) { connect_fail (pJob, fUserCancel, strMode); return ; } // read response r = m_pFeeed->ReadLine (m_pErrList, strModeAck); if (r) { connect_fail (pJob, fUserCancel, strMode); return ; } } if (!m_fEmergencyPump) { BOOL fPostingOK = (200 == srvCode || 205 == srvCode); if (cpNewsServer->GetPostingAllowed() != fPostingOK) { cpNewsServer->SetPostingAllowed (fPostingOK); cpNewsServer->SaveSettings (); } } TSPASession * pSPA = cpNewsServer->LockSPASession (); try { r = logon_style (srvCode, errorMsg, cpNewsServer->GetLogonStyle(), cpNewsServer->GetAccountName(), cpNewsServer->GetAccountPassword(), pSPA); } catch(...) { cpNewsServer->UnlockSPASession (); throw; } cpNewsServer->UnlockSPASession (); if (r) { connect_fail ( pJob, fUserCancel, errorMsg ); return; } } break; case 4: case 5: // error { TError sErr(welcome, kError, kClassNNTP); m_pErrList->PushError (sErr); connect_fail ( pJob, fUserCancel, errorMsg ); return; } } // end switch // CONTINUE SETUP if (0 == AfterConnect (pJob)) { // success! return ; } else connect_fail ( pJob, fUserCancel, errorMsg ); } // ------------------------------------------------------------------------ // Returns 0 for success. Uses m_pErrList to store errors int TPump::logon_style (int iWelcomeCode, CString & errorMsg, int iLogonStyle, LPCTSTR usrname, LPCTSTR password, void * pVoidSPA) { // clear status line when done TUserDisplay_Auto sAuto(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); CString status_msg; status_msg = "Authorizing with " + m_server; gpUserDisplay->SetText( status_msg, m_fEmergencyPump ); int r; switch (iLogonStyle) { case 0: // no password required return 0; case 1: // plaintext authorization { CString line_name; CString ack; int authret; line_name.Format ("AUTHINFO user %s", usrname); r = m_pFeeed->WriteLine ( m_pErrList, line_name, line_name.GetLength() ); if (r) return r; if (m_pFeeed->ReadLine ( m_pErrList, authret, ack )) return 1; if (authret >= 500) { CString rbuild; rbuild.Format ("%d %s", authret, LPCTSTR(ack)); TError sError(rbuild, kError, kClassNNTP); m_pErrList->PushError (sError); errorMsg.LoadString (IDS_ERR_AUTHORIZING); return 1; } line_name.Format (_T("AUTHINFO pass %s"), password); r = m_pFeeed->WriteLine ( m_pErrList, line_name, line_name.GetLength() ); if (r) return 1; r = m_pFeeed->ReadLine ( m_pErrList, authret, ack ); if (r) return 1; if (authret < 200 || authret > 299) { CString rbuild; rbuild.Format (_T("%d %s"), authret, LPCTSTR(ack)); TError sError(rbuild, kError, kClassNNTP); m_pErrList->PushError (sError); errorMsg.LoadString (IDS_ERR_AUTHORIZING_PASS); return 1; } } return 0; case 2: // Secure Password Authentication return CryptoLogin (pVoidSPA); default: ASSERT(0); // unknown case } return 1; } // ------------------------------------------------------------------------ int TPump::connect_fail (TPumpJobConnect * pJob, BOOL fUserCancel, CString & errorMsg) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); pJob->m_eErrorClass = eErrorClass; pJob->m_dwErrorID = dwErrorID; switch (eErrorClass) { case kClassWinsock: { switch (dwErrorID) { case WSAEINTR: // no reconnect, user interrupted PostDisconnectMsg (false, false); fUserCancel = TRUE; break; case WSAETIMEDOUT: // reconnect = yes PostDisconnectMsg (false, true); break; case WSAECONNREFUSED: case WSAENETDOWN: case WSAENOBUFS: case WSAEFAULT: case WSAHOST_NOT_FOUND: case WSANO_RECOVERY: case WSANO_DATA: case WSANOTINITIALISED: case WSATRY_AGAIN: case WSAECONNABORTED: // no reconnect, we pretty much can't recover from this PostDisconnectMsg (false, false); break; default: // fIdle, fReconnect ( no reconnect ) PostDisconnectMsg (false, false); break; } } break; case kClassExternal: case kClassNNTP: { if (!errorMsg.IsEmpty()) { pJob->m_errorMessage.Format ("%s - Server responded: %s", LPCTSTR(errorMsg), LPCTSTR(strError)); } else pJob->m_errorMessage = strError; // no reconnect PostDisconnectMsg (false, false); } break; default: pJob->m_errorMessage = strError; ERRDLG(dwErrorID, strError); PostDisconnectMsg (false, false); break; } // switch // Tasker does the actual reporting of the error // Notify tasker, he will clean up his ptrs to us pJob->m_fUserCancel = fUserCancel; m_pMasterTasker->AddResult ( pJob ); return 1; } // ------------------------------------------------------------------------ // Do more stuff after connecting and sending password int TPump::AfterConnect (TPumpJobConnect* pJob) { // Gosh! it worked! pJob->m_fSuccess = TRUE; m_pLink->m_fConnected = true; m_pMasterTasker->AddResult ( pJob ); // TSubject Interface if (false == m_pLink->m_fEmergencyPump) m_pLink->Update_Observers (); return 0; } // ------------------------------------------------------------------------ class TGetListData { public: typedef CTypedPtrList<CPtrList, CString*> TStringPool; static const int BUFSIZE; // size of free list TGetListData(TPumpJobBigList* pPumpJob, HANDLE hKillReq, BOOL fPrioPump); ~TGetListData(); CRITICAL_SECTION critAll; CRITICAL_SECTION critProtectFreeList; HANDLE hEventGroupReady; HANDLE hSemSpaceAvail; BOOL fAllDone; BOOL m_fPrioPump; TStringPool sBigList; TStringPool sFreeList; CTime newCheck; TPumpJobBigList* m_pPumpJob; HANDLE hEventReaderDone; HANDLE hPumpKillRequest; int iNTPRet; CString strAck; }; const int TGetListData::BUFSIZE = 250; TGetListData::TGetListData(TPumpJobBigList* pPumpJob, HANDLE hKillReq, BOOL fPrioPump) : m_pPumpJob(pPumpJob), hPumpKillRequest(hKillReq), m_fPrioPump(fPrioPump) { int i; InitializeCriticalSection(&critAll); InitializeCriticalSection(&critProtectFreeList); hEventReaderDone = CreateEvent (NULL, TRUE, FALSE, NULL); hEventGroupReady = CreateEvent ( NULL, // no security TRUE, // we want manual reset FALSE, // start out unsignaled NULL ); // no name hSemSpaceAvail = CreateSemaphore (NULL, // no security BUFSIZE, // inital count BUFSIZE, // max count NULL); // no name // make some empty strings for (i = 0; i < BUFSIZE; ++i) sFreeList.AddTail ( new CString ); // clear out just in case while (!sBigList.IsEmpty()) delete sBigList.RemoveHead(); fAllDone = FALSE; newCheck = CTime::GetCurrentTime(); iNTPRet = 0; } TGetListData::~TGetListData() { // free the CString pointers while (!sFreeList.IsEmpty()) delete sFreeList.RemoveHead(); // clear out just in case while (!sBigList.IsEmpty()) delete sBigList.RemoveHead(); CloseHandle (hEventReaderDone); CloseHandle (hSemSpaceAvail); CloseHandle (hEventGroupReady); DeleteCriticalSection(&critProtectFreeList); DeleteCriticalSection(&critAll); } /////////////////////////////////////////////////////////////////////////// // Check KillRequest too // void TPump::DoGetNewsgroupList ( TPumpJob* pOneJob ) { CString* pLine = 0; TPumpJobBigList * pJob = static_cast<TPumpJobBigList*>(pOneJob); auto_ptr<CObject> job_deleter(pOneJob); TGetListData sGL(pJob, m_KillRequest, m_fEmergencyPump); // start the READER thread AfxBeginThread ((AFX_THREADPROC)fnProcessNewsgroups, (LPVOID) &sGL); // we are the WRITER thread try { auto_prio boost(auto_prio::kNormal); // boost priority of Pump Thread int iInitRet; CString strNewAck; if (pJob->m_fRecent) iInitRet = m_pFeeed->Newgroups (m_pErrList, pJob->m_prevCheck, strNewAck); else iInitRet = m_pFeeed->StartList (m_pErrList, _T("LIST"), &sGL.iNTPRet, &sGL.strAck ); if (0 == iInitRet) { // semaphore counts objects in free list WaitForSingleObject (sGL.hSemSpaceAvail, INFINITE); { TEnterCSection mgr(&sGL.critProtectFreeList); pLine = sGL.sFreeList.RemoveHead(); } while (0 == m_pFeeed->NextListLine (m_pErrList, pLine )) { if (*pLine == ".\r\n") break; { TEnterCSection mgr(&sGL.critAll); ResetEvent ( sGL.hEventGroupReady ); sGL.sBigList.AddTail ( pLine ); SetEvent ( sGL.hEventGroupReady ); } // get storage string from FreeList while (WAIT_TIMEOUT == WaitForSingleObject (sGL.hSemSpaceAvail, 200)) TRACE0("wait on freelist\n"); { TEnterCSection mgr(&sGL.critProtectFreeList); pLine = sGL.sFreeList.RemoveHead(); } // peek at KillRequest if (WAIT_OBJECT_0 == WaitForSingleObject(m_KillRequest, 0)) { m_fQuitNNTP = FALSE; break; } } // No more data delete pLine; pLine = 0; { TEnterCSection mgr(&sGL.critAll); sGL.fAllDone = TRUE; // one last prod... SetEvent ( sGL.hEventGroupReady ); } } else { TEnterCSection mgr(&sGL.critAll); sGL.fAllDone = TRUE; // one last prod... SetEvent ( sGL.hEventGroupReady ); } } catch (...) { m_fQuitNNTP = FALSE; if (pLine) { delete pLine; pLine = 0; } { TEnterCSection mgr(&sGL.critAll); sGL.fAllDone = TRUE; // one last prod... SetEvent ( sGL.hEventGroupReady ); } // Wait for the reader thread to finish, before we // destroy the goodies in 'sGL' WaitForSingleObject(sGL.hEventReaderDone, INFINITE); //TRACE0("Leaving DoGetNewsgroupList\n"); throw; } // Wait for the reader thread to finish WaitForSingleObject(sGL.hEventReaderDone, INFINITE); //TRACE0("Leaving DoGetNewsgroupList\n"); } /////////////////////////////////////////////////////////////////////////// // // static int freeCount; static int lowWater; static const int UPDATE_FREQUENCY = 20; static void fnChangeStatusLine(int count, BOOL fPriority) { if (0 == (count % UPDATE_FREQUENCY)) { CString mesg; CString szCount; #if !defined(_DEBUG) szCount.Format("%d", count); #else szCount.Format("%d (lomark %d free %d)", count, lowWater, freeCount); #endif AfxFormatString1(mesg, IDS_DOWNLOAD_GROUP, szCount); gpUserDisplay->SetText ( mesg , fPriority ); } } enum ELineFormat { kSNNM, // String Number Number Modifier kSM, // String Modifier kLineError // other crap }; // ----------------------------------------------------------------------------------- ELineFormat fnAnalyzeLine (CString * pLine, LPTSTR pTok1, LPTSTR pTok2, LPTSTR pTok3, LPTSTR pTok4) { CString & rLine = *pLine; LPCTSTR pInputLine = rLine; *pTok1 = *pTok2 = *pTok3 = *pTok4 = NULL; int nFound = _stscanf (pInputLine, _T("%s %s %s %s"), pTok1, pTok2, pTok3, pTok4); // test for String | Number | Number | Modifier if ((nFound >= 4) && isdigit(*pTok2) && isdigit(*pTok3) && !isdigit(*pTok4)) { return kSNNM; } // test for String | Modifier if ((2 == nFound) && !isdigit(*pTok2)) { return kSM; } return kLineError; } ////////////////////////////////////////////////////////////////////////////// // 1-22-96 If unknown classification, then don't add it to our list // at all. // Upon return rTrueName points to the name we should use BOOL fnModifyLine (CString* pLine, int idxSpace, TGlobalDef::ENewsGroupType* eType, LPTSTR pWorkingBuf, int iBufSize, CString& strRename, CString& rTrueName) { TCHAR rcTok1[9999]; TCHAR rcTok2[9999]; TCHAR rcTok4[9999]; TCHAR rcTok3[9999]; BOOL fRet = TRUE; int ln = pLine->GetLength(); if (ln < 3) return FALSE; // just a CRLF? if (ln > iBufSize) return FALSE; ELineFormat ef = fnAnalyzeLine (pLine, rcTok1, rcTok2, rcTok3, rcTok4); switch (ef) { case kSNNM: pWorkingBuf = rcTok4; break; case kSM: pWorkingBuf = rcTok2; break; default: { CString str; str.LoadString (IDS_ERR_UNKNOWN_GROUP_TYPE); gpEventLog->AddInfo ( TEventEntry::kGeneral, str, *pLine ); return FALSE; break; } } rTrueName = pLine->Left (idxSpace); // check the modifier switch (*pWorkingBuf) { case 'N': case 'n': *eType = TGlobalDef::kPostNotAllowed; break; case 'X': // this is disabled. case 'x': { return FALSE; } case 'Y': case 'y': *eType = TGlobalDef::kPostAllowed; break; case 'G': // Hamster local group case 'g': *eType = TGlobalDef::kPostAllowed; break; default: { CString modToken(pWorkingBuf); modToken.MakeLower(); // it might be '=' to indicate a renaming if ('=' == modToken[0]) { *eType = TGlobalDef::kPostAllowed; strRename = modToken.Mid(1); if (strRename.IsEmpty()) { CString str; str.LoadString (IDS_ERR_UNKNOWN_GROUP_TYPE); gpEventLog->AddInfo ( TEventEntry::kGeneral, str, *pLine ); return FALSE; } // this is the new name rTrueName = strRename; } // it might be 'm' 'M' or "(Moderated)" else if ('m' == modToken[0] || modToken.Find(_T("moder")) != -1) { *eType = TGlobalDef::kPostModerated; } else { CString str; str.LoadString (IDS_ERR_UNKNOWN_GROUP_TYPE); gpEventLog->AddInfo ( TEventEntry::kGeneral, str, *pLine ); return FALSE; } } break; } return fRet; } /////////////////////////////////////////////////////////////////// // Save Newsgroup List to disk // void fnSaveGroupResults (TGetListData * pGetList, TGroupList * pGroups, TGroupList * pFreshGroups, int count, const CTime & newCheckTime) { TServerCountedPtr cpNewsServer; if (count > 0) { TCHAR buf[15]; CString statusMsg; AfxFormatString1( statusMsg, IDS_SAVING_NGLIST, _itot(count, buf, 10) ); gpUserDisplay->SetText ( statusMsg, pGetList->m_fPrioPump ); } if (!pGetList->m_pPumpJob->m_fRecent) { // We are doing ALL groups cpNewsServer->SaveServerGroupList( pGroups ); } else { // Recent groups == Incremental Update TGroupList* pAllGroups = 0; // this is some heavy duty work, so might as well do it in // this background thread // load current groups pAllGroups = cpNewsServer->LoadServerGroupList (); if (0 == pAllGroups) cpNewsServer->SaveServerGroupList( pFreshGroups ); else { if (pFreshGroups->NumGroups() > 0) { // add in the fresh groups (*pAllGroups) += *pFreshGroups; // save the whole mess back out. cpNewsServer->SaveServerGroupList( pAllGroups ); } } delete pAllGroups; } // write out the time cpNewsServer->SetNewsGroupCheckTime( newCheckTime ); cpNewsServer->SaveSettings(); } // fnSaveGroupResults /////////////////////////////////////////////////////////////////// // Read from the pool // UINT fnProcessNewsgroups (LPVOID pVoid) { BOOL fKilled = FALSE; TGetListData* pGetList = (TGetListData*) pVoid; TGroupList allGroups; TGroupList * pFreshGroups = 0; CTime newCheckTime = CTime::GetCurrentTime(); GetGmtTime ( newCheckTime ); TGetListData::TStringPool& sBigList = pGetList->sBigList; TGetListData::TStringPool& sFreeList = pGetList->sFreeList; if (pGetList->m_pPumpJob->m_fRecent) pFreshGroups = new TGroupList; gfGettingNewsgroupList = TRUE; int iWorkingSize = 4096; TCHAR * pWorkingBuf = new TCHAR[iWorkingSize]; auto_ptr<TCHAR> deleter(pWorkingBuf); // status bar will refresh on a timer interval TUserDisplay_Auto autoRefreshStatus(TUserDisplay_Auto::kClearDisplay, pGetList->m_fPrioPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); try { CString* pLine=0; BOOL fEndReader = FALSE; DWORD dwWait; int count = 0; lowWater = 500; HANDLE rEvents[2]; rEvents[0] = pGetList->hEventGroupReady; rEvents[1] = pGetList->hPumpKillRequest; CString strRename; for (;;) { dwWait = WaitForMultipleObjects(2, rEvents, FALSE, INFINITE); if (dwWait - WAIT_OBJECT_0 == 1) { fKilled = TRUE; break; } pLine = NULL; { TEnterCSection mgr(&pGetList->critAll); int size = sBigList.GetCount(); if (size >= 1) { pLine = sBigList.RemoveHead(); if (size == 1) { // the bucket is empty if (pGetList->fAllDone) fEndReader = TRUE; else ResetEvent (pGetList->hEventGroupReady); } } else if (size == 0 && pGetList->fAllDone) fEndReader = TRUE; } // critsect scope if (pLine) { // character indicates if Posting is Allowed [Yes|No|Moderated] int idxSpace = pLine->Find(' '); if (idxSpace > -1) { CString sTrueName; TGlobalDef::ENewsGroupType eType; if (fnModifyLine ( pLine, idxSpace, &eType, pWorkingBuf, iWorkingSize, strRename, sTrueName )) { #if defined(_DEBUG) if (sTrueName == "local.test.norsk") sTrueName = "local.test.n\xF8rsk"; #endif if (pGetList->m_pPumpJob->m_fRecent) pFreshGroups->AddGroup (sTrueName, WORD(0), eType); else allGroups.AddGroup (sTrueName, WORD(0), eType); } fnChangeStatusLine ( ++count, pGetList->m_fPrioPump ); } { TEnterCSection pro(&pGetList->critProtectFreeList); sFreeList.AddHead ( pLine ); freeCount = sFreeList.GetCount(); if (freeCount < lowWater) lowWater = freeCount; // the free list is bigger ReleaseSemaphore (pGetList->hSemSpaceAvail, 1, NULL); } } if (fEndReader) break; } // for loop if (WAIT_OBJECT_0 == WaitForSingleObject(pGetList->hPumpKillRequest,0)) fKilled = TRUE; if (!fKilled && (pGetList->iNTPRet < 300)) fnSaveGroupResults ( pGetList, &allGroups, pFreshGroups, count, newCheckTime ); } // try-block catch (TException *exc) { SetEvent(pGetList->hEventReaderDone); gfGettingNewsgroupList = FALSE; delete pFreshGroups; exc->PushError (IDS_ERR_PROCESSING_GROUPS, kInfo); exc->PushError (IDS_ERR_MAYBE_CONTINUE, kFatal); exc->Display (); exc->Delete(); return 0; } if (!fKilled) { LPT_GROUPLISTDONE pDone = new T_GROUPLISTDONE; pDone->pGroupList = pFreshGroups; pDone->iNTPRet = pGetList->iNTPRet; pDone->strAck = pGetList->strAck; AfxGetMainWnd()->PostMessage(WMU_GETLIST_DONE, pGetList->m_pPumpJob->m_wParam, (LPARAM) pDone); } gfGettingNewsgroupList = FALSE; // calling thread waits for event // once this is unlocked, the m_pPumpJob will be destroyed SetEvent(pGetList->hEventReaderDone); return 0; } // fnProcessNewsgroups /////////////////////////////////////////////////////////////////////////// // Take ownership of pHdrArray // Called from DownloadOverview() // int TPump::deliver_headers_to_scribe(TPumpJobOverview* pJob, TArtHdrArray*& pHdrArray, BOOL fGetBodies) { if (pHdrArray->GetSize() == 0) { delete pHdrArray; pHdrArray = 0; // send back an 'event' for the VCR window PostMainWndMsg (WMU_VCR_GROUPDONE); return 0; } TScribePrep::EPrepDone eDone = (TPumpJob::kDoneShow == pJob->GetDisposition()) ? TScribePrep::kDoneDisplay : TScribePrep::kDoneNothing; TArtHdrArray * pMyPtr = pHdrArray; pHdrArray = 0; BatchSaveHeader_and_Request ( pJob->GetGroup(), pJob->GetGroupID(), pMyPtr, fGetBodies, pJob->GetDisposition() ); return 0; } //------------------------------------------------------------------------- // isolate each newsgroup name & add it to the Header // void TPump::process_ng_line(CString& line, int offset, TArticleHeader* pHdr) { int len = line.GetLength(); LPTSTR lpszNG = line.GetBuffer(len) + offset; LPTSTR lpszFwd = 0; do { // advance over WS while (*lpszNG && (isspace(*lpszNG) || ',' == *lpszNG)) ++lpszNG; if (*lpszNG) { lpszFwd = lpszNG + 1; while (*lpszFwd && !isspace(*lpszFwd) && ',' != *lpszFwd) ++lpszFwd; if (lpszFwd > lpszNG) { TCHAR tmp = *lpszFwd; // cap off a substring *lpszFwd = '\0'; // check for "group1, , group2" if (lpszFwd > lpszNG + 1) pHdr->AddNewsGroup ( lpszNG ); *lpszFwd = tmp; lpszNG = lpszFwd; } } } while (*lpszNG); line.ReleaseBuffer(len); } // ------------------------------------------------------------------------- // I want the newspump to treat this set as an atomic operation void TPump::PingMultiGroup ( TPumpJob * pBaseJob ) { auto_ptr<CObject> job_deleter(pBaseJob); TPumpJobPingMultiGroup * pMulti = static_cast<TPumpJobPingMultiGroup *>(pBaseJob); // startup - shutdown status bar TUserDisplay_Auto refresher(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); while (!pMulti->m_pGroupNames->IsEmpty()) { CString groupName = pMulti->m_pGroupNames->RemoveHead (); // put name on status bar CString strStatus; AfxFormatString1 (strStatus, IDS_CHECKING_GROUP1, LPCTSTR(groupName)); gpUserDisplay->SetText ( strStatus ); FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); sSG.lpszNewsGroup = groupName; TPumpJobPingGroup* pChildJob = new TPumpJobPingGroup( groupName ); if (0 == m_pFeeed->SetGroup ( m_pErrList, &sSG )) { pChildJob->fRefreshUI = pMulti->m_pGroupNames->IsEmpty(); pChildJob->SetGroupResults ( sSG.fOK, sSG.iRet, sSG.first, sSG.last ); m_CurrentGroup = sSG.strGroupName; pChildJob->m_NewsGroup = sSG.strGroupName; // hard reset m_pMasterTasker->AddResult ( pChildJob ); } else { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassWinsock: delete pChildJob; // this is not Job that is important enough to resubmit if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else // disconnect and reconnect PostDisconnectMsg (false, true); break; case kClassNNTP: { TCHAR rcNum[10]; _itot(sSG.iRet, rcNum, 10); // no such news group CString desc; AfxFormatString1(desc, IDS_WARN_1NOSUCHNG, sSG.lpszNewsGroup); CString extDesc; AfxFormatString2(extDesc, IDS_WARN_2NOSUCHNGEXT, rcNum, (LPCTSTR) sSG.strAck); gpEventLog->AddWarning (TEventEntry::kPump, desc, extDesc); // present log window to user PostMainWndMsg (WM_COMMAND, ID_VIEW_EVENTLOG); m_CurrentGroup.Empty(); pChildJob->SetGroupResults ( FALSE, sSG.iRet, 0, 0 ); pChildJob->m_iRet = sSG.iRet; pChildJob->m_Ack = sSG.strAck; m_pMasterTasker->AddResult ( pChildJob ); break; } default: delete pChildJob; ERRDLG(dwErrorID, strError); break; } // switch } // else } // end while loop } // --------------------------------------------------------------------------- void TPump::ExpireHeadersNotFound (TExpiryData*& pExpiryData) { //TRACE0("Pump posting EXPIRE msg\n"); extern HWND ghwndMainFrame; // pass off to UI thread. pass ownership ::PostMessage (ghwndMainFrame, WMU_EXPIRE_ARTICLES, 0, (LPARAM)pExpiryData); pExpiryData = NULL; //TRACE0("Pump done posting EXPIRE msg\n"); return; } // -------------------------------------------------------------------------- // FindBlankLineIndex -- find a line that is all whitespace. Return 0 // on success. static int FindBlankLineIndex (CString& body, int& rEndHdr, int& rStartBody) { // start with simple search int n = body.Find(_T("\r\n\r\n")); if (n != -1) { rEndHdr = n + 2; rStartBody = n + 4; return 0; } // do a more involved search int ret = 1; int len = body.GetLength(); TCHAR * pLine = new TCHAR[len+2]; auto_ptr<TCHAR> sLineDeleter (pLine); LPTSTR pBuf = body.GetBuffer(len); // make a stream! _tstrstream in(pBuf); streampos pos = 0; while (in.getline (pLine, len+1)) // extracts \n { bool fEntirelyWS = true; LPTSTR pTravel = pLine; while (*pTravel) { if (!_istspace(*pTravel++)) { fEntirelyWS=false; break; } } if (fEntirelyWS) { rEndHdr = pos; rStartBody = in.tellg(); // body should be right after This blankline ret = 0; break; } pos = in.tellg(); } body.ReleaseBuffer(len); return ret; } #if defined(PERFMON_STATS) // class wide function BOOL TPump::PreparePerformanceMonitoring (LPHANDLE pHandle) { HANDLE hMappedObject; TCHAR szMappedObjectName[] = TEXT("GRAVITY_COUNTER_MEMCHUNK"); // initial value pCounterBlock = NULL; hMappedObject = CreateFileMapping ((HANDLE) 0xFFFFFFFF, NULL, PAGE_READWRITE, 0, 4096, szMappedObjectName); if (NULL == hMappedObject) { //TRACE1 ("Could not create mapped object for perfmon %x\n", // GetLastError ()); pCounterBlock = NULL; } else { // mapped object created okay // // map the section and assign the counter block pointer // to this section of memory pCounterBlock = (PPERF_COUNTER_BLOCK) MapViewOfFile (hMappedObject, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (NULL == pCounterBlock) { //TRACE1 ("Failed to Map View of File %x\n", GetLastError()); // cleanup CloseHandle (hMappedObject); return FALSE; } ZeroMemory (pCounterBlock, sizeof(DWORD) * 3); *pHandle = hMappedObject; } return TRUE; } // class wide function BOOL TPump::ShutdownPerformanceMonitoring (HANDLE hMap) { // undo MapViewOfFile if (pCounterBlock) { UnmapViewOfFile (pCounterBlock); pCounterBlock = NULL; } // undo CreateFileMapping CloseHandle (hMap); return TRUE; } #endif // PERFMON_STATS // ------------------------------------------------------------------------ // CryptoLogin -- Handle MSN login. Returns 0 for success, or Pushes error // int TPump::CryptoLogin (void * pVoidSPA) { CString errorMessage; BOOL done = FALSE; CString strStatusLine; strStatusLine.LoadString (IDS_SPA_STATUS); // clear status line when done TUserDisplay_Auto dauto(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); gpUserDisplay->SetText ( strStatusLine, m_fEmergencyPump ); TSPASession * pSPA = static_cast<TSPASession*>(pVoidSPA); if (m_fEmergencyPump) pSPA = &pSPA[1]; // mega super hack int authret = 0; CString cmd = "AUTHINFO GENERIC"; CString ack; int channel = 0; CString strPackage; pSPA->m_fNewConversation = true; if (!pSPA->m_strPackage.IsEmpty()) strPackage = pSPA->m_strPackage; else { if (m_pFeeed->WriteLine (m_pErrList, cmd, cmd.GetLength() ) || m_pFeeed->ReadLine (m_pErrList, authret, ack )) return 1; CStringList strList; if (2 != authret/100) // should be 281 { // push error errorMessage.Format(IDS_SPA_ERROR2, authret, LPCTSTR(ack)); TError sErr(errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); // event log entry CString msg; msg.LoadString (IDS_SPA_ERROR); gpEventLog->AddError (TEventEntry::kPump, msg, errorMessage); return 1; } for (;;) // read list of packages { ack.Empty(); if (m_pFeeed->ReadLine ( m_pErrList, ack )) return 1; if (ack[0] == '.') break; ack.TrimRight(); strList.AddTail (ack); } if (strList.IsEmpty()) { CString msg; msg.LoadString (IDS_SPA_ERROR); errorMessage.LoadString (IDS_SPA_ERROR_NOPACKS); gpEventLog->AddError (TEventEntry::kPump, msg, errorMessage); TError sErr (errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); return 1; } bool fFoundMatchingPackage = false; while (!strList.IsEmpty()) { strPackage = strList.RemoveHead(); // see what we have if (0 == pSPA->InitPackage (strPackage)) { fFoundMatchingPackage = true; break; } } if (false == fFoundMatchingPackage) { CString msg; msg.LoadString (IDS_SPA_ERROR); errorMessage.LoadString (IDS_SPA_ERROR_MATCHPACKS); gpEventLog->AddError (TEventEntry::kPump, msg, errorMessage); TError sErr (errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); return 1; } } cmd.Format ("AUTHINFO GENERIC %s", LPCTSTR(strPackage)); if (m_pFeeed->WriteLine (m_pErrList, cmd, cmd.GetLength())) return 1; ack.Empty(); if (m_pFeeed->ReadLine (m_pErrList, authret, ack)) return 1; if (3 != authret/100) { pSPA->TermPackage (); CString msg; msg.LoadString (IDS_SPA_ERROR); errorMessage.Format (IDS_SPA_ERROR2, authret, LPCTSTR(ack)); gpEventLog->AddError (TEventEntry::kPump, msg, errorMessage); TError sErr(errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); return 1; } CString strLeg1; DWORD dwLegError = 0; if (0 != pSPA->CreateLeg1 (m_server, strLeg1, dwLegError)) { pSPA->TermPackage (); // if we can't get an English description, just show Hex if (pSPA->FormatMessage (dwLegError, errorMessage)) errorMessage.Format (IDS_SPA_HEXERROR1, dwLegError); TError sErr(errorMessage, kError, kClassExternal); m_pErrList->PushError (sErr); return 1; } cmd.Format ("AUTHINFO TRANSACT %s", LPCTSTR(strLeg1) ); if (m_pFeeed->WriteLine (m_pErrList, cmd, cmd.GetLength())) return 1; // read Leg2 from Server ack.Empty(); if (m_pFeeed->ReadLine (m_pErrList, authret, ack)) return 1; if (3 != authret/100) // should be 381 { pSPA->TermPackage (); errorMessage.Format (IDS_SPA_ERROR2, authret, LPCTSTR(ack)); TError sErr(errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); return 1; } CString strLeg3; if (0 != pSPA->CreateLeg3 (m_server, ack, strLeg3, dwLegError)) { pSPA->TermPackage (); // if we can't get an English description, just show Hex if (pSPA->FormatMessage (dwLegError, errorMessage)) errorMessage.Format (IDS_SPA_HEXERROR1, dwLegError); TError sErr(errorMessage, kError, kClassExternal); m_pErrList->PushError (sErr); return 1; } cmd.Format ("AUTHINFO TRANSACT %s", LPCTSTR(strLeg3)); if (m_pFeeed->WriteLine (m_pErrList, cmd, cmd.GetLength())) return 1; authret = 0; ack.Empty(); if (m_pFeeed->ReadLine (m_pErrList, authret, ack )) return 1; if (2 != authret / 100) { pSPA->TermPackage (); errorMessage.Format (IDS_SPA_ERROR2, authret, LPCTSTR(ack)); TError sErr(errorMessage, kError, kClassNNTP); m_pErrList->PushError (sErr); return 1; } // success ! return 0; } // ------------------------------------------------------------------------ // // output: post message to ghwndMainFrame. data = what has expired. int TPump::DoPingArticles (TPumpJob * pBaseJob) { auto_ptr<CObject> job_deleter(pBaseJob); TPumpJobPingArticles * pPingJob = static_cast<TPumpJobPingArticles *>(pBaseJob); int r; FEED_SETGROUP sSG(m_logFile, m_fEmergencyPump); do { // switch into NG m_CurrentGroup.Empty(); r = iSyncGroup (pPingJob->GroupName(), &sSG); if (r) break; pPingJob->m_iServerLow = sSG.first; POINT ptLogical; ptLogical.x = 0; ptLogical.y = kiPumpStatusBarRange; // turns on automatic refreshing of statusbar - clear when destruct TUserDisplay_Auto oRefresher(TUserDisplay_Auto::kClearDisplay, m_fEmergencyPump ? TUserDisplay_Auto::kPriority : TUserDisplay_Auto::kNormal); CString statusBarText; statusBarText.Format ("Verifying local articles in %s", LPCTSTR(pPingJob->GroupName())); gpUserDisplay->SetText (statusBarText, m_fEmergencyPump); gpUserDisplay->SetRange (ptLogical.x, ptLogical.y, m_fEmergencyPump); // use this function, since it's already written r = ping_articles (pPingJob->m_pPing, TRUE /* fExpirePhase */, pPingJob->GetGroupID(), pPingJob->m_iServerLow, // expire arts lower than X pPingJob->m_pPing->CountItems(), &ptLogical, sSG.est, TRUE); if (0 == r) return 0; } while (false); // handle errors here DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: // should display error, since something is weird here $$ break; case kClassWinsock: if (WSAEINTR == dwErrorID) PostDisconnectMsg (false, false); else PostDisconnectMsg (false, true); break; default: ASSERT(0); break; } return 1; } // ------------------------------------------------------------------------ // FreeConnection -- int TPump::FreeConnection () { delete m_pFeeed; m_pFeeed = 0; return 0; } // ------------------------------------------------------------------------ EErrorClass TPump::GetErrorClass (DWORD & dwError, CString & desc) { ASSERT(m_sErrorList.GetSize() >= 1); ESeverity eSeverity; EErrorClass eClass; m_sErrorList.GetErrorByIndex (0, eSeverity, eClass, dwError, desc); return eClass; } // ------------------------------------------------------------------------ void TPump::PostDisconnectMsg (bool fIdleDisconnect, bool fReconnect, int iSleepSecs /* =0 */) { // stop doing jobs - this affects CustomizedWait m_fProcessJobs = false; PostMainWndMsg (WMU_INTERNAL_DISCONNECT, m_fEmergencyPump ? 1 : 0, fIdleDisconnect); // same ID as the menu item if (fReconnect) { // note ID_FILE_SERVER_RECONNECT is like ID_FILE_SERVER_CONNECT // except that it keeps track of the retry attemps PostMainWndMsg (WM_COMMAND, ID_FILE_SERVER_RECONNECTDELAY); } // event log stuff CString strMsg; int stringID; if (fReconnect) stringID = IDS_UTIL_RECONNECT; else if (fIdleDisconnect) stringID = IDS_UTIL_IDLEDCONN; else stringID = IDS_UTIL_DCONN; strMsg.LoadString (stringID); gpEventLog->AddInfo (TEventEntry::kPump, strMsg); } // ------------------------------------------------------------------------ // Last ditch dialog static void errorDialog (LPCSTR file, DWORD line, DWORD error, CString & strError) { CString msg; if (error) msg.Format (_T("Error in %s line %d. ErrorID: %d"), file, line, error); else msg.Format (_T("Error in %s line %d.\n\n%s"), file, line, LPCTSTR(strError)); gpEventLog->AddShowError (TEventEntry::kPump, _T("Error"), msg); } // take job ptr and simply and resubmit it into the queue int TPump::resubmit_job ( TPumpJob * pJob ) { m_pLink->m_pJobs->AddJobToFront ( pJob ); return 0; } // ------------------------------------------------------------------------ int TPump::log_nntp_error (CString & ack) { CString msg = "xover failed"; gpEventLog->AddError (TEventEntry::kPump, msg, ack ); return 0; } // ------------------------------------------------------------------------ // get_xpost_info -- returns 0 for success int TPump::get_xpost_info ( TPumpJobOverview * pJob, int low, int high, void * pVoid, MPBAR_INFO * psBarInfo ) { int r; CString command; CString output; bool fReadxref = true; //bool fReadnewsgroups; TYP_OVERVIEW_EXTRA * psExtra = (TYP_OVERVIEW_EXTRA *) pVoid; if ( (m_wServerCap & kXRefinXOver) ) { // we are skipping the 'xhdr xref' command if (psBarInfo->m_iLogSubRangeLen != -1) { int fraction = psBarInfo->m_iLogSubRangeLen; fraction /= psBarInfo->m_nDivide; // user feedback gpUserDisplay->SetPos (psBarInfo->m_iLogPos + fraction, FALSE, m_fEmergencyPump); } } else { #if defined(_DEBUG) { CString statMsg; statMsg.Format ("(debug) getting XRefs for arts"); gpUserDisplay->SetText (statMsg, m_fEmergencyPump); } #endif // RLW - Modified so we do not ask for more than 300 articles in one go int nStart = low; while (nStart <= high) { command.Format("XHDR xref %d-%d", nStart, (nStart + 300 < high) ? nStart + 300 : high); //TRACE("%s\n", command); // request this block of xref lines if (!m_pFeeed->Direct(m_pErrList, command)) { // Process the reply while (true) { // read cross-posting information (XREF lines) if (!m_pFeeed->DirectNext(m_pErrList, output)) { if (output.GetLength() == 3 && output == _T(".\r\n")) break; // End of reply data if (-1 != output.Find(':')) { int ai = _ttoi(output); if (ai >= low && ai <= high) psExtra->m_crossPost[ai - low] = output; else ASSERT(0); } psBarInfo->m_nPos++; if (psBarInfo->m_iLogSubRangeLen != -1) { int fraction = MulDiv(psBarInfo->m_iLogSubRangeLen, psBarInfo->m_nPos, psBarInfo->m_nSubRangeLen ); if (fraction != -1) { fraction /= psBarInfo->m_nDivide; // user feedback gpUserDisplay->SetPos(psBarInfo->m_iLogPos + fraction, FALSE, m_fEmergencyPump); } } } else // Error reading reply { r = error_xref(_T("Reading xrefs lines")); if (r) return r; } } // while (true) } else // Error sending command { // return 0 to continue if ((r = error_xref(command)) != 0) return r; } nStart += 301; } // while (nStart < high) } // test bitflag if (-1 != psBarInfo->m_iLogSubRangeLen) psBarInfo->m_iLogPos += psBarInfo->m_iLogSubRangeLen / psBarInfo->m_nDivide; #if defined(_DEBUG) { CString statMsg; statMsg.Format ("(debug) Getting Newsgroups line for arts "); gpUserDisplay->SetText (statMsg, m_fEmergencyPump); } #endif psBarInfo->m_nPos = 0; // reset for this phase psBarInfo->m_nDivide = 4; // RLW - Modified so we do not ask for more than 300 items in one go int nStart = low; while (nStart < high) { command.Format("XHDR newsgroups %d-%d", nStart, (nStart + 300 < high) ? nStart + 300 : high); //TRACE("%s\n", command); if (!m_pFeeed->Direct (m_pErrList, command)) { while (true) { if (!m_pFeeed->DirectNext (m_pErrList, output)) { if (3 == output.GetLength() && output == _T(".\r\n")) break; // End of reply data int ai = _ttoi(output); if (ai >= low && ai <= high) psExtra->m_groups[ai - low] = output; else ASSERT(0); psBarInfo->m_nPos ++; if (psBarInfo->m_iLogSubRangeLen != -1) { int fraction = MulDiv (psBarInfo->m_iLogSubRangeLen, psBarInfo->m_nPos, psBarInfo->m_nSubRangeLen ); if (fraction != -1) { fraction /= psBarInfo->m_nDivide; // user feedback gpUserDisplay->SetPos(psBarInfo->m_iLogPos + fraction, FALSE, m_fEmergencyPump); } } } else // Error receiving reply { r = error_xref(_T("Reading newsgroups lines")); if (r) return r; } } // while(true) } else // Error sending command { r = error_xref (command); if (r) return r; } nStart += 301; } // while (nStart < high) //command.Format("xhdr newsgroups %d-%d", low, high); //TRACE("%s\n", command); //r = m_pFeeed->Direct (m_pErrList, command); //if (r) //{ // fReadnewsgroups = false; // r = error_xref (command); // if (r) // return r; //} //else // fReadnewsgroups = true; //while (fReadnewsgroups) //{ // r = m_pFeeed->DirectNext (m_pErrList, output); // if (r) // { // r = error_xref (_T("Reading newsgroups lines")); // if (r) // return r; // } // if (3 == output.GetLength() && output == _T(".\r\n")) // break; // int ai = _ttoi(output); // if (ai >= low && ai <= high) // psExtra->m_groups[ai - low] = output; // else // ASSERT(0); // psBarInfo->m_nPos ++; // if (psBarInfo->m_iLogSubRangeLen != -1) // { // int fraction = MulDiv (psBarInfo->m_iLogSubRangeLen, psBarInfo->m_nPos, // psBarInfo->m_nSubRangeLen ); // if (fraction != -1) // { // fraction /= psBarInfo->m_nDivide; // // user feedback // gpUserDisplay->SetPos (psBarInfo->m_iLogPos + fraction, FALSE, m_fEmergencyPump); // } // } //} // while return 0; } // ------------------------------------------------------------------------ // return 0 for caller to continue with function int TPump::error_xref (LPCTSTR cmd) { DWORD dwErrorID; CString strError; EErrorClass eErrorClass = GetErrorClass (dwErrorID, strError); switch (eErrorClass) { case kClassNNTP: { CString strMsg; strMsg.Format ("%s returned %s", cmd, LPCTSTR(strError)); gpEventLog->AddError (TEventEntry::kPump, strMsg); m_pErrList->ClearErrors(); } return 0; case kClassWinsock: if (WSAEINTR == dwErrorID) { // no reconnect PostDisconnectMsg (false, false); } else // fIdle, fReconnect PostDisconnectMsg (false, true); return 1; default: ERRDLG(dwErrorID, strError); break; } return 0; }
24.618185
118
0.596311
[ "object" ]
3a7a42f5bfbb5b2a8523ecfa8c87847a6323ec9f
13,025
cc
C++
src/bgp/bgp_condition_listener.cc
codilime/contrail-controller-arch
e87a974950fc1bbdc2b834212dbdfee5e94008de
[ "Apache-2.0" ]
null
null
null
src/bgp/bgp_condition_listener.cc
codilime/contrail-controller-arch
e87a974950fc1bbdc2b834212dbdfee5e94008de
[ "Apache-2.0" ]
null
null
null
src/bgp/bgp_condition_listener.cc
codilime/contrail-controller-arch
e87a974950fc1bbdc2b834212dbdfee5e94008de
[ "Apache-2.0" ]
1
2020-07-04T12:08:02.000Z
2020-07-04T12:08:02.000Z
/* * Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. */ #include "bgp/bgp_condition_listener.h" #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <utility> #include "base/task_annotations.h" #include "base/task_trigger.h" #include "bgp/bgp_route.h" #include "bgp/bgp_server.h" #include "bgp/bgp_table.h" #include "db/db_table_partition.h" #include "db/db_table_walk_mgr.h" using std::make_pair; using std::map; using std::pair; using std::set; // // ConditionMatchTableState // State managed by the BgpConditionListener for each of the table it is // listening to. // BgpConditionListener registers for a DBTable when application request // for ConditionMatch // BgpConditionListener unregisters from the DBTable when application removes // the ConditionMatch and all table walks have finished // Holds a table reference to ensure that table with active walk or listener // is not deleted // class ConditionMatchTableState { public: typedef set<ConditionMatchPtr> MatchList; typedef map<ConditionMatchPtr, BgpConditionListener::RequestDoneCb> WalkList; ConditionMatchTableState(BgpTable *table, DBTableBase::ListenerId id); ~ConditionMatchTableState(); void ManagedDelete() { } DBTableBase::ListenerId GetListenerId() const { return id_; } MatchList *match_objects() { return &match_object_list_; } void AddMatchObject(ConditionMatch *obj) { match_object_list_.insert(ConditionMatchPtr(obj)); } void StoreDoneCb(ConditionMatch *obj, BgpConditionListener::RequestDoneCb cb) { pair<WalkList::iterator, bool> ret = walk_list_.insert(make_pair(obj, cb)); if (!ret.second) { if (ret.first->second.empty()) { ret.first->second = cb; } } } // Mutex required to manager MatchState list for concurrency tbb::mutex &table_state_mutex() { return table_state_mutex_; } void set_walk_ref(DBTable::DBTableWalkRef walk_ref) { walk_ref_ = walk_ref; } const DBTable::DBTableWalkRef &walk_ref() const { return walk_ref_; } DBTable::DBTableWalkRef &walk_ref() { return walk_ref_; } WalkList *walk_list() { return &walk_list_; } BgpTable *table() const { return table_; } private: tbb::mutex table_state_mutex_; BgpTable *table_; DBTableBase::ListenerId id_; DBTable::DBTableWalkRef walk_ref_; WalkList walk_list_; MatchList match_object_list_; LifetimeRef<ConditionMatchTableState> table_delete_ref_; DISALLOW_COPY_AND_ASSIGN(ConditionMatchTableState); }; BgpConditionListener::BgpConditionListener(BgpServer *server) : server_(server), purge_trigger_(new TaskTrigger( boost::bind(&BgpConditionListener::PurgeTableState, this), TaskScheduler::GetInstance()->GetTaskId("bgp::Config"), 0)) { } bool BgpConditionListener::PurgeTableState() { CHECK_CONCURRENCY("bgp::Config"); BOOST_FOREACH(ConditionMatchTableState *ts, purge_list_) { if (ts->match_objects()->empty()) { BgpTable *bgptable = ts->table(); if (ts->walk_ref() != NULL) bgptable->ReleaseWalker(ts->walk_ref()); bgptable->Unregister(ts->GetListenerId()); map_.erase(bgptable); delete ts; } } purge_list_.clear(); return true; } // // AddMatchCondition: // API to add ConditionMatch object against a table // All entries present in this table will be matched for this ConditionMatch // object.[All table partition] // Match is done either in TableWalk or During Table entry notification // void BgpConditionListener::AddMatchCondition(BgpTable *table, ConditionMatch *obj, RequestDoneCb cb) { CHECK_CONCURRENCY("bgp::Config"); ConditionMatchTableState *ts = NULL; TableMap::iterator loc = map_.find(table); if (loc == map_.end()) { DBTableBase::ListenerId id = table->Register( boost::bind(&BgpConditionListener::BgpRouteNotify, this, server(), _1, _2), "BgpConditionListener"); ts = new ConditionMatchTableState(table, id); map_.insert(make_pair(table, ts)); } else { ts = loc->second; } ts->AddMatchObject(obj); TableWalk(ts, obj, cb); } // // RemoveMatchCondition: // API to Remove ConditionMatch object from a table // All entries present in this table will be matched for this ConditionMatch // object[All table partition] and notified to application with "DELETE" flag // All Match notifications after invoking this API is called with "DELETE" flag // void BgpConditionListener::RemoveMatchCondition(BgpTable *table, ConditionMatch *obj, RequestDoneCb cb) { CHECK_CONCURRENCY("bgp::Config"); obj->SetDeleted(); TableMap::iterator loc = map_.find(table); assert(loc != map_.end()); TableWalk(loc->second, obj, cb); } // // MatchState // BgpConditionListener will hold this as DBState for each BgpRoute // class MatchState : public DBState { public: typedef map<ConditionMatchPtr, ConditionMatchState *> MatchStateList; private: friend class BgpConditionListener; MatchStateList list_; }; // // CheckMatchState // API to check if MatchState is added by module registering ConditionMatch // object. // bool BgpConditionListener::CheckMatchState(BgpTable *table, BgpRoute *route, ConditionMatch *obj) { TableMap::iterator loc = map_.find(table); ConditionMatchTableState *ts = loc->second; tbb::mutex::scoped_lock lock(ts->table_state_mutex()); // Get the DBState. MatchState *dbstate = static_cast<MatchState *>(route->GetState(table, ts->GetListenerId())); if (dbstate == NULL) return false; // Index with ConditionMatch object to check. MatchState::MatchStateList::iterator it = dbstate->list_.find(ConditionMatchPtr(obj)); return (it != dbstate->list_.end()) ? true : false; } // // GetMatchState // API to fetch MatchState added by module registering ConditionMatch object // MatchState is maintained as Map of ConditionMatch object and State in // DBState added BgpConditionListener module // ConditionMatchState * BgpConditionListener::GetMatchState(BgpTable *table, BgpRoute *route, ConditionMatch *obj) { TableMap::iterator loc = map_.find(table); ConditionMatchTableState *ts = loc->second; tbb::mutex::scoped_lock lock(ts->table_state_mutex()); // Get the DBState MatchState *dbstate = static_cast<MatchState *>(route->GetState(table, ts->GetListenerId())); if (dbstate == NULL) return NULL; // Index with ConditionMatch object to retrieve the MatchState MatchState::MatchStateList::iterator it = dbstate->list_.find(ConditionMatchPtr(obj)); return (it != dbstate->list_.end()) ? it->second : NULL; } // // SetMatchState // API for module registering ConditionMatch object to add MatchState // void BgpConditionListener::SetMatchState(BgpTable *table, BgpRoute *route, ConditionMatch *obj, ConditionMatchState *state) { TableMap::iterator loc = map_.find(table); ConditionMatchTableState *ts = loc->second; tbb::mutex::scoped_lock lock(ts->table_state_mutex()); // Get the DBState MatchState *dbstate = static_cast<MatchState *>(route->GetState(table, ts->GetListenerId())); if (!dbstate) { // Add new DBState when first application requests for MatchState dbstate = new MatchState(); route->SetState(table, ts->GetListenerId(), dbstate); } else { // Add Match to the existing list MatchState::MatchStateList::iterator it = dbstate->list_.find(ConditionMatchPtr(obj)); assert(it == dbstate->list_.end()); } dbstate->list_.insert(make_pair(obj, state)); obj->IncrementNumMatchstate(); } // // RemoveMatchState // Clear the module specific MatchState // void BgpConditionListener::RemoveMatchState(BgpTable *table, BgpRoute *route, ConditionMatch *obj) { TableMap::iterator loc = map_.find(table); ConditionMatchTableState *ts = loc->second; tbb::mutex::scoped_lock lock(ts->table_state_mutex()); // Get the DBState MatchState *dbstate = static_cast<MatchState *>(route->GetState(table, ts->GetListenerId())); MatchState::MatchStateList::iterator it = dbstate->list_.find(ConditionMatchPtr(obj)); assert(it != dbstate->list_.end()); dbstate->list_.erase(it); obj->DecrementNumMatchstate(); if (dbstate->list_.empty()) { // Remove the DBState when last module removes the MatchState route->ClearState(table, ts->GetListenerId()); delete dbstate; } } void BgpConditionListener::TableWalk(ConditionMatchTableState *ts, ConditionMatch *obj, BgpConditionListener::RequestDoneCb cb) { CHECK_CONCURRENCY("bgp::Config"); if (ts->walk_ref() == NULL) { DBTable::DBTableWalkRef walk_ref = ts->table()->AllocWalker( boost::bind(&BgpConditionListener::BgpRouteNotify, this, server(), _1, _2), boost::bind(&BgpConditionListener::WalkDone, this, ts, _2)); ts->set_walk_ref(walk_ref); } ts->StoreDoneCb(obj, cb); obj->reset_walk_done(); ts->table()->WalkTable(ts->walk_ref()); } // Table listener bool BgpConditionListener::BgpRouteNotify(BgpServer *server, DBTablePartBase *root, DBEntryBase *entry) { BgpTable *bgptable = static_cast<BgpTable *>(root->parent()); BgpRoute *rt = static_cast<BgpRoute *> (entry); // Either the route is deleted or no valid path exists bool del_rt = !rt->IsUsable(); TableMap::iterator loc = map_.find(bgptable); assert(loc != map_.end()); ConditionMatchTableState *ts = loc->second; DBTableBase::ListenerId id = ts->GetListenerId(); assert(id != DBTableBase::kInvalidId); for (ConditionMatchTableState::MatchList::iterator match_obj_it = ts->match_objects()->begin(); match_obj_it != ts->match_objects()->end(); match_obj_it++) { bool deleted = false; if ((*match_obj_it)->deleted() || del_rt) { deleted = true; } (*match_obj_it)->Match(server, bgptable, rt, deleted); } return true; } // // WalkComplete function // WalkComplete is invoked only after all walk requests for BgpConditionListener // is served. (say after multiple walkagain, only one WalkDone is invoked) // Invoke the RequestDoneCb for all objects for which walk was started // Clear the walk_list_ // void BgpConditionListener::WalkDone(ConditionMatchTableState *ts, DBTableBase *table) { BgpTable *bgptable = static_cast<BgpTable *>(table); // Invoke the RequestDoneCb after the TableWalk for (ConditionMatchTableState::WalkList::iterator walk_it = ts->walk_list()->begin(); walk_it != ts->walk_list()->end(); ++walk_it) { walk_it->first->set_walk_done(); // If application has registered a WalkDone callback, invoke it if (!walk_it->second.empty()) { walk_it->second(bgptable, walk_it->first.get()); } } ts->walk_list()->clear(); } void BgpConditionListener::UnregisterMatchCondition(BgpTable *bgptable, ConditionMatch *obj) { TableMap::iterator loc = map_.find(bgptable); assert(loc != map_.end()); ConditionMatchTableState *ts = loc->second; // Wait for Walk completion of deleted ConditionMatch object if (obj->deleted() && obj->walk_done()) { ts->match_objects()->erase(obj); purge_list_.insert(ts); } purge_trigger_->Set(); } void BgpConditionListener::DisableTableWalkProcessing() { DBTableWalkMgr *walk_mgr = server()->database()->GetWalkMgr(); walk_mgr->DisableWalkProcessing(); } void BgpConditionListener::EnableTableWalkProcessing() { DBTableWalkMgr *walk_mgr = server()->database()->GetWalkMgr(); walk_mgr->EnableWalkProcessing(); } ConditionMatchTableState::ConditionMatchTableState(BgpTable *table, DBTableBase::ListenerId id) : table_(table), id_(id), table_delete_ref_(this, table->deleter()) { assert(table->deleter() != NULL); } ConditionMatchTableState::~ConditionMatchTableState() { }
32.974684
80
0.64499
[ "object" ]
3a7d0c7f5555ce141d6a25cf08a641c61e2689c6
8,011
hxx
C++
include/sched/job.hxx
jcbaillie/libport
b8192b177ae0ae63979c17ea7685a8617b03e11f
[ "BSD-3-Clause" ]
3
2015-05-29T09:35:32.000Z
2021-02-23T07:45:01.000Z
include/sched/job.hxx
jcbaillie/libport
b8192b177ae0ae63979c17ea7685a8617b03e11f
[ "BSD-3-Clause" ]
2
2019-01-31T10:23:47.000Z
2019-01-31T10:35:06.000Z
include/sched/job.hxx
jcbaillie/libport
b8192b177ae0ae63979c17ea7685a8617b03e11f
[ "BSD-3-Clause" ]
7
2015-01-29T20:49:06.000Z
2019-04-24T04:06:22.000Z
/* * Copyright (C) 2009-2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ /** ** \file sched/job.hxx ** \brief Inline implementation of Job. */ #ifndef SCHED_JOB_HXX # define SCHED_JOB_HXX # include <libport/bind.hh> # include <libport/cassert> # include <libport/debug.hh> # include <sched/scheduler.hh> # include <sched/coroutine.hh> namespace sched { /*------------. | job_state. | `------------*/ inline const char* name(job_state state) { #define CASE(State) case State: return #State; switch (state) { CASE(to_start) CASE(running) CASE(sleeping) CASE(waiting) CASE(joining) CASE(zombie) } #undef CASE return "<unknown state>"; } inline std::ostream& operator<<(std::ostream& o, job_state s) { return o << name(s); } /*------. | Job. | `------*/ inline void Job::init_common(size_t stack_size) { state_ = to_start; frozen_since_ = 0; time_shift_ = 0; coro_ = coroutine_new(stack_size); non_interruptible_ = false; check_stack_space_ = stack_size == 0; ignore_pending_exceptions_ = false; alive_jobs_++; } inline Job::Job(Scheduler& scheduler) : RefCounted() , scheduler_(scheduler) , stats_() { init_common(); } inline Job::Job(const Job& model, size_t stack_size) : RefCounted() , scheduler_(model.scheduler_) , stats_() { init_common(stack_size); time_shift_ = model.time_shift_; } inline Job::~Job() { aver(children_.empty(), children_); coroutine_free(coro_); alive_jobs_--; } inline Scheduler& Job::scheduler_get() const { return scheduler_; } inline bool Job::terminated() const { return state_ == zombie; } inline void Job::yield() { // The only case where we yield while being non-interruptible // is when we get frozen. This is used to suspend a task // and resume it in non-interruptible contexts. if (non_interruptible_ && !frozen()) return; state_ = running; resume_scheduler_(); } inline void Job::yield_until(libport::utime_t deadline) { if (non_interruptible_) scheduling_error("attempt to sleep in non-interruptible code"); state_ = sleeping; deadline_ = deadline; resume_scheduler_(); } inline void Job::yield_for(libport::utime_t delay) { yield_until(scheduler_.get_time() + delay); } inline Coro* Job::coro_get() const { aver(coro_); return coro_; } inline void Job::start_job() { aver(state_ == to_start); scheduler_.add_job(this); } inline bool Job::non_interruptible_get() const { return non_interruptible_; } inline void Job::non_interruptible_set(bool ni) { non_interruptible_ = ni; } inline void Job::check_stack_space() { GD_CATEGORY(Sched.Job); if (check_stack_space_ && coroutine_stack_space_almost_gone(coro_)) { // Cannot be nicely converted to using FINALLY because of // MSVC2005. See finally.hh. libport::Finally finally(libport::scoped_set(check_stack_space_, false)); GD_ERROR("Stack space exhausted"); scheduling_error("stack space exhausted"); } } inline job_state Job::state_get() const { return state_; } inline void Job::state_set(job_state state) { state_ = state; if (state_ == running) scheduler_get().job_was_woken_up(); } inline libport::utime_t Job::deadline_get() const { return deadline_; } inline void Job::notice_frozen(libport::utime_t current_time) { if (!frozen_since_) frozen_since_ = current_time; } inline void Job::notice_not_frozen(libport::utime_t current_time) { if (frozen_since_) { libport::utime_t time_spent_frozen = current_time - frozen_since_; time_shift_ += time_spent_frozen; if (state_ == sleeping) deadline_ += time_spent_frozen; } frozen_since_ = 0; } inline libport::utime_t Job::frozen_since_get() const { return frozen_since_; } inline libport::utime_t Job::time_shift_get() const { return time_shift_; } inline void Job::time_shift_set(libport::utime_t ts) { time_shift_ = ts; } inline bool Job::has_pending_exception() const { return pending_exception_.get(); } inline bool Job::child_job() const { return parent_; } inline bool Job::ancester_of(const rJob& that) const { for (const Job* j = that.get(); j; j = j->parent_.get()) if (j == this) return true; return false; } inline std::ostream& operator<< (std::ostream& o, const Job& j) { return j.dump(o); } inline void Job::resume_scheduler_() { hook_preempted(); job_state last_state = state_; if (frozen()) { last_state = waiting; if (non_interruptible_) scheduling_error("attempt to wait in non-interruptible code"); } // Ensure that a non-interruptible job does not let other job scheduled // between the beginning and the end. aver(!non_interruptible_); if (stats_.logging) { libport::utime_t start_resume = scheduler_.get_time(); stats_.job.running.add_sample( start_resume - stats_.last_resume); scheduler_.resume_scheduler(this); stats_.last_resume = scheduler_.get_time(); switch (last_state) { case waiting: stats_.job.waiting.add_sample(stats_.last_resume - start_resume); break; case sleeping: stats_.job.sleeping.add_sample(stats_.last_resume - start_resume); break; default: break; } } else scheduler_.resume_scheduler(this); hook_resumed(); } /*--------. | Stats. | `--------*/ inline const Job::stats_type& Job::stats_get() const { return stats_; } inline Job::stats_type& Job::stats_get() { return stats_; } inline Job::stats_type::stats_type() : logging(true) { job.reset(); terminated_children.reset(); } inline void Job::stats_type::thread_stats_type::reset() { running.resize(0); waiting.resize(0); sleeping.resize(0); nb_fork = 0; nb_join = 0; nb_exn = 0; } inline void Job::stats_reset() { stats_.job.reset(); stats_.terminated_children.reset(); } inline void Job::stats_log(bool log) { stats_.logging = log; if (log) stats_.last_resume = scheduler_.get_time(); } inline bool Job::ignore_pending_exceptions_get() const { return ignore_pending_exceptions_; } inline void Job::ignore_pending_exceptions_set(bool v) { ignore_pending_exceptions_ = v; } inline rJob Job::parent_get() const { return parent_; } inline const jobs_type Job::children_get() const { return children_; } /*-----------------. | ChildException. | `-----------------*/ inline ChildException::ChildException(exception_ptr exc) : child_exception_(exc) { } inline ChildException::ChildException(const ChildException& exc) : SchedulerException(exc) , child_exception_(exc.child_exception_) { } inline exception_ptr ChildException::clone() const { return exception_ptr(new ChildException(child_exception_)); } inline void ChildException::rethrow_() const { throw *this; } inline void ChildException::rethrow_child_exception() const { child_exception_->rethrow(); abort(); // Help clang++ 2.1. } /*------------. | Collector. | `------------*/ ATTRIBUTE_ALWAYS_INLINE Job::Collector::Collector(rJob parent, size_t) : super_type() , parent_(parent) { } } // namespace sched #endif // !SCHED_JOB_HXX
18.206818
79
0.630009
[ "model" ]
3a7fadb9dc9d71d9ab0c984c8d7eb51aa740118b
4,970
cpp
C++
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/media/APSSpriteSheetHolder.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/media/APSSpriteSheetHolder.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
01_Develop/libXMCocos2D/Source/extensions/CCArtPig/media/APSSpriteSheetHolder.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File APSSpriteSheetHolder.cpp * Author Y.H Mun * * -------------------------------------------------------------------------- * * Created by Kim Kiyoung on 5/7/12. * Copyright (c) 2012 ArtPig Software LLC * * http://www.artpigsoft.com * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. All rights reserved. * * Contact Email: xmsoft77@gmail.com * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or ( at your option ) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "extensions/CCArtPig/APSSpriteSheetHolder.h" #include "extensions/CCArtPig/APSResourceManager.h" #include "sprite_nodes/CCSpriteFrameCache.h" NS_APS_BEGIN const std::string& APSSpriteSheetHolder::getFramesKey ( KDvoid ) { static const std::string sKey = "frames"; return sKey; } APSSpriteSheetHolder::APSSpriteSheetHolder ( const KDchar* szCode, APSResourceManager* pManager ) : APSImageHolder ( szCode, pManager ) { m_pRuntimePlPath = KD_NULL; m_bIsCached = KD_FALSE; } APSSpriteSheetHolder::APSSpriteSheetHolder ( APSDictionary* pProperties ) { m_pRuntimePlPath = KD_NULL; m_bIsCached = KD_FALSE; if ( pProperties ) { this->initWithProperties ( pProperties ); } } APSSpriteSheetHolder::~APSSpriteSheetHolder ( KDvoid ) { this->clearCachedData ( ); APS_FOREACH ( std::vector<APSSpriteFrame*>, this->m_aFrames, iter ) { APS_SAFE_DELETE ( *iter ); } } KDbool APSSpriteSheetHolder::initWithProperties ( APSDictionary* pProperties ) { KDbool bOk = APSImageHolder::initWithProperties ( pProperties ); APSArray* pArray = (APSArray*) pProperties->getObjectForKey ( this->getFramesKey ( ) ); if ( pArray ) { APS_FOREACH ( APSArrayStorage, *pArray, iter ) { APSSpriteFrame* pFrame = new APSSpriteFrame ( (APSDictionary*) *iter, this ); this->m_aFrames.push_back ( pFrame ); } } return bOk; } KDvoid APSSpriteSheetHolder::preloadData ( KDvoid ) { this->getFrames ( ); } KDvoid APSSpriteSheetHolder::clearCachedData ( KDvoid ) { APSImageHolder::clearCachedData ( ); APS_FOREACH ( std::vector<APSSpriteFrame*>, this->m_aFrames, iter ) { ( *iter )->setCCSpriteFrame ( KD_NULL ); } this->setIsCached ( KD_FALSE ); } CCSpriteFrame* APSSpriteSheetHolder::getCCSpriteFrameAtIndex ( KDuint uIndex ) { std::vector<APSSpriteFrame*>* pFrames = this->getFrames ( ); KDuint uCount = pFrames->size ( ); if ( uIndex >= uCount ) { uIndex = uCount - 1; } return pFrames->at ( uIndex )->getCCSpriteFrame ( ); } const KDchar* APSSpriteSheetHolder::getRuntimePlPath ( KDvoid ) { if ( !m_pRuntimePlPath ) { m_pRuntimePlPath = new std::string ( ); this->getPlFilenameWithImageFilename ( m_pRuntimePlPath, this->getRuntimeFullPath ( )->c_str ( ) ); } return m_pRuntimePlPath->c_str ( ); } KDvoid APSSpriteSheetHolder::getPlFilenameWithImageFilename ( std::string* pPlFilename, const KDchar* szImageFile ) { *pPlFilename = szImageFile; KDint nIdx = pPlFilename->rfind ( "." ); KDint nSize = pPlFilename->size ( ); pPlFilename->replace ( nIdx + 1, nSize - nIdx - 1, APSSpriteSheetHolder::getPlFileExtension ( ) ); } std::vector<APSSpriteFrame*>* APSSpriteSheetHolder::getFrames ( KDbool bLoadCache ) { if ( bLoadCache && !this->getIsCached ( ) ) { CCSpriteFrameCache* pSpriteFrameCache = CCSpriteFrameCache::sharedSpriteFrameCache ( ); pSpriteFrameCache->addSpriteFramesWithFile ( this->getRuntimePlPath ( ) ); APS_FOREACH ( std::vector<APSSpriteFrame*>, this->m_aFrames, iter ) { ( *iter )->setCCSpriteFrame ( pSpriteFrameCache->spriteFrameByName ( ( *iter )->getInternalName ( ) ) ); } this->setIsCached ( KD_TRUE ); } return &this->m_aFrames; } NS_APS_END
30.679012
116
0.614085
[ "vector" ]
3a83c053899feee788fb28f8590eda521e196cdf
75,007
cpp
C++
src/mods/FirstPerson.cpp
MeatSafeMurderer/REFramework
e275d7eccccfcb70311863b3f822428bdd74ce95
[ "MIT" ]
583
2021-06-05T06:56:54.000Z
2022-03-31T19:16:09.000Z
src/mods/FirstPerson.cpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
198
2021-07-13T02:54:19.000Z
2022-03-29T20:28:53.000Z
src/mods/FirstPerson.cpp
drowhunter/REFramework
49ef476d13439110cc0ae565cc323cd615d9b327
[ "MIT" ]
73
2021-07-12T18:52:12.000Z
2022-03-31T17:12:56.000Z
#include <unordered_set> #include <spdlog/spdlog.h> #include <imgui.h> #include "utility/Scan.hpp" #include "REFramework.hpp" #include "sdk/REMath.hpp" #include "sdk/MurmurHash.hpp" #include "VR.hpp" #include "FirstPerson.hpp" #if defined(RE2) || defined(RE3) FirstPerson* g_first_person = nullptr; std::shared_ptr<FirstPerson>& FirstPerson::get() { static std::shared_ptr<FirstPerson> inst{}; if (inst == nullptr) { inst = std::make_shared<FirstPerson>(); } return inst; } FirstPerson::FirstPerson() { // thanks imgui g_first_person = this; m_attach_bone_imgui.reserve(256); #ifdef RE3 // Carlos m_attach_offsets["pl0000"] = Vector4f{ 0.0f, 0.667f, 1.1f, 0.0f }; // Jill (it looks better with 0?) m_attach_offsets["pl2000"] = Vector4f{ 0.0f, 0.5f, 0.776f, 0.0f }; //m_attach_offsets["pl2000"] = Vector4f{ -0.23f, 0.4f, 1.0f, 0.0f }; #else // Specific player model configs // Leon m_attach_offsets["pl0000"] = Vector4f{ -0.26f, 0.435f, 1.0f, 0.0f }; // Claire m_attach_offsets["pl1000"] = Vector4f{ -0.23f, 0.4f, 1.0f, 0.0f }; // Sherry m_attach_offsets["pl3000"] = Vector4f{ -0.278f, 0.435f, 0.945f, 0.0f }; // Hunk m_attach_offsets["pl4000"] = Vector4f{ -0.26f, 0.435f, 1.0f, 0.0f }; // Kendo m_attach_offsets["pl5000"] = Vector4f{ -0.24f, 0.4f, 1.0f, 0.0f }; // Forgotten Soldier m_attach_offsets["pl5600"] = Vector4f{ -0.316, 0.556f, 1.02f, 0.0f }; // Elizabeth m_attach_offsets["pl6400"] = Vector4f{ -0.316, 0.466f, 0.79f, 0.0f }; #endif } void FirstPerson::toggle() { if (!m_enabled->toggle()) { on_disabled(); } } std::optional<std::string> FirstPerson::on_initialize() { /*auto vignetteCode = utility::scan(g_framework->getModule().as<HMODULE>(), "8B 87 3C 01 00 00 89 83 DC 00 00 00"); if (!vignetteCode) { return "Failed to find Disable Vignette pattern"; } // xor eax, eax m_disable_vignettePatch = Patch::create(*vignetteCode, { 0x31, 0xC0, 0x90, 0x90, 0x90, 0x90 }, false);*/ return Mod::on_initialize(); } void FirstPerson::on_frame() { } void FirstPerson::on_draw_ui() { ImGui::SetNextTreeNodeOpen(false, ImGuiCond_::ImGuiCond_FirstUseEver); if (!ImGui::CollapsingHeader(get_name().data())) { return; } std::lock_guard _{ m_frame_mutex }; /*auto last_controller_matrix = glm::extractMatrixRotation(Matrix4x4f{ m_last_controller_rotation }); // Create 4 DragFloat4's for the 4x4 matrix for (int i = 0; i < 4; i++) { auto elem = last_controller_matrix[i]; ImGui::DragFloat4("##", (float*)&elem, 1.0f, -1.0f, 1.0f); }*/ if (m_enabled->draw("Enabled")) { // Disable fov and camera light changes m_wants_disable = !m_enabled->value(); } ImGui::SameLine(); // Revert the updateCamera value to normal if (m_show_in_cutscenes->draw("Show In Cutscenes") && m_camera_system != nullptr && m_camera_system->mainCameraController != nullptr) { m_camera_system->mainCameraController->updateCamera = true; } ImGui::Separator(); ImGui::Text("VR Specific Settings"); m_smooth_xz_movement->draw("Smooth XZ Movement (VR)"); m_smooth_y_movement->draw("Smooth Y Movement (VR)"); m_roomscale->draw("Experimental Roomscale (VR)"); ImGui::DragFloat4("Scale Debug", (float*)&m_scale_debug.x, 1.0f, -1.0f, 1.0f); ImGui::DragFloat4("Scale Debug 2", (float*)&m_scale_debug2.x, 1.0f, -1.0f, 1.0f); ImGui::DragFloat4("Offset Debug", (float*)&m_offset_debug.x, 1.0f, -1.0f, 1.0f); ImGui::DragFloat("VR Scale", (float*)&m_vr_scale, 0.01f, 0.01f, 1.0f); ImGui::DragFloat3("Controller rotation (Left)", (float*)&m_left_hand_rotation_offset, 0.1f, -360.0f, 360.0f); ImGui::DragFloat3("Controller rotation (Right)", (float*)&m_right_hand_rotation_offset, 0.1f, -360.0f, 360.0f); ImGui::DragFloat3("Controller position (Left)", (float*)&m_left_hand_position_offset, 0.01f, -2.0f, 2.0f); ImGui::DragFloat3("Controller position (Right)", (float*)&m_right_hand_position_offset, 0.01f, -2.0f, 2.0f); ImGui::DragFloat3("Controller 1", (float*)&m_last_controller_euler[0].x, 1.0f, -360.0f, 360.0f); ImGui::DragFloat3("Controller 2", (float*)&m_last_controller_euler[1].x, 1.0f, -360.0f, 360.0f); ImGui::Separator(); ImGui::Text("General Settings"); m_disable_light_source->draw("Disable Camera Light"); m_hide_mesh->draw("Hide Joint Mesh"); ImGui::SameLine(); m_rotate_mesh->draw("Force Rotate Joint"); m_rotate_body->draw("Rotate Body"); if (m_disable_vignette->draw("Disable Vignette") && m_disable_vignette->value() == false) { set_vignette(via::render::ToneMapping::Vignetting::KerarePlus); } m_toggle_key->draw("Change Toggle Key"); ImGui::SliderFloat3("CameraOffset", (float*)&m_attach_offsets[m_player_name], -2.0f, 2.0f, "%.3f", 1.0f); m_camera_scale->draw("CameraSpeed"); m_bone_scale->draw("CameraShake"); if (m_camera_system != nullptr) { if (m_fov_offset->draw("FOVOffset")) { update_fov(m_camera_system->cameraController); } if (m_fov_mult->draw("FOVMultiplier")) { update_fov(m_camera_system->cameraController); m_last_fov_mult = m_fov_mult->value(); } m_current_fov->value() = m_camera_system->cameraController->activeCamera->fov; m_current_fov->draw("CurrentFOV"); } m_body_rotate_speed->draw("BodyRotateSpeed"); if (ImGui::InputText("Joint", m_attach_bone_imgui.data(), 256)) { m_attach_bone = std::wstring{ std::begin(m_attach_bone_imgui), std::end(m_attach_bone_imgui) }; } static auto list_box_handler = [](void* data, int idx, const char** out_text) -> bool { return g_first_person->list_box_handler_attach(data, idx, out_text); }; if (ImGui::ListBox("Joints", &m_attach_selected, list_box_handler, &m_attach_names, (int32_t)m_attach_names.size())) { m_attach_bone_imgui = m_attach_names[m_attach_selected]; m_attach_bone = std::wstring{ std::begin(m_attach_names[m_attach_selected]), std::end(m_attach_names[m_attach_selected]) }; } } void FirstPerson::on_lua_state_created(sol::state& state) { state.new_usertype<FirstPerson>("FirstPerson", "new", sol::no_constructor, "is_enabled", &FirstPerson::is_enabled, "will_be_used", &FirstPerson::will_be_used, "on_pre_flashlight_apply_transform", &FirstPerson::on_pre_flashlight_apply_transform ); state["firstpersonmod"] = this; // this may seem counterintuitive // but it's the easiest way to do this. // it will fix the positioning and rotation of the flashlight's light // when using VR controllers // one of the main reasons for this is to allow // compatibility with Lua's sdk.hook which supports multiple hook callbacks under one hook #ifdef RE2 try { state.do_string(R"( -- re3 doesnt have handheld flashlights if reframework:get_game_name() ~= "re2" then return end local function on_pre_apply_transform(args) local flashlight = sdk.to_managed_object(args[2]) if not firstpersonmod:on_pre_flashlight_apply_transform(flashlight) then return sdk.PreHookResult.SKIP_ORIGINAL end end local function on_post_apply_transform(retval) return retval end sdk.hook(sdk.find_type_definition(sdk.game_namespace("FlashLight")):get_method("applyTransform"), on_pre_apply_transform, on_post_apply_transform) )"); } catch (const std::exception& e) { spdlog::info("Error while trying to hook FlashLight.applyTransform: {}", e.what()); } #endif } void FirstPerson::on_config_load(const utility::Config& cfg) { for (IModValue& option : m_options) { option.config_load(cfg); } m_last_fov_mult = m_fov_mult->value(); // turn the patch on if (m_disable_vignette->value()) { //m_disable_vignettePatch->toggle(m_disable_vignette->value()); } } void FirstPerson::on_config_save(utility::Config& cfg) { for (IModValue& option : m_options) { option.config_save(cfg); } } thread_local bool g_in_player_transform = false; thread_local bool g_first_time = true; thread_local glm::quat g_old_rotation{}; void FirstPerson::on_pre_update_transform(RETransform* transform) { if (!m_enabled->value() || m_camera == nullptr || m_camera->ownerGameObject == nullptr) { return; } if (m_player_camera_controller == nullptr || m_player_transform == nullptr || m_camera_system == nullptr || m_camera_system->cameraController == nullptr) { return; } // We need to lock a mutex because these UpdateTransform functions // are called from multiple threads if (transform == m_player_transform) { if (!is_first_person_allowed()) { return; } g_in_player_transform = true; g_first_time = true; m_matrix_mutex.lock(); // Update this beforehand so we don't see the player's head disappear when using the inventory const auto gui_state = *sdk::get_object_field<int32_t>(m_gui_master, "<State_>k__BackingField"); const auto is_paused = gui_state == (int32_t)app::ropeway::gui::GUIMaster::GuiState::PAUSE || gui_state == (int32_t)app::ropeway::gui::GUIMaster::GuiState::INVENTORY; m_last_pause_state = is_paused; m_last_camera_type = utility::re_managed_object::get_field<app::ropeway::camera::CameraControlType>(m_camera_system, "BusyCameraType"); m_cached_bone_matrix = nullptr; update_player_vr(m_player_transform); update_player_body_rotation(m_player_transform); } // This is because UpdateTransform recursively calls UpdateTransform on its children, // and the player transform (topmost) is the one that actually updates the bone matrix, // and all the child transforms operate on the bones that it updated else if (g_in_player_transform) { if (!is_first_person_allowed()) { return; } /*if (g_first_time) { g_old_rotation = *(glm::quat*)&m_player_transform->angles; }*/ //update_player_transform(m_player_transform); update_player_bones(m_player_transform); } } void FirstPerson::on_update_transform(RETransform* transform) { // Do this first before anything else. if (g_in_player_transform && transform == m_player_transform) { // By also updating this in here, it fixes the out of sync issue sometimes seen for one frame // where the player body appears slightly ahead of the camera // This should especially help with frametime fluctuations if (m_camera_system != nullptr && m_camera_system->mainCamera != nullptr && m_camera_system->mainCamera->ownerGameObject != nullptr) { update_camera_transform(m_camera_system->mainCamera->ownerGameObject->transform); } update_joint_names(); //update_player_transform(transform); //transform->angles = *(Vector4f*)&g_old_rotation; g_in_player_transform = false; m_matrix_mutex.unlock(); } if (m_disable_vignette->value() && m_post_effect_controller != nullptr && transform == m_post_effect_controller->ownerGameObject->transform) { set_vignette(via::render::ToneMapping::Vignetting::Disable); } if (!m_enabled->value()) { return; } if (m_sweet_light_manager == nullptr || m_gui_master == nullptr) { return; } if (m_camera == nullptr || m_camera->ownerGameObject == nullptr) { return; } if (m_player_camera_controller == nullptr || m_player_transform == nullptr || m_camera_system == nullptr || m_camera_system->cameraController == nullptr) { return; } // Remove the camera light if specified if (transform == m_sweet_light_manager->ownerGameObject->transform) { // SweetLight update_sweet_light_context(utility::ropeway_sweetlight_manager::get_context(m_sweet_light_manager, 0)); // EnvironmentSweetLight update_sweet_light_context(utility::ropeway_sweetlight_manager::get_context(m_sweet_light_manager, 1)); } if (transform == m_camera_system->mainCamera->ownerGameObject->transform) { update_camera_transform(transform); update_fov(m_camera_system->cameraController); } } void FirstPerson::on_update_camera_controller(RopewayPlayerCameraController* controller) { if (!m_enabled->value() || m_player_transform == nullptr || controller != m_camera_system->cameraController) { return; } std::lock_guard _{ m_matrix_mutex }; auto nudged_mtx = m_last_camera_matrix; //nudged_mtx[3] += VR::get()->get_current_offset(); // The following code fixes inaccuracies between the rotation set by the game and what's set in updateCameraTransform //controller->worldPosition = nudged_mtx[3]; //*(glm::quat*)&controller->worldRotation = glm::quat{ nudged_mtx }; //m_last_controller_pos = controller->worldPosition; m_last_controller_rotation = *(glm::quat*)&controller->worldRotation; update_camera_transform(m_camera->ownerGameObject->transform); if (!will_be_used() && !m_last_pause_state) { return; } //m_camera->ownerGameObject->transform->worldTransform = nudged_mtx; //m_camera->ownerGameObject->transform->angles = *(Vector4f*)&controller->worldRotation; } void FirstPerson::on_update_camera_controller2(RopewayPlayerCameraController* controller) { if (!m_enabled->value() || m_player_transform == nullptr || controller != m_camera_system->cameraController) { return; } std::lock_guard _{ m_matrix_mutex }; const auto allowed = is_first_person_allowed(); if (!allowed && !m_ignore_next_player_angles) { m_last_controller_angles = Vector3f{ controller->pitch, controller->yaw, 0.0f }; m_last_controller_pos = controller->worldPosition; m_last_controller_rotation = *(glm::quat*) & controller->worldRotation; return; } if (allowed) { // Just update the FOV in here. Whatever. update_fov(controller); } if (m_camera_system->cameraController == m_player_camera_controller) { m_ignore_next_player_angles = m_ignore_next_player_angles || utility::re_managed_object::get_field<bool>(m_camera_system->mainCameraController, "SwitchingCamera"); if (m_ignore_next_player_angles) { // keep ignoring player input until no longer switching cameras if (m_ignore_next_player_angles) { m_ignore_next_player_angles = false; } *(glm::quat*)&controller->worldRotation = m_last_controller_rotation; controller->pitch = m_last_controller_angles.x; controller->yaw = m_last_controller_angles.y; } else { m_ignore_next_player_angles = false; } m_last_controller_angles = Vector3f{ controller->pitch, controller->yaw, 0.0f }; } m_last_controller_pos = controller->worldPosition; m_last_controller_rotation = *(glm::quat*) & controller->worldRotation; } void FirstPerson::on_pre_application_entry(void* entry, const char* name, size_t hash) { switch (hash) { case "UpdateBehavior"_fnv: on_pre_update_behavior(entry); break; case "LateUpdateBehavior"_fnv: on_pre_late_update_behavior(entry); break; default: break; } } void FirstPerson::on_application_entry(void* entry, const char* name, size_t hash) { switch (hash) { case "UpdateMotion"_fnv: on_post_update_motion(entry, true); // fixes like literally every problem ever to exist break; case "LateUpdateBehavior"_fnv: on_post_late_update_behavior(entry); break; default: break; } } void FirstPerson::on_pre_update_behavior(void* entry) { if ((m_toggle_key->is_key_down_once() && !m_enabled->toggle()) || m_wants_disable) { on_disabled(); } if (!m_enabled->value()) { return; } update_pointers(); } void FirstPerson::on_pre_late_update_behavior(void* entry) { on_post_update_motion(entry); } void FirstPerson::on_post_late_update_behavior(void* entry) { } void FirstPerson::on_post_update_motion(void* entry, bool true_motion) { if (!will_be_used()) { return; } // check it every time i guess becuase who knows what's going to happen. if (!update_pointers()) { return; } if (m_player_transform != nullptr) { if (m_camera_system != nullptr && m_camera_system->mainCamera != nullptr && m_camera_system->mainCamera->ownerGameObject != nullptr) { auto player_object = m_player_transform->ownerGameObject; if (player_object != nullptr) { update_player_vr(m_player_transform, true_motion); } } } } bool FirstPerson::on_pre_flashlight_apply_transform(::REManagedObject* flashlight_component) { if (!will_be_used()) { return true; } auto& vr_mod = VR::get(); if (!vr_mod->is_hmd_active() || !vr_mod->is_using_controllers()) { return true; } static auto via_render_mesh = sdk::RETypeDB::get()->find_type("via.render.Mesh"); static auto via_render_mesh_enabled = via_render_mesh->get_method("get_Enabled"); auto flashlight_go = ((::REComponent*)flashlight_component)->ownerGameObject; if (flashlight_go == nullptr) { return true; } auto flashlight_transform = flashlight_go->transform; if (flashlight_transform == nullptr) { return true; } auto flashlight_mesh = utility::re_component::find(flashlight_transform, via_render_mesh->get_type()); if (flashlight_mesh == nullptr) { return true; } const auto is_mesh_visible = via_render_mesh_enabled->call<bool>(sdk::get_thread_context(), flashlight_mesh); // if the mesh isn't being drawn, let the game handle it // this will happen if the player is holding a two handed weapon and aiming it if (!is_mesh_visible) { return true; } auto ies_light = *sdk::get_object_field<::REComponent*>(flashlight_component, "<IESLight>k__BackingField"); if (ies_light == nullptr) { return true; } auto ies_light_go = ies_light->ownerGameObject; if (ies_light_go == nullptr) { return true; } auto ies_light_transform = ies_light_go->transform; if (ies_light_transform == nullptr) { return true; } static auto root_hash = sdk::murmur_hash::calc32("root"); static auto via_transform = sdk::RETypeDB::get()->find_type("via.Transform"); static auto via_transform_get_joint_by_hash = via_transform->get_method("getJointByHash"); auto root_joint = via_transform_get_joint_by_hash->call<::REJoint*>(sdk::get_thread_context(), flashlight_transform, root_hash); if (root_joint == nullptr) { return true; } Vector4f light_direction{}; sdk::call_object_func<Vector4f*>(ies_light, "get_Direction", &light_direction, sdk::get_thread_context(), ies_light); const auto flashlight_position = sdk::get_joint_position(root_joint); const auto flashlight_rotation = sdk::get_joint_rotation(root_joint); const auto light_offset = flashlight_rotation * *sdk::get_object_field<Vector4f>(flashlight_component, "_IESLightOffset"); const auto light_rot_offset = utility::math::to_quat(light_direction); sdk::set_transform_position(ies_light_transform, flashlight_position + light_offset); sdk::set_transform_rotation(ies_light_transform, flashlight_rotation * light_rot_offset); // do not call the original function return false; } void FirstPerson::reset() { m_rotation_offset = glm::identity<decltype(m_rotation_offset)>(); m_interpolated_bone = glm::identity<decltype(m_interpolated_bone)>(); m_last_camera_matrix = glm::identity<decltype(m_last_camera_matrix)>(); m_last_camera_matrix_pre_vr = glm::identity<decltype(m_last_camera_matrix_pre_vr)>(); m_last_headset_rotation_pre_cutscene = glm::identity<decltype(m_last_headset_rotation_pre_cutscene)>(); m_last_bone_matrix = glm::identity<decltype(m_last_bone_matrix)>(); m_last_controller_pos = Vector4f{}; m_last_controller_rotation = glm::quat{}; m_last_controller_rotation_vr = glm::quat{}; m_cached_bone_matrix = nullptr; std::lock_guard _{ m_frame_mutex }; m_attach_names.clear(); } void FirstPerson::set_vignette(via::render::ToneMapping::Vignetting value) { // Assign tone mapping controller if (m_tone_mapping_controller == nullptr && m_post_effect_controller != nullptr) { m_tone_mapping_controller = utility::re_component::find<RopewayPostEffectControllerBase>(m_post_effect_controller, game_namespace("posteffect.ToneMapController")); } if (m_tone_mapping_controller == nullptr) { return; } // Overwrite vignetting auto update_param = [&value](auto param) { if (param == nullptr) { return; } ((RopewayPostEffectToneMapping*)param)->vignetting = (int32_t)value; }; update_param(m_tone_mapping_controller->param1); update_param(m_tone_mapping_controller->param2); update_param(m_tone_mapping_controller->param3); update_param(m_tone_mapping_controller->param4); update_param(m_tone_mapping_controller->filterSetting->param); update_param(m_tone_mapping_controller->filterSetting->currentParam); update_param(m_tone_mapping_controller->filterSetting->param1); update_param(m_tone_mapping_controller->filterSetting->param2); } bool FirstPerson::update_pointers() { // Update our global pointers if (m_post_effect_controller == nullptr || m_post_effect_controller->ownerGameObject == nullptr || m_camera_system == nullptr || m_camera_system->ownerGameObject == nullptr || m_sweet_light_manager == nullptr || m_sweet_light_manager->ownerGameObject == nullptr || m_gui_master == nullptr) { auto& globals = *g_framework->get_globals(); m_sweet_light_manager = globals.get<RopewaySweetLightManager>(game_namespace("SweetLightManager")); m_camera_system = globals.get<RopewayCameraSystem>(game_namespace("camera.CameraSystem")); m_post_effect_controller = globals.get<RopewayPostEffectController>(game_namespace("posteffect.PostEffectController")); m_gui_master = globals.get<REBehavior>(game_namespace("gui.GUIMaster")); reset(); return false; } if (m_camera_system != nullptr && m_camera_system->ownerGameObject != nullptr) { if (!update_pointers_from_camera_system(m_camera_system)) { reset(); return false; } return true; } reset(); return false; } bool FirstPerson::update_pointers_from_camera_system(RopewayCameraSystem* camera_system) { if (camera_system == nullptr) { return false; } if (m_camera = camera_system->mainCamera; m_camera == nullptr) { m_player_transform = nullptr; return false; } auto joint = camera_system->playerJoint; if (joint == nullptr) { m_player_transform = nullptr; return false; } // Update player name and log it if (m_player_transform != joint->parentTransform && joint->parentTransform != nullptr) { if (joint->parentTransform->ownerGameObject == nullptr) { return false; } m_player_name = utility::re_string::get_string(joint->parentTransform->ownerGameObject->name); if (m_player_name.empty()) { return false; } spdlog::info("Found Player {:s} {:p}", m_player_name.data(), (void*)joint->parentTransform); } // Update player transform pointer if (m_player_transform = joint->parentTransform; m_player_transform == nullptr) { return false; } // Update PlayerCameraController camera pointer if (m_player_camera_controller == nullptr) { auto controller = camera_system->cameraController; if (controller == nullptr || controller->ownerGameObject == nullptr || controller->activeCamera == nullptr || controller->activeCamera->ownerGameObject == nullptr) { return false; } if (utility::re_string::equals(controller->activeCamera->ownerGameObject->name, L"PlayerCameraController")) { m_player_camera_controller = controller; spdlog::info("Found PlayerCameraController {:p}", (void*)m_player_camera_controller); } return m_player_camera_controller != nullptr; } return true; } void FirstPerson::update_player_vr(RETransform* transform, bool first) { update_player_body_ik(transform, false, first); update_player_muzzle_behavior(transform); m_was_hmd_active = VR::get()->is_hmd_active(); } void FirstPerson::update_player_arm_ik(RETransform* transform) { if (!m_enabled->value() || m_camera_system == nullptr) { return; } // so we don't go spinning everywhere in cutscenes if (m_last_camera_type != app::ropeway::camera::CameraControlType::PLAYER) { return; } auto vr_mod = VR::get(); auto& controllers = vr_mod->get_controllers(); if (controllers.empty()) { return; } const auto is_hmd_active = vr_mod->is_hmd_active(); const auto is_using_controllers = vr_mod->is_using_controllers(); if (!is_hmd_active || !is_using_controllers) { return; } auto context = sdk::get_thread_context(); auto update_joint = [&](uint32_t hash, int32_t controller_index) { auto wrist_joint = sdk::get_transform_joint_by_hash(transform, hash); if (wrist_joint == nullptr) { return; } auto& wrist = utility::re_transform::get_joint_matrix(*transform, wrist_joint); /*auto look_matrix = glm::extractMatrixRotation(Matrix4x4f{ m_last_controller_rotation }) * Matrix4x4f{ m_scale_debug2.x, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.y, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.z, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.w };*/ // m_last_controller_rotation_vr is for the controller rotation, but // the Y component is zero'd out so only the HMD can look up/down auto cam_rot_mat = glm::extractMatrixRotation(Matrix4x4f{ m_last_controller_rotation_vr }); auto& cam_forward3 = *(Vector3f*)&cam_rot_mat[2]; auto attach_offset = m_attach_offsets[m_player_name]; if (is_hmd_active) { attach_offset.x = 0.0f; attach_offset.z = 0.0f; } auto offset = glm::extractMatrixRotation(m_last_camera_matrix) * (attach_offset * Vector4f{ -0.1f, 0.1f, 0.1f, 0.0f }); auto final_pos = Vector3f{ m_last_bone_matrix[3] + offset }; // what the fuck is this auto look_matrix = glm::extractMatrixRotation(glm::rowMajor4(glm::lookAtLH(final_pos, Vector3f{ m_last_controller_pos } + (cam_forward3 * 8192.0f), Vector3f{ 0.0f, 1.0f, 0.0f }))); //auto look_matrix = glm::extractMatrixRotation(m_last_camera_matrix); look_matrix = look_matrix * Matrix4x4f{ m_scale_debug2.x, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.y, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.z, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug2.w }; const auto hmd_pos = vr_mod->get_position(0); auto controller_offset = vr_mod->get_position(controllers[controller_index]) - hmd_pos; controller_offset.w = 1.0f; auto controller_rotation = vr_mod->get_rotation(controllers[controller_index]) * Matrix4x4f{ m_scale_debug.x, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug.y, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug.z, 0.0f, 0.0f, 0.0f, 0.0f, m_scale_debug.w }; const auto hand_rotation_offset = controller_index == 0 ? m_left_hand_rotation_offset : m_right_hand_rotation_offset; const auto hand_position_offset = controller_index == 0 ? m_left_hand_position_offset : m_right_hand_position_offset; const auto offset_quat = glm::normalize(glm::quat{ hand_rotation_offset }); const auto controller_quat = glm::normalize(glm::quat{ controller_rotation }); const auto look_quat = glm::normalize(glm::quat{ look_matrix }); // fix up the controller_rotation by rotating it with the camera rotation (look_matrix) auto rotation_quat = glm::normalize(look_quat * controller_quat * offset_quat); // be sure to always multiply the MATRIX BEFORE THE VECTOR!! WHAT HTE FUCK auto hand_pos = look_quat * ((controller_offset * m_vr_scale)); hand_pos += (glm::normalize(look_quat * controller_quat) * hand_position_offset); auto new_pos = m_last_camera_matrix_pre_vr[3] + hand_pos; new_pos.w = 1.0f; // Get Arm IK component static auto arm_fit_t = sdk::RETypeDB::get()->find_type(game_namespace("IkArmFit")); auto arm_fit = utility::re_component::find<REComponent>(transform, arm_fit_t->get_type()); // We will use the game's IK system instead of building our own because it's a pain in the ass // The arm fit component by default will only update the left wrist position (I don't know why, maybe the right arm is a blended animation?) // So we will not only abuse that, but we will repurpose it to update the right arm as well if (arm_fit != nullptr) { auto arm_fit_list_field = arm_fit_t->get_field("ArmFitList"); auto arm_fit_list = arm_fit_list_field->get_data<REArrayBase*>(arm_fit); if (arm_fit_list != nullptr && arm_fit_list->numElements > 0) { //spdlog::info("Inside arm fit, arm fit list: {:x}", (uintptr_t)arm_fit_list); auto arm_fit_data = utility::re_array::get_element<REManagedObject>(arm_fit_list, 0); if (arm_fit_data != nullptr) { //spdlog::info("First element: {:x}", (uintptr_t)first_element); auto arm_fit_data_t = utility::re_managed_object::get_type_definition(arm_fit_data); auto arm_fit_data_tmatrix_field = arm_fit_data_t->get_field("<TargetMatrix>k__BackingField"); auto& target_matrix = arm_fit_data_tmatrix_field->get_data<Matrix4x4f>(arm_fit_data); auto solver_list_field = arm_fit_t->get_field("<SolverList>k__BackingField"); auto solver_list = solver_list_field->get_data<::DotNetGenericList*>(arm_fit); // Keep track of the old joints so we can set them back after updating the IK REJoint* old_apply_joint = nullptr; REJoint** apply_joint_ptr = nullptr; // Using the solver list, we are going to override the target joint to the current wrist joint // So we can use the IK system to update both wrists if (solver_list != nullptr) { //spdlog::info("Solver list: {:x}", (uintptr_t)solver_list); auto raw_solver_list = solver_list->data; if (raw_solver_list != nullptr && raw_solver_list->numElements > 0) { auto first_solver = utility::re_array::get_element<REManagedObject>(raw_solver_list, 0); if (first_solver != nullptr) { //spdlog::info("First solver: {:x}", (uintptr_t)first_solver); auto first_solver_t = utility::re_managed_object::get_type_definition(first_solver); auto apply_joint_field = first_solver_t->get_field("<ApplyJoint>k__BackingField"); auto& apply_joint = apply_joint_field->get_data<REJoint*>(first_solver); old_apply_joint = apply_joint; apply_joint_ptr = &apply_joint; // Set the apply joint to the wrist joint apply_joint = wrist_joint; auto l0_field = first_solver_t->get_field("<L0>k__BackingField"); auto l1_field = first_solver_t->get_field("<L1>k__BackingField"); auto& l0 = l0_field->get_data<float>(first_solver); auto& l1 = l1_field->get_data<float>(first_solver); const auto total_length = l0 + l1; // Get shoulder joint by getting the parents of the wrist joint auto elbow_joint = sdk::get_joint_parent(wrist_joint); auto shoulder_joint = elbow_joint != nullptr ? sdk::get_joint_parent(elbow_joint) : (REJoint*)nullptr; auto shoulder_parent_joint = shoulder_joint != nullptr ? sdk::get_joint_parent(shoulder_joint) : (REJoint*)nullptr; if (elbow_joint != nullptr && shoulder_joint != nullptr && shoulder_parent_joint != nullptr) { const auto transform_pos = sdk::get_transform_position(transform); const auto transform_rotation = sdk::get_transform_rotation(transform); // grab the T-pose of the elbow and shoulder // then set the current position of the elbow and shoulder to the T-pose const auto original_elbow_transform = utility::re_transform::calculate_base_transform(*transform, elbow_joint); const auto original_shoulder_transform = utility::re_transform::calculate_base_transform(*transform, shoulder_joint); const auto original_shoulder_parent_transform = utility::re_transform::calculate_base_transform(*transform, shoulder_parent_joint); const auto original_elbow_pos = transform_pos + (transform_rotation * original_elbow_transform[3]); const auto original_elbow_rot = transform_rotation * glm::quat{glm::extractMatrixRotation(original_elbow_transform)}; const auto original_shoulder_pos = transform_pos + (transform_rotation * original_shoulder_transform[3]); const auto original_shoulder_rot = transform_rotation * glm::quat{glm::extractMatrixRotation(original_shoulder_transform)}; const auto original_shoulder_parent_pos = transform_pos + (transform_rotation * original_shoulder_parent_transform[3]); const auto original_shoulder_parent_rot = transform_rotation * glm::quat{glm::extractMatrixRotation(original_shoulder_parent_transform)}; const auto current_shoulder_parent_pos = sdk::get_joint_position(shoulder_parent_joint); const auto current_shoulder_parent_rot = sdk::get_joint_rotation(shoulder_parent_joint); const auto shoulder_diff = original_shoulder_pos - original_shoulder_parent_pos; const auto elbow_diff = original_elbow_pos - original_shoulder_pos; const auto updated_shoulder_pos = current_shoulder_parent_pos + shoulder_diff; const auto updated_elbow_pos = updated_shoulder_pos + elbow_diff; sdk::set_joint_position(shoulder_joint, updated_shoulder_pos); sdk::set_joint_rotation(shoulder_joint, original_shoulder_rot); sdk::set_joint_position(elbow_joint, updated_elbow_pos); sdk::set_joint_rotation(elbow_joint, original_elbow_rot); const auto shoulder_joint_pos = sdk::get_joint_position(shoulder_joint); // Bring the new_pos back to the shoulder joint + dir to the wrist joint * total length/ // This will keep the arm properly extended instead of contracting back to the original animation // When the wanted position exceeds the total IK length. // Usually that's what IK is supposed to do, but not in this game, i guess if (glm::length(new_pos - shoulder_joint_pos) > total_length) { new_pos = shoulder_joint_pos + (glm::normalize(new_pos - shoulder_joint_pos) * total_length); } } } } } // Set the target matrix to the VR controller's position (new_pos, rotation_quat) target_matrix = Matrix4x4f{ rotation_quat }; target_matrix[3] = new_pos; //spdlog::info("About to call updateIk"); auto blend_rate_field = arm_fit_t->get_field("BlendRateField"); auto& blend_rate = blend_rate_field->get_data<float>(arm_fit); auto armfit_data_blend_rate_field = arm_fit_data_t->get_field("BlendRate"); auto& armfit_data_blend_rate = armfit_data_blend_rate_field->get_data<float>(arm_fit_data); blend_rate = 1.0f; armfit_data_blend_rate = 1.0f; // Call the IK update function (index 0, first element) sdk::call_object_func<void*>(arm_fit, "updateIk", context, arm_fit, 0); // Reset the apply joint to the old value if (apply_joint_ptr != nullptr) { *apply_joint_ptr = old_apply_joint; } } } else { spdlog::info("Arm fit list is empty"); } } else { spdlog::info("Arm fit component not found"); } // radians -> deg m_last_controller_euler[controller_index] = glm::eulerAngles(rotation_quat) * (180.0f / glm::pi<float>()); }; if (is_using_controllers) { static auto l_arm_wrist_hash = sdk::murmur_hash::calc32(L"l_arm_wrist"); static auto r_arm_wrist_hash = sdk::murmur_hash::calc32(L"r_arm_wrist"); update_joint(l_arm_wrist_hash, 0); update_joint(r_arm_wrist_hash, 1); } } void FirstPerson::update_player_muzzle_behavior(RETransform* transform, bool restore) { if (!restore && !m_enabled->value()) { return; } if (m_camera_system == nullptr) { return; } if (m_last_camera_type != app::ropeway::camera::CameraControlType::PLAYER) { return; } auto vr_mod = VR::get(); auto& controllers = vr_mod->get_controllers(); const auto is_hmd_active = vr_mod->is_hmd_active(); const auto is_using_controllers = vr_mod->is_using_controllers(); auto context = sdk::get_thread_context(); // user just took off their headset if (!is_hmd_active && m_was_hmd_active) { restore = true; } if (!restore) { if (!is_hmd_active) { return; } } // We're going to modify the player's weapon (gun) to fire from the muzzle instead of the camera // Luckily the game has that built-in so we don't really need to hook anything static auto equipment_t = sdk::RETypeDB::get()->find_type(game_namespace("survivor.Equipment")); auto equipment = utility::re_component::find<REComponent>(transform, equipment_t->get_type()); if (equipment != nullptr) { auto main_weapon_field = equipment_t->get_field("<EquipWeapon>k__BackingField"); auto& main_weapon = main_weapon_field->get_data<REManagedObject*>(equipment); if (main_weapon != nullptr) { auto main_weapon_game_object = sdk::call_object_func<REGameObject*>(main_weapon, "get_GameObject", context, main_weapon); auto main_weapon_transform = main_weapon_game_object != nullptr ? main_weapon_game_object->transform : (RETransform*)nullptr; static auto implement_gun_typedef = sdk::RETypeDB::get()->find_type(game_namespace("implement.Gun")); static auto implement_melee_typedef = sdk::RETypeDB::get()->find_type(game_namespace("implement.Melee")); auto main_weapon_t = utility::re_managed_object::get_type_definition(main_weapon); if (main_weapon_game_object != nullptr && main_weapon_t != nullptr && main_weapon_t->is_a(implement_gun_typedef)) { auto& fire_bullet_param = *sdk::get_object_field<REManagedObject*>(main_weapon, "<FireBulletParam>k__BackingField"); if (fire_bullet_param != nullptr) { auto fire_bullet_param_t = utility::re_managed_object::get_type_definition(fire_bullet_param); auto& fire_bullet_type = *sdk::get_object_field<app::ropeway::weapon::shell::ShellDefine::FireBulletType>(fire_bullet_param, "_FireBulletType"); // Set the fire bullet type to AlongMuzzle, which fires from the muzzle's position and rotation if (is_using_controllers && !restore) { static auto throw_grenade_generator_type = sdk::RETypeDB::get()->find_type(game_namespace("weapon.generator.ThrowGrenadeGenerator")); auto shell_generator = *sdk::get_object_field<REManagedObject*>(main_weapon, "<ShellGenerator>k__BackingField"); auto is_grenade = false; if (shell_generator != nullptr) { auto shell_generator_t = utility::re_managed_object::get_type_definition(shell_generator); if (shell_generator_t != nullptr && shell_generator_t->is_a(throw_grenade_generator_type)) { is_grenade = true; } } if (!is_grenade) { fire_bullet_type = app::ropeway::weapon::shell::ShellDefine::FireBulletType::AlongMuzzle; } } else { if (fire_bullet_type == app::ropeway::weapon::shell::ShellDefine::FireBulletType::AlongMuzzle) { fire_bullet_type = app::ropeway::weapon::shell::ShellDefine::FireBulletType::Camera; } } auto muzzle_joint_param = *sdk::get_object_field<REManagedObject*>(fire_bullet_param, "_MuzzleJointParameter"); auto muzzle_joint_extra = *sdk::get_object_field<REManagedObject*>(main_weapon, "<MuzzleJoint>k__BackingField"); // Set the muzzle joint to the VFX muzzle position used for stuff like muzzle flashes if (muzzle_joint_param != nullptr && muzzle_joint_extra != nullptr) { static auto vfx_muzzle1_hash = sdk::murmur_hash::calc32(L"vfx_muzzle1"); auto vfx_muzzle1 = sdk::get_transform_joint_by_hash(main_weapon_transform, vfx_muzzle1_hash); auto current_muzzle_joint = *sdk::get_object_field<REJoint*>(muzzle_joint_extra, "_Parent"); // Set the parent joint name to the VFX muzzle joint which will set _Parent later on if (vfx_muzzle1 != nullptr && current_muzzle_joint != vfx_muzzle1) { auto muzzle_joint_name = sdk::VM::create_managed_string(L"vfx_muzzle1"); // call set_ParentJointNameForm sdk::call_object_func<void*>(muzzle_joint_param, "set_ParentJointNameForm", context, muzzle_joint_param, muzzle_joint_name); } } } } else if (main_weapon_game_object != nullptr && main_weapon_t != nullptr && main_weapon_t->is_a(implement_melee_typedef)) { auto collider_field = main_weapon_t->get_field("<RequestSetCollider>k__BackingField"); auto& collider = collider_field->get_data<REManagedObject*>(main_weapon); if (collider != nullptr) { // TODO! it's a lua script, maybe implement natively later? } } } } } void FirstPerson::update_player_body_ik(RETransform* transform, bool restore, bool first) { if (!restore && !m_enabled->value()) { return; } if (m_camera_system == nullptr) { return; } if (m_last_camera_type != app::ropeway::camera::CameraControlType::PLAYER) { return; } auto vr_mod = VR::get(); auto& controllers = vr_mod->get_controllers(); const auto is_hmd_active = vr_mod->is_hmd_active(); const auto is_using_controllers = vr_mod->is_using_controllers(); auto context = sdk::get_thread_context(); // user just took headset off if (!is_hmd_active && m_was_hmd_active) { restore = true; } if (!restore) { if (!is_hmd_active) { return; } } static auto ik_leg_def = sdk::RETypeDB::get()->find_type("via.motion.IkLeg"); static auto via_motion_def = sdk::RETypeDB::get()->find_type("via.motion.Motion"); auto ik_leg = utility::re_component::find<REComponent>(transform, ik_leg_def->type); auto via_motion = utility::re_component::find<REComponent>(transform, via_motion_def->type); // We're going to use the leg IK to adjust the height of the player according to headset position if (ik_leg != nullptr && via_motion != nullptr) { // disabling FirstPerson triggers this if (restore) { Vector4f zero_offset{}; sdk::call_object_func<void*>(ik_leg, "set_CenterPositionCtrl", sdk::get_thread_context(), ik_leg, via::motion::IkLeg::EffectorCtrl::None); sdk::call_object_func<void*>(ik_leg, "set_CenterOffset", sdk::get_thread_context(), ik_leg, &zero_offset); utility::re_managed_object::call_method(ik_leg, "set_CenterAdjust", via::motion::IkLeg::CenterAdjust::Center); return; } const auto headset_pos = vr_mod->get_position(0); auto standing_origin = vr_mod->get_standing_origin(); auto hmd_offset = headset_pos - standing_origin; glm::quat rotation{}; if (is_using_controllers) { rotation = m_last_controller_rotation_vr; } else { rotation = utility::math::remove_y_component(Matrix4x4f{glm::normalize(m_last_controller_rotation_vr)}); } bool updated_transform = false; // Experimental roomscale movement. if (m_roomscale->value() && first && glm::length(Vector3f{hmd_offset.x, 0.0f, hmd_offset.z}) > 0.5f) { const auto current_pos = sdk::get_transform_position(transform); sdk::set_transform_position(transform, current_pos + (rotation * Vector4f{ hmd_offset.x, 0.0f, hmd_offset.z, 0.0f })); standing_origin = Vector4f{headset_pos.x, standing_origin.y, headset_pos.z, standing_origin.w}; vr_mod->set_standing_origin(standing_origin); hmd_offset = headset_pos - standing_origin; updated_transform = true; } // Create a final offset which will keep the player's head where they want // while also stabilizing any undesired head movement from the original animation Vector4f final_offset{ rotation * hmd_offset }; const auto smooth_xz_movement = m_smooth_xz_movement->value(); const auto smooth_y_movement = m_smooth_y_movement->value(); static auto cog_hash = sdk::murmur_hash::calc32(L"COG"); static auto head_hash = sdk::murmur_hash::calc32(L"head"); static auto root_hash = sdk::murmur_hash::calc32(L"root"); auto center_joint = sdk::get_transform_joint_by_hash(transform, cog_hash); if (smooth_xz_movement || smooth_y_movement) { auto head_joint = sdk::get_transform_joint_by_hash(transform, head_hash); auto root_joint = sdk::get_transform_joint_by_hash(transform, root_hash); if (head_joint != nullptr && center_joint != nullptr && root_joint != nullptr) { const auto head_joint_index = ((sdk::Joint*)head_joint)->get_joint_index(); const auto cog_joint_index = ((sdk::Joint*)center_joint)->get_joint_index(); const auto root_joint_index = ((sdk::Joint*)root_joint)->get_joint_index(); const auto base_transform_pos = sdk::get_transform_position(transform); const auto base_transform_rot = sdk::get_transform_rotation(transform); Vector4f original_head_pos{}; sdk::call_object_func<Vector4f*>(via_motion, "getWorldPosition", &original_head_pos, sdk::get_thread_context(), via_motion, head_joint_index); original_head_pos = base_transform_rot * original_head_pos; // the reference pose for the head joint const auto head_base_transform = utility::re_transform::calculate_base_transform(*transform, head_joint); const auto reference_height = head_base_transform[3].y; if (smooth_xz_movement) { final_offset.x -= original_head_pos.x; final_offset.z -= original_head_pos.z; } if (smooth_y_movement) { final_offset.y += (reference_height - original_head_pos.y); } } } sdk::call_object_func<void*>(ik_leg, "set_CenterPositionCtrl", sdk::get_thread_context(), ik_leg, via::motion::IkLeg::EffectorCtrl::WorldOffset); sdk::call_object_func<void*>(ik_leg, "set_CenterOffset", sdk::get_thread_context(), ik_leg, &final_offset); // this will allow the player to physically move higher than the model's standing height // so the head adjustment will be more accurate and smooth if the player is standing straight. // a small side effect is that the player can slightly float, but it's worth it. // not a TDB method unfortunately. utility::re_managed_object::call_method(ik_leg, "set_CenterAdjust", via::motion::IkLeg::CenterAdjust::None); if (updated_transform && center_joint != nullptr) { Vector4f true_cog_pos{}; const auto cog_joint_index = ((sdk::Joint*)center_joint)->get_joint_index(); sdk::call_object_func<Vector4f*>(via_motion, "getWorldPosition", &true_cog_pos, sdk::get_thread_context(), via_motion, cog_joint_index); const auto original_cog_pos = sdk::get_joint_position(center_joint); sdk::set_joint_position(center_joint, true_cog_pos); sdk::call_object_func<void*>(ik_leg, "firstUpdate", sdk::get_thread_context(), ik_leg); sdk::call_object_func<void*>(ik_leg, "secondUpdate", sdk::get_thread_context(), ik_leg); update_player_arm_ik(transform); sdk::set_joint_position(center_joint, original_cog_pos); } else { update_player_arm_ik(transform); } } } void FirstPerson::update_player_body_rotation(RETransform* transform) { if (!m_enabled->value() || m_camera_system == nullptr) { return; } if (m_last_camera_type != app::ropeway::camera::CameraControlType::PLAYER) { return; } if (!m_rotate_body->value()) { return; } static auto jack_dominator_typedef = sdk::RETypeDB::get()->find_type(game_namespace("JackDominator")); static auto jacked_method = jack_dominator_typedef->get_method("get_Jacked"); auto jack_dominator = utility::re_component::find<::REComponent*>(transform, jack_dominator_typedef->get_type()); if (jack_dominator != nullptr) { const auto is_jacked = jacked_method->call<bool>(sdk::get_thread_context(), jack_dominator); // using a ladder, being grabbed, jumping down, etc if (is_jacked) { return; } } auto player_matrix = glm::mat4{ *(glm::quat*)&transform->angles }; auto player_right = *(Vector3f*)&player_matrix[0] * -1.0f; player_right[1] = 0.0f; player_right = glm::normalize(player_right); auto player_forward = *(Vector3f*)&player_matrix[2] * -1.0f; player_forward[1] = 0.0f; player_forward = glm::normalize(player_forward); auto camera_matrix = m_last_camera_matrix; auto cam_forward3 = *(Vector3f*)&camera_matrix[2]; // Remove the upwards facing component of the forward vector cam_forward3[1] = 0.0f; cam_forward3 = glm::normalize(cam_forward3); auto angle_between = glm::degrees(glm::orientedAngle(player_forward, cam_forward3, Vector3f{ 0.0f, 1.0f, 0.0f })); if (std::abs(angle_between) == 0.0f) { return; } if (angle_between > 0) { player_right *= -1.0f; } auto angle_diff = std::abs(angle_between) / 720.0f; auto diff = (player_forward - player_right) * angle_diff * update_delta_time(transform) * m_body_rotate_speed->value(); // Create a two-dimensional representation of the forward vector as a rotation matrix auto rot = glm::lookAtRH(Vector3f{}, glm::normalize(player_forward + diff), Vector3f{ 0.0f, 1.0f, 0.0f }); camera_matrix = glm::extractMatrixRotation(glm::rowMajor4(rot)); auto camera_quat = glm::quat{ camera_matrix }; // Finally rotate the player transform to match the camera in a two-dimensional fashion transform->angles = *(Vector4f*)&camera_quat; } void FirstPerson::update_camera_transform(RETransform* transform) { if (!m_enabled->value()) { return; } std::lock_guard _{ m_matrix_mutex }; auto vr = VR::get(); /*if (vr->is_hmd_active() && m_camera_system->cameraController != nullptr) { m_last_controller_rotation = *(glm::quat*)&m_camera_system->cameraController->worldRotation; }*/ const auto gui_state = *sdk::get_object_field<int32_t>(m_gui_master, "<State_>k__BackingField"); const auto is_paused = gui_state == (int32_t)app::ropeway::gui::GUIMaster::GuiState::PAUSE || gui_state == (int32_t)app::ropeway::gui::GUIMaster::GuiState::INVENTORY; m_last_camera_type = utility::re_managed_object::get_field<app::ropeway::camera::CameraControlType>(m_camera_system, "BusyCameraType"); m_last_pause_state = is_paused; const auto is_player_camera = m_last_camera_type == app::ropeway::camera::CameraControlType::PLAYER && !is_paused; const auto is_switching_camera = utility::re_managed_object::get_field<bool>(m_camera_system->mainCameraController, "SwitchingCamera"); const auto is_player_in_control = (is_player_camera && !is_switching_camera && !m_last_pause_state); const auto is_switching_to_player_camera = is_player_camera && is_switching_camera; auto& mtx = transform->worldTransform; // Don't mess with the camera if we're in a cutscene if (!is_first_person_allowed()) { if (m_camera_system->mainCameraController != nullptr && !is_paused && !is_switching_to_player_camera) { m_camera_system->mainCameraController->updateCamera = true; } if (is_paused) { return; } if (vr->is_hmd_active()) { //m_last_camera_matrix = vr->get_last_render_matrix(); //m_last_camera_matrix_pre_vr = glm::inverse(vr->get_rotation(0)) * glm::extractMatrixRotation(m_last_camera_matrix); //m_last_camera_matrix_pre_vr[3] = m_last_camera_matrix[3]; } } auto delta_time = update_delta_time(transform); auto& camera_pos = mtx[3]; auto cam_pos3 = Vector3f{ m_last_controller_pos }; auto camera_matrix = m_last_camera_matrix_pre_vr * Matrix4x4f{ -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }; //is_player_camera = is_player_camera && !is_switching_camera; // fix some crazy spinning bullshit if (gui_state == (int32_t)app::ropeway::gui::GUIMaster::GuiState::PAUSE) { //*(Matrix3x4f*)&mtx = m_last_camera_matrix_pre_vr; } const auto wanted_camera_shake = vr->is_hmd_active() ? 0.0f : m_bone_scale->value(); const auto wanted_camera_speed = vr->is_hmd_active() ? 100.0f : m_camera_scale->value(); m_interp_bone_scale = glm::lerp(m_interp_bone_scale, wanted_camera_shake, std::clamp(delta_time * 0.05f, 0.0f, 1.0f)); m_interp_camera_speed = glm::lerp(m_interp_camera_speed, wanted_camera_speed, std::clamp(delta_time * 0.05f, 0.0f, 1.0f)); if (is_switching_camera || !is_player_camera) { if (is_switching_camera) { m_interp_camera_speed = 100.0f; auto c = m_camera_system->mainCameraController; if (is_player_camera) { auto len = c->switchInterpolationTime; if (len == 0.0f) { len = 1.0f; } m_interp_bone_scale = (5.0f / len); //m_interp_bone_scale = 10.0f; } else { m_interp_bone_scale = 100.0f; } } else { m_interp_camera_speed = 100.0f; m_interp_bone_scale = 50.0f; } } // Lets camera modification work in cutscenes/action camera etc if (!is_player_camera && !is_switching_camera && is_first_person_allowed()) { m_camera_system->mainCameraController->updateCamera = false; } else { m_camera_system->mainCameraController->updateCamera = true; } if (is_first_person_allowed()) { camera_matrix[3] = m_last_bone_matrix[3]; } auto& bone_pos = camera_matrix[3]; const auto real_headset_rotation = vr->get_rotation(0); // Fix rotation after returning to player control if (is_player_in_control && m_has_cutscene_rotation) { if (vr->is_hmd_active()) { m_last_headset_rotation_pre_cutscene = utility::math::remove_y_component(real_headset_rotation); m_last_controller_rotation = glm::quat{vr->get_last_render_matrix()}; } else { m_last_headset_rotation_pre_cutscene = glm::identity<Matrix4x4f>(); } const auto cutscene_inverse = glm::inverse(m_last_headset_rotation_pre_cutscene); const auto cutscene_quat = glm::quat{ cutscene_inverse }; m_last_controller_rotation = glm::normalize((cutscene_quat) * m_last_controller_rotation); m_last_controller_angles = utility::math::euler_angles(Matrix4x4f{m_last_controller_rotation}); if (m_player_camera_controller != nullptr) { m_player_camera_controller->worldRotation = m_camera_system->cameraController->worldRotation; m_player_camera_controller->pitch = m_last_controller_angles.x; m_player_camera_controller->yaw = m_last_controller_angles.y; } m_camera_system->mainCameraController->cameraRotation = *(Vector4f*)&m_last_controller_rotation; m_camera_system->cameraController->worldRotation = *(Vector4f*)&m_last_controller_rotation; m_has_cutscene_rotation = false; m_ignore_next_player_angles = true; m_camera_system->mainCameraController->updateCamera = false; //*(Matrix3x4f*)&mtx = cutscene_inverse * m_last_camera_matrix_pre_vr; // Do not interpolate these so the camera doesn't jump after exiting a cutscene. m_interp_bone_scale = 0.0f; m_interp_camera_speed = 100.0f; } auto bone_scale = (is_player_in_control || is_switching_to_player_camera) ? (m_interp_bone_scale * 0.01f) : 1.0f; auto cam_rot_mat = glm::extractMatrixRotation(Matrix4x4f{ m_last_controller_rotation }); auto head_rot_mat = glm::extractMatrixRotation(m_last_bone_matrix) * Matrix4x4f { -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }; auto& cam_forward3 = *(Vector3f*)&cam_rot_mat[2]; // Zero out the Y component of the forward vector // When using VR so only the user can control the up/down rotation with the headset if (vr->is_hmd_active() && vr->is_using_controllers() && !is_paused) { cam_forward3[1] = 0.0f; cam_forward3 = glm::normalize(cam_forward3); } auto attach_offset = m_attach_offsets[m_player_name]; if (vr->is_hmd_active()) { attach_offset.x = 0.0f; attach_offset.z = 0.0f; } auto offset = glm::extractMatrixRotation(camera_matrix) * (attach_offset * Vector4f{ -0.1f, 0.1f, 0.1f, 0.0f }); auto final_pos = Vector3f{ bone_pos + offset }; // Average the distance to the wanted rotation auto dist = (glm::distance(m_interpolated_bone[0], head_rot_mat[0]) + glm::distance(m_interpolated_bone[1], head_rot_mat[1]) + glm::distance(m_interpolated_bone[2], head_rot_mat[2])) / 3.0f; // interpolate the bone rotation (it's snappy otherwise) if (is_player_in_control || is_switching_to_player_camera) { if (vr->is_hmd_active()) { m_interpolated_bone = glm::identity<Matrix4x4f>(); } else { m_interpolated_bone = glm::interpolate(m_interpolated_bone, head_rot_mat, delta_time * bone_scale * dist); } } else { m_interpolated_bone = head_rot_mat; } // Look at where the camera is pointing from the head position cam_rot_mat = glm::extractMatrixRotation(glm::rowMajor4(glm::lookAtLH(final_pos, cam_pos3 + (cam_forward3 * 8192.0f), Vector3f{ 0.0f, 1.0f, 0.0f }))); // Follow the bone rotation, but rotate towards where the camera is looking. auto wanted_mat = glm::inverse(m_interpolated_bone) * cam_rot_mat; if (is_player_in_control || is_switching_to_player_camera) { if (is_player_in_control && m_interp_camera_speed >= 100.0f && bone_scale == 0.0f) { m_rotation_offset = wanted_mat; } else { // Average the distance to the wanted rotation dist = (glm::distance(m_rotation_offset[0], wanted_mat[0]) + glm::distance(m_rotation_offset[1], wanted_mat[1]) + glm::distance(m_rotation_offset[2], wanted_mat[2])) / 3.0f; m_rotation_offset = glm::interpolate(m_rotation_offset, wanted_mat, delta_time * (m_interp_camera_speed * 0.01f) * dist); } } else { m_rotation_offset = wanted_mat; } auto final_mat = is_player_camera ? (m_interpolated_bone * m_rotation_offset) : m_interpolated_bone; auto mtx_pre_vr = final_mat; mtx_pre_vr[3] = mtx[3]; const auto final_mat_pre_vr = final_mat; const auto final_quat_pre_vr = glm::normalize(glm::quat{final_mat}); //if (!is_paused && m_has_cutscene_rotation) { //final_mat *= glm::inverse(m_last_headset_rotation_pre_cutscene); //} if (vr->is_hmd_active()) { const auto last_headset_rotation = !is_player_in_control ? m_last_headset_rotation_pre_cutscene : glm::identity<Matrix4x4f>(); const auto inverse_last_headset_rotation = !is_player_in_control ? glm::inverse(m_last_headset_rotation_pre_cutscene) : glm::identity<Matrix4x4f>(); const auto headset_rotation = inverse_last_headset_rotation * real_headset_rotation; if (is_first_person_allowed()) { final_mat *= headset_rotation; vr->recenter_view(); // only affects third person/cutscenes } else { //final_mat *= Matrix4x4f{glm::normalize(vr->get_rotation_offset() * glm::quat{real_headset_rotation})}; final_mat = vr->get_last_render_matrix(); } } auto final_quat = glm::normalize(glm::quat{ final_mat }); // Apply the same matrix data to other things stored in-game (positions/quaternions) if (is_first_person_allowed()) { camera_pos = Vector4f{ final_pos, 1.0f }; m_camera_system->cameraController->worldPosition = *(Vector4f*)&camera_pos; m_camera_system->cameraController->worldRotation = *(Vector4f*)&final_quat; transform->position = *(Vector4f*)&camera_pos; transform->angles = *(Vector4f*)&final_quat; // Apply the new matrix *(Matrix3x4f*)&mtx = final_mat; } if (is_player_in_control || is_first_person_allowed()) { m_last_camera_matrix = final_mat; m_last_camera_matrix[3] = mtx[3]; m_last_camera_matrix_pre_vr = mtx_pre_vr; } // Fixes snappiness after camera switching if (!is_player_in_control) { m_last_controller_pos = m_camera_system->cameraController->worldPosition; if (!is_switching_to_player_camera) { m_last_controller_rotation = final_quat; } m_camera_system->mainCameraController->cameraPosition = m_last_controller_pos; m_camera_system->mainCameraController->cameraRotation = *(Vector4f*)&final_quat_pre_vr; m_camera_system->cameraController->worldRotation = *(Vector4f*)&final_quat_pre_vr; //if (!is_switching_to_player_camera) { //m_last_controller_angles = utility::math::euler_angles(final_mat_pre_vr); //} if (!is_switching_to_player_camera) { m_last_controller_angles = utility::math::euler_angles(final_mat_pre_vr); } // These are what control the real rotation, so only set it in a cutscene or something // If we did it all the time, the view would drift constantly //m_camera_system->cameraController->pitch = m_last_controller_angles.x; //m_camera_system->cameraController->yaw = m_last_controller_angles.y; if (m_player_camera_controller != nullptr) { m_player_camera_controller->worldPosition = m_camera_system->cameraController->worldPosition; m_player_camera_controller->worldRotation = m_camera_system->cameraController->worldRotation; /*if (m_last_camera_type == app::ropeway::camera::CameraControlType::PLAYER) { m_last_controller_angles.z = 0.0f; m_last_controller_angles += (prev_angles - m_last_controller_angles) * delta_time; }*/ // Forces the game to keep the previous angles/rotation we set after exiting a cutscene //if (is_switching_to_player_camera) { m_player_camera_controller->pitch = m_last_controller_angles.x; m_player_camera_controller->yaw = m_last_controller_angles.y; //} m_ignore_next_player_angles = m_ignore_next_player_angles || is_switching_to_player_camera; } } if (transform->joints.matrices != nullptr && is_first_person_allowed()) { auto joint = utility::re_transform::get_joint(*transform, 0); if (joint != nullptr) { sdk::set_joint_rotation(joint, m_last_camera_matrix); sdk::set_joint_position(joint, m_last_camera_matrix[3]); } } m_last_controller_rotation_vr = glm::quat { cam_rot_mat }; // Keep track of the last pre-cutscene headset rotation // so the player doesn't do something like flip 180 when a cutscene starts // which would be especially prevalent for a user with a large playspace if (!is_player_in_control && !is_switching_to_player_camera && !m_has_cutscene_rotation) { if (vr->is_hmd_active()) { m_last_headset_rotation_pre_cutscene = utility::math::remove_y_component(real_headset_rotation); } else { m_last_headset_rotation_pre_cutscene = glm::identity<Matrix4x4f>(); } m_has_cutscene_rotation = true; } else if (is_player_in_control) { m_has_cutscene_rotation = false; } } void FirstPerson::update_sweet_light_context(RopewaySweetLightManagerContext* ctx) { if (ctx->controller == nullptr || ctx->controller->ownerGameObject == nullptr) { return; } // Disable the camera light source. ctx->controller->ownerGameObject->shouldDraw = !(m_enabled->value() && m_disable_light_source->value() && m_camera_system->cameraController == m_player_camera_controller); } void FirstPerson::update_player_bones(RETransform* transform) { if (g_first_time) { auto& bone_matrix = utility::re_transform::get_joint_matrix(*m_player_transform, m_attach_bone); m_cached_bone_matrix = &bone_matrix; m_last_bone_matrix = bone_matrix; g_first_time = false; } if (m_cached_bone_matrix == nullptr) { return; } auto& bone_matrix = *m_cached_bone_matrix; // Forcefully rotate the bone to match the camera direction if (m_camera_system->cameraController == m_player_camera_controller && m_rotate_mesh->value()) { auto wanted_mat = m_last_camera_matrix * Matrix4x4f{ -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1 }; *(Matrix3x4f*)&bone_matrix = wanted_mat; } // Hide the head model by moving it out of view of the camera (and hopefully shadows...) if (m_hide_mesh->value()) { bone_matrix[0] = Vector4f{ 0.0f, 0.0f, 0.0f, 0.0f }; bone_matrix[1] = Vector4f{ 0.0f, 0.0f, 0.0f, 0.0f }; bone_matrix[2] = Vector4f{ 0.0f, 0.0f, 0.0f, 0.0f }; } } void FirstPerson::update_fov(RopewayPlayerCameraController* controller) { if (controller == nullptr) { return; } auto is_active_camera = m_camera_system != nullptr && m_camera_system->cameraController != nullptr && m_camera_system->cameraController->cameraParam != nullptr && m_camera_system->cameraController->activeCamera != nullptr && m_camera_system->mainCameraController != nullptr && m_camera_system->mainCameraController->mainCamera != nullptr; if (!is_active_camera) { return; } if (!is_first_person_allowed()) { return; } if (auto param = controller->cameraParam; param != nullptr) { auto new_value = (param->fov * m_fov_mult->value()) + m_fov_offset->value(); if (m_last_camera_type == app::ropeway::camera::CameraControlType::PLAYER) { if (m_fov_mult->value() != m_last_fov_mult) { auto prev_value = (param->fov * m_last_fov_mult) + m_fov_offset->value(); auto delta = prev_value - new_value; m_fov_offset->value() += delta; m_camera_system->mainCameraController->mainCamera->fov = (param->fov * m_fov_mult->value()) + m_fov_offset->value(); controller->activeCamera->fov = m_camera_system->mainCameraController->mainCamera->fov; } else { m_camera_system->mainCameraController->mainCamera->fov = new_value; controller->activeCamera->fov = m_camera_system->mainCameraController->mainCamera->fov; } m_last_player_fov = controller->activeCamera->fov; } else { if (m_last_player_fov == 0.0f) { m_last_player_fov = 90.0f; } m_camera_system->mainCameraController->mainCamera->fov = m_last_player_fov; controller->activeCamera->fov = m_last_player_fov; } // Causes the camera to ignore the FOV inside the param param->useParam = !m_enabled->value(); } } void FirstPerson::update_joint_names() { if (m_player_transform == nullptr || !m_attach_names.empty()) { return; } auto& joints = m_player_transform->joints; #if !defined(RE8) && !defined(MHRISE) for (int32_t i = 0; joints.data != nullptr && i < joints.size; ++i) { auto joint = joints.data->joints[i]; #else for (int32_t i = 0; joints.data != nullptr && i < joints.data->numElements; ++i) { auto joint = utility::re_array::get_element<REJoint>(joints.data, i); #endif if (joint == nullptr || joint->info == nullptr || joint->info->name == nullptr) { continue; } auto name = std::wstring{ joint->info->name }; m_attach_names.push_back(utility::narrow(name).c_str()); } } float FirstPerson::update_delta_time(REComponent* component) { return utility::re_component::get_delta_time(component); } bool FirstPerson::is_first_person_allowed() const { if (m_last_pause_state) { return false; } // Don't mess with the camera if we're in a cutscene if (m_show_in_cutscenes->value()) { return m_allowed_camera_types.count(m_last_camera_type) > 0; } return m_last_camera_type == app::ropeway::camera::CameraControlType::PLAYER; } void FirstPerson::on_disabled() { VR::get()->set_rotation_offset(glm::identity<glm::quat>()); if (!update_pointers()) { m_wants_disable = false; return; } // restore the muzzle and body IK behavior // so we don't lean off to the side when we're not in first person // and not shoot out of the camera if (m_player_transform != nullptr) { update_player_muzzle_behavior(m_player_transform, true); update_player_body_ik(m_player_transform, true); } // Disable fov and camera light changes if (m_camera_system != nullptr && m_sweet_light_manager != nullptr) { update_fov(m_camera_system->cameraController); update_sweet_light_context(utility::ropeway_sweetlight_manager::get_context(m_sweet_light_manager, 0)); update_sweet_light_context(utility::ropeway_sweetlight_manager::get_context(m_sweet_light_manager, 1)); if (m_camera_system->mainCameraController != nullptr) { m_camera_system->mainCameraController->updateCamera = true; } } m_wants_disable = false; } #endif
42.257465
188
0.6451
[ "mesh", "render", "vector", "model", "transform" ]
3a86c14aeee48b9c3c964d8318bd4fb37dc7a1e9
9,265
hpp
C++
Source/AllProjects/DataUtils/CIDRegX/CIDRegX_RegExNFA.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
1
2019-05-28T06:33:01.000Z
2019-05-28T06:33:01.000Z
Source/AllProjects/DataUtils/CIDRegX/CIDRegX_RegExNFA.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
Source/AllProjects/DataUtils/CIDRegX/CIDRegX_RegExNFA.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
// // FILE NAME: CIDRegX_RegExNFA.hpp // // AUTHOR: Dean Roddey // // CREATED: 07/28/1998 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the header for the CIDRegX_RegExNFA.cpp file, which implements // the TRegXNFA class. This class represents the transition table for the // regular expression engine, TRegEx. // // It also provides a public abstract interface, TGrepMatcher, which is the // base for the pluggable objects that provide various variations on pattern // matching operations. The rest of the derivatives of this class are provided // in an internal only hpp/cpp file since the outside world does not need // to see them. // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // ---------------------------------------------------------------------------- // CLASS: TRXMatcher // PREFIX: match // ---------------------------------------------------------------------------- class CIDREGXEXP TRXMatcher : public TObject, public MFormattable { public : // -------------------------------------------------------------------- // Constructors and Destructor // -------------------------------------------------------------------- TRXMatcher() {} TRXMatcher(const TRXMatcher&) = delete; ~TRXMatcher() {} // -------------------------------------------------------------------- // Public operators // -------------------------------------------------------------------- TRXMatcher& operator=(const TRXMatcher&) = delete; // -------------------------------------------------------------------- // Public, virtual methods // -------------------------------------------------------------------- virtual tCIDLib::TBoolean bMatches ( const tCIDLib::TCh chToCheck , const tCIDLib::TCard4 c4CurOfs , const tCIDLib::TCard4 c4SearchLen , const tCIDLib::TBoolean bCaseSensitive ) const = 0; private : // -------------------------------------------------------------------- // Magic macros // -------------------------------------------------------------------- RTTIDefs(TRXMatcher,TObject) }; // ---------------------------------------------------------------------------- // CLASS: TRegExNFA // PREFIX: rxnfa // ---------------------------------------------------------------------------- class CIDREGXEXP TRegExNFA : public TObject, public MFormattable { public : // -------------------------------------------------------------------- // Constructors and Destructor // -------------------------------------------------------------------- TRegExNFA() = delete; TRegExNFA ( const tCIDLib::TCard4 c4MaxStates ); TRegExNFA(const TRegExNFA&) = delete; ~TRegExNFA(); // -------------------------------------------------------------------- // Public operators // -------------------------------------------------------------------- TRegExNFA& operator==(const TRegExNFA&) = delete; // -------------------------------------------------------------------- // Public, non-virtual methods // -------------------------------------------------------------------- tCIDLib::TBoolean bIsEpsilonState ( const tCIDLib::TCard4 c4At ) const; tCIDLib::TBoolean bIsNullable() const { return m_bNullable; } tCIDLib::TCard4 c4AddState(); tCIDLib::TCard4 c4AddState ( TRXMatcher* const pmatchNew , const tCIDLib::TCard4 c4Trans1 , const tCIDLib::TCard4 c4Trans2 ); tCIDLib::TCard4 c4AddStatePointedPastEnd ( TRXMatcher* const pmatchNew = nullptr ); tCIDLib::TCard4 c4Reset ( const tCIDLib::TCard4 c4MaxStates ); tCIDLib::TCard4 c4StateCount() const; tCIDLib::TCard4 c4LastState() const; tCIDLib::TCard4 c4MaxStates() const; tCIDLib::TCard4 c4State1At ( const tCIDLib::TCard4 c4At ) const; tCIDLib::TCard4 c4State2At ( const tCIDLib::TCard4 c4At ) const; tCIDLib::TVoid Complete(); const TRXMatcher& matchAt ( const tCIDLib::TCard4 c4At ) const; TRXMatcher& matchAt ( const tCIDLib::TCard4 c4At ); TRXMatcher* pmatchAt ( const tCIDLib::TCard4 c4At ); tCIDLib::TVoid PointPastEnd ( const tCIDLib::TCard4 c4At ); tCIDLib::TVoid UpdateLast ( TRXMatcher* const pmatchNew , const tCIDLib::TCard4 c4Trans ); tCIDLib::TVoid UpdateLast ( const tCIDLib::TCard4 c4Trans1 , const tCIDLib::TCard4 c4Trans2 ); tCIDLib::TVoid UpdateMatchAt ( const tCIDLib::TCard4 c4At , TRXMatcher* const pmatchNew ); tCIDLib::TVoid UpdateStateAt ( const tCIDLib::TCard4 c4At , TRXMatcher* const pmatchNew , const tCIDLib::TCard4 c4Trans ); tCIDLib::TVoid UpdateStateAt ( const tCIDLib::TCard4 c4At , const tCIDLib::TCard4 c4Trans1 , const tCIDLib::TCard4 c4Trans2 ); tCIDLib::TVoid UpdateState1At ( const tCIDLib::TCard4 c4At , const tCIDLib::TCard4 c4Trans1 ); tCIDLib::TVoid UpdateState2At ( const tCIDLib::TCard4 c4At , const tCIDLib::TCard4 c4Trans2 ); protected : // ------------------------------------------------------------------- // Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TVoid FormatTo ( TTextOutStream& strmDest ) const override; private : // -------------------------------------------------------------------- // Private, non-virtual methods // -------------------------------------------------------------------- tCIDLib::TVoid CleanupMatches(); tCIDLib::TVoid TestIndex ( const tCIDLib::TCard4 c4At , const tCIDLib::TCard4 c4Line , const tCIDLib::TCh* const pszFile ) const; // -------------------------------------------------------------------- // Private data members // // m_bNullable // When Complete is called, we see if there is path through the NFA // from start to end via epsilon nodes. If so, then this expression will // match an empty input pattern. // // m_bReady // After setting all states the client code must call Complete to finish // setup and we set this to indicate we are ready. We clear it upon // a call to Reset() which the client code uses to get us ready to start // setting up a new parsed expression. // // m_c4StateCount // The number of states in our NFA. // // m_c4Entries // The number of entries in the m_pc4StateX and m_pmatchTrans // arrays. We don't know how many statse we can have so we // allocated them to the worst case. // // m_pc4State1 // m_pc4State2 // The state transition arrays for each state in the NFA. // // m_pmatchTrans // The array of transition matchers. Each one of them is matcher // object that represents a single state's match criteria. // -------------------------------------------------------------------- tCIDLib::TBoolean m_bNullable; tCIDLib::TBoolean m_bReady; tCIDLib::TCard4 m_c4StateCount; tCIDLib::TCard4 m_c4Entries; tCIDLib::TCard4* m_pc4State1; tCIDLib::TCard4* m_pc4State2; TRXMatcher** m_pmatchTrans; // -------------------------------------------------------------------- // Magic macros // -------------------------------------------------------------------- RTTIDefs(TRegExNFA,TObject) }; #pragma CIDLIB_POPPACK
30.986622
85
0.418025
[ "object" ]
3a8f3a5f866bd448cfefa7a35e13bc4f88275ad2
115,971
cpp
C++
Engine/Source/Developer/Profiler/Private/Widgets/SEventGraph.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Developer/Profiler/Private/Widgets/SEventGraph.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Developer/Profiler/Private/Widgets/SEventGraph.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "Widgets/SEventGraph.h" #include "Widgets/Layout/SSplitter.h" #include "Containers/MapBuilder.h" #include "Widgets/SOverlay.h" #include "SlateOptMacros.h" #include "Framework/Application/SlateApplication.h" #include "Widgets/Layout/SSeparator.h" #include "Widgets/Images/SImage.h" #include "Framework/MultiBox/MultiBoxBuilder.h" #include "Widgets/Input/SButton.h" #include "Widgets/Input/SComboBox.h" #include "Widgets/Input/SComboButton.h" #include "Widgets/Input/SCheckBox.h" #include "EditorStyleSet.h" #include "Widgets/StatDragDropOp.h" #include "Widgets/SEventGraphTooltip.h" #include "Widgets/Input/SSearchBox.h" #include "HAL/PlatformApplicationMisc.h" #define LOCTEXT_NAMESPACE "SEventGraph" namespace EEventGraphViewModes { FText ToName( const Type EventGraphViewMode ) { switch( EventGraphViewMode ) { case Hierarchical: return LOCTEXT("ViewMode_Name_Hierarchical", "Hierarchical"); case FlatInclusive: return LOCTEXT("ViewMode_Name_FlatInclusive", "Inclusive"); case FlatInclusiveCoalesced: return LOCTEXT("ViewMode_Name_FlatInclusiveCoalesced", "Inclusive"); case FlatExclusive: return LOCTEXT("ViewMode_Name_FlatExclusive", "Exclusive"); case FlatExclusiveCoalesced: return LOCTEXT("ViewMode_Name_FlatExclusiveCoalesced", "Exclusive" ); case ClassAggregate: return LOCTEXT("ViewMode_Name_ClassAggregate", "ClassAggregate"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FText ToDescription( const Type EventGraphViewMode ) { switch( EventGraphViewMode ) { case Hierarchical: return LOCTEXT("ViewMode_Desc_Hierarchical", "Hierarchical tree view of the events"); case FlatInclusive: return LOCTEXT("ViewMode_Desc_Flat", "Flat list of the events, sorted by the inclusive time"); case FlatInclusiveCoalesced: return LOCTEXT("ViewMode_Desc_FlatCoalesced", "Flat list of the events coalesced by the event name, sorted by the inclusive time"); case FlatExclusive: return LOCTEXT("ViewMode_Desc_FlatExclusive", "Flat list of the events, sorted by the exclusive time"); case FlatExclusiveCoalesced: return LOCTEXT("ViewMode_Desc_FlatExclusiveCoalesced", "Flat list of the events coalesced by the event name, sorted by the exclusive time"); case ClassAggregate: return LOCTEXT("ViewMode_Desc_ClassAggregate", "ClassAggregate @TBD"); default: return LOCTEXT("InvalidOrMax", "InvalidOrMax"); } } FName ToBrushName( const Type EventGraphViewMode ) { switch( EventGraphViewMode ) { case Hierarchical: return TEXT("Profiler.EventGraph.HierarchicalIcon"); case FlatInclusive: return TEXT("Profiler.EventGraph.FlatIcon"); case FlatInclusiveCoalesced: return TEXT("Profiler.EventGraph.FlatCoalescedIcon"); case FlatExclusive: return TEXT("Profiler.EventGraph.FlatIcon"); case FlatExclusiveCoalesced: return TEXT("Profiler.EventGraph.FlatCoalescedIcon"); default: return NAME_None; } } } struct FEventGraphColumns { /** Default constructor. */ FEventGraphColumns() : NumColumns( EEventPropertyIndex::None+1 ) { // Make event property is initialized. FEventGraphSample::InitializePropertyManagement(); Collection = new FEventGraphColumn[NumColumns]; Collection[EEventPropertyIndex::StatName] = FEventGraphColumn ( EEventPropertyIndex::StatName, TEXT( "name" ), LOCTEXT( "EventNameColumnTitle", "Event Name" ), LOCTEXT( "EventNameColumnDesc", "Name of the event" ), false, true, true, false, false, HAlign_Left, 0.0f ); Collection[EEventPropertyIndex::InclusiveTimeMS] = FEventGraphColumn ( EEventPropertyIndex::InclusiveTimeMS, TEXT( "inc" ), LOCTEXT( "InclusiveTimeMSTitle", "Inc Time (MS)" ), LOCTEXT( "InclusiveTimeMSDesc", "Duration of the sample and its children, in milliseconds" ), false, true, true, true, true, HAlign_Right, 72.0f ); Collection[EEventPropertyIndex::InclusiveTimePct] = FEventGraphColumn ( EEventPropertyIndex::InclusiveTimePct, TEXT( "inc%" ), LOCTEXT( "InclusiveTimePercentageTitle", "Inc Time (%)" ), LOCTEXT( "InclusiveTimePercentageDesc", "Duration of the sample and its children as percent of the caller" ), true, true, true, false, false, HAlign_Right, 72.0f ); Collection[EEventPropertyIndex::ExclusiveTimeMS] = FEventGraphColumn ( EEventPropertyIndex::ExclusiveTimeMS, TEXT( "exc" ), LOCTEXT( "ExclusiveTimeMSTitle", "Exc Time (MS)" ), LOCTEXT( "ExclusiveTimeMSDesc", "Exclusive time of this event, in milliseconds" ), false, true, true, true, false, HAlign_Right, 72.0f ); Collection[EEventPropertyIndex::ExclusiveTimePct] = FEventGraphColumn ( EEventPropertyIndex::ExclusiveTimePct, TEXT( "exc%" ), LOCTEXT( "ExclusiveTimePercentageTitle", "Exc Time (%)" ), LOCTEXT( "ExclusiveTimePercentageDesc", "Exclusive time of this event as percent of this call's inclusive time" ), true, true, true, false, false, HAlign_Right, 72.0f ); Collection[EEventPropertyIndex::NumCallsPerFrame] = FEventGraphColumn ( EEventPropertyIndex::NumCallsPerFrame, TEXT( "calls" ), LOCTEXT( "CallsPerFrameTitle", "Calls" ), LOCTEXT( "CallsPerFrameDesc", "Number of times this event was called" ), false, true, true, true, false, HAlign_Right, 48.0f ); // Fake column used as a default column for NAME_None Collection[EEventPropertyIndex::None] = FEventGraphColumn ( EEventPropertyIndex::None, TEXT( "None" ), LOCTEXT( "None", "None" ), LOCTEXT( "None", "None" ), false, false, false, false, false, HAlign_Left, 0.0f ); ColumnNameToIndexMapping = TMapBuilder<FName, const FEventGraphColumn*>() .Add( TEXT( "StatName" ), &Collection[EEventPropertyIndex::StatName] ) .Add( TEXT( "InclusiveTimeMS" ), &Collection[EEventPropertyIndex::InclusiveTimeMS] ) .Add( TEXT( "InclusiveTimePct" ), &Collection[EEventPropertyIndex::InclusiveTimePct] ) .Add( TEXT( "ExclusiveTimeMS" ), &Collection[EEventPropertyIndex::ExclusiveTimeMS] ) .Add( TEXT( "ExclusiveTimePct" ), &Collection[EEventPropertyIndex::ExclusiveTimePct] ) .Add( TEXT( "NumCallsPerFrame" ), &Collection[EEventPropertyIndex::NumCallsPerFrame] ) .Add( NAME_None, &Collection[EEventPropertyIndex::None] ) ; } ~FEventGraphColumns() { delete[] Collection; } /** Contains basic information about columns used in the event graph widget. Names should be localized. */ FEventGraphColumn* Collection; const uint32 NumColumns; // Generated from a XLSX file. TMap<FName, const FEventGraphColumn*> ColumnNameToIndexMapping; static const FEventGraphColumns& Get() { static FEventGraphColumns Instance; return Instance; } }; /*----------------------------------------------------------------------------- SEventTreeItem -----------------------------------------------------------------------------*/ DECLARE_DELEGATE_TwoParams( FSetHoveredTableCell, const FName /*ColumnID*/, const FEventGraphSamplePtr /*SamplePtr*/ ); DECLARE_DELEGATE_RetVal_OneParam( bool, FIsColumnVisibleDelegate, const FName /*ColumnID*/ ); DECLARE_DELEGATE_RetVal_OneParam( EHorizontalAlignment, FGetColumnOutlineHAlignmentDelegate, const FName /*ColumnID*/ ); class SEventGraphTableCell : public SCompoundWidget { public: SLATE_BEGIN_ARGS( SEventGraphTableCell ){} SLATE_EVENT( FSetHoveredTableCell, OnSetHoveredTableCell ) SLATE_ARGUMENT( FEventGraphSamplePtr, EventPtr ) SLATE_ARGUMENT( FName, ColumnID ) SLATE_ARGUMENT( bool, IsEventNameColumn ) SLATE_END_ARGS() /** * Construct this widget. * * @param InArgs - the declaration data for this widget. */ void Construct( const FArguments& InArgs, const TSharedRef<class ITableRow>& TableRow, const TWeakPtr<IEventGraph>& InOwnerEventGraph ) { SetHoveredTableCellDelegate = InArgs._OnSetHoveredTableCell; EventPtr = InArgs._EventPtr; OwnerEventGraph = InOwnerEventGraph; ColumnID = InArgs._ColumnID; ChildSlot [ GenerateWidgetForColumnID( ColumnID, InArgs._IsEventNameColumn, TableRow ) ]; } protected: BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION TSharedRef<SWidget> GenerateWidgetForColumnID( const FName& InColumnID, const bool bIsEventNameColumn, const TSharedRef<class ITableRow>& TableRow ) { const FEventGraphColumn& Column = *FEventGraphColumns::Get().ColumnNameToIndexMapping.FindChecked( InColumnID ); if( bIsEventNameColumn ) { return SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Right) .VAlign(VAlign_Center) [ SNew( SExpanderArrow, TableRow ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SImage ) .Visibility( this, &SEventGraphTableCell::GetHotPathIconVisibility ) .Image( FEditorStyle::GetBrush(TEXT("Profiler.EventGraph.HotPathSmall")) ) ] +SHorizontalBox::Slot() .AutoWidth() .VAlign( VAlign_Center ) .HAlign( Column.HorizontalAlignment ) .Padding( FMargin( 2.0f, 0.0f ) ) [ SNew( STextBlock ) .Text( FText::FromName(EventPtr->_StatName) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .ColorAndOpacity( this, &SEventGraphTableCell::GetColorAndOpacity ) .ShadowColorAndOpacity( this, &SEventGraphTableCell::GetShadowColorAndOpacity ) ] +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SButton ) .ButtonStyle( FEditorStyle::Get(), TEXT("HoverHintOnly") ) .ContentPadding( 0.0f ) .IsFocusable( false ) .OnClicked( this, &SEventGraphTableCell::ExpandCulledEvents_OnClicked ) [ SNew( SImage ) .Visibility( this, &SEventGraphTableCell::GetCulledEventsIconVisibility ) .Image( FEditorStyle::GetBrush("Profiler.EventGraph.HasCulledEventsSmall") ) .ToolTipText( LOCTEXT("HasCulledEvents_TT","This event contains culled children, if you want to see all children, please disable culling or use function details, or press this icon") ) ] ] +SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SImage ) .Visibility( this, &SEventGraphTableCell::GetHintIconVisibility ) .Image( FEditorStyle::GetBrush("Profiler.Tooltip.HintIcon10") ) .ToolTip( SEventGraphTooltip::GetTableCellTooltip( EventPtr ) ) ]; } else { const FString FormattedValue = EventPtr->GetFormattedValue( Column.Index ); return SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth( 1.0f ) .VAlign( VAlign_Center ) .HAlign( Column.HorizontalAlignment ) .Padding( FMargin( 2.0f, 0.0f ) ) [ SNew( STextBlock ) .Text( FText::FromString(FormattedValue) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) .ColorAndOpacity( this, &SEventGraphTableCell::GetColorAndOpacity ) .ShadowColorAndOpacity( this, &SEventGraphTableCell::GetShadowColorAndOpacity ) ]; } } END_SLATE_FUNCTION_BUILD_OPTIMIZATION /** * The system will use this event to notify a widget that the cursor has entered it. This event is NOT bubbled. * * @param MyGeometry The Geometry of the widget receiving the event * @param MouseEvent Information about the input event */ virtual void OnMouseEnter( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent ) override { SCompoundWidget::OnMouseEnter( MyGeometry, MouseEvent ); SetHoveredTableCellDelegate.ExecuteIfBound( ColumnID, EventPtr ); } /** * The system will use this event to notify a widget that the cursor has left it. This event is NOT bubbled. * * @param MouseEvent Information about the input event */ virtual void OnMouseLeave( const FPointerEvent& MouseEvent ) override { SCompoundWidget::OnMouseLeave( MouseEvent ); SetHoveredTableCellDelegate.ExecuteIfBound( NAME_None, nullptr ); } /** * Called during drag and drop when the drag enters a widget. * * Enter/Leave events in slate are meant as lightweight notifications. * So we do not want to capture mouse or set focus in response to these. * However, OnDragEnter must also support external APIs (e.g. OLE Drag/Drop) * Those require that we let them know whether we can handle the content * being dragged OnDragEnter. * * The concession is to return a can_handled/cannot_handle * boolean rather than a full FReply. * * @param MyGeometry The geometry of the widget receiving the event. * @param DragDropEvent The drag and drop event. * * @return A reply that indicated whether the contents of the DragDropEvent can potentially be processed by this widget. */ virtual void OnDragEnter( const FGeometry& MyGeometry, const FDragDropEvent& DragDropEvent ) override { SCompoundWidget::OnDragEnter( MyGeometry, DragDropEvent ); SetHoveredTableCellDelegate.ExecuteIfBound( ColumnID, EventPtr ); } /** * Called during drag and drop when the drag leaves a widget. * * @param DragDropEvent The drag and drop event. */ virtual void OnDragLeave( const FDragDropEvent& DragDropEvent ) override { SCompoundWidget::OnDragLeave( DragDropEvent ); SetHoveredTableCellDelegate.ExecuteIfBound( NAME_None, nullptr ); } EVisibility GetHotPathIconVisibility() const { const bool bIsHotPathIconVisible = EventPtr->_bIsHotPath; return bIsHotPathIconVisible ? EVisibility::Visible : EVisibility::Collapsed; } EVisibility GetHintIconVisibility() const { return IsHovered() ? EVisibility::Visible : EVisibility::Hidden; } EVisibility GetCulledEventsIconVisibility() const { return EventPtr->HasCulledChildren() ? EVisibility::Visible : EVisibility::Collapsed; } FSlateColor GetColorAndOpacity() const { const FLinearColor TextColor = EventPtr->_bIsFiltered ? FLinearColor(1.0f,1.0f,1.0f,0.5f) : FLinearColor::White; return TextColor; } FLinearColor GetShadowColorAndOpacity() const { const FLinearColor ShadowColor = EventPtr->_bIsFiltered ? FLinearColor(0.f,0.f,0.f,0.25f) : FLinearColor(0.f,0.f,0.f,0.5f); return ShadowColor; } FReply ExpandCulledEvents_OnClicked() { OwnerEventGraph.Pin()->ExpandCulledEvents( EventPtr ); return FReply::Handled(); } protected: FSetHoveredTableCell SetHoveredTableCellDelegate; /** A shared pointer to the event graph sample. */ FEventGraphSamplePtr EventPtr; /** The event graph that owns this event graph cell. */ TWeakPtr< IEventGraph > OwnerEventGraph; /** The ID of the column where this event graph belongs. */ FName ColumnID; }; /** Widget that represents a table row in the event graph widget. Generates widgets for each column on demand. */ class SEventGraphTableRow : public SMultiColumnTableRow< FEventGraphSamplePtr > { public: SLATE_BEGIN_ARGS( SEventGraphTableRow ){} SLATE_EVENT( FIsColumnVisibleDelegate, OnIsColumnVisible ) SLATE_EVENT( FSetHoveredTableCell, OnSetHoveredTableCell ) SLATE_EVENT( FGetColumnOutlineHAlignmentDelegate, OnGetColumnOutlineHAlignmentDelegate ) SLATE_ATTRIBUTE( FName, HighlightedEventName ) SLATE_ARGUMENT( FEventGraphSamplePtr, EventPtr ) SLATE_END_ARGS() /** * Construct this widget. Called by the SNew() Slate macro. * * @param InArgs - Declaration used by the SNew() macro to construct this widget. * @param InOwnerTableView - The owner table into which this row is being placed. */ void Construct( const FArguments& InArgs, const TSharedRef<STableViewBase>& InOwnerTableView, const TSharedRef<IEventGraph>& InOwnerEventGraph ) { IsColumnVisibleDelegate = InArgs._OnIsColumnVisible; SetHoveredTableCellDelegate = InArgs._OnSetHoveredTableCell; GetColumnOutlineHAlignmentDelegate = InArgs._OnGetColumnOutlineHAlignmentDelegate; HighlightedEventName = InArgs._HighlightedEventName; EventPtr = InArgs._EventPtr; OwnerEventGraph = InOwnerEventGraph; SMultiColumnTableRow< FEventGraphSamplePtr >::Construct( SMultiColumnTableRow< FEventGraphSamplePtr >::FArguments(), InOwnerTableView ); } /** * Users of SMultiColumnTableRow would usually some piece of data associated with it. * The type of this data is ItemType; it's the stuff that your TableView (i.e. List or Tree) is visualizing. * The ColumnID tells you which column of the TableView we need to make a widget for. * Make a widget and return it. * * @param ColumnID A unique ID for a column in this TableView; see SHeaderRow::FColumn for more info. * * @return a widget to represent the contents of a cell in this row of a TableView. */ BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION virtual TSharedRef<SWidget> GenerateWidgetForColumn( const FName& ColumnID ) override { return SNew(SOverlay) .Visibility( EVisibility::SelfHitTestInvisible ) +SOverlay::Slot() .Padding( 0.0f ) [ SNew( SImage ) .Image( FEditorStyle::GetBrush("Profiler.LineGraphArea") ) .ColorAndOpacity( this, &SEventGraphTableRow::GetBackgroundColorAndOpacity ) ] +SOverlay::Slot() .Padding( 0.0f ) [ SNew( SImage ) .Image( this, &SEventGraphTableRow::GetOutlineBrush, ColumnID ) .ColorAndOpacity( this, &SEventGraphTableRow::GetOutlineColorAndOpacity ) ] +SOverlay::Slot() [ SNew( SEventGraphTableCell, SharedThis(this), OwnerEventGraph ) .Visibility( this, &SEventGraphTableRow::IsColumnVisible, ColumnID ) .ColumnID( ColumnID ) .IsEventNameColumn( ColumnID == FEventGraphColumns::Get().Collection[EEventPropertyIndex::StatName].ID ) .EventPtr( EventPtr ) .OnSetHoveredTableCell( this, &SEventGraphTableRow::OnSetHoveredTableCell ) ]; } END_SLATE_FUNCTION_BUILD_OPTIMIZATION /** * Called when Slate detects that a widget started to be dragged. * Usage: * A widget can ask Slate to detect a drag. * OnMouseDown() reply with FReply::Handled().DetectDrag( SharedThis(this) ). * Slate will either send an OnDragDetected() event or do nothing. * If the user releases a mouse button or leaves the widget before * a drag is triggered (maybe user started at the very edge) then no event will be * sent. * * @param InMyGeometry Widget geometry * @param InMouseEvent MouseMove that triggered the drag * */ virtual FReply OnDragDetected( const FGeometry& MyGeometry, const FPointerEvent& MouseEvent ) override { if( MouseEvent.IsMouseButtonDown( EKeys::LeftMouseButton ) ) { return FReply::Handled().BeginDragDrop( FStatIDDragDropOp::NewSingle( EventPtr->_StatID, EventPtr->_StatName.GetPlainNameString() ) ); } return SMultiColumnTableRow< FEventGraphSamplePtr >::OnDragDetected(MyGeometry,MouseEvent); } protected: FSlateColor GetBackgroundColorAndOpacity() const { const FLinearColor ThreadColor(5.0f,0.0f,0.0f,1.0f); const FLinearColor DefaultColor(0.0f,0.0f,0.0f,0.0f); const float Alpha = EventPtr->_FramePct * 0.01f; const FLinearColor BackgroundColorAndOpacity = FMath::Lerp(DefaultColor,ThreadColor,Alpha); return BackgroundColorAndOpacity; } FSlateColor GetOutlineColorAndOpacity() const { const FLinearColor NoColor(0.0f,0.0f,0.0f,0.0f); const bool bShouldBeHighlighted = EventPtr->_StatName == HighlightedEventName.Get(); const FLinearColor OutlineColorAndOpacity = bShouldBeHighlighted ? FLinearColor(FColorList::SlateBlue) : NoColor; return OutlineColorAndOpacity; } const FSlateBrush* GetOutlineBrush( const FName ColumnID ) const { EHorizontalAlignment Result = HAlign_Center; if( IsColumnVisibleDelegate.IsBound() ) { Result = GetColumnOutlineHAlignmentDelegate.Execute( ColumnID ); } const FSlateBrush* Brush = nullptr; if( Result == HAlign_Left ) { Brush = FEditorStyle::GetBrush("Profiler.EventGraph.Border.L"); } else if( Result == HAlign_Right ) { Brush = FEditorStyle::GetBrush("Profiler.EventGraph.Border.R"); } else { Brush = FEditorStyle::GetBrush("Profiler.EventGraph.Border.TB"); } return Brush; } EVisibility IsColumnVisible( const FName ColumnID ) const { EVisibility Result = EVisibility::Collapsed; if( IsColumnVisibleDelegate.IsBound() ) { Result = IsColumnVisibleDelegate.Execute( ColumnID ) ? EVisibility::Visible : EVisibility::Collapsed; } return Result; } void OnSetHoveredTableCell( const FName InColumnID, const FEventGraphSamplePtr InSamplePtr ) { SetHoveredTableCellDelegate.ExecuteIfBound( InColumnID, InSamplePtr ); } protected: FIsColumnVisibleDelegate IsColumnVisibleDelegate; FSetHoveredTableCell SetHoveredTableCellDelegate; FGetColumnOutlineHAlignmentDelegate GetColumnOutlineHAlignmentDelegate; /** Name of the event that should be drawn as highlighted. */ TAttribute<FName> HighlightedEventName; /** A shared pointer to the event graph sample. */ FEventGraphSamplePtr EventPtr; /** The event graph that owns this event graph row. */ TWeakPtr< IEventGraph > OwnerEventGraph; }; /*----------------------------------------------------------------------------- SEventTree -----------------------------------------------------------------------------*/ SEventGraph::SEventGraph() : CurrentStateIndex( 0 ) {} SEventGraph::~SEventGraph() { // Remove ourselves from the profiler manager. if( FProfilerManager::Get().IsValid() ) { FProfilerManager::Get()->OnViewModeChanged().RemoveAll( this ); } } /*----------------------------------------------------------------------------- Event graph construction related functions -----------------------------------------------------------------------------*/ BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void SEventGraph::Construct( const FArguments& InArgs ) { static TArray<FEventGraphSamplePtr> StaticEventArray; SAssignNew(ExternalScrollbar, SScrollBar) .AlwaysShowScrollbar(true); ChildSlot [ SNew(SSplitter) .Orientation(Orient_Vertical) + SSplitter::Slot() .Value(0.5f) [ SNew(SVerticalBox) + SVerticalBox::Slot() .AutoHeight() [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) .Padding(2.0f) [ SNew(SVerticalBox) + SVerticalBox::Slot() [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .AutoWidth() [ GetWidgetForEventGraphTypes() ] + SHorizontalBox::Slot() .AutoWidth() .Padding(2.0f, 0.0f, 0.0f, 0.0f) [ GetWidgetForEventGraphViewModes() ] + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f, 0.0f, 0.0f, 0.0f) [ GetWidgetBoxForOptions() ] ] + SVerticalBox::Slot() .Padding(0.0f, 2.0f, 0.0f, 0.0f) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() .FillWidth(1.0f) [ GetWidgetForThreadFilter() ] ] ] ] // Function details view ( @see VS2012 profiler ) + SVerticalBox::Slot() .FillHeight(1.0f) .Padding(0.0f, 2.0f, 0.0f, 0.0f) [ SAssignNew(FunctionDetailsBox,SBox) .HeightOverride(224.0f) [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) .Padding(2.0f) .Clipping(EWidgetClipping::ClipToBounds) [ SNew(SHorizontalBox) // Calling Functions + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f) [ GetVerticalBoxForFunctionDetails(VerticalBox_TopCalling, LOCTEXT("FunctionDetails_CallingFunctions","Calling Functions")) ] // Current Function + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f) [ GetVerticalBoxForCurrentFunction() ] // Called Functions + SHorizontalBox::Slot() .FillWidth(1.0f) .Padding(2.0f) [ GetVerticalBoxForFunctionDetails( VerticalBox_TopCalled, LOCTEXT("FunctionDetails_CalledFunctions","Called Functions") ) ] ] ] ] ] + SSplitter::Slot() .Value(0.5f) [ SNew(SBorder) .BorderImage( FEditorStyle::GetBrush("ToolPanel.GroupBorder") ) .Padding(0.0f) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .FillWidth(1.0f) [ SNew(SHorizontalBox) + SHorizontalBox::Slot() [ SAssignNew(TreeView_Base, STreeView<FEventGraphSamplePtr>) .ExternalScrollbar(ExternalScrollbar) .SelectionMode(ESelectionMode::Multi) .TreeItemsSource(&StaticEventArray) .OnGetChildren(this, &SEventGraph::EventGraph_OnGetChildren) .OnGenerateRow(this, &SEventGraph::EventGraph_OnGenerateRow) .OnSelectionChanged(this, &SEventGraph::EventGraph_OnSelectionChanged) .OnContextMenuOpening(FOnContextMenuOpening::CreateSP(this, &SEventGraph::EventGraph_GetMenuContent)) .ItemHeight(12.0f) .HeaderRow ( SAssignNew(TreeViewHeaderRow,SHeaderRow) .Visibility(EVisibility::Visible) ) ] ] + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(FOptionalSize(16.0f)) [ ExternalScrollbar.ToSharedRef() ] ] ] ] ]; InitializeAndShowHeaderColumns(); BindCommands(); FProfilerManager::Get()->OnViewModeChanged().AddSP( this, &SEventGraph::ProfilerManager_OnViewModeChanged ); } TSharedRef<SWidget> SEventGraph::GetToggleButtonForEventGraphType( const EEventGraphTypes::Type EventGraphType, const FName BrushName ) { TSharedRef<SHorizontalBox> ButtonContent = SNew(SHorizontalBox); if( BrushName != NAME_None ) { ButtonContent->AddSlot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) [ SNew(SImage) .Image( FEditorStyle::GetBrush( BrushName ) ) ]; } ButtonContent->AddSlot() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) [ SNew( STextBlock ) .Text( FText::FromString(EEventGraphTypes::ToName( EventGraphType )) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Caption") ) ]; return SNew( SCheckBox ) .Style(FEditorStyle::Get(), "ToggleButtonCheckbox") .IsEnabled( this, &SEventGraph::EventGraphType_IsEnabled, EventGraphType ) .HAlign( HAlign_Center ) .Padding( 2.0f ) .OnCheckStateChanged( this, &SEventGraph::EventGraphType_OnCheckStateChanged, EventGraphType ) .IsChecked( this, &SEventGraph::EventGraphType_IsChecked, EventGraphType ) .ToolTipText( FText::FromString(EEventGraphTypes::ToDescription( EventGraphType )) ) [ ButtonContent ]; } TSharedRef<SWidget> SEventGraph::GetToggleButtonForEventGraphViewMode( const EEventGraphViewModes::Type EventGraphViewMode ) { return SNew( SCheckBox ) .Style(FEditorStyle::Get(), "ToggleButtonCheckbox") .IsEnabled( this, &SEventGraph::EventGraph_IsEnabled ) .HAlign( HAlign_Center ) .Padding( 2.0f ) .OnCheckStateChanged( this, &SEventGraph::EventGraphViewMode_OnCheckStateChanged, EventGraphViewMode ) .IsChecked( this, &SEventGraph::EventGraphViewMode_IsChecked, EventGraphViewMode ) .ToolTipText( EEventGraphViewModes::ToDescription( EventGraphViewMode ) ) .Visibility( this, &SEventGraph::EventGraphViewMode_GetVisibility, EventGraphViewMode ) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) [ SNew(SImage) .Image( FEditorStyle::GetBrush( EEventGraphViewModes::ToBrushName( EventGraphViewMode ) ) ) ] +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) [ SNew( STextBlock ) .Text( EEventGraphViewModes::ToName( EventGraphViewMode ) ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Caption") ) ] ]; } TSharedRef<SWidget> SEventGraph::GetWidgetForEventGraphTypes() { return SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("Profiler.Group.16") ) .Padding(FMargin(2.0f, 0.0)) [ SNew( SHorizontalBox ) // EventGraph - Type +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .AutoWidth() .Padding( 2.0f ) [ SNew(STextBlock) .Text( LOCTEXT("Toolbar_Type","Type") ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.CaptionBold") ) ] // One-frame +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphType( EEventGraphTypes::OneFrame, NAME_None ) ] // Avg +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphType( EEventGraphTypes::Average, TEXT("Profiler.EventGraph.AverageIcon") ) ] // Max +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphType( EEventGraphTypes::Maximum, TEXT("Profiler.EventGraph.MaximumIcon") ) ] ]; } TSharedRef<SWidget> SEventGraph::GetWidgetForEventGraphViewModes() { return SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("Profiler.Group.16") ) .Padding(FMargin(2.0f, 0.0)) [ SNew( SHorizontalBox ) // View mode - Type +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .AutoWidth() .Padding( 2.0f ) [ SNew(STextBlock) .Text( LOCTEXT("Toolbar_ViewMode","View mode") ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.CaptionBold") ) ] // View mode - Hierarchical +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphViewMode( EEventGraphViewModes::Hierarchical ) ] // View mode - Flat (Inclusive) +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphViewMode( EEventGraphViewModes::FlatInclusive ) ] // View mode - Flat Coalesced (Inclusive) +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .Padding( 2.0f ) [ GetToggleButtonForEventGraphViewMode( EEventGraphViewModes::FlatInclusiveCoalesced ) ] // View mode - Flat (Exclusive) +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 1.0f ) [ GetToggleButtonForEventGraphViewMode( EEventGraphViewModes::FlatExclusive ) ] // View mode - Flat Coalesced (Exclusive) +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ GetToggleButtonForEventGraphViewMode( EEventGraphViewModes::FlatExclusiveCoalesced ) ] ]; } TSharedRef<SWidget> SEventGraph::GetWidgetForThreadFilter() { return SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("Profiler.Group.16")) .Padding(FMargin(2.0f, 0.0)) [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .AutoWidth() .Padding( 2.0f ) [ SNew ( STextBlock ) .Text( LOCTEXT( "Toolbar_Thread", "Thread" ) ) .TextStyle( FEditorStyle::Get(), TEXT( "Profiler.CaptionBold" ) ) ] +SHorizontalBox::Slot() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .AutoWidth() .Padding( 2.0f ) [ SAssignNew( ThreadFilterComboBox, SComboBox<TSharedPtr<FName>> ) .ContentPadding( FMargin( 6.0f, 2.0f ) ) .OptionsSource( &ThreadNamesForCombo ) .OnSelectionChanged( this, &SEventGraph::OnThreadFilterChanged ) .OnGenerateWidget( this, &SEventGraph::OnGenerateWidgetForThreadFilter ) [ SNew( STextBlock ) .Text( this, &SEventGraph::GenerateTextForThreadFilter, FName( TEXT( "SelectedThreadName" ) ) ) ] ] ]; } void SEventGraph::FillThreadFilterOptions() { ThreadNamesForCombo.Empty(); // Allow None as an option ThreadNamesForCombo.Add(MakeShareable(new FName())); if ( EventGraphStatesHistory.Num() == 0 ) { return; } FEventGraphSamplePtr Root = GetCurrentState()->GetRoot(); if ( !Root.IsValid() ) { return; } // Add a thread filter entry for each root child for ( const FEventGraphSamplePtr Child : Root->GetChildren() ) { ThreadNamesForCombo.Add( MakeShareable( new FName( Child->_ThreadName ) ) ); } // Sort the thread names alphabetically ThreadNamesForCombo.Sort([]( const TSharedPtr<FName> Lhs, const TSharedPtr<FName> Rhs ) { return Lhs->IsNone() || ( !Rhs->IsNone() && *Lhs < *Rhs ); }); // Refresh the combo box if ( ThreadFilterComboBox.IsValid() ) { ThreadFilterComboBox->RefreshOptions(); } } FText SEventGraph::GenerateTextForThreadFilter( FName ThreadName ) const { static const FName SelectedThreadName( TEXT( "SelectedThreadName" ) ); if ( ThreadName == SelectedThreadName ) { if ( EventGraphStatesHistory.Num() > 0 ) { ThreadName = GetCurrentState()->ThreadFilter; } else { ThreadName = NAME_None; } } return FText::FromName( ThreadName ); } void SEventGraph::OnThreadFilterChanged( TSharedPtr<FName> NewThread, ESelectInfo::Type SelectionType ) { if ( NewThread.IsValid() ) { GetCurrentState()->ThreadFilter = *NewThread; RestoreEventGraphStateFrom( GetCurrentState() ); GetCurrentState()->GetRoot()->SetBooleanStateForAllChildren<EEventPropertyIndex::bNeedNotCulledChildrenUpdate>(true); } } TSharedRef<SWidget> SEventGraph::OnGenerateWidgetForThreadFilter( TSharedPtr<FName> ThreadName ) const { return SNew( STextBlock ) .Text( GenerateTextForThreadFilter( ThreadName.IsValid() ? *ThreadName : NAME_None ) ); } TSharedRef<SWidget> SEventGraph::GetWidgetBoxForOptions() { return SNew( SBorder ) .BorderImage( FEditorStyle::GetBrush("Profiler.Group.16") ) .Padding( 0.0f ) [ SNew(SHorizontalBox) // History Back +SHorizontalBox::Slot() .AutoWidth() .Padding( 1.0f ) [ SNew( SButton ) .OnClicked( this, &SEventGraph::HistoryBack_OnClicked ) .IsEnabled( this, &SEventGraph::HistoryBack_IsEnabled ) .ToolTipText( this, &SEventGraph::HistoryBack_GetToolTipText ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .ContentPadding( 2.0f ) [ SNew(SImage) .Image( FEditorStyle::GetBrush("Profiler.EventGraph.HistoryBack") ) ] ] // History Forward +SHorizontalBox::Slot() .AutoWidth() .Padding( 1.0f ) [ SNew( SButton ) .OnClicked( this, &SEventGraph::HistoryForward_OnClicked ) .IsEnabled( this, &SEventGraph::HistoryForward_IsEnabled ) .ToolTipText( this, &SEventGraph::HistoryForward_GetToolTipText ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .ContentPadding( 2.0f ) [ SNew(SImage) .Image( FEditorStyle::GetBrush("Profiler.EventGraph.HistoryForward") ) ] ] // History List +SHorizontalBox::Slot() .AutoWidth() .Padding( 1.0f ) [ SNew( SComboButton ) .IsEnabled( this, &SEventGraph::HistoryList_IsEnabled ) .ContentPadding( 0.0f ) .OnGetMenuContent( this, &SEventGraph::HistoryList_GetMenuContent ) ] // Expand hot path +SHorizontalBox::Slot() .AutoWidth() .Padding( 1.0f ) [ SNew( SButton ) .IsEnabled( this, &SEventGraph::ContextMenu_ExpandHotPath_CanExecute ) .ToolTipText( LOCTEXT("ContextMenu_Header_Expand_ExpandHotPath_Desc", "Expands hot path for the selected events, based on the inclusive time, also enables descending sorting by inclusive time") ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .OnClicked( this, &SEventGraph::ExpandHotPath_OnClicked ) [ SNew( SImage ) .Image( FEditorStyle::GetBrush(TEXT("Profiler.EventGraph.ExpandHotPath16")) ) ] ] // Highlight hot path +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .Padding( 1.0f ) [ SNew( SCheckBox ) .Visibility( EVisibility::Collapsed ) .IsEnabled( false ) .OnCheckStateChanged( this, &SEventGraph::HighlightHotPath_OnCheckStateChanged ) [ SNew( STextBlock ) .Text( LOCTEXT("HighlightHotPathCheckboxLabel", "HP") ) ] ] // Configuration +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .Padding( 1.0f ) [ SNew( SButton ) .Visibility( EVisibility::Collapsed ) .IsEnabled( false ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Text( LOCTEXT("ConfigurationButtonLabel", "CF") ) ] // Export +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .Padding( 1.0f ) [ SNew( SButton ) .Visibility( EVisibility::Collapsed ) .IsEnabled( false ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Text( LOCTEXT("ExportButtonLabel", "EX") ) ] // Search box +SHorizontalBox::Slot() .FillWidth( 1.0f ) .HAlign( HAlign_Fill ) .VAlign( VAlign_Center ) .Padding( 1.0f ) [ SAssignNew( FilteringSearchBox, SSearchBox ) .HintText( LOCTEXT("FilteringSearchBox_HintText", "Search or filter event(s)") ) .OnTextChanged( this, &SEventGraph::FilteringSearchBox_OnTextChanged ) .OnTextCommitted( this, &SEventGraph::FilteringSearchBox_OnTextCommitted ) .IsEnabled( this, &SEventGraph::FilteringSearchBox_IsEnabled ) .ToolTipText( LOCTEXT("FilteringSearchBox_TT", "Type here to search or filter events") ) ] // Aggressive filtering + SHorizontalBox::Slot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Fill) .Padding(1.0f) [ SNew(SCheckBox) .Visibility(EVisibility::Visible) .IsEnabled(true) .OnCheckStateChanged(this, &SEventGraph::OnAggressiveFilteringToggled) [ SNew(STextBlock) .Text( LOCTEXT("AggressiveFilteringLabel", "AF") ) .ToolTipText(LOCTEXT("AggressiveFiltering_TT", "Toggle aggressive filtering")) ] ] // Filtering help +SHorizontalBox::Slot() .AutoWidth() .HAlign( HAlign_Center ) .VAlign( VAlign_Fill ) .Padding( 1.0f ) [ SNew( SButton ) .Visibility( EVisibility::Collapsed ) .IsEnabled( false ) .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Text( LOCTEXT("FilteringHelpButtonLabel", "?") ) ] ]; } TSharedRef<SVerticalBox> SEventGraph::GetVerticalBoxForFunctionDetails( TSharedPtr<SVerticalBox>& out_VerticalBoxTopFuncions, const FText& Caption ) { return SNew(SVerticalBox) +SVerticalBox::Slot() .AutoHeight() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Padding( 2.0f ) [ SNew(STextBlock) .Text( Caption ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.CaptionBold") ) ] +SVerticalBox::Slot() .AutoHeight() .HAlign( HAlign_Fill ) .VAlign( VAlign_Center ) .Padding( 2.0f ) [ SNew(SSeparator) .Orientation( Orient_Horizontal ) ] +SVerticalBox::Slot() .FillHeight( 1.0f ) .HAlign( HAlign_Fill ) .VAlign( VAlign_Fill ) .Padding( 0.0f ) [ SAssignNew(out_VerticalBoxTopFuncions,SVerticalBox) ]; } TSharedRef<SVerticalBox> SEventGraph::GetVerticalBoxForCurrentFunction() { return SNew(SVerticalBox) +SVerticalBox::Slot() .AutoHeight() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Padding( 2.0f ) [ SNew(STextBlock) .Text( LOCTEXT("FunctionDetails_CurrentFunction","Current Function") ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.CaptionBold") ) ] +SVerticalBox::Slot() .AutoHeight() .HAlign( HAlign_Fill ) .VAlign( VAlign_Center ) .Padding( 2.0f ) [ SNew(SSeparator) .Orientation( Orient_Horizontal ) ] +SVerticalBox::Slot() .AutoHeight() .HAlign( HAlign_Center ) .VAlign( VAlign_Center ) .Padding( 2.0f ) .Expose( CurrentFunctionDescSlot ); } END_SLATE_FUNCTION_BUILD_OPTIMIZATION /*----------------------------------------------------------------------------- ... -----------------------------------------------------------------------------*/ TSharedRef< ITableRow > SEventGraph::EventGraph_OnGenerateRow( FEventGraphSamplePtr EventPtr, const TSharedRef<STableViewBase>& OwnerTable ) { TSharedRef< ITableRow > ReturnRow = SNew(SEventGraphTableRow, OwnerTable, SharedThis(this)) .OnIsColumnVisible( this, &SEventGraph::EventGraphTableRow_IsColumnVisible ) .OnSetHoveredTableCell( this, &SEventGraph::EventGraphTableRow_SetHoveredTableCell ) .OnGetColumnOutlineHAlignmentDelegate( this, &SEventGraph::EventGraphRow_GetColumnOutlineHAlignment ) .HighlightedEventName( this, &SEventGraph::EventGraphRow_GetHighlightedEventName ) .EventPtr( EventPtr ) ; return ReturnRow; } void SEventGraph::EventGraph_OnSelectionChanged( FEventGraphSamplePtr SelectedItem, ESelectInfo::Type SelectInfo ) { if( SelectInfo != ESelectInfo::Direct ) { UpdateFunctionDetails(); } } bool SEventGraph::EventGraphTableRow_IsColumnVisible( const FName ColumnID ) const { bool bResult = false; const FEventGraphColumn& ColumnPtr = TreeViewHeaderColumns.FindChecked(ColumnID); return ColumnPtr.bIsVisible; } void SEventGraph::EventGraphTableRow_SetHoveredTableCell( const FName ColumnID, const FEventGraphSamplePtr EventPtr ) { HoveredColumnID = ColumnID; const bool bIsAnyMenusVisible = FSlateApplication::Get().AnyMenusVisible(); if( !HasMouseCapture() && !bIsAnyMenusVisible ) { HoveredSamplePtr = EventPtr; } #if DEBUG_PROFILER_PERFORMANCE UE_LOG( Profiler, Log, TEXT("%s -> %s"), *HoveredColumnID.GetPlainNameString(), EventPtr.IsValid() ? *EventPtr->_StatName.GetPlainNameString() : TEXT("nullptr") ); #endif // DEBUG_PROFILER_PERFORMANCE } FName SEventGraph::EventGraphRow_GetHighlightedEventName() const { return HighlightedEventName; } EHorizontalAlignment SEventGraph::EventGraphRow_GetColumnOutlineHAlignment( const FName ColumnID ) const { const TIndirectArray<SHeaderRow::FColumn>& Columns = TreeViewHeaderRow->GetColumns(); const int32 LastColumnIdx = Columns.Num()-1; // First column if( Columns[0].ColumnId == ColumnID ) { return HAlign_Left; } // Last column else if( Columns[LastColumnIdx].ColumnId == ColumnID ) { return HAlign_Right; } // Middle columns { return HAlign_Center; } } void SEventGraph::EventGraph_OnGetChildren( FEventGraphSamplePtr InParent, TArray< FEventGraphSamplePtr >& out_Children ) { if( GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical ) { out_Children = InParent->GetNotCulledChildren(); } } void SEventGraph::TreeView_SetItemsExpansion_Recurrent( TArray<FEventGraphSamplePtr>& InEventPtrs, const bool bShouldExpand ) { for( int32 EventIndex = 0; EventIndex < InEventPtrs.Num(); EventIndex++ ) { const FEventGraphSamplePtr EventPtr = InEventPtrs[EventIndex]; TreeView_Base->SetItemExpansion( EventPtr, bShouldExpand ); TreeView_SetItemsExpansion_Recurrent( EventPtr->GetChildren(), bShouldExpand ); } } void SEventGraph::SetSortModeForColumn( const FName& ColumnID, const EColumnSortMode::Type SortMode ) { ColumnBeingSorted = ColumnID; ColumnSortMode = SortMode; SortEvents(); } /*----------------------------------------------------------------------------- ShowSelectedEventsInViewMode -----------------------------------------------------------------------------*/ void SEventGraph::ShowSelectedEventsInViewMode_Execute( EEventGraphViewModes::Type NewViewMode ) { const TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); ShowEventsInViewMode( SelectedEvents, NewViewMode ); } bool SEventGraph::ShowSelectedEventsInViewMode_CanExecute( EEventGraphViewModes::Type NewViewMode ) const { return TreeView_Base->GetNumItemsSelected() > 0; } ECheckBoxState SEventGraph::ShowSelectedEventsInViewMode_GetCheckState( EEventGraphViewModes::Type NewViewMode ) const { return GetCurrentStateViewMode() == NewViewMode ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } static EEventCompareOps::Type EColumnSortModeToEventCompareOp( const EColumnSortMode::Type ColumnSortMode ) { if( ColumnSortMode == EColumnSortMode::Descending ) { return EEventCompareOps::Greater; } else if( ColumnSortMode == EColumnSortMode::Ascending ) { return EEventCompareOps::Less; } check( 0 ); return EEventCompareOps::InvalidOrMax; } void SEventGraph::SortEvents() { PROFILER_SCOPE_LOG_TIME( TEXT( "SEventGraph::SortEvents" ), nullptr ); if( ColumnBeingSorted != NAME_None ) { const FEventGraphColumn& Column = *FEventGraphColumns::Get().ColumnNameToIndexMapping.FindChecked( ColumnBeingSorted ); if( GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical || GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusive || GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusiveCoalesced || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusive || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusiveCoalesced ) { FEventArraySorter::Sort( GetCurrentState()->GetRealRoot()->GetChildren(), Column.ID, EColumnSortModeToEventCompareOp( ColumnSortMode ) ); FEventArraySorter::Sort( Events_FlatCoalesced, Column.ID, EColumnSortModeToEventCompareOp( ColumnSortMode ) ); FEventArraySorter::Sort( Events_Flat, Column.ID, EColumnSortModeToEventCompareOp( ColumnSortMode ) ); // Update not culled children. GetCurrentState()->GetRoot()->SetBooleanStateForAllChildren<EEventPropertyIndex::bNeedNotCulledChildrenUpdate>(true); } } } void SEventGraph::FilteringSearchBox_OnTextChanged( const FText& InFilterText ) { } static bool RecursiveShowUnfilteredItems(TSharedPtr< STreeView<FEventGraphSamplePtr> >& TreeView, TArray<FEventGraphSamplePtr>& Nodes) { bool bExpandedAnyChildren = false; for (FEventGraphSamplePtr& Node : Nodes) { const bool bChildIsExpanded = RecursiveShowUnfilteredItems(TreeView, Node->GetChildren()); const bool bThisWantsExpanded = !Node->PropertyValueAsBool(EEventPropertyIndex::bIsFiltered); const bool bExpandThis = bChildIsExpanded || bThisWantsExpanded; bExpandedAnyChildren |= bExpandThis; TreeView->SetItemExpansion(Node, bExpandThis); } return bExpandedAnyChildren; } void SEventGraph::FilteringSearchBox_OnTextCommitted(const FText& NewText, ETextCommit::Type CommitType) { PROFILER_SCOPE_LOG_TIME(TEXT("SEventGraph::FilterOutByText_Execute"), nullptr); SaveCurrentEventGraphState(); FEventGraphState* Op = GetCurrentState()->CreateCopyWithTextFiltering(NewText.ToString()); CurrentStateIndex = EventGraphStatesHistory.Insert(MakeShareable(Op), CurrentStateIndex + 1); RestoreEventGraphStateFrom(GetCurrentState()); // Auto-expand to view the unfiltered items if (GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical) { RecursiveShowUnfilteredItems(TreeView_Base, GetCurrentState()->GetRoot()->GetChildren()); TreeView_Refresh(); } } bool SEventGraph::FilteringSearchBox_IsEnabled() const { return true; } void SEventGraph::OnAggressiveFilteringToggled(ECheckBoxState InState) { GetCurrentState()->SetAggressiveFiltering( InState == ECheckBoxState::Checked ? true : false ); RestoreEventGraphStateFrom(GetCurrentState()); // Auto-expand to view the unfiltered items if (GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical) { RecursiveShowUnfilteredItems(TreeView_Base, GetCurrentState()->GetRoot()->GetChildren()); TreeView_Refresh(); } } TSharedPtr<SWidget> SEventGraph::EventGraph_GetMenuContent() const { const FEventGraphColumn& Column = *FEventGraphColumns::Get().ColumnNameToIndexMapping.FindChecked( HoveredColumnID ); const TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); const int NumSelectedEvents = SelectedEvents.Num(); FEventGraphSamplePtr SelectedEvent = NumSelectedEvents ? SelectedEvents[0] : nullptr; FText SelectionStr; FText PropertyName; FText PropertyValue; if( NumSelectedEvents == 0 ) { SelectionStr = LOCTEXT( "NothingSelected", "Nothing selected" ); } else if( NumSelectedEvents == 1 ) { SelectionStr = FText::FromString( SelectedEvent->_StatName.GetPlainNameString() ); PropertyName = Column.ShortName; PropertyValue = FText::FromString( SelectedEvent->GetFormattedValue(Column.Index) ); } else { SelectionStr = LOCTEXT( "MultipleSelection", "Multiple selection" ); } const bool bShouldCloseWindowAfterMenuSelection = true; FMenuBuilder MenuBuilder( bShouldCloseWindowAfterMenuSelection, NULL ); // Selection menu MenuBuilder.BeginSection("Selection", LOCTEXT("ContextMenu_Header_Selection", "Selection") ); { struct FLocal { static bool ReturnFalse() { return false; } }; FUIAction DummyUIAction; DummyUIAction.CanExecuteAction = FCanExecuteAction::CreateStatic( &FLocal::ReturnFalse ); MenuBuilder.AddMenuEntry ( SelectionStr, LOCTEXT("ContextMenu_Selection", "Currently selected events"), FSlateIcon(FEditorStyle::GetStyleSetName(), "@missing.icon"), DummyUIAction, NAME_None, EUserInterfaceActionType::Button ); } MenuBuilder.EndSection(); // Root menu MenuBuilder.BeginSection("Root/Culling/Filtering", LOCTEXT("ContextMenu_Header_Root", "Root") ); { MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Root_Set", "Set Root"), LOCTEXT("ContextMenu_Root_Set_Desc", "Sets the root to the selected event(s) and switches to hierarchical view"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.SetRoot"), SetRoot_Custom(), NAME_None, EUserInterfaceActionType::Button ); FUIAction Action_AggregateForSelection; // MenuBuilder.AddMenuEntry // ( // LOCTEXT("ContextMenu_Root_Reset", "Reset To Default"), // LOCTEXT("ContextMenu_Root_Reset_Desc", "Resets the root options and removes from the history"), // TEXT("Profiler.Misc.ResetToDefault"), ResetRoot_Custom(), NAME_None, EUserInterfaceActionType::Button // ); } //MenuBuilder.EndSection(); // Culling menu //MenuBuilder.BeginSection("Culling", LOCTEXT("ContextMenu_Culling","Culling") ); { FText CullingDesc; if( !Column.bCanBeCulled ) { CullingDesc = LOCTEXT("ContextMenu_Culling_DescErrCol","Culling not available, please select a different column"); } else if( NumSelectedEvents == 1 ) { CullingDesc = FText::Format( LOCTEXT("ContextMenu_Culling_DescFmt","Cull events to '{0}' based on '{1}'"), PropertyValue, PropertyName ); } else { CullingDesc = LOCTEXT("ContextMenu_Culling_DescErrEve","Culling not available, please select one event"); } MenuBuilder.AddMenuEntry ( CullingDesc, LOCTEXT("ContextMenu_Culling_Desc_TT","Culls the event graph based on the property value of the selected event"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.CullEvents"), CullByProperty_Custom(SelectedEvent,HoveredColumnID,false), NAME_None, EUserInterfaceActionType::Button ); // Filtering menu FText FilteringDesc; if( !Column.bCanBeFiltered ) { FilteringDesc = LOCTEXT("ContextMenu_Filtering_DescErrCol","Filtering not available, please select a different column"); } else if( NumSelectedEvents == 1 ) { FilteringDesc = FText::Format( LOCTEXT("ContextMenu_Filtering_DescFmt","Filter events to '{0}' based on '{1}'"), PropertyValue, PropertyName ); } else { FilteringDesc = LOCTEXT("ContextMenu_Filtering_DescErrEve","Filtering not available, please select one event"); } MenuBuilder.AddMenuEntry ( FilteringDesc, LOCTEXT("ContextMenu_Filtering_Desc_TT","Filters the event graph based on the property value of the selected event"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.FilterEvents"), FilterOutByProperty_Custom(SelectedEvent,HoveredColumnID,false), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuSeparator(); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_ClearHistory", "Reset to default"), LOCTEXT("ContextMenu_ClearHistory_Reset_Desc", "For the selected event graph resets root/culling/filter to the default state and clears the history"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.ResetToDefault"), ClearHistory_Custom(), NAME_None, EUserInterfaceActionType::Button ); } MenuBuilder.EndSection(); MenuBuilder.BeginSection("Expand", LOCTEXT("ContextMenu_Header_Expand", "Expand") ); { MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_ExpandAll", "Expand All"), LOCTEXT("ContextMenu_Header_Expand_ExpandAll_Desc", "Expands all events"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ExpandAll"), SetExpansionForEvents_Custom( ESelectedEventTypes::AllEvents, true ), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_CollapseAll", "Collapse All"), LOCTEXT("ContextMenu_Header_Expand_CollapseAll_Desc", "Collapses all events"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.CollapseAll"), SetExpansionForEvents_Custom( ESelectedEventTypes::AllEvents, false ), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_ExpandSelection", "Expand Selection"), LOCTEXT("ContextMenu_Header_Expand_ExpandSelection_Desc", "Expands selected events"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ExpandSelection"), SetExpansionForEvents_Custom( ESelectedEventTypes::SelectedEvents, true ), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_CollapseSelection", "Collapse Selection"), LOCTEXT("ContextMenu_Header_Expand_CollapseSelection_Desc", "Collapses selected events"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.CollapseSelection"), SetExpansionForEvents_Custom( ESelectedEventTypes::SelectedEvents, false ), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_ExpandThread", "Expand Thread"), LOCTEXT("ContextMenu_Header_Expand_ExpandThread_Desc", "Expands selected threads"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ExpandThread"), SetExpansionForEvents_Custom( ESelectedEventTypes::SelectedThreadEvents, true ), NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_CollapseThread", "Collapse Thread"), LOCTEXT("ContextMenu_Header_Expand_CollapseThread_Desc", "Collapses selected threads"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.CollapseThread"), SetExpansionForEvents_Custom( ESelectedEventTypes::SelectedThreadEvents, false ), NAME_None, EUserInterfaceActionType::Button ); //----------------------------------------------------------------------------- FUIAction Action_ExpandHotPath ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ExpandHotPath_Execute ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ExpandHotPath_CanExecute ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Expand_ExpandHotPath", "Expand Hot Path"), LOCTEXT("ContextMenu_Header_Expand_ExpandHotPath_Desc", "Expands hot path for the selected events, based on the inclusive time, also enables descending sorting by inclusive time"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ExpandHotPath"), Action_ExpandHotPath, NAME_None, EUserInterfaceActionType::Button ); } MenuBuilder.EndSection(); MenuBuilder.BeginSection("Navigation", LOCTEXT("ContextMenu_Header_Navigation", "Navigation") ); { MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Navigation_ShowInHierarchicalView", "Show In Hierarchical View"), LOCTEXT("ContextMenu_Header_Navigation_ShowInHierarchicalView_Desc", "Switches to hierarchical view and expands selected events"), FSlateIcon(FEditorStyle::GetStyleSetName(), EEventGraphViewModes::ToBrushName(EEventGraphViewModes::Hierarchical)), ShowSelectedEventsInViewMode_Custom(EEventGraphViewModes::Hierarchical), NAME_None, EUserInterfaceActionType::Check ); //----------------------------------------------------------------------------- MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatView", "Show In FlatInclusive View"), LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatView_Desc", "Switches to flat view, also enables descending sorting by inclusive time"), FSlateIcon(FEditorStyle::GetStyleSetName(), EEventGraphViewModes::ToBrushName(EEventGraphViewModes::FlatExclusive)), ShowSelectedEventsInViewMode_Custom(EEventGraphViewModes::FlatExclusive), NAME_None, EUserInterfaceActionType::Check ); if( FProfilerManager::GetSettings().bShowCoalescedViewModesInEventGraph ) { MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatCoalesced", "Show In FlatInclusive Coalesced"), LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatCoalesced_Desc", "Switches to flat coalesced, also enables descending sorting by inclusive time"), FSlateIcon(FEditorStyle::GetStyleSetName(), EEventGraphViewModes::ToBrushName(EEventGraphViewModes::FlatInclusiveCoalesced)), ShowSelectedEventsInViewMode_Custom(EEventGraphViewModes::FlatInclusiveCoalesced), NAME_None, EUserInterfaceActionType::Check ); } //----------------------------------------------------------------------------- MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatExclusiveView", "Show In Flat Exclusive View"), LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatExclusiveView_Desc", "Switches to flat exclusive view, also enables ascending sorting by exclusive time"), FSlateIcon(FEditorStyle::GetStyleSetName(), EEventGraphViewModes::ToBrushName(EEventGraphViewModes::FlatExclusive)), ShowSelectedEventsInViewMode_Custom(EEventGraphViewModes::FlatExclusive), NAME_None, EUserInterfaceActionType::Check ); if( FProfilerManager::GetSettings().bShowCoalescedViewModesInEventGraph ) { MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatExclusiveCoalescedView", "Show In Flat Exclusive Coalesced View"), LOCTEXT("ContextMenu_Header_Navigation_ShowInFlatExclusiveCoalescedView_Desc", "Switches to flat exclusive coalesced view, also enables ascending sorting by exclusive time enabled"), FSlateIcon(FEditorStyle::GetStyleSetName(), EEventGraphViewModes::ToBrushName(EEventGraphViewModes::FlatExclusiveCoalesced)), ShowSelectedEventsInViewMode_Custom(EEventGraphViewModes::FlatExclusiveCoalesced), NAME_None, EUserInterfaceActionType::Check ); } //----------------------------------------------------------------------------- FUIAction Action_ShowInClassAggregate; FUIAction Action_ShowInGraphPanel; // Highlight all occurrences based on object's name/class FUIAction Action_HighlightBasedOnClass; } MenuBuilder.EndSection(); /* Event graph coloring based on inclusive time as a gradient from black to red? */ MenuBuilder.BeginSection("Misc", LOCTEXT("ContextMenu_Header_Misc", "Miscellaneous") ); { FUIAction Action_CopySelectedToClipboard ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_CopySelectedToClipboard_Execute ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_CopySelectedToClipboard_CanExecute ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_CopySelectedToClipboard", "Copy To Clipboard"), LOCTEXT("ContextMenu_Header_Misc_CopySelectedToClipboard_Desc", "Copies selection to clipboard"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.CopyToClipboard"), Action_CopySelectedToClipboard, NAME_None, EUserInterfaceActionType::Button ); FUIAction Action_SaveSelectedToFile; FUIAction Action_SelectStack ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SelectStack_Execute ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SelectStack_CanExecute ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_SelectStack", "Select Stack"), LOCTEXT("ContextMenu_Header_Misc_SelectStack_Desc", "Selects all events in the stack"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.SelectStack"), Action_SelectStack, NAME_None, EUserInterfaceActionType::Button ); MenuBuilder.AddSubMenu ( LOCTEXT("ContextMenu_Header_Misc_Sort", "Sort By"), LOCTEXT("ContextMenu_Header_Misc_Sort_Desc", "Sort by column"), FNewMenuDelegate::CreateSP( this, &SEventGraph::EventGraph_BuildSortByMenu ), false, FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.SortBy") ); } MenuBuilder.EndSection(); MenuBuilder.BeginSection("Columns", LOCTEXT("ContextMenu_Header_Columns", "Columns") ); { MenuBuilder.AddSubMenu ( LOCTEXT("ContextMenu_Header_Columns_View", "View Column"), LOCTEXT("ContextMenu_Header_Columns_View_Desc", "Hides or shows columns"), FNewMenuDelegate::CreateSP( this, &SEventGraph::EventGraph_BuildViewColumnMenu ), false, FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ViewColumn") ); FUIAction Action_ResetColumns ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ResetColumns_Execute ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ResetColumns_CanExecute ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Columns_ResetColumns", "Reset Columns To Default"), LOCTEXT("ContextMenu_Header_Columns_ResetColumns_Desc", "Resets columns to default"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.EventGraph.ResetColumn"), Action_ResetColumns, NAME_None, EUserInterfaceActionType::Button ); } MenuBuilder.EndSection(); return MenuBuilder.MakeWidget(); } void SEventGraph::EventGraph_BuildSortByMenu( FMenuBuilder& MenuBuilder ) { // TODO: Refactor later @see TSharedPtr<SWidget> SCascadePreviewViewportToolBar::GenerateViewMenu() const MenuBuilder.BeginSection("ColumnName", LOCTEXT("ContextMenu_Header_Misc_ColumnName","Column Name")); for( auto It = TreeViewHeaderColumns.CreateConstIterator(); It; ++It ) { const FEventGraphColumn& Column = It.Value(); if( Column.bIsVisible && Column.bCanBeSorted ) { FUIAction Action_SortByColumn ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortByColumn_Execute, Column.ID ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortByColumn_CanExecute, Column.ID ), FIsActionChecked::CreateSP( this, &SEventGraph::ContextMenu_SortByColumn_IsChecked, Column.ID ) ); MenuBuilder.AddMenuEntry ( Column.ShortName, Column.Description, FSlateIcon(), Action_SortByColumn, NAME_None, EUserInterfaceActionType::RadioButton ); } } MenuBuilder.EndSection(); //----------------------------------------------------------------------------- MenuBuilder.BeginSection("SortMode", LOCTEXT("ContextMenu_Header_Misc_Sort_SortMode", "Sort Mode") ); { FUIAction Action_SortAscending ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortMode_Execute, EColumnSortMode::Ascending ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortMode_CanExecute, EColumnSortMode::Ascending ), FIsActionChecked::CreateSP( this, &SEventGraph::ContextMenu_SortMode_IsChecked, EColumnSortMode::Ascending ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_Sort_SortAscending", "Sort Ascending"), LOCTEXT("ContextMenu_Header_Misc_Sort_SortAscending_Desc", "Sorts ascending"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.SortAscending"), Action_SortAscending, NAME_None, EUserInterfaceActionType::RadioButton ); FUIAction Action_SortDescending ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortMode_Execute, EColumnSortMode::Descending ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_SortMode_CanExecute, EColumnSortMode::Descending ), FIsActionChecked::CreateSP( this, &SEventGraph::ContextMenu_SortMode_IsChecked, EColumnSortMode::Descending ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_Sort_SortDescending", "Sort Descending"), LOCTEXT("ContextMenu_Header_Misc_Sort_SortDescending_Desc", "Sorts descending"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.SortDescending"), Action_SortDescending, NAME_None, EUserInterfaceActionType::RadioButton ); } MenuBuilder.EndSection(); } void SEventGraph::EventGraph_BuildViewColumnMenu( FMenuBuilder& MenuBuilder ) { MenuBuilder.BeginSection("ViewColumn", LOCTEXT("ContextMenu_Header_Columns_View", "View Column") ); for( auto It = TreeViewHeaderColumns.CreateConstIterator(); It; ++It ) { const FEventGraphColumn& Column = It.Value(); FUIAction Action_ToggleColumn ( FExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ToggleColumn_Execute, Column.ID ), FCanExecuteAction::CreateSP( this, &SEventGraph::ContextMenu_ToggleColumn_CanExecute, Column.ID ), FIsActionChecked::CreateSP( this, &SEventGraph::ContextMenu_ToggleColumn_IsChecked, Column.ID ) ); MenuBuilder.AddMenuEntry ( Column.ShortName, Column.Description, FSlateIcon(), Action_ToggleColumn, NAME_None, EUserInterfaceActionType::ToggleButton ); } MenuBuilder.EndSection(); } void SEventGraph::EventGraphViewMode_OnCheckStateChanged( ECheckBoxState NewRadioState, const EEventGraphViewModes::Type InViewMode ) { if( NewRadioState == ECheckBoxState::Checked && GetCurrentStateViewMode() != InViewMode) { const TArray< FEventGraphSamplePtr > SelectedEvents = TreeView_Base->GetSelectedItems(); ShowEventsInViewMode( SelectedEvents, InViewMode ); } } ECheckBoxState SEventGraph::EventGraphViewMode_IsChecked( const EEventGraphViewModes::Type InViewMode ) const { return (GetCurrentStateViewMode() == InViewMode) ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } void SEventGraph::EventGraphType_OnCheckStateChanged( ECheckBoxState NewRadioState, const EEventGraphTypes::Type NewEventGraphType ) { const uint32 NumFrames = GetCurrentState()->GetNumFrames(); if( NewRadioState == ECheckBoxState::Checked && GetCurrentStateEventGraphType() != NewEventGraphType ) { FEventGraphStateRef EventGraphState = GetCurrentState(); GetHierarchicalExpandedEvents( EventGraphState->ExpandedEvents ); GetHierarchicalSelectedEvents( EventGraphState->SelectedEvents ); EventGraphState->UpdateToNewEventGraphType( NewEventGraphType ); SetEventGraphFromStateInternal( EventGraphState ); } } ECheckBoxState SEventGraph::EventGraphType_IsChecked( const EEventGraphTypes::Type InEventGraphType ) const { if( IsEventGraphStatesHistoryValid() ) { const uint32 NumFrames = GetCurrentState()->GetNumFrames(); if( NumFrames == 1 ) { return GetCurrentStateEventGraphType() == InEventGraphType ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } else if( NumFrames > 1 ) { return GetCurrentStateEventGraphType() == InEventGraphType ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; } } return ECheckBoxState::Unchecked; } bool SEventGraph::EventGraphType_IsEnabled( const EEventGraphTypes::Type InEventGraphType ) const { if( IsEventGraphStatesHistoryValid() ) { const uint32 NumFrames = GetCurrentState()->GetNumFrames(); if( InEventGraphType == EEventGraphTypes::OneFrame ) { return NumFrames == 1 ? true : false; } else { return NumFrames > 1 ? true : false; } } return false; } void SEventGraph::SetTreeItemsForViewMode( const EEventGraphViewModes::Type NewViewMode, EEventGraphTypes::Type NewEventGraphType ) { GetCurrentState()->ViewMode = NewViewMode; GetCurrentState()->EventGraphType = NewEventGraphType; GetCurrentState()->ApplyCulling(); GetCurrentState()->ApplyFiltering(); if( GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical ) { TreeView_Base->SetTreeItemsSource( &GetCurrentState()->GetRoot()->GetChildren() ); } else if( GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusive || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusive ) { TreeView_Base->SetTreeItemsSource( &Events_Flat ); } else if( GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusiveCoalesced || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusiveCoalesced ) { TreeView_Base->SetTreeItemsSource( &Events_FlatCoalesced ); } } FReply SEventGraph::ExpandHotPath_OnClicked() { ContextMenu_ExpandHotPath_Execute(); return FReply::Handled(); } void SEventGraph::HighlightHotPath_OnCheckStateChanged( ECheckBoxState InState ) { } void SEventGraph::TreeView_Refresh() { if( TreeView_Base.IsValid() ) { TreeView_Base->RequestTreeRefresh(); } } void SEventGraph::TreeViewHeaderRow_CreateColumnArgs( const uint32 ColumnIndex ) { const FEventGraphColumn Column = FEventGraphColumns::Get().Collection[ColumnIndex]; SHeaderRow::FColumn::FArguments ColumnArgs; ColumnArgs .ColumnId( Column.ID ) .DefaultLabel( Column.ShortName ) .SortMode( EColumnSortMode::None ) .HAlignHeader( HAlign_Fill ) .VAlignHeader( VAlign_Fill ) .HeaderContentPadding( TOptional<FMargin>( 2.0f ) ) .HAlignCell( HAlign_Fill ) .VAlignCell( VAlign_Fill ) .SortMode( this, &SEventGraph::TreeViewHeaderRow_GetSortModeForColumn, Column.ID ) .OnSort( this, &SEventGraph::TreeViewHeaderRow_OnSortModeChanged ) .FixedWidth( Column.FixedColumnWidth > 0.0f ? Column.FixedColumnWidth : TOptional<float>() ) .HeaderContent() [ SNew(SHorizontalBox) +SHorizontalBox::Slot() .HAlign( Column.HorizontalAlignment ) .VAlign( VAlign_Center ) [ SNew(STextBlock) .Text( Column.ShortName ) .ToolTipText( Column.Description ) ] ] .MenuContent() [ TreeViewHeaderRow_GenerateColumnMenu( Column ) ]; TreeViewHeaderColumnArgs.Add( Column.ID, ColumnArgs ); TreeViewHeaderColumns.Add( Column.ID, Column ); } void SEventGraph::InitializeAndShowHeaderColumns() { ColumnSortMode = EColumnSortMode::Descending; ColumnBeingSorted = FEventGraphColumns::Get().Collection[EEventPropertyIndex::InclusiveTimeMS].ID; for (uint32 ColumnIndex = 0; ColumnIndex < FEventGraphColumns::Get().NumColumns; ColumnIndex++) { TreeViewHeaderRow_CreateColumnArgs( ColumnIndex ); } for( auto It = TreeViewHeaderColumns.CreateConstIterator(); It; ++It ) { const FEventGraphColumn& Column = It.Value(); if( Column.bIsVisible ) { TreeViewHeaderRow_ShowColumn( Column.ID ); } } } void SEventGraph::TreeViewHeaderRow_OnSortModeChanged( const EColumnSortPriority::Type SortPriority, const FName& ColumnID, const EColumnSortMode::Type SortMode ) { SetSortModeForColumn( ColumnID, SortMode ); TreeView_Refresh(); } EColumnSortMode::Type SEventGraph::TreeViewHeaderRow_GetSortModeForColumn( const FName ColumnID ) const { if( ColumnBeingSorted != ColumnID ) { return EColumnSortMode::None; } return ColumnSortMode; } void SEventGraph::HeaderMenu_HideColumn_Execute( const FName ColumnID ) { FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); Column.bIsVisible = false; TreeViewHeaderRow->RemoveColumn( ColumnID ); } void SEventGraph::TreeViewHeaderRow_ShowColumn( const FName ColumnID ) { FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked( ColumnID ); Column.bIsVisible = true; SHeaderRow::FColumn::FArguments& ColumnArgs = TreeViewHeaderColumnArgs.FindChecked( ColumnID ); const int32 NumColumns = TreeViewHeaderRow->GetColumns().Num(); const int32 ColumnIndex = FMath::Max( 0, FMath::Min( (int32)Column.Index, NumColumns ) ); TreeViewHeaderRow->InsertColumn( ColumnArgs, ColumnIndex ); } bool SEventGraph::HeaderMenu_HideColumn_CanExecute( const FName ColumnID ) const { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); return Column.bCanBeHidden; } TSharedRef< SWidget > SEventGraph::TreeViewHeaderRow_GenerateColumnMenu( const FEventGraphColumn& Column ) { bool bIsMenuVisible = false; const bool bShouldCloseWindowAfterMenuSelection = true; FMenuBuilder MenuBuilder( bShouldCloseWindowAfterMenuSelection, NULL ); { if( Column.bCanBeHidden ) { MenuBuilder.BeginSection("Column", LOCTEXT("TreeViewHeaderRow_Header_Column", "Column") ); FUIAction Action_HideColumn ( FExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_HideColumn_Execute, Column.ID ), FCanExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_HideColumn_CanExecute, Column.ID ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("TreeViewHeaderRow_HideColumn", "Hide"), LOCTEXT("TreeViewHeaderRow_HideColumn_Desc", "Hides the selected column"), FSlateIcon(), Action_HideColumn, NAME_None, EUserInterfaceActionType::Button ); bIsMenuVisible = true; MenuBuilder.EndSection(); } if( Column.bCanBeSorted ) { MenuBuilder.BeginSection("SortMode", LOCTEXT("ContextMenu_Header_Misc_Sort_SortMode", "Sort Mode") ); FUIAction Action_SortAscending ( FExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_Execute, Column.ID, EColumnSortMode::Ascending ), FCanExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_CanExecute, Column.ID, EColumnSortMode::Ascending ), FIsActionChecked::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_IsChecked, Column.ID, EColumnSortMode::Ascending ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_Sort_SortAscending", "Sort Ascending"), LOCTEXT("ContextMenu_Header_Misc_Sort_SortAscending_Desc", "Sorts ascending"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.SortAscending"), Action_SortAscending, NAME_None, EUserInterfaceActionType::RadioButton ); FUIAction Action_SortDescending ( FExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_Execute, Column.ID, EColumnSortMode::Descending ), FCanExecuteAction::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_CanExecute, Column.ID, EColumnSortMode::Descending ), FIsActionChecked::CreateSP( this, &SEventGraph::HeaderMenu_SortMode_IsChecked, Column.ID, EColumnSortMode::Descending ) ); MenuBuilder.AddMenuEntry ( LOCTEXT("ContextMenu_Header_Misc_Sort_SortDescending", "Sort Descending"), LOCTEXT("ContextMenu_Header_Misc_Sort_SortDescending_Desc", "Sorts descending"), FSlateIcon(FEditorStyle::GetStyleSetName(), "Profiler.Misc.SortDescending"), Action_SortDescending, NAME_None, EUserInterfaceActionType::RadioButton ); bIsMenuVisible = true; MenuBuilder.EndSection(); } if( Column.bCanBeFiltered ) { MenuBuilder.BeginSection("FilterMode", LOCTEXT("ContextMenu_Header_Misc_Filter_FilterMode", "Filter Mode") ); bIsMenuVisible = true; MenuBuilder.EndSection(); } if( Column.bCanBeCulled ) { MenuBuilder.BeginSection("CullMode", LOCTEXT("ContextMenu_Header_Misc_Cull_CullMode", "Cull Mode") ); bIsMenuVisible = true; MenuBuilder.EndSection(); } } /* HEADER COLUMN Show top ten Show top bottom Filter by list (avg, median, 10%,90%,etc.) Text box for filtering for each column instead of one text box used for filtering Grouping button for flat view modes (show at most X groups, show all groups for names) */ return bIsMenuVisible ? MenuBuilder.MakeWidget() : (TSharedRef<SWidget>)SNullWidget::NullWidget; } //----------------------------------------------------------------------------- void SEventGraph::ContextMenu_ExecuteDummy( const FName ActionName ) { #if DEBUG_PROFILER_PERFORMANCE UE_LOG( Profiler, Log, TEXT("SEventGraph::ContextMenu_ExecuteDummy -> %s"), *ActionName.ToString() ); #endif // DEBUG_PROFILER_PERFORMANCE } bool SEventGraph::ContextMenu_CanExecuteDummy( const FName ActionName ) const { #if DEBUG_PROFILER_PERFORMANCE UE_LOG( Profiler, Log, TEXT("SEventGraph::ContextMenu_CanExecuteDummy -> %s"), *ActionName.ToString() ); #endif // DEBUG_PROFILER_PERFORMANCE return false; } bool SEventGraph::ContextMenu_IsCheckedDummy( const FName ActionName ) const { #if DEBUG_PROFILER_PERFORMANCE UE_LOG( Profiler, Log, TEXT("SEventGraph::ContextMenu_IsCheckedDummy -> %s"), *ActionName.ToString() ); #endif // DEBUG_PROFILER_PERFORMANCE return false; } /*----------------------------------------------------------------------------- UI ACTIONS -----------------------------------------------------------------------------*/ void SEventGraph::ContextMenu_ExpandHotPath_Execute() { TArray<FEventGraphSamplePtr> SelectedItems = TreeView_Base->GetSelectedItems(); FEventGraphSamplePtr EventPtr = SelectedItems[0]; ColumnSortMode = EColumnSortMode::Descending; ColumnBeingSorted = FEventGraphColumns::Get().Collection[EEventPropertyIndex::InclusiveTimeMS].ID; SortEvents(); // Clear hot path TreeView_Base->ClearExpandedItems(); GetCurrentState()->GetRoot()->SetBooleanStateForAllChildren<EEventPropertyIndex::bIsHotPath>(false); FEventGraphSamplePtr LastHotEvent; for( FEventGraphSamplePtr HotEvent = EventPtr; HotEvent.IsValid(); HotEvent = HotEvent->GetChildren().Num() > 0 ? HotEvent->GetChildren()[0] : NULL ) { HotEvent->PropertyValueAsBool(EEventPropertyIndex::bIsHotPath) = true; HotEvent->_bIsHotPath = true; LastHotEvent = HotEvent; } // Expand all events from the bottom to the top most event. TArray<FEventGraphSamplePtr> StackToExpand; LastHotEvent->GetStack( StackToExpand ); for( int EventIndex = StackToExpand.Num()-1; EventIndex >= 0; EventIndex-- ) { TreeView_Base->SetItemExpansion( StackToExpand[EventIndex], true ); } TreeView_Refresh(); } bool SEventGraph::ContextMenu_ExpandHotPath_CanExecute() const { return GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical && TreeView_Base->GetNumItemsSelected() == 1; } void SEventGraph::ContextMenu_CopySelectedToClipboard_Execute() { TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); FString Result; // Prepare header. for (uint32 ColumnIndex = 0; ColumnIndex < FEventGraphColumns::Get().NumColumns; ColumnIndex++) { const FEventGraphColumn& Column = FEventGraphColumns::Get().Collection[ColumnIndex]; Result += FString::Printf( TEXT("\"%s\","), *Column.ShortName.ToString() ); } Result += LINE_TERMINATOR; // Prepare selected samples. for( int32 EventIndex = 0; EventIndex < SelectedEvents.Num(); EventIndex++ ) { const FEventGraphSamplePtr EventPtr = SelectedEvents[EventIndex]; for (uint32 ColumnIndex = 0; ColumnIndex < FEventGraphColumns::Get().NumColumns; ColumnIndex++) { const FEventGraphColumn& Column = FEventGraphColumns::Get().Collection[ColumnIndex]; if( Column.Index != EEventPropertyIndex::None ) { const FString FormattedValue = EventPtr->GetFormattedValue( Column.Index ); Result += FString::Printf( TEXT("\"%s\","), *FormattedValue ); } } Result += LINE_TERMINATOR; } if( Result.Len() ) { FPlatformApplicationMisc::ClipboardCopy( *Result ); } } bool SEventGraph::ContextMenu_CopySelectedToClipboard_CanExecute() const { const int32 NumSelectedItems = TreeView_Base->GetNumItemsSelected(); return NumSelectedItems > 0; } void SEventGraph::ContextMenu_SelectStack_Execute() { TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); TArray<FEventGraphSamplePtr> ArrayStack; SelectedEvents[0]->GetStack( ArrayStack ); for( int32 Nx = 0; Nx < ArrayStack.Num(); ++Nx ) { TreeView_Base->SetItemSelection( ArrayStack[Nx], true, ESelectInfo::Direct ); } } bool SEventGraph::ContextMenu_SelectStack_CanExecute() const { bool bResult = false; TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); if( SelectedEvents.Num() == 1 ) { FEventGraphSamplePtr StackEvent = SelectedEvents[0]; bResult = StackEvent->GetParent().IsValid() && !StackEvent->GetParent()->IsRoot(); } return bResult; } void SEventGraph::ContextMenu_SortByColumn_Execute( const FName ColumnID ) { SetSortModeForColumn( ColumnID, EColumnSortMode::Descending ); TreeView_Refresh(); } bool SEventGraph::ContextMenu_SortByColumn_CanExecute( const FName ColumnID ) const { return ColumnID != ColumnBeingSorted; } bool SEventGraph::ContextMenu_SortByColumn_IsChecked( const FName ColumnID ) { return ColumnID == ColumnBeingSorted; } void SEventGraph::ContextMenu_SortMode_Execute( const EColumnSortMode::Type InSortMode ) { SetSortModeForColumn( ColumnBeingSorted, InSortMode ); TreeView_Refresh(); } bool SEventGraph::ContextMenu_SortMode_CanExecute( const EColumnSortMode::Type InSortMode ) const { return ColumnSortMode != InSortMode; } bool SEventGraph::ContextMenu_SortMode_IsChecked( const EColumnSortMode::Type InSortMode ) { return ColumnSortMode == InSortMode; } void SEventGraph::ContextMenu_ResetColumns_Execute() { ColumnSortMode = EColumnSortMode::Descending; ColumnBeingSorted = FEventGraphColumns::Get().Collection[EEventPropertyIndex::InclusiveTimeMS].ID; for( uint32 ColumnIndex = 0; ColumnIndex < FEventGraphColumns::Get().NumColumns; ColumnIndex++ ) { const FEventGraphColumn& DefaultColumn = FEventGraphColumns::Get().Collection[ColumnIndex]; const FEventGraphColumn& CurrentColumn = TreeViewHeaderColumns.FindChecked( DefaultColumn.ID ); if( DefaultColumn.bIsVisible && !CurrentColumn.bIsVisible ) { TreeViewHeaderRow_ShowColumn( DefaultColumn.ID ); } else if( !DefaultColumn.bIsVisible && CurrentColumn.bIsVisible ) { HeaderMenu_HideColumn_Execute( DefaultColumn.ID ); } } } bool SEventGraph::ContextMenu_ResetColumns_CanExecute() const { return true; } void SEventGraph::ContextMenu_ToggleColumn_Execute( const FName ColumnID ) { FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); if( Column.bIsVisible ) { HeaderMenu_HideColumn_Execute( ColumnID ); } else { TreeViewHeaderRow_ShowColumn( ColumnID ); } } bool SEventGraph::ContextMenu_ToggleColumn_CanExecute( const FName ColumnID ) const { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); return Column.bCanBeHidden; } bool SEventGraph::ContextMenu_ToggleColumn_IsChecked( const FName ColumnID ) { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); return Column.bIsVisible; } void SEventGraph::HeaderMenu_SortMode_Execute( const FName ColumnID, const EColumnSortMode::Type InSortMode ) { SetSortModeForColumn( ColumnID, InSortMode ); TreeView_Refresh(); } bool SEventGraph::HeaderMenu_SortMode_CanExecute( const FName ColumnID, const EColumnSortMode::Type InSortMode ) const { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(ColumnID); const bool bIsValid = Column.bCanBeSorted; bool bCanExecute = ColumnBeingSorted != ColumnID ? true : ColumnSortMode != InSortMode; bCanExecute = bCanExecute && bIsValid; return bCanExecute; } bool SEventGraph::HeaderMenu_SortMode_IsChecked( const FName ColumnID, const EColumnSortMode::Type InSortMode ) { return ColumnBeingSorted == ColumnID && ColumnSortMode == InSortMode; } /*----------------------------------------------------------------------------- CreateEvents_... -----------------------------------------------------------------------------*/ void SEventGraph::CreateEvents() { // #YRX_Profiler 2015-12-17 Fix recursive calls accounting. // Linear GetCurrentState()->GetRoot()->GetLinearEvents( Events_Flat, true ); // Linear Coalesced by Name // Event name -> Events TMap< FName, TArray<FEventGraphSamplePtr> > FlatIncCoalescedEvents; const int32 NumLinearSamples = Events_Flat.Num(); Events_FlatCoalesced.Reset( NumLinearSamples ); HierarchicalToFlatCoalesced.Reset(); for( int32 LinearEventIndex = 0; LinearEventIndex < NumLinearSamples; LinearEventIndex++ ) { const FEventGraphSamplePtr EventPtr = Events_Flat[LinearEventIndex]; FlatIncCoalescedEvents.FindOrAdd( EventPtr->_StatName ).Add( EventPtr->DuplicateSimplePtr() ); HierarchicalToFlatCoalesced.Add( EventPtr->_StatName, EventPtr ); } // Should ignore recursion! for( auto It = FlatIncCoalescedEvents.CreateConstIterator(); It; ++It ) { const TArray<FEventGraphSamplePtr>& InclusiveCoalescedEvents = It.Value(); FEventGraphSamplePtr CoalescedEvent = InclusiveCoalescedEvents[0]; for( int32 EventIndex = 1; EventIndex < InclusiveCoalescedEvents.Num(); EventIndex++ ) { CoalescedEvent->Combine( InclusiveCoalescedEvents[EventIndex] ); } Events_FlatCoalesced.Add( CoalescedEvent ); } // CoalesceEventsByColumnName/ID } void SEventGraph::ShowEventsInViewMode( const TArray<FEventGraphSamplePtr>& EventsToSynchronize, const EEventGraphViewModes::Type NewViewMode ) { FEventGraphStateRef EventGraphState = GetCurrentState(); GetHierarchicalSelectedEvents( EventGraphState->SelectedEvents, &EventsToSynchronize ); GetHierarchicalExpandedEvents( EventGraphState->ExpandedEvents ); SetTreeItemsForViewMode( NewViewMode, GetCurrentStateEventGraphType() ); SetHierarchicalSelectedEvents( EventGraphState->SelectedEvents ); SetHierarchicalExpandedEvents( EventGraphState->ExpandedEvents ); EEventPropertyIndex ColumnIndex = FEventGraphColumns::Get().ColumnNameToIndexMapping.FindChecked( ColumnBeingSorted )->Index; if( NewViewMode == EEventGraphViewModes::FlatInclusive || NewViewMode == EEventGraphViewModes::FlatInclusiveCoalesced || NewViewMode == EEventGraphViewModes::Hierarchical ) { ColumnIndex = EEventPropertyIndex::InclusiveTimeMS; SetSortModeForColumn( FEventGraphColumns::Get().Collection[ColumnIndex].ID, EColumnSortMode::Descending ); } else if( NewViewMode == EEventGraphViewModes::FlatExclusive || NewViewMode == EEventGraphViewModes::FlatExclusiveCoalesced ) { ColumnIndex = EEventPropertyIndex::ExclusiveTimeMS; SetSortModeForColumn( FEventGraphColumns::Get().Collection[ColumnIndex].ID, EColumnSortMode::Descending ); } ScrollToTheSlowestSelectedEvent( ColumnIndex ); if( NewViewMode == EEventGraphViewModes::Hierarchical ) { TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); for( int32 Nx = 0; Nx < SelectedEvents.Num(); ++Nx ) { // Find stack for the specified event and expand that stack. FEventGraphSamplePtr EventToExpand = SelectedEvents[Nx]; TArray<FEventGraphSamplePtr> StackToExpand; EventToExpand->GetStack( StackToExpand ); for( int32 Index = 0; Index < StackToExpand.Num(); ++Index ) { TreeView_Base->SetItemExpansion( StackToExpand[Index], true ); } } } TreeView_Refresh(); } void SEventGraph::ScrollToTheSlowestSelectedEvent( EEventPropertyIndex ColumnIndex ) { TArray<FEventGraphSamplePtr> SelectedEvents = TreeView_Base->GetSelectedItems(); if( SelectedEvents.Num() > 0 ) { // Sort events by the inclusive or the exclusive time, depends on the view mode. const FEventGraphColumn& Column = FEventGraphColumns::Get().Collection[ColumnIndex]; FEventArraySorter::Sort( SelectedEvents, Column.ID, EEventCompareOps::Greater ); // Scroll to the the slowest item. TreeView_Base->RequestScrollIntoView( SelectedEvents[0] ); } } /*----------------------------------------------------------------------------- Get/Set HierarchicalSelectedEvents -----------------------------------------------------------------------------*/ void SEventGraph::GetHierarchicalSelectedEvents( TArray< FEventGraphSamplePtr >& out_HierarchicalSelectedEvents, const TArray<FEventGraphSamplePtr>* SelectedEvents /*= NULL*/ ) const { out_HierarchicalSelectedEvents.Reset(); TArray<FEventGraphSamplePtr> ViewSelectedEvents; if( SelectedEvents != NULL ) { ViewSelectedEvents = *SelectedEvents; } else { ViewSelectedEvents = TreeView_Base->GetSelectedItems(); } if( GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusiveCoalesced || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusiveCoalesced ) { for( int32 Nx = 0; Nx < ViewSelectedEvents.Num(); ++Nx ) { HierarchicalToFlatCoalesced.MultiFind( ViewSelectedEvents[Nx]->_StatName, out_HierarchicalSelectedEvents ); } } else { out_HierarchicalSelectedEvents = ViewSelectedEvents; } } void SEventGraph::SetHierarchicalSelectedEvents( const TArray<FEventGraphSamplePtr>& HierarchicalSelectedEvents ) { struct FCoalescedEventMatcher { FCoalescedEventMatcher( const FEventGraphSamplePtr& InEventPtr ) : EventPtr( InEventPtr ) {} bool operator()(const FEventGraphSamplePtr& Other) const { return EventPtr->_StatName == Other->_StatName; } protected: const FEventGraphSamplePtr& EventPtr; }; TArray<FEventGraphSamplePtr> SelectedEvents; if( GetCurrentStateViewMode() == EEventGraphViewModes::FlatInclusiveCoalesced || GetCurrentStateViewMode() == EEventGraphViewModes::FlatExclusiveCoalesced ) { for( int32 Nx = 0; Nx < HierarchicalSelectedEvents.Num(); ++Nx ) { const int32 Index = Events_FlatCoalesced.IndexOfByPredicate(FCoalescedEventMatcher(HierarchicalSelectedEvents[Nx])); if( Index != INDEX_NONE ) { SelectedEvents.AddUnique( Events_FlatCoalesced[Index] ); } } } else { SelectedEvents = HierarchicalSelectedEvents; } TreeView_Base->ClearSelection(); for( int32 Nx = 0; Nx < SelectedEvents.Num(); ++Nx ) { TreeView_Base->SetItemSelection( SelectedEvents[Nx], true ); } } /*----------------------------------------------------------------------------- Get/Set HierarchicalExpandedEvents -----------------------------------------------------------------------------*/ void SEventGraph::GetHierarchicalExpandedEvents( TSet<FEventGraphSamplePtr>& out_HierarchicalExpandedEvents ) const { if( GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical ) { out_HierarchicalExpandedEvents.Empty(); TreeView_Base->GetExpandedItems( out_HierarchicalExpandedEvents ); } } void SEventGraph::SetHierarchicalExpandedEvents( const TSet<FEventGraphSamplePtr>& HierarchicalExpandedEvents ) { if( GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical ) { TreeView_Base->ClearExpandedItems(); for( auto It = HierarchicalExpandedEvents.CreateConstIterator(); It; ++It ) { TreeView_Base->SetItemExpansion( *It, true ); } } } /*----------------------------------------------------------------------------- Function details -----------------------------------------------------------------------------*/ FReply SEventGraph::CallingCalledFunctionButton_OnClicked( FEventGraphSamplePtr EventPtr ) { if( !EventPtr->_bIsCulled ) { UpdateFunctionDetailsForEvent( EventPtr ); TArray<FEventGraphSamplePtr> Events; Events.Add( EventPtr ); ShowEventsInViewMode( Events, GetCurrentStateViewMode() ); } return FReply::Handled(); } void SEventGraph::DisableFunctionDetails() { (*CurrentFunctionDescSlot ) [ SNew(STextBlock) .WrapTextAt( 128.0f ) .Text( LOCTEXT("FunctionDetails_SelectOneEvent","Function details view works only if you select one event. Please select an individual event to proceed.") ) .TextStyle( FEditorStyle::Get(), TEXT("Profiler.Tooltip") ) ]; VerticalBox_TopCalling->ClearChildren(); VerticalBox_TopCalled->ClearChildren(); HighlightedEventName = NAME_None; } void SEventGraph::UpdateFunctionDetailsForEvent( FEventGraphSamplePtr SelectedEvent ) { GenerateCallerCalleeGraph( SelectedEvent ); (*CurrentFunctionDescSlot) [ GetContentForEvent(SelectedEvent,1.0f,true) ]; RecreateWidgetsForTopEvents( VerticalBox_TopCalling, TopCallingFunctionEvents ); RecreateWidgetsForTopEvents( VerticalBox_TopCalled, TopCalledFunctionEvents ); HighlightedEventName = SelectedEvent->_StatName; } void SEventGraph::UpdateFunctionDetails() { TArray<FEventGraphSamplePtr> SelectedItems = TreeView_Base->GetSelectedItems(); if( SelectedItems.Num() == 1 ) { UpdateFunctionDetailsForEvent( SelectedItems[0] ); } else { DisableFunctionDetails(); } } /*----------------------------------------------------------------------------- Function details -----------------------------------------------------------------------------*/ void SEventGraph::GenerateCallerCalleeGraph( FEventGraphSamplePtr SelectedEvent ) { TArray< FEventGraphSamplePtr > EventsByName; HierarchicalToFlatCoalesced.MultiFind( SelectedEvent->_StatName, EventsByName ); // Parent TSet< FEventGraphSamplePtr > CallingFunctionEventSet; for( int32 Nx = 0; Nx < EventsByName.Num(); ++Nx ) { FEventGraphSamplePtr ParentPtr = EventsByName[Nx]->GetParent(); if( ParentPtr.IsValid() && !ParentPtr->IsRoot() ) { CallingFunctionEventSet.Add( ParentPtr ); } } GenerateTopEvents( CallingFunctionEventSet, TopCallingFunctionEvents ); CalculateEventWeights( TopCallingFunctionEvents ); // Children TSet< FEventGraphSamplePtr > CalledFunctionEventSet; for( int32 Nx = 0; Nx < EventsByName.Num(); ++Nx ) { CalledFunctionEventSet.Append( EventsByName[Nx]->GetChildren() ); } GenerateTopEvents( CalledFunctionEventSet, TopCalledFunctionEvents ); CalculateEventWeights( TopCalledFunctionEvents ); } void SEventGraph::GenerateTopEvents( const TSet< FEventGraphSamplePtr >& EventPtrSet, TArray<FEventPtrAndMisc>& out_Results ) { const int NumTopEvents = 5; TArray<FEventGraphSamplePtr> EventPtrArray = EventPtrSet.Array(); // Calculate total time. double TotalTimeMS = 0.0f; for( int32 Nx = 0; Nx < EventPtrArray.Num(); ++Nx ) { TotalTimeMS += EventPtrArray[Nx]->_InclusiveTimeMS; } // Sort events by the inclusive time. const FEventGraphColumn& Column = FEventGraphColumns::Get().Collection[EEventPropertyIndex::InclusiveTimeMS]; FEventArraySorter::Sort( EventPtrArray, Column.ID, EEventCompareOps::Greater ); // Calculate total time for the top events. double Top5TimeMS = 0.0f; for( int32 Nx = 0; Nx < EventPtrArray.Num() && Nx < NumTopEvents; ++Nx ) { Top5TimeMS += EventPtrArray[Nx]->_InclusiveTimeMS; } // Calculate values for top events. out_Results.Reset(); for( int32 Nx = 0; Nx < EventPtrArray.Num() && Nx < NumTopEvents; ++Nx ) { const FEventGraphSamplePtr EventPtr = EventPtrArray[Nx]; const float IncTimeToTotalPct = EventPtr->_InclusiveTimeMS / TotalTimeMS; const float HeightPct = EventPtr->_InclusiveTimeMS / Top5TimeMS; out_Results.Add( FEventPtrAndMisc(EventPtr,IncTimeToTotalPct,HeightPct) ); } } void SEventGraph::CalculateEventWeights( TArray<FEventPtrAndMisc>& Events ) { // TODO: This value was calculated by hand // and gives reasonable results for scaling button in the function details. // Maximum number of visible buttons is 5, 5 buttons require 100px, where 20px for each button // The height of the area is 190px so 190px/20px = ~9 const float MaxButtons = 9.0f; const float TotalHeightPct = MaxButtons / 5.0f; const float MinHeightPct = TotalHeightPct / MaxButtons; // Update min height pct for buttons where the ratio is too low float CurrentHeightPct = 0.0f; for( int32 Tx = 0; Tx < Events.Num(); ++Tx ) { FEventPtrAndMisc& EventPtr = Events[Tx]; EventPtr.HeightPct = FMath::Max( EventPtr.HeightPct, MinHeightPct ); CurrentHeightPct += EventPtr.HeightPct; } // Update height pct to fit all button into visible area. const float FitHeightPct = TotalHeightPct / CurrentHeightPct; for( int32 Tx = 0; Tx < Events.Num(); ++Tx ) { FEventPtrAndMisc& EventPtr = Events[Tx]; EventPtr.HeightPct *= FitHeightPct; } } void SEventGraph::RecreateWidgetsForTopEvents( const TSharedPtr<SVerticalBox>& DestVerticalBox, const TArray<FEventPtrAndMisc>& TopEvents ) { DestVerticalBox->ClearChildren(); for( int32 Nx = 0; Nx < TopEvents.Num(); ++Nx ) { const FEventPtrAndMisc& EventPtrAndPct = TopEvents[Nx]; DestVerticalBox->AddSlot() .FillHeight( EventPtrAndPct.HeightPct ) .Padding( 1.0f ) [ SNew(SButton) .HAlign( HAlign_Left ) .VAlign( VAlign_Center ) .TextStyle( FEditorStyle::Get(), "Profiler.Tooltip" ) .ContentPadding( FMargin(4.0f, 1.0f) ) .OnClicked( this, &SEventGraph::CallingCalledFunctionButton_OnClicked, EventPtrAndPct.EventPtr ) [ GetContentForEvent( EventPtrAndPct.EventPtr, EventPtrAndPct.IncTimeToTotalPct, false ) ] ]; } } FString SEventGraph::GetEventDescription( FEventGraphSamplePtr EventPtr, float Pct, const bool bSimple ) { const bool bIgnoreEventName = EventPtr->_ThreadName == EventPtr->_StatName; const FString ThreadName = EventPtr->_ThreadName.GetPlainNameString().LeftChop( 9 );// TODO: Fix this const FString EventName = FProfilerHelper::ShortenName(EventPtr->_StatName.GetPlainNameString(),28); const FString ThreadAndEventName = bIgnoreEventName ? ThreadName : FString::Printf( TEXT("%s:%s"), *ThreadName, *EventName ); const FString Caption = FString::Printf ( TEXT("%s, %.1f%% (%s)"), *ThreadAndEventName, Pct*100.0f, *EventPtr->GetFormattedValue(EEventPropertyIndex::InclusiveTimeMS) ); return bSimple ? ThreadAndEventName : Caption; } TSharedRef<SHorizontalBox> SEventGraph::GetContentForEvent( FEventGraphSamplePtr EventPtr, float Pct, const bool bSimple ) { TSharedRef<SHorizontalBox> Content = SNew(SHorizontalBox); Content->AddSlot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew(STextBlock) .Text( FText::FromString(GetEventDescription(EventPtr,Pct,bSimple)) ) .TextStyle( FEditorStyle::Get(), bSimple ? TEXT("Profiler.Tooltip") : TEXT("Profiler.EventGraph.DarkText") ) ]; if( EventPtr->_bIsCulled ) { Content->AddSlot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SImage ) .Image( FEditorStyle::GetBrush("Profiler.EventGraph.CulledEvent") ) .ToolTipText( LOCTEXT("Misc_EventCulled","Event is culled") ) ]; } if( EventPtr->_bIsFiltered ) { Content->AddSlot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SImage ) .Image( FEditorStyle::GetBrush("Profiler.EventGraph.FilteredEvent") ) .ToolTipText( LOCTEXT("Misc_EventFiltered","Event is filtered") ) ]; } Content->AddSlot() .AutoWidth() .HAlign(HAlign_Center) .VAlign(VAlign_Center) [ SNew( SImage ) .Image( FEditorStyle::GetBrush("Profiler.Tooltip.HintIcon10") ) .ToolTip( SEventGraphTooltip::GetTableCellTooltip( EventPtr ) ) ]; return Content; } /*----------------------------------------------------------------------------- History management -----------------------------------------------------------------------------*/ void SEventGraph::SetNewEventGraphState( const FEventGraphDataRef AverageEventGraph, const FEventGraphDataRef MaximumEventGraph, bool bInitial ) { PROFILER_SCOPE_LOG_TIME( TEXT( "SEventGraph::UpdateEventGraph" ), nullptr ); // Store current operation. SaveCurrentEventGraphState(); FEventGraphState* Op = new FEventGraphState( AverageEventGraph->DuplicateAsRef(), MaximumEventGraph->DuplicateAsRef() ); CurrentStateIndex = EventGraphStatesHistory.Add( MakeShareable(Op) ); RestoreEventGraphStateFrom( GetCurrentState(), bInitial ); FillThreadFilterOptions(); } FReply SEventGraph::HistoryBack_OnClicked() { SwitchToEventGraphState( CurrentStateIndex-1 ); return FReply::Handled(); } bool SEventGraph::HistoryBack_IsEnabled() const { return EventGraphStatesHistory.Num() > 1 && CurrentStateIndex > 0; } FText SEventGraph::HistoryBack_GetToolTipText() const { // TODO: Add a nicer custom tooltip. if( HistoryBack_IsEnabled() ) { return FText::Format( LOCTEXT("HistoryBack_Tooltip", "Back to {0}"), EventGraphStatesHistory[CurrentStateIndex-1]->GetFullDescription() ); } return FText::GetEmpty(); } FReply SEventGraph::HistoryForward_OnClicked() { SwitchToEventGraphState( CurrentStateIndex+1 ); return FReply::Handled(); } bool SEventGraph::HistoryForward_IsEnabled() const { return EventGraphStatesHistory.Num() > 1 && CurrentStateIndex < EventGraphStatesHistory.Num()-1; } FText SEventGraph::HistoryForward_GetToolTipText() const { // TODO: Add a nicer custom tooltip. if( HistoryForward_IsEnabled() ) { return FText::Format( LOCTEXT("HistoryForward_Tooltip", "Forward to {0}"), EventGraphStatesHistory[CurrentStateIndex+1]->GetFullDescription() ); } return FText::GetEmpty(); } bool SEventGraph::EventGraph_IsEnabled() const { return EventGraphStatesHistory.Num() > 0; } bool SEventGraph::HistoryList_IsEnabled() const { return EventGraphStatesHistory.Num() > 1; } TSharedRef<SWidget> SEventGraph::HistoryList_GetMenuContent() const { FMenuBuilder MenuBuilder(true, NULL); for( int32 StateIndex = 0; StateIndex < EventGraphStatesHistory.Num(); ++StateIndex ) { const FEventGraphStateRef StateRef = EventGraphStatesHistory[StateIndex]; MenuBuilder.AddMenuEntry ( StateRef->GetFullDescription(), FText(), FSlateIcon(), HistoryList_GoTo_Custom( StateIndex ), NAME_None, EUserInterfaceActionType::RadioButton ); } return MenuBuilder.MakeWidget(); } void SEventGraph::HistoryList_GoTo_Execute( int32 StateIndex ) { if( StateIndex != CurrentStateIndex ) { SwitchToEventGraphState( StateIndex ); } } void SEventGraph::SaveCurrentEventGraphState() { if( EventGraphStatesHistory.Num() > 0 ) { FEventGraphStateRef EventGraphState = GetCurrentState(); GetHierarchicalExpandedEvents( EventGraphState->ExpandedEvents ); GetHierarchicalSelectedEvents( EventGraphState->SelectedEvents ); } } void SEventGraph::SetEventGraphFromStateInternal( const FEventGraphStateRef& EventGraphState ) { EventGraphState->ApplyCulling(); EventGraphState->ApplyFiltering(); if( EventGraphState->ExpandedCulledEvents.Num() > 0 ) { const int32 NumChildren = EventGraphState->ExpandedCulledEvents.Num(); for( int32 Nx = 0; Nx < NumChildren; ++Nx ) { const FEventGraphSamplePtr& EventPtr = EventGraphState->ExpandedCulledEvents[Nx]; //EventPtr->PropertyValueAsBool( EEventPropertyIndex::bIsCulled) = false; EventPtr->_bIsCulled = false; EventPtr->RequestNotCulledChildrenUpdate(); } } CreateEvents(); SetTreeItemsForViewMode( EventGraphState->ViewMode, EventGraphState->EventGraphType ); SetHierarchicalSelectedEvents( EventGraphState->SelectedEvents ); SetHierarchicalExpandedEvents( EventGraphState->ExpandedEvents ); SortEvents(); ScrollToTheSlowestSelectedEvent( EEventPropertyIndex::InclusiveTimeMS ); UpdateFunctionDetails(); TreeView_Refresh(); } void SEventGraph::RestoreEventGraphStateFrom( const FEventGraphStateRef EventGraphState, const bool bRestoredFromHistoryEvent /*= true*/ ) { SetEventGraphFromStateInternal( EventGraphState ); if( bRestoredFromHistoryEvent ) { // Broadcast that a new graph event has been set. EventGraphRestoredFromHistoryEvent.Broadcast( EventGraphState->GetEventGraph()->GetFrameStartIndex(), EventGraphState->GetEventGraph()->GetFrameEndIndex() ); } } void SEventGraph::SwitchToEventGraphState( int32 StateIndex ) { SaveCurrentEventGraphState(); CurrentStateIndex = StateIndex; RestoreEventGraphStateFrom( GetCurrentState() ); } /*----------------------------------------------------------------------------- UI Actions -----------------------------------------------------------------------------*/ void SEventGraph::BindCommands() { Map_SelectAllFrames_Global(); } void SEventGraph::SetRoot_Execute() { TArray<FEventGraphSamplePtr> SelectedLeafs; GetHierarchicalSelectedEvents( SelectedLeafs ); TMap< FEventGraphSamplePtr, TSet<FEventGraphSamplePtr> > StacksForSelectedLeafs; // Grab stack for all selected events. for( int32 Nx = 0; Nx < SelectedLeafs.Num(); ++Nx ) { const FEventGraphSamplePtr SelectedLeaf = SelectedLeafs[Nx]; TArray<FEventGraphSamplePtr> ArrayStack; SelectedLeaf->GetStack( ArrayStack ); TSet<FEventGraphSamplePtr> SetStack; SetStack.Append( ArrayStack ); StacksForSelectedLeafs.Add( SelectedLeaf, SetStack ); } // Remove duplicated stacks. // Not super efficient, but should be ok for now. for( auto OuterIt = StacksForSelectedLeafs.CreateIterator(); OuterIt; ++OuterIt ) { const TSet<FEventGraphSamplePtr>& OuterStack = OuterIt.Value(); const FEventGraphSamplePtr OuterLeafPtr = OuterIt.Key(); for( auto InnerIt = StacksForSelectedLeafs.CreateIterator(); InnerIt; ++InnerIt ) { const TSet<FEventGraphSamplePtr>& InnerStack = InnerIt.Value(); const FEventGraphSamplePtr InnerLeafPtr = InnerIt.Key(); // The same roots, so ignore. if( InnerLeafPtr == OuterLeafPtr ) { continue; } const bool bRemoveInner = InnerStack.Contains( OuterLeafPtr ); const bool bRemoveOuter = OuterStack.Contains( InnerLeafPtr ); if( bRemoveOuter ) { OuterIt.RemoveCurrent(); break; } else if( bRemoveInner ) { InnerIt.RemoveCurrent(); } } } TArray<FEventGraphSamplePtr> UniqueLeafs; StacksForSelectedLeafs.GenerateKeyArray( UniqueLeafs ); // Store current operation. SaveCurrentEventGraphState(); FEventGraphState* Op = GetCurrentState()->CreateCopyWithNewRoot( UniqueLeafs ); CurrentStateIndex = EventGraphStatesHistory.Insert( MakeShareable(Op), CurrentStateIndex+1 ); RestoreEventGraphStateFrom( GetCurrentState() ); } bool SEventGraph::SetRoot_CanExecute() const { const int32 NumItemsSelected = TreeView_Base->GetNumItemsSelected(); return NumItemsSelected > 0 && NumItemsSelected < 16; } void SEventGraph::ClearHistory_Execute() { // Remove all history from the currently visible event graph, but leave the default state. const FEventGraphStateRef EventGraphState = GetCurrentState(); for( int32 Nx = 0; Nx < EventGraphStatesHistory.Num(); ++Nx ) { const FEventGraphStateRef It = EventGraphStatesHistory[Nx]; if( It->MaximumEventGraph == EventGraphState->MaximumEventGraph && It->HistoryType != EEventHistoryTypes::NewEventGraph ) { EventGraphStatesHistory.RemoveAt( Nx, 1, false ); Nx--; } } // Find new index of the current state. for( int32 Nx = 0; Nx < EventGraphStatesHistory.Num(); ++Nx ) { const FEventGraphStateRef It = EventGraphStatesHistory[Nx]; if( It->MaximumEventGraph == EventGraphState->MaximumEventGraph ) { CurrentStateIndex = Nx; break; } } RestoreEventGraphStateFrom( GetCurrentState() ); } bool SEventGraph::ClearHistory_CanExecute() const { bool bCanExecute = false; const FEventGraphStateRef EventGraphState = GetCurrentState(); for( int32 Nx = 0; Nx < EventGraphStatesHistory.Num(); ++Nx ) { const FEventGraphStateRef It = EventGraphStatesHistory[Nx]; if( It->MaximumEventGraph == EventGraphState->MaximumEventGraph && It->HistoryType != EEventHistoryTypes::NewEventGraph ) { bCanExecute = true; } } return bCanExecute; } void SEventGraph::FilterOutByProperty_Execute( const FEventGraphSamplePtr EventPtr, const FName PropertyName, const bool bReset ) { PROFILER_SCOPE_LOG_TIME( TEXT( "SEventGraph::FilterOutByProperty_Execute" ), nullptr ); // Store current operation. SaveCurrentEventGraphState(); FEventGraphState* Op = GetCurrentState()->CreateCopyWithFiltering( PropertyName, EventPtr ); CurrentStateIndex = EventGraphStatesHistory.Insert( MakeShareable(Op), CurrentStateIndex+1 ); RestoreEventGraphStateFrom( GetCurrentState() ); } bool SEventGraph::FilterOutByProperty_CanExecute( const FEventGraphSamplePtr EventPtr, const FName PropertyName, const bool bReset ) const { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(PropertyName); if( bReset ) { return false; } else { return EventPtr.IsValid() && Column.bCanBeFiltered; } } void SEventGraph::CullByProperty_Execute( const FEventGraphSamplePtr EventPtr, const FName PropertyName, const bool bReset ) { PROFILER_SCOPE_LOG_TIME( TEXT( "SEventGraph::CullByProperty_Execute" ), nullptr ); // Store current operation. SaveCurrentEventGraphState(); FEventGraphState* Op = GetCurrentState()->CreateCopyWithCulling( PropertyName, EventPtr ); CurrentStateIndex = EventGraphStatesHistory.Insert( MakeShareable(Op), CurrentStateIndex+1 ); RestoreEventGraphStateFrom( GetCurrentState() ); } bool SEventGraph::CullByProperty_CanExecute( const FEventGraphSamplePtr EventPtr, const FName PropertyName, const bool bReset ) const { const FEventGraphColumn& Column = TreeViewHeaderColumns.FindChecked(PropertyName); if( bReset ) { return false; } else { return EventPtr.IsValid() && Column.bCanBeCulled; } } void SEventGraph::GetEventsForChangingExpansion( TArray<FEventGraphSamplePtr>& out_Events, const ESelectedEventTypes::Type SelectedEventType ) { if( SelectedEventType == ESelectedEventTypes::AllEvents ) { out_Events = GetCurrentState()->GetRealRoot()->GetChildren(); } else if( SelectedEventType == ESelectedEventTypes::SelectedEvents ) { out_Events = TreeView_Base->GetSelectedItems(); } else if( SelectedEventType == ESelectedEventTypes::SelectedThreadEvents ) { TArray<FEventGraphSamplePtr> SelectedItems = TreeView_Base->GetSelectedItems(); TSet<FEventGraphSamplePtr> ThreadEventSet; for( int32 EventIndex = 0; EventIndex < SelectedItems.Num(); EventIndex++ ) { const FEventGraphSamplePtr ThreadEvent = SelectedItems[EventIndex]->GetOutermost(); ThreadEventSet.Add( ThreadEvent ); } out_Events = ThreadEventSet.Array(); } } void SEventGraph::SetExpansionForEvents_Execute( const ESelectedEventTypes::Type SelectedEventType, bool bShouldExpand ) { TArray<FEventGraphSamplePtr> Events; GetEventsForChangingExpansion( Events, SelectedEventType ); TreeView_SetItemsExpansion_Recurrent( Events, bShouldExpand ); } bool SEventGraph::SetExpansionForEvents_CanExecute( const ESelectedEventTypes::Type SelectedEventType, bool bShouldExpand ) const { const int32 NumSelectedItems = TreeView_Base->GetNumItemsSelected(); if( SelectedEventType == ESelectedEventTypes::AllEvents ) { return GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical; } else if( SelectedEventType == ESelectedEventTypes::SelectedEvents ) { return GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical && NumSelectedItems > 0; } else if( SelectedEventType == ESelectedEventTypes::SelectedThreadEvents ) { return GetCurrentStateViewMode() == EEventGraphViewModes::Hierarchical && NumSelectedItems > 0; } return false; } void SEventGraph::Map_SelectAllFrames_Global() { TSharedRef<FUICommandList> ProfilerCommandList = FProfilerManager::Get()->GetCommandList(); const FProfilerCommands& ProfilerCommands = FProfilerManager::GetCommands(); const FProfilerActionManager& ProfilerActionManager = FProfilerManager::GetActionManager(); // Assumes only one instance of the event graph, this may change in future. const FUIAction* UIAction = ProfilerCommandList->GetActionForCommand( ProfilerCommands.EventGraph_SelectAllFrames ); if( !UIAction ) { ProfilerCommandList->MapAction( ProfilerCommands.EventGraph_SelectAllFrames, SelectAllFrames_Custom() ); } else { // Replace with the new UI Action. const FUIAction NewUIAction = SelectAllFrames_Custom(); new((void*)UIAction) FUIAction(NewUIAction); } } /*----------------------------------------------------------------------------- Settings -----------------------------------------------------------------------------*/ EVisibility SEventGraph::EventGraphViewMode_GetVisibility( const EEventGraphViewModes::Type ViewMode ) const { if( ViewMode == EEventGraphViewModes::FlatInclusiveCoalesced || ViewMode == EEventGraphViewModes::FlatExclusiveCoalesced ) { const EVisibility Vis = FProfilerManager::GetSettings().bShowCoalescedViewModesInEventGraph ? EVisibility::Visible : EVisibility::Collapsed; if( Vis == EVisibility::Collapsed ) { // If view mode is not available event graph will switch to the hierarchical view mode. SEventGraph* MutableThis = const_cast< SEventGraph* >( this ); MutableThis->EventGraphViewMode_OnCheckStateChanged( ECheckBoxState::Checked, EEventGraphViewModes::Hierarchical ); } return Vis; } else { return EVisibility::Visible; } } void SEventGraph::ExpandCulledEvents( FEventGraphSamplePtr EventPtr ) { // Update not culled children. EventPtr->SetBooleanStateForAllChildren<EEventPropertyIndex::bIsCulled>(false); EventPtr->SetBooleanStateForAllChildren<EEventPropertyIndex::bNeedNotCulledChildrenUpdate>(true); struct FAddExcludedCulledEvents { FORCEINLINE void operator()( FEventGraphSample* InEventPtr, TArray<FEventGraphSamplePtr>& out_ExpandedCulledEvents ) { out_ExpandedCulledEvents.Add( InEventPtr->AsShared() ); } }; EventPtr->ExecuteOperationForAllChildren( FAddExcludedCulledEvents(), GetCurrentState()->ExpandedCulledEvents ); CreateEvents(); TreeView_Refresh(); } void SEventGraph::SelectAllFrames_Execute() { SwitchToEventGraphState( 0 ); } bool SEventGraph::SelectAllFrames_CanExecute() const { return IsEventGraphStatesHistoryValid(); } void SEventGraph::ProfilerManager_OnViewModeChanged( EProfilerViewMode NewViewMode ) { // if( NewViewMode == EProfilerViewMode::LineIndexBased ) // { // FunctionDetailsBox->SetVisibility( EVisibility::Visible ); // FunctionDetailsBox->SetEnabled( true ); // } // else if( NewViewMode == EProfilerViewMode::ThreadViewTimeBased ) // { // FunctionDetailsBox->SetVisibility( EVisibility::Collapsed ); // FunctionDetailsBox->SetEnabled( false ); // } } #undef LOCTEXT_NAMESPACE /*----------------------------------------------------------------------------- EventGraphState -----------------------------------------------------------------------------*/ #define LOCTEXT_NAMESPACE "FEventGraphState" FText SEventGraph::FEventGraphState::GetFullDescription() const { FTextBuilder Builder; FFormatNamedArguments Args; Args.Add(TEXT("FrameStartIndex"), GetEventGraph()->GetFrameStartIndex()); Args.Add(TEXT("FrameEndIndex"), GetEventGraph()->GetFrameEndIndex()); Args.Add(TEXT("NumberOfFrames"), GetNumFrames()); Builder.AppendLineFormat(LOCTEXT("FullDesc", "Event graph with range ({FrameStartIndex},{FrameEndIndex}) contains {NumberOfFrames} frame(s)"), Args); Builder.Indent(); if( IsRooted() ) { Builder.AppendLine(GetRootedDesc()); } if( IsCulled() ) { Builder.AppendLine(GetCullingDesc()); } if( IsFiltered() ) { Builder.AppendLine(GetFilteringDesc()); } return Builder.ToText(); } FText SEventGraph::FEventGraphState::GetRootedDesc() const { const int32 NumFakeRoots = FakeRoot->GetChildren().Num(); if (NumFakeRoots == 1) { FFormatNamedArguments Args; Args.Add(TEXT("StatName"), FText::FromName(FakeRoot->GetChildren()[0]->_StatName)); return FText::Format(LOCTEXT("RootedDesc_SingleChild", "Rooted: {StatName}"), Args); } return LOCTEXT("RootedDesc_MultipleChildren", "Rooted: Multiple"); } FText SEventGraph::FEventGraphState::GetCullingDesc() const { FFormatNamedArguments Args; Args.Add(TEXT("CulledPropertyName"), FText::FromName(CullPropertyName)); Args.Add(TEXT("EventName"), FText::FromString(CullEventPtr->GetFormattedValue(FEventGraphSample::GetEventPropertyByName(CullPropertyName).Index))); return FText::Format(LOCTEXT("CulledDesc", "Culled: {CulledPropertyName} {EventName}"), Args); } FText SEventGraph::FEventGraphState::GetFilteringDesc() const { FFormatNamedArguments Args; Args.Add(TEXT("FilterPropertyName"), FText::FromName(FilterPropertyName)); Args.Add(TEXT("EventName"), FText::FromString(FilterEventPtr->GetFormattedValue(FEventGraphSample::GetEventPropertyByName(FilterPropertyName).Index))); return FText::Format(LOCTEXT("FilteredDesc", "Filtered: {FilterPropertyName} {EventName}"), Args); } FText SEventGraph::FEventGraphState::GetHistoryDesc() const { FText Result = LOCTEXT("DefaultDesc", "Default state"); if( HistoryType == EEventHistoryTypes::Rooted ) { Result = GetRootedDesc(); } else if( HistoryType == EEventHistoryTypes::Culled ) { Result = GetCullingDesc(); } else if( HistoryType == EEventHistoryTypes::Filtered ) { Result = GetFilteringDesc(); } return Result; } static void CreateOneToOneMapping_EventGraphSample ( const FEventGraphSamplePtr LocalEvent, const FEventGraphSamplePtr SourceEvent, TMap< FEventGraphSamplePtr, FEventGraphSamplePtr >& out_MaximumToAverageMapping, TMap< FEventGraphSamplePtr, FEventGraphSamplePtr >& out_AverageToMaximumMapping ) { out_MaximumToAverageMapping.Add( LocalEvent, SourceEvent ); out_AverageToMaximumMapping.Add( SourceEvent, LocalEvent ); check( LocalEvent->GetChildren().Num() == SourceEvent->GetChildren().Num() ); for( int32 Index = 0; Index < LocalEvent->GetChildren().Num(); ++Index ) { CreateOneToOneMapping_EventGraphSample( LocalEvent->GetChildren()[Index], SourceEvent->GetChildren()[Index], out_MaximumToAverageMapping, out_AverageToMaximumMapping ); } } void SEventGraph::FEventGraphState::CreateOneToOneMapping() { CreateOneToOneMapping_EventGraphSample( MaximumEventGraph->GetRoot(), AverageEventGraph->GetRoot(), MaximumToAverageMapping, AverageToMaximumMapping ); } #undef LOCTEXT_NAMESPACE
32.825078
256
0.736977
[ "geometry", "object" ]
3a97d26d256b7093a9aa5a27f01db2baa930d534
1,450
cpp
C++
lxt/file/unit_tests/test_path.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
null
null
null
lxt/file/unit_tests/test_path.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
2
2017-06-08T21:51:34.000Z
2017-06-08T21:51:56.000Z
lxt/file/unit_tests/test_path.cpp
justinsaunders/luxatron
d474c21fb93b8ee9230ad25e6113d43873d75393
[ "MIT" ]
null
null
null
/* * test_path.cpp * mac_test_runner * * Created by Justin on 5/04/09. * Copyright 2009 Monkey Style Games. All rights reserved. * */ #include <UnitTest++.h> #include "file/path.h" namespace Lxt { TEST( Test_Path_GetExtension ) { Path no_extension = "file"; Path empty_extension = "file."; Path single_extension = "file.a"; Path double_extension = "file.a.b"; Path real_file = "/Users/Justin/Projects/msg/src/prototypes/model/build/Debug-iphoneos/Quack!.app/duck_triangulate.lxtm.ref"; CHECK_EQUAL( "", Path_GetExtension( no_extension ) ); CHECK_EQUAL( ".", Path_GetExtension( empty_extension ) ); CHECK_EQUAL( ".a", Path_GetExtension( single_extension ) ); CHECK_EQUAL( ".b", Path_GetExtension( double_extension ) ); CHECK_EQUAL( ".ref", Path_GetExtension( real_file ) ); } TEST( Test_Path_GetFilename ) { Path no_filename = ""; Path simple_filename = "file"; Path simple_filename2 = "/file"; Path folder_filename = "folder/file"; Path real_file = "/Users/Justin/Projects/msg/src/prototypes/model/build/Debug-iphoneos/Quack!.app/duck_triangulate.lxtm.ref"; CHECK_EQUAL( "", Path_GetFilename( no_filename ) ); CHECK_EQUAL( "file", Path_GetFilename( simple_filename ) ); CHECK_EQUAL( "file", Path_GetFilename( simple_filename2 ) ); CHECK_EQUAL( "file", Path_GetFilename( folder_filename ) ); CHECK_EQUAL( "duck_triangulate.lxtm.ref", Path_GetFilename( real_file ) ); } }
31.521739
110
0.708966
[ "model" ]
3a982bd0f822929cc50e103b927a40b4789f005b
1,005
hpp
C++
include/Client/IGraphicLibrary.hpp
semper24/R-Type
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
[ "MIT" ]
null
null
null
include/Client/IGraphicLibrary.hpp
semper24/R-Type
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
[ "MIT" ]
null
null
null
include/Client/IGraphicLibrary.hpp
semper24/R-Type
b91184d656ffcec39b0a43e7a42c1a1ecd236c9b
[ "MIT" ]
null
null
null
/* ** IGraphicLibrary.hpp for OOP_arcade_2019 in /home/arthurbertaud/Second_year/OOP/OOP_arcade_2019/core/include ** ** Made by arthurbertaud ** Login <EPITECH> ** ** Started on Mon Mar 9 11:16:44 AM 2020 arthurbertaud ** Last update Sun Apr 4 6:44:49 PM 2020 arthurbertaud */ #ifndef IGRAPHICLIBRARY_HPP_ #define IGRAPHICLIBRARY_HPP_ #include <string> #include <vector> #include <map> #include <memory> #include "entityType.hpp" #include "Entity.hpp" namespace Graphic { enum Command { NOTHING, EXIT, RIGHT, LEFT, UP, DOWN, SHOOT, }; class IGraphicLibrary { public: virtual ~IGraphicLibrary() = default; virtual void init(const sf::Vector2f &scale) = 0; virtual void stop() = 0; virtual Command eventHandler() = 0; virtual void drawGame(const std::vector<std::shared_ptr<Graphic::Entity>> &) = 0; virtual const std::string getPlayerName() = 0; virtual void displayWindow() = 0; protected: private: }; } #endif /* !IGRAPHICLIBRARY_HPP_ */
19.705882
110
0.694527
[ "vector" ]
3a9b7249b6a0600f29d6912d74dc8fdadf420f38
5,114
cpp
C++
tests/draw.cpp
dave7895/libchess
f32d66249830c0cb2c378121dcca473c49b17e3e
[ "MIT" ]
null
null
null
tests/draw.cpp
dave7895/libchess
f32d66249830c0cb2c378121dcca473c49b17e3e
[ "MIT" ]
null
null
null
tests/draw.cpp
dave7895/libchess
f32d66249830c0cb2c378121dcca473c49b17e3e
[ "MIT" ]
2
2022-02-15T15:19:55.000Z
2022-02-21T22:54:13.000Z
#include <array> #include <libchess/position.hpp> #include <string> #include <vector> #include "catch.hpp" TEST_CASE("Position::threefold() static") { using pair_type = std::pair<std::string, bool>; const std::array<pair_type, 4> tests = {{ {"startpos", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 99 1", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 100 1", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 101 1", false}, }}; for (const auto &[fen, threefold] : tests) { const auto pos = libchess::Position{fen}; REQUIRE(pos.threefold() == threefold); } } TEST_CASE("Position::threefold() positive sequence") { using pair_type = std::pair<std::string, std::vector<std::string>>; const std::array<pair_type, 2> tests = {{ {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8"}}, {"r2q1rk1/pp1bppbp/2np1np1/8/2BNP3/2N1BP2/PPPQ2PP/R3K2R w KQ - 5 10", {"c3a4", "c6a5", "a4c3", "a5c6", "c3a4", "c6a5", "a4c3", "a5c6"}}, }}; for (const auto &[fen, moves] : tests) { auto pos = libchess::Position(fen); for (const auto &movestr : moves) { REQUIRE(!pos.threefold()); pos.makemove(movestr); } // Terminal position threefold REQUIRE(pos.threefold()); } } TEST_CASE("Position::threefold() negative sequence") { using pair_type = std::pair<std::string, std::vector<std::string>>; const std::array<pair_type, 3> tests = {{ {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1"}}, {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "e2e3", "e7e6", "g1f3", "g8f6", "f3g1", "f6g8"}}, // Make sure castling permissions are considered {"r2q1rk1/pp1bppbp/2np1np1/8/2BNP3/2N1BP2/PPPQ2PP/R3K2R w KQ - 5 10", {"c3a4", "c6a5", "a4c3", "a5c6", "e1g1", "d7e6", "g1f2", "e6d7", "f2e1", "d7e6", "f1h1", "e6d7", "c3a4", "c6a5", "a4c3", "a5c6"}}, }}; for (const auto &[fen, moves] : tests) { auto pos = libchess::Position(fen); for (const auto &movestr : moves) { REQUIRE(!pos.threefold()); pos.makemove(movestr); } // Terminal position not threefold REQUIRE(!pos.threefold()); } } TEST_CASE("Position::fiftymoves()") { using pair_type = std::pair<std::string, bool>; const std::array<pair_type, 4> tests = {{ {"startpos", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 99 1", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 100 1", true}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 101 1", true}, }}; for (const auto &[fen, ans] : tests) { auto pos = libchess::Position{fen}; REQUIRE(pos.fiftymoves() == ans); } } TEST_CASE("Position::is_draw() fiftymoves") { const std::array<std::pair<std::string, bool>, 5> tests = {{ {"startpos", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 99 1", false}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 100 1", true}, {"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 101 1", true}, // more than fiftymoves according to fen, but checkmate {"3k1R2/8/3K4/8/8/8/8/8 b - - 110 1", false}, }}; for (const auto &[fen, ans] : tests) { auto pos = libchess::Position{fen}; REQUIRE(pos.is_draw() == ans); } } TEST_CASE("Position::is_draw() threefold") { using test_type = std::tuple<std::string, std::vector<std::string>, bool>; const std::array<test_type, 5> tests = {{ {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1", "f6g8"}, true}, {"r2q1rk1/pp1bppbp/2np1np1/8/2BNP3/2N1BP2/PPPQ2PP/R3K2R w KQ - 5 10", {"c3a4", "c6a5", "a4c3", "a5c6", "c3a4", "c6a5", "a4c3", "a5c6"}, true}, {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "g1f3", "g8f6", "f3g1"}, false}, {"startpos", {"g1f3", "g8f6", "f3g1", "f6g8", "e2e3", "e7e6", "g1f3", "g8f6", "f3g1", "f6g8"}, false}, // Make sure castling permissions are considered {"r2q1rk1/pp1bppbp/2np1np1/8/2BNP3/2N1BP2/PPPQ2PP/R3K2R w KQ - 5 10", {"c3a4", "c6a5", "a4c3", "a5c6", "e1g1", "d7e6", "g1f2", "e6d7", "f2e1", "d7e6", "f1h1", "e6d7", "c3a4", "c6a5", "a4c3", "a5c6"}, false}, }}; for (const auto &[fen, moves, ans] : tests) { auto pos = libchess::Position(fen); for (const auto &movestr : moves) { REQUIRE(!pos.is_draw()); pos.makemove(movestr); } // Terminal position threefold REQUIRE(pos.is_draw() == ans); REQUIRE(pos.is_terminal() == ans); } }
33.207792
110
0.530309
[ "vector" ]
3a9e26901245b54016d47d92c7871eb11b697ba9
40,341
cpp
C++
src/llvmir2hlltool/llvmir2hll.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/llvmir2hlltool/llvmir2hll.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/llvmir2hlltool/llvmir2hll.cpp
Andrik-555/retdec
1ac63a520da02912daf836b924f41d95b1b5fa10
[ "MIT", "BSD-3-Clause" ]
null
null
null
/** * @file src/llvmir2hlltool/llvmir2hll.cpp * @brief Convertor of LLVM IR into the specified target high-level language. * @copyright (c) 2017 Avast Software, licensed under the MIT license * * The implementation of this tool is based on llvm/tools/llc/llc.cpp. */ #include <algorithm> #include <fstream> #include <memory> #include <llvm/ADT/Triple.h> #include <llvm/Analysis/LoopInfo.h> #include <llvm/Analysis/ScalarEvolution.h> #include <llvm/Analysis/TargetLibraryInfo.h> #include <llvm/IR/DataLayout.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/LegacyPassManager.h> #include <llvm/IR/Module.h> #include <llvm/IRReader/IRReader.h> #include <llvm/MC/SubtargetFeature.h> #include <llvm/Pass.h> #include <llvm/Support/CommandLine.h> #include <llvm/Support/Debug.h> #include <llvm/Support/ErrorHandling.h> #include <llvm/Support/FileSystem.h> #include <llvm/Support/FormattedStream.h> #include <llvm/Support/Host.h> #include <llvm/Support/ManagedStatic.h> #include <llvm/Support/PluginLoader.h> #include <llvm/Support/PrettyStackTrace.h> #include <llvm/Support/Signals.h> #include <llvm/Support/SourceMgr.h> #include <llvm/Support/TargetRegistry.h> #include <llvm/Support/TargetSelect.h> #include <llvm/Support/ToolOutputFile.h> #include <llvm/Target/TargetMachine.h> #include <llvm/Target/TargetSubtargetInfo.h> #include "retdec/llvmir2hll/analysis/alias_analysis/alias_analysis.h" #include "retdec/llvmir2hll/analysis/alias_analysis/alias_analysis_factory.h" #include "retdec/llvmir2hll/analysis/value_analysis.h" #include "retdec/llvmir2hll/config/configs/json_config.h" #include "retdec/llvmir2hll/evaluator/arithm_expr_evaluator.h" #include "retdec/llvmir2hll/evaluator/arithm_expr_evaluator_factory.h" #include "retdec/llvmir2hll/graphs/cfg/cfg_builders/non_recursive_cfg_builder.h" #include "retdec/llvmir2hll/graphs/cfg/cfg_writer.h" #include "retdec/llvmir2hll/graphs/cfg/cfg_writer_factory.h" #include "retdec/llvmir2hll/graphs/cg/cg_builder.h" #include "retdec/llvmir2hll/graphs/cg/cg_writer.h" #include "retdec/llvmir2hll/graphs/cg/cg_writer_factory.h" #include "retdec/llvmir2hll/hll/hll_writer.h" #include "retdec/llvmir2hll/hll/hll_writer_factory.h" #include "retdec/llvmir2hll/ir/function.h" #include "retdec/llvmir2hll/ir/module.h" #include "retdec/llvmir2hll/llvm/llvm_debug_info_obtainer.h" #include "retdec/llvmir2hll/llvm/llvm_intrinsic_converter.h" #include "retdec/llvmir2hll/llvm/llvmir2bir_converter.h" #include "retdec/llvmir2hll/llvm/llvmir2bir_converter_factory.h" #include "retdec/llvmir2hll/obtainer/call_info_obtainer.h" #include "retdec/llvmir2hll/obtainer/call_info_obtainer_factory.h" #include "retdec/llvmir2hll/optimizer/optimizer_manager.h" #include "retdec/llvmir2hll/pattern/pattern_finder_factory.h" #include "retdec/llvmir2hll/pattern/pattern_finder_runner.h" #include "retdec/llvmir2hll/pattern/pattern_finder_runners/cli_pattern_finder_runner.h" #include "retdec/llvmir2hll/pattern/pattern_finder_runners/no_action_pattern_finder_runner.h" #include "retdec/llvmir2hll/semantics/semantics/compound_semantics_builder.h" #include "retdec/llvmir2hll/semantics/semantics/default_semantics.h" #include "retdec/llvmir2hll/semantics/semantics_factory.h" #include "retdec/llvmir2hll/support/const_symbol_converter.h" #include "retdec/llvmir2hll/support/debug.h" #include "retdec/llvmir2hll/support/expr_types_fixer.h" #include "retdec/llvmir2hll/support/funcs_with_prefix_remover.h" #include "retdec/llvmir2hll/support/library_funcs_remover.h" #include "retdec/llvmir2hll/support/unreachable_code_in_cfg_remover.h" #include "retdec/llvmir2hll/utils/ir.h" #include "retdec/llvmir2hll/utils/string.h" #include "retdec/llvmir2hll/validator/validator.h" #include "retdec/llvmir2hll/validator/validator_factory.h" #include "retdec/llvmir2hll/var_name_gen/var_name_gen_factory.h" #include "retdec/llvmir2hll/var_name_gen/var_name_gens/num_var_name_gen.h" #include "retdec/llvmir2hll/var_renamer/var_renamer.h" #include "retdec/llvmir2hll/var_renamer/var_renamer_factory.h" #include "retdec/llvm-support/diagnostics.h" #include "retdec/utils/container.h" #include "retdec/utils/conversion.h" #include "retdec/utils/memory.h" #include "retdec/utils/string.h" using namespace llvm; using retdec::llvmir2hll::ShPtr; using retdec::utils::hasItem; using retdec::utils::joinStrings; using retdec::utils::limitSystemMemory; using retdec::utils::limitSystemMemoryToHalfOfTotalSystemMemory; using retdec::utils::split; using retdec::utils::strToNum; namespace { // // Parameters. // cl::opt<std::string> TargetHLL("target-hll", cl::desc("Name of the target HLL (set to 'help' to list all the supported HLLs)."), cl::init("!bad!")); // We cannot use just -debug because it has been already registered :(. cl::opt<bool> Debug("enable-debug", cl::desc("Enables the emission of debugging messages, like information about the current phase."), cl::init(false)); cl::opt<std::string> Semantics("semantics", cl::desc("The used semantics in the form 'sem1,sem2,...'." " When not given, the semantics is created based on the data in the input LLVM IR." " If you want to use no semantics, set this to 'none'."), cl::init("")); cl::opt<std::string> ConfigPath("config-path", cl::desc("Path to the configuration file."), cl::init("")); cl::opt<bool> EmitDebugComments("emit-debug-comments", cl::desc("Emits debugging comments in the generated code."), cl::init(false)); cl::opt<std::string> EnabledOpts("enabled-opts", cl::desc("A comma separated list of optimizations to be enabled, i.e. only they will run."), cl::init("")); cl::opt<std::string> DisabledOpts("disabled-opts", cl::desc("A comma separated list of optimizations to be disabled, i.e. they will not run."), cl::init("")); cl::opt<bool> NoOpts("no-opts", cl::desc("Disables all optimizations."), cl::init(false)); cl::opt<bool> AggressiveOpts("aggressive-opts", cl::desc("Enables aggressive optimizations."), cl::init(false)); cl::opt<bool> NoVarRenaming("no-var-renaming", cl::desc("Disables renaming of variables."), cl::init(false)); cl::opt<bool> NoSymbolicNames("no-symbolic-names", cl::desc("Disables conversion of constants into symbolic names."), cl::init(false)); cl::opt<bool> KeepAllBrackets("keep-all-brackets", cl::desc("All brackets in the generated code will be kept."), cl::init(false)); cl::opt<bool> KeepLibraryFunctions("keep-library-funcs", cl::desc("Functions from standard libraries will be kept, not turned into declarations."), cl::init(false)); cl::opt<bool> NoTimeVaryingInfo("no-time-varying-info", cl::desc("Do not emit time-varying information, like dates."), cl::init(false)); cl::opt<bool> NoCompoundOperators("no-compound-operators", cl::desc("Do not emit compound operators (like +=) instead of assignments."), cl::init(false)); cl::opt<bool> ValidateModule("validate-module", cl::desc("Validates the resulting module before generating the target code."), cl::init(false)); cl::opt<std::string> FindPatterns("find-patterns", cl::desc("If set, runs the selected comma-separated pattern finders " "(set to 'all' to run all of them)."), cl::init("")); cl::opt<std::string> AliasAnalysis("alias-analysis", cl::desc("Name of the used alias analysis " "(the default is 'simple'; set to 'help' to list all the supported analyses)."), cl::init("simple")); cl::opt<std::string> VarNameGen("var-name-gen", cl::desc("Name of the used generator of variable names " "(the default is 'fruit'; set to 'help' to list all the supported generators)."), cl::init("fruit")); cl::opt<std::string> VarNameGenPrefix("var-name-gen-prefix", cl::desc("Prefix for all variable names returned by the used generator of variable names " "(the default is '')."), cl::init("")); cl::opt<std::string> VarRenamer("var-renamer", cl::desc("Name of the used renamer of variable names " "(the default is 'readable'; set to 'help' to list all the supported renamers)."), cl::init("readable")); cl::opt<std::string> LLVMIR2BIRConverter("llvmir2bir-converter", cl::desc("Name of the used convereter of LLVM IR to BIR " "(the default is 'orig'; set to 'help' to list all the supported renamers)."), cl::init("orig")); cl::opt<bool> EmitCFGs("emit-cfgs", cl::desc("Enables the emission of control-flow graphs (CFGs) for each " "function (creates a separate file for each function in the resulting module)."), cl::init(false)); cl::opt<std::string> CFGWriter("cfg-writer", cl::desc("Name of the used CFG writer (set to 'help' to list all " "the supported writers, the default is 'dot')."), cl::init("dot")); cl::opt<bool> EmitCG("emit-cg", cl::desc("Emits a call graph (CG) for the decompiled module."), cl::init(false)); cl::opt<std::string> CGWriter("cg-writer", cl::desc("Name of the used CG writer (set to 'help' to list all " "the supported writers, the default is 'dot')."), cl::init("dot")); cl::opt<std::string> CallInfoObtainer("call-info-obtainer", cl::desc("Name of the used obtainer of information about function calls (set to " "'help' to list all the supported obtainers, the default is 'optim')."), cl::init("optim")); cl::opt<std::string> ArithmExprEvaluator("arithm-expr-evaluator", cl::desc("Name of the used evaluator of arithmetical expressions (set to " "'help' to list all the supported evaluators, the default is 'c')."), cl::init("c")); cl::opt<std::string> ForcedModuleName("force-module-name", cl::desc("If nonempty, overwrites the module name that was detected/generated by the front-end. " "This includes the identifier of the input LLVM IR module as well as module names in debug information."), cl::init("")); cl::opt<bool> StrictFPUSemantics("strict-fpu-semantics", cl::desc("Forces strict FPU semantics to be used. " "This option may result into more correct code, although slightly less readable."), cl::init(false)); // Does not work with std::size_t or std::uint64_t (passing -max-memory=100 // fails with "Cannot find option named '100'!"), so we have to use unsigned // long long, which should be 64b. cl::opt<unsigned long long> MaxMemoryLimit("max-memory", cl::desc("Limit maximal memory to the given number of bytes (0 means no limit)."), cl::init(0)); static cl::opt<bool> MaxMemoryLimitHalfRAM("max-memory-half-ram", cl::desc("Limit maximal memory to half of system RAM."), cl::init(false)); cl::opt<std::string> InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-")); cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename")); /** * @brief Returns a list of all supported objects by the given factory. * * @tparam FactoryType Type of the factory in whose objects we are interested in. * * The list is comma separated and has no beginning or trailing whitespace. */ template<typename FactoryType> std::string getListOfSupportedObjects() { return joinStrings(FactoryType::getInstance().getRegisteredObjects()); } /** * @brief Prints an error message concerning the situation when an unsupported * object has been selected from the given factory. * * @param[in] typeOfObjectsSingular A human-readable description of the type of * objects the factory provides. In the * singular form, e.g. "HLL writer". * @param[in] typeOfObjectsPlural A human-readable description of the type of * objects the factory provides. In the plural * form, e.g. "HLL writers". * * @tparam FactoryType Type of the factory in whose objects we are interested in. */ template<typename FactoryType> void printErrorUnsupportedObject(const std::string &typeOfObjectsSingular, const std::string &typeOfObjectsPlural) { std::string supportedObjects(getListOfSupportedObjects<FactoryType>()); if (!supportedObjects.empty()) { retdec::llvm_support::printErrorMessage("Invalid name of the ", typeOfObjectsSingular, " (supported names are: ", supportedObjects, ")."); } else { retdec::llvm_support::printErrorMessage("There are no available ", typeOfObjectsPlural, ". Please, recompile the backend and try it" " again."); } } } // anonymous namespace namespace llvmir2hlltool { /** * @brief This class is the main chunk of code that converts an LLVM * module to the specified high-level language (HLL). * * The decompilation is composed of the following steps: * 1) LLVM instantiates Decompiler with the output stream, where the target * code will be emitted. * 2) The function runOnModule() is called, which decompiles the given * LLVM IR into BIR (backend IR). * 3) The resulting IR is then converted into the requested HLL at the end of * runOnModule(). * * The HLL is specified in `-target-hll` when running llvmir2hll. Debug comments * can be enabled by using the `-emit-debug-comments` parameter. For more * information, run llvmir2hll with `-help`. */ class Decompiler: public ModulePass { public: explicit Decompiler(raw_pwrite_stream &out); virtual const char *getPassName() const override { return "Decompiler"; } virtual bool runOnModule(Module &m) override; public: /// Class identification. static char ID; private: virtual void getAnalysisUsage(AnalysisUsage &au) const override { au.addRequired<LoopInfoWrapperPass>(); au.addRequired<ScalarEvolutionWrapperPass>(); au.setPreservesAll(); } bool initialize(Module &m); bool limitMaximalMemoryIfRequested(); void createSemantics(); void createSemanticsFromParameter(); void createSemanticsFromLLVMIR(); bool loadConfig(); void saveConfig(); bool convertLLVMIRToBIR(); void removeLibraryFuncs(); void removeCodeUnreachableInCFG(); void removeFuncsPrefixedWith(const retdec::llvmir2hll::StringSet &prefixes); void fixSignedUnsignedTypes(); void convertLLVMIntrinsicFunctions(); void obtainDebugInfo(); void initAliasAnalysis(); void runOptimizations(); void renameVariables(); void convertConstantsToSymbolicNames(); void validateResultingModule(); void findPatterns(); void emitCFGs(); void emitCG(); void emitTargetHLLCode(); void finalize(); void cleanup(); retdec::llvmir2hll::StringSet parseListOfOpts(const std::string &opts) const; std::string getTypeOfRunOptimizations() const; retdec::llvmir2hll::StringVector getIdsOfPatternFindersToBeRun() const; retdec::llvmir2hll::PatternFinderRunner::PatternFinders instantiatePatternFinders( const retdec::llvmir2hll::StringVector &pfsIds); ShPtr<retdec::llvmir2hll::PatternFinderRunner> instantiatePatternFinderRunner() const; retdec::llvmir2hll::StringSet getPrefixesOfFuncsToBeRemoved() const; private: /// Output stream into which the generated code will be emitted. raw_pwrite_stream &out; /// The input LLVM module. Module *llvmModule; /// The resulting module in BIR. ShPtr<retdec::llvmir2hll::Module> resModule; /// The used semantics. ShPtr<retdec::llvmir2hll::Semantics> semantics; /// The used config. ShPtr<retdec::llvmir2hll::Config> config; /// The used HLL writer. ShPtr<retdec::llvmir2hll::HLLWriter> hllWriter; /// The used alias analysis. ShPtr<retdec::llvmir2hll::AliasAnalysis> aliasAnalysis; /// The used obtainer of information about function and function calls. ShPtr<retdec::llvmir2hll::CallInfoObtainer> cio; /// The used evaluator of arithmetical expressions. ShPtr<retdec::llvmir2hll::ArithmExprEvaluator> arithmExprEvaluator; /// The used generator of variable names. ShPtr<retdec::llvmir2hll::VarNameGen> varNameGen; /// The used renamer of variables. ShPtr<retdec::llvmir2hll::VarRenamer> varRenamer; }; // Static variables and constants initialization. char Decompiler::ID = 0; /** * @brief Constructs a new decompiler. * * @param[in] out Output stream into which the generated HLL code will be * emitted. */ Decompiler::Decompiler(raw_pwrite_stream &out): ModulePass(ID), out(out), llvmModule(nullptr), resModule(), semantics(), hllWriter(), aliasAnalysis(), cio(), arithmExprEvaluator(), varNameGen(), varRenamer() {} bool Decompiler::runOnModule(Module &m) { if (Debug) retdec::llvm_support::printPhase("initialization"); bool decompilationShouldContinue = initialize(m); if (!decompilationShouldContinue) { return false; } if (Debug) retdec::llvm_support::printPhase("conversion of LLVM IR into BIR"); decompilationShouldContinue = convertLLVMIRToBIR(); if (!decompilationShouldContinue) { return false; } retdec::llvmir2hll::StringSet funcPrefixes(getPrefixesOfFuncsToBeRemoved()); if (Debug) retdec::llvm_support::printPhase("removing functions prefixed with [" + joinStrings(funcPrefixes) + "]"); removeFuncsPrefixedWith(funcPrefixes); if (!KeepLibraryFunctions) { if (Debug) retdec::llvm_support::printPhase("removing functions from standard libraries"); removeLibraryFuncs(); } // The following phase needs to be done right after the conversion because // there may be code that is not reachable in a CFG. This happens because // the conversion of LLVM IR to BIR is not perfect, so it may introduce // unreachable code. This causes problems later during optimizations // because the code exists in BIR, but not in a CFG. if (Debug) retdec::llvm_support::printPhase("removing code that is not reachable in a CFG"); removeCodeUnreachableInCFG(); if (Debug) retdec::llvm_support::printPhase("signed/unsigned types fixing"); fixSignedUnsignedTypes(); if (Debug) retdec::llvm_support::printPhase("converting LLVM intrinsic functions to standard functions"); convertLLVMIntrinsicFunctions(); if (resModule->isDebugInfoAvailable()) { if (Debug) retdec::llvm_support::printPhase("obtaining debug information"); obtainDebugInfo(); } if (!NoOpts) { if (Debug) retdec::llvm_support::printPhase("alias analysis [" + aliasAnalysis->getId() + "]"); initAliasAnalysis(); if (Debug) retdec::llvm_support::printPhase("optimizations [" + getTypeOfRunOptimizations() + "]"); runOptimizations(); } if (!NoVarRenaming) { if (Debug) retdec::llvm_support::printPhase("variable renaming [" + varRenamer->getId() + "]"); renameVariables(); } if (!NoSymbolicNames) { if (Debug) retdec::llvm_support::printPhase("converting constants to symbolic names"); convertConstantsToSymbolicNames(); } if (ValidateModule) { if (Debug) retdec::llvm_support::printPhase("module validation"); validateResultingModule(); } if (!FindPatterns.empty()) { if (Debug) retdec::llvm_support::printPhase("finding patterns"); findPatterns(); } if (EmitCFGs) { if (Debug) retdec::llvm_support::printPhase("emission of control-flow graphs"); emitCFGs(); } if (EmitCG) { if (Debug) retdec::llvm_support::printPhase("emission of a call graph"); emitCG(); } if (Debug) retdec::llvm_support::printPhase("emission of the target code [" + hllWriter->getId() + "]"); emitTargetHLLCode(); if (Debug) retdec::llvm_support::printPhase("finalization"); finalize(); if (Debug) retdec::llvm_support::printPhase("cleanup"); cleanup(); return false; } /** * @brief Initializes all the needed private variables. * * @return @c true if the decompilation should continue (the initialization went * OK), @c false otherwise. */ bool Decompiler::initialize(Module &m) { llvmModule = &m; // Maximal memory limitation. bool memoryLimitationSucceeded = limitMaximalMemoryIfRequested(); if (!memoryLimitationSucceeded) { return false; } // Instantiate the requested HLL writer and make sure it exists. We need to // explicitly specify template parameters because raw_pwrite_stream has // a private copy constructor, so it needs to be passed by reference. if (Debug) retdec::llvm_support::printSubPhase("creating the used HLL writer [" + TargetHLL + "]"); hllWriter = retdec::llvmir2hll::HLLWriterFactory::getInstance().createObject< raw_pwrite_stream &>(TargetHLL, out); if (!hllWriter) { printErrorUnsupportedObject<retdec::llvmir2hll::HLLWriterFactory>( "target HLL", "target HLLs"); return false; } // Instantiate the requested alias analysis and make sure it exists. if (Debug) retdec::llvm_support::printSubPhase("creating the used alias analysis [" + AliasAnalysis + "]"); aliasAnalysis = retdec::llvmir2hll::AliasAnalysisFactory::getInstance().createObject( AliasAnalysis); if (!aliasAnalysis) { printErrorUnsupportedObject<retdec::llvmir2hll::AliasAnalysisFactory>( "alias analysis", "alias analyses"); return false; } // Instantiate the requested obtainer of information about function // calls and make sure it exists. if (Debug) retdec::llvm_support::printSubPhase("creating the used call info obtainer [" + CallInfoObtainer + "]"); cio = retdec::llvmir2hll::CallInfoObtainerFactory::getInstance().createObject( CallInfoObtainer); if (!cio) { printErrorUnsupportedObject<retdec::llvmir2hll::CallInfoObtainerFactory>( "call info obtainer", "call info obtainers"); return false; } // Instantiate the requested evaluator of arithmetical expressions and make // sure it exists. if (Debug) retdec::llvm_support::printSubPhase("creating the used evaluator of arithmetical expressions [" + ArithmExprEvaluator + "]"); arithmExprEvaluator = retdec::llvmir2hll::ArithmExprEvaluatorFactory::getInstance().createObject( ArithmExprEvaluator); if (!arithmExprEvaluator) { printErrorUnsupportedObject<retdec::llvmir2hll::ArithmExprEvaluatorFactory>( "evaluator of arithmetical expressions", "evaluators of arithmetical expressions"); return false; } // Instantiate the requested variable names generator and make sure it // exists. if (Debug) retdec::llvm_support::printSubPhase("creating the used variable names generator [" + VarNameGen + "]"); varNameGen = retdec::llvmir2hll::VarNameGenFactory::getInstance().createObject( VarNameGen, VarNameGenPrefix); if (!varNameGen) { printErrorUnsupportedObject<retdec::llvmir2hll::VarNameGenFactory>( "variable names generator", "variable names generators"); return false; } // Instantiate the requested variable renamer and make sure it exists. if (Debug) retdec::llvm_support::printSubPhase("creating the used variable renamer [" + VarRenamer + "]"); varRenamer = retdec::llvmir2hll::VarRenamerFactory::getInstance().createObject( VarRenamer, varNameGen, true); if (!varRenamer) { printErrorUnsupportedObject<retdec::llvmir2hll::VarRenamerFactory>( "renamer of variables", "renamers of variables"); return false; } createSemantics(); bool configLoaded = loadConfig(); if (!configLoaded) { return false; } // Everything went OK. return true; } /** * @brief Limits the maximal memory of the tool based on the command-line * parameters. */ bool Decompiler::limitMaximalMemoryIfRequested() { if (MaxMemoryLimitHalfRAM) { auto limitationSucceeded = limitSystemMemoryToHalfOfTotalSystemMemory(); if (!limitationSucceeded) { retdec::llvm_support::printErrorMessage( "Failed to limit maximal memory to half of system RAM." ); return false; } } else if (MaxMemoryLimit > 0) { auto limitationSucceeded = limitSystemMemory(MaxMemoryLimit); if (!limitationSucceeded) { retdec::llvm_support::printErrorMessage( "Failed to limit maximal memory to " + std::to_string(MaxMemoryLimit) + "." ); } } return true; } /** * @brief Creates the used semantics. */ void Decompiler::createSemantics() { if (!Semantics.empty()) { // The user has requested some concrete semantics, so use it. createSemanticsFromParameter(); } else { // The user didn't request any semantics, so create it based on the // data in the input LLVM IR. createSemanticsFromLLVMIR(); } } /** * @brief Creates the used semantics as requested by the user. */ void Decompiler::createSemanticsFromParameter() { if (Semantics.empty() || Semantics == "-") { // Do no use any semantics. if (Debug) retdec::llvm_support::printSubPhase("creating the used semantics [none]"); semantics = retdec::llvmir2hll::DefaultSemantics::create(); } else { // Use the given semantics. if (Debug) retdec::llvm_support::printSubPhase("creating the used semantics [" + Semantics + "]"); semantics = retdec::llvmir2hll::CompoundSemanticsBuilder::build(split(Semantics, ',')); } } /** * @brief Creates the used semantics based on the data in the input LLVM IR. */ void Decompiler::createSemanticsFromLLVMIR() { // Create a list of the semantics to be used. // TODO Use some data from the input LLVM IR, like the used compiler. std::string usedSemantics("libc,gcc-general,win-api"); // Use the list to create the semantics. if (Debug) retdec::llvm_support::printSubPhase("creating the used semantics [" + usedSemantics + "]"); semantics = retdec::llvmir2hll::CompoundSemanticsBuilder::build(split(usedSemantics, ',')); } /** * @brief Loads a config for the module. * * @return @a true if the config was loaded successfully, @c false otherwise. */ bool Decompiler::loadConfig() { // Currently, we always use the JSON config. if (ConfigPath.empty()) { if (Debug) retdec::llvm_support::printSubPhase("creating a new config"); config = retdec::llvmir2hll::JSONConfig::empty(); return true; } if (Debug) retdec::llvm_support::printSubPhase("loading the input config"); try { config = retdec::llvmir2hll::JSONConfig::fromFile(ConfigPath); return true; } catch (const retdec::llvmir2hll::ConfigError &ex) { retdec::llvm_support::printErrorMessage( "Loading of the config failed: " + ex.getMessage() + "." ); return false; } } /** * @brief Saves the config file. */ void Decompiler::saveConfig() { if (!ConfigPath.empty()) { config->saveTo(ConfigPath); } } /** * @brief Convert the LLVM IR module into a BIR module using the instantiated * converter. * @return @c True if decompilation should continue, @c False if something went * wrong and decompilation should abort. */ bool Decompiler::convertLLVMIRToBIR() { // Instantiate the requested converter of LLVM IR to BIR and make sure it // exists. if (Debug) { retdec::llvm_support::printSubPhase("creating the used LLVM IR to BIR converter [" + LLVMIR2BIRConverter + "]"); } auto llvm2BIRConverter = retdec::llvmir2hll::LLVMIR2BIRConverterFactory::getInstance().createObject( LLVMIR2BIRConverter, this); if (!llvm2BIRConverter) { printErrorUnsupportedObject<retdec::llvmir2hll::LLVMIR2BIRConverterFactory>( "converter of LLVM IR to BIR", "converters of LLVM IR to BIR"); return false; } // Options llvm2BIRConverter->setOptionStrictFPUSemantics(StrictFPUSemantics); std::string moduleName = ForcedModuleName.empty() ? llvmModule->getModuleIdentifier() : ForcedModuleName; resModule = llvm2BIRConverter->convert(llvmModule, moduleName, semantics, config, Debug); return true; } /** * @brief Removes defined functions which are from some standard library whose * header file has to be included because of some function declarations. */ void Decompiler::removeLibraryFuncs() { retdec::llvmir2hll::FuncVector removedFuncs(retdec::llvmir2hll::LibraryFuncsRemover::removeFuncs( resModule)); if (Debug) { // Emit the functions that were turned into declarations. Before that, // however, sort them by name to provide a more deterministic output. retdec::llvmir2hll::sortByName(removedFuncs); for (const auto &func : removedFuncs) { retdec::llvm_support::printSubPhase("removing " + func->getName() + "()"); } } } /** * @brief Removes code from all the functions in the module that is unreachable * in the CFG. */ void Decompiler::removeCodeUnreachableInCFG() { retdec::llvmir2hll::UnreachableCodeInCFGRemover::removeCode(resModule); } /** * @brief Removes functions with the given prefix. */ void Decompiler::removeFuncsPrefixedWith(const retdec::llvmir2hll::StringSet &prefixes) { retdec::llvmir2hll::FuncsWithPrefixRemover::removeFuncs(resModule, prefixes); } /** * @brief Fixes signed and unsigned types in the resulting module. */ void Decompiler::fixSignedUnsignedTypes() { retdec::llvmir2hll::ExprTypesFixer::fixTypes(resModule); } /** * @brief Converts LLVM intrinsic functions to functions from the standard * library. */ void Decompiler::convertLLVMIntrinsicFunctions() { retdec::llvmir2hll::LLVMIntrinsicConverter::convert(resModule); } /** * @brief When available, obtains debugging information. */ void Decompiler::obtainDebugInfo() { retdec::llvmir2hll::LLVMDebugInfoObtainer::obtainVarNames(resModule); } /** * @brief Initializes the alias analysis. */ void Decompiler::initAliasAnalysis() { aliasAnalysis->init(resModule); } /** * @brief Runs the optimizations over the resulting module. */ void Decompiler::runOptimizations() { ShPtr<retdec::llvmir2hll::OptimizerManager> optManager(new retdec::llvmir2hll::OptimizerManager( parseListOfOpts(EnabledOpts), parseListOfOpts(DisabledOpts), hllWriter, retdec::llvmir2hll::ValueAnalysis::create(aliasAnalysis, true), cio, arithmExprEvaluator, AggressiveOpts, Debug)); optManager->optimize(resModule); } /** * @brief Renames variables in the resulting module by using the selected * variable renamer. */ void Decompiler::renameVariables() { varRenamer->renameVars(resModule); } /** * @brief Converts constants in function calls to symbolic names. */ void Decompiler::convertConstantsToSymbolicNames() { retdec::llvmir2hll::ConstSymbolConverter::convert(resModule); } /** * @brief Validates the resulting module. */ void Decompiler::validateResultingModule() { // Run all the registered validators over the resulting module, sorted by // name. retdec::llvmir2hll::StringVector regValidatorIDs( retdec::llvmir2hll::ValidatorFactory::getInstance().getRegisteredObjects()); std::sort(regValidatorIDs.begin(), regValidatorIDs.end()); for (const auto &id : regValidatorIDs) { if (Debug) retdec::llvm_support::printSubPhase("running " + id + "Validator"); ShPtr<retdec::llvmir2hll::Validator> validator( retdec::llvmir2hll::ValidatorFactory::getInstance().createObject(id)); validator->validate(resModule, true); } } /** * @brief Finds patterns in the resulting module. */ void Decompiler::findPatterns() { retdec::llvmir2hll::StringVector pfsIds(getIdsOfPatternFindersToBeRun()); retdec::llvmir2hll::PatternFinderRunner::PatternFinders pfs(instantiatePatternFinders(pfsIds)); ShPtr<retdec::llvmir2hll::PatternFinderRunner> pfr(instantiatePatternFinderRunner()); pfr->run(pfs, resModule); } /** * @brief Emits the target HLL code. */ void Decompiler::emitTargetHLLCode() { hllWriter->setOptionEmitDebugComments(EmitDebugComments); hllWriter->setOptionKeepAllBrackets(KeepAllBrackets); hllWriter->setOptionEmitTimeVaryingInfo(!NoTimeVaryingInfo); hllWriter->setOptionUseCompoundOperators(!NoCompoundOperators); hllWriter->emitTargetCode(resModule); } /** * @brief Finalizes the run of the back-end part. */ void Decompiler::finalize() { saveConfig(); } /** * @brief Cleanup. */ void Decompiler::cleanup() { // Nothing to do. // Note: Do not remove this phase, even if there is nothing to do. The // presence of this phase is needed for the analyzing scripts in // scripts/decompiler_tests (it marks the very last phase of a successful // decompilation). } /** * @brief Emits a control-flow graph (CFG) for each function in the resulting * module. */ void Decompiler::emitCFGs() { // Make sure that the requested CFG writer exists. retdec::llvmir2hll::StringVector availCFGWriters( retdec::llvmir2hll::CFGWriterFactory::getInstance().getRegisteredObjects()); if (!hasItem(availCFGWriters, std::string(CFGWriter))) { printErrorUnsupportedObject<retdec::llvmir2hll::CFGWriterFactory>( "CFG writer", "CFG writers"); return; } // Instantiate a CFG builder. ShPtr<retdec::llvmir2hll::CFGBuilder> cfgBuilder(retdec::llvmir2hll::NonRecursiveCFGBuilder::create()); // Get the extension of the files that will be written (we use the CFG // writer's name for this purpose). std::string fileExt(CFGWriter); // For each function in the resulting module... for (auto i = resModule->func_definition_begin(), e = resModule->func_definition_end(); i != e; ++i) { // Open the output file. std::string fileName(OutputFilename + ".cfg." + (*i)->getName() + "." + fileExt); std::ofstream out(fileName.c_str()); if (!out) { retdec::llvm_support::printErrorMessage("Cannot open " + fileName + " for writing."); return; } // Create a CFG for the current function and emit it into the opened // file. ShPtr<retdec::llvmir2hll::CFGWriter> writer(retdec::llvmir2hll::CFGWriterFactory::getInstance( ).createObject<ShPtr<retdec::llvmir2hll::CFG>, std::ostream &>( CFGWriter, cfgBuilder->getCFG(*i), out)); ASSERT_MSG(writer, "instantiation of the requested CFG writer `" << CFGWriter << "` failed"); writer->emitCFG(); } } /** * @brief Emits a call graph (CG) for the resulting module. */ void Decompiler::emitCG() { // Make sure that the requested CG writer exists. retdec::llvmir2hll::StringVector availCGWriters( retdec::llvmir2hll::CGWriterFactory::getInstance().getRegisteredObjects()); if (!hasItem(availCGWriters, std::string(CGWriter))) { printErrorUnsupportedObject<retdec::llvmir2hll::CGWriterFactory>( "CG writer", "CG writers"); return; } // Get the extension of the file that will be written (we use the CG // writer's name for this purpose). std::string fileExt(CGWriter); // Open the output file. std::string fileName(OutputFilename + ".cg." + fileExt); std::ofstream out(fileName.c_str()); if (!out) { retdec::llvm_support::printErrorMessage("Cannot open " + fileName + " for writing."); return; } // Create a CG for the current module and emit it into the opened file. ShPtr<retdec::llvmir2hll::CGWriter> writer(retdec::llvmir2hll::CGWriterFactory::getInstance( ).createObject<ShPtr<retdec::llvmir2hll::CG>, std::ostream &>( CGWriter, retdec::llvmir2hll::CGBuilder::getCG(resModule), out)); ASSERT_MSG(writer, "instantiation of the requested CG writer `" << CGWriter << "` failed"); writer->emitCG(); } /** * @brief Parses the given list of optimizations. * * @a opts should be a list of strings separated by a comma. */ retdec::llvmir2hll::StringSet Decompiler::parseListOfOpts(const std::string &opts) const { retdec::llvmir2hll::StringVector parsedOpts(split(opts, ',')); return retdec::llvmir2hll::StringSet(parsedOpts.begin(), parsedOpts.end()); } /** * @brief Returns the type of optimizations that should be run (as a string). */ std::string Decompiler::getTypeOfRunOptimizations() const { return AggressiveOpts ? "aggressive" : "normal"; } /** * @brief Returns the IDs of pattern finders to be run. */ retdec::llvmir2hll::StringVector Decompiler::getIdsOfPatternFindersToBeRun() const { if (FindPatterns == "all") { // Get all of them. return retdec::llvmir2hll::PatternFinderFactory::getInstance().getRegisteredObjects(); } else { // Get only the selected IDs. return split(FindPatterns, ','); } } /** * @brief Instantiates and returns the pattern finders described by their ID. * * If a pattern finder cannot be instantiated, a warning message is emitted. */ retdec::llvmir2hll::PatternFinderRunner::PatternFinders Decompiler::instantiatePatternFinders( const retdec::llvmir2hll::StringVector &pfsIds) { // Pattern finders need a value analysis, so create it. initAliasAnalysis(); ShPtr<retdec::llvmir2hll::ValueAnalysis> va(retdec::llvmir2hll::ValueAnalysis::create(aliasAnalysis, true)); // Re-initialize cio to be sure its up-to-date. cio->init(retdec::llvmir2hll::CGBuilder::getCG(resModule), va); retdec::llvmir2hll::PatternFinderRunner::PatternFinders pfs; for (const auto pfId : pfsIds) { ShPtr<retdec::llvmir2hll::PatternFinder> pf( retdec::llvmir2hll::PatternFinderFactory::getInstance().createObject(pfId, va, cio)); if (!pf && Debug) { retdec::llvm_support::printWarningMessage("the requested pattern finder '" + pfId + "' does not exist"); } else { pfs.push_back(pf); } } return pfs; } /** * @brief Instantiates and returns a proper PatternFinderRunner. */ ShPtr<retdec::llvmir2hll::PatternFinderRunner> Decompiler::instantiatePatternFinderRunner() const { if (Debug) { return ShPtr<retdec::llvmir2hll::PatternFinderRunner>(new retdec::llvmir2hll::CLIPatternFinderRunner(llvm::errs())); } return ShPtr<retdec::llvmir2hll::PatternFinderRunner>(new retdec::llvmir2hll::NoActionPatternFinderRunner()); } /** * @brief Returns the prefixes of functions to be removed. */ retdec::llvmir2hll::StringSet Decompiler::getPrefixesOfFuncsToBeRemoved() const { return config->getPrefixesOfFuncsToBeRemoved(); } // // External interface // class DecompilerTargetMachine: public TargetMachine { public: DecompilerTargetMachine(const Target &t, StringRef dataLayoutString, const Triple &targetTriple, StringRef cpu, StringRef fs, const TargetOptions &options): TargetMachine(t, dataLayoutString, targetTriple, cpu, fs, options) {} virtual bool addPassesToEmitFile(PassManagerBase &pm, raw_pwrite_stream &out, CodeGenFileType fileType, bool disableVerify, AnalysisID startBefore, AnalysisID startAfter, AnalysisID stopAfter, MachineFunctionInitializer *mfInitializer) override; }; bool DecompilerTargetMachine::addPassesToEmitFile(PassManagerBase &pm, raw_pwrite_stream &out, CodeGenFileType fileType, bool disableVerify, AnalysisID startBefore, AnalysisID startAfter, AnalysisID stopAfter, MachineFunctionInitializer *mfInitializer) { if (fileType != TargetMachine::CGFT_AssemblyFile) { return true; } // Add and initialize all required passes to perform the decompilation. pm.add(new LoopInfoWrapperPass()); pm.add(new ScalarEvolutionWrapperPass()); pm.add(new Decompiler(out)); return false; } } // namespace llvmir2hlltool // // llvm/tools/llc/llc.cpp // namespace { Target decompilerTarget; std::unique_ptr<tool_output_file> getOutputStream() { // Open the file. std::error_code ec; auto out = std::make_unique<tool_output_file>(OutputFilename, ec, sys::fs::F_None); if (ec) { errs() << ec.message() << '\n'; return {}; } return out; } int compileModule(char **argv, LLVMContext &context) { // Load the module to be compiled. SMDiagnostic err; std::unique_ptr<Module> mod(parseIRFile(InputFilename, err, context)); if (!mod) { err.print(argv[0], errs()); return 1; } // If we are supposed to override the target triple, do so now. Triple triple(mod->getTargetTriple()); if (triple.getTriple().empty()) { triple.setTriple(sys::getDefaultTargetTriple()); } // Get the target-specific parser. auto target = std::make_unique<llvmir2hlltool::DecompilerTargetMachine>( decompilerTarget, "", triple, "", "", TargetOptions() ); assert(target && "Could not allocate target machine!"); assert(mod && "Should have exited after outputting help!"); // Figure out where we are going to send the output. auto out = getOutputStream(); if (!out) { return 1; } // Build up all of the passes that we want to do to the module. legacy::PassManager pm; // Add an appropriate TargetLibraryInfo pass for the module's triple. TargetLibraryInfoImpl tlii(Triple(mod->getTargetTriple())); pm.add(new TargetLibraryInfoWrapperPass(tlii)); // Override default to generate verbose assembly. { raw_pwrite_stream &os(out->os()); bool disableVerify = false; AnalysisID startBefore = nullptr; AnalysisID startAfter = nullptr; AnalysisID stopAfter = nullptr; MachineFunctionInitializer *mfInitializer = nullptr; // Ask the target to add back-end passes as necessary. if (target->addPassesToEmitFile(pm, os, TargetMachine::CodeGenFileType(), disableVerify, startBefore, startAfter, stopAfter, mfInitializer)) { errs() << argv[0] << ": target does not support generation of this" << " file type!\n"; return 1; } // Before executing passes, print the final values of the LLVM options. cl::PrintOptionValues(); pm.run(*mod); } // Declare success. out->keep(); return 0; } } // anonymous namespace int main(int argc, char **argv) { sys::PrintStackTraceOnErrorSignal(argv[0]); PrettyStackTraceProgram X(argc, argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. EnableDebugBuffering = true; cl::ParseCommandLineOptions(argc, argv, "convertor of LLVMIR into the target high-level language\n"); LLVMContext context; int rc = compileModule(argv, context); return rc; }
34.538527
118
0.741553
[ "object" ]
3a9f10c30dddb6f182d55180fab56acbb41e8b23
4,603
cpp
C++
src/smt/theory_utvpi.cpp
rashchedrin/z3
5de699f9cb301a34f71cd5734e0fd619590b0a90
[ "MIT" ]
2
2021-04-21T21:22:00.000Z
2021-06-18T14:57:42.000Z
src/smt/theory_utvpi.cpp
ekpyron/z3
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
[ "MIT" ]
16
2016-04-13T23:48:33.000Z
2020-02-02T12:38:52.000Z
src/smt/theory_utvpi.cpp
ekpyron/z3
28cb13fb96c15714eb244bf05d1d7f56e84cda5e
[ "MIT" ]
null
null
null
/*++ Copyright (c) 2013 Microsoft Corporation Module Name: theory_utvpi.h Author: Nikolaj Bjorner (nbjorner) 2013-04-26 Revision History: The implementaton is derived from theory_diff_logic. --*/ #include "smt/theory_utvpi.h" #include "smt/theory_utvpi_def.h" namespace smt { template class theory_utvpi<idl_ext>; template class theory_utvpi<rdl_ext>; // similar to test_diff_logic: utvpi_tester::utvpi_tester(ast_manager& m): m(m), a(m) {} bool utvpi_tester::operator()(expr* e) { m_todo.reset(); m_mark.reset(); m_todo.push_back(e); expr* e1, *e2; while (!m_todo.empty()) { expr* e = m_todo.back(); m_todo.pop_back(); if (!m_mark.is_marked(e)) { m_mark.mark(e, true); if (is_var(e)) { continue; } if (!is_app(e)) { return false; } app* ap = to_app(e); if (m.is_eq(ap, e1, e2)) { if (!linearize(e1, e2)) { return false; } } else if (ap->get_family_id() == m.get_basic_family_id()) { continue; } else if (a.is_le(e, e1, e2) || a.is_ge(e, e2, e1) || a.is_lt(e, e1, e2) || a.is_gt(e, e2, e1)) { if (!linearize(e1, e2)) { return false; } } else if (is_uninterp_const(e)) { continue; } else { return false; } } } return true; } vector<std::pair<expr*, rational> > const& utvpi_tester::get_linearization() const { SASSERT(m_terms.size() <= 2); return m_terms; } bool utvpi_tester::operator()(unsigned num_fmls, expr* const* fmls) { for (unsigned i = 0; i < num_fmls; ++i) { if (!(*this)(fmls[i])) { return false; } } return true; } bool utvpi_tester::linearize(expr* e) { m_terms.reset(); m_terms.push_back(std::make_pair(e, rational(1))); return linearize(); } bool utvpi_tester::linearize(expr* e1, expr* e2) { m_terms.reset(); m_terms.push_back(std::make_pair(e1, rational(1))); m_terms.push_back(std::make_pair(e2, rational(-1))); return linearize(); } bool utvpi_tester::linearize() { m_weight.reset(); m_coeff_map.reset(); while (!m_terms.empty()) { expr* e1, *e2; rational num; rational mul = m_terms.back().second; expr* e = m_terms.back().first; m_terms.pop_back(); if (a.is_add(e)) { for (unsigned i = 0; i < to_app(e)->get_num_args(); ++i) { m_terms.push_back(std::make_pair(to_app(e)->get_arg(i), mul)); } } else if (a.is_mul(e, e1, e2) && a.is_numeral(e1, num)) { m_terms.push_back(std::make_pair(e2, mul*num)); } else if (a.is_mul(e, e2, e1) && a.is_numeral(e1, num)) { m_terms.push_back(std::make_pair(e2, mul*num)); } else if (a.is_sub(e, e1, e2)) { m_terms.push_back(std::make_pair(e1, mul)); m_terms.push_back(std::make_pair(e2, -mul)); } else if (a.is_uminus(e, e1)) { m_terms.push_back(std::make_pair(e1, -mul)); } else if (a.is_numeral(e, num)) { m_weight += num*mul; } else if (a.is_to_real(e, e1)) { m_terms.push_back(std::make_pair(e1, mul)); } else if (!is_uninterp_const(e)) { return false; } else { m_coeff_map.insert_if_not_there2(e, rational(0))->get_data().m_value += mul; } } for (auto const& kv : m_coeff_map) { rational r = kv.m_value; if (r.is_zero()) { continue; } m_terms.push_back(std::make_pair(kv.m_key, r)); if (m_terms.size() > 2) { return false; } if (!r.is_one() && !r.is_minus_one()) { return false; } } return true; } }
28.949686
92
0.451879
[ "vector" ]
3aa4d3ac919c96f4f7a0589606e5f1d9776bdbad
4,687
cc
C++
examples/simulated_annealing_rosenbrock.cc
eglrp/pallas-solver
c38f1f1d04d93cf8f553bc7395e8ecd96202671a
[ "BSD-2-Clause" ]
39
2016-05-16T11:54:34.000Z
2022-03-27T00:10:19.000Z
examples/simulated_annealing_rosenbrock.cc
eglrp/pallas-solver
c38f1f1d04d93cf8f553bc7395e8ecd96202671a
[ "BSD-2-Clause" ]
7
2017-12-15T15:11:04.000Z
2021-10-18T10:35:47.000Z
examples/simulated_annealing_rosenbrock.cc
latture/pallas-solver
c38f1f1d04d93cf8f553bc7395e8ecd96202671a
[ "BSD-2-Clause" ]
9
2018-04-17T22:36:40.000Z
2021-07-26T07:18:56.000Z
// Pallas Solver // Copyright 2015. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. // // Author: ryan.latture@gmail.com (Ryan Latture) #include "glog/logging.h" // Each solver is defined in its own header file. // include the solver you wish you use: #include "pallas/simulated_annealing.h" // define a problem you wish to solve by inheriting // from the pallas::GradientCostFunction interface // and implementing the Evaluate and NumParameters methods. class Rosenbrock : public pallas::GradientCostFunction { public: virtual ~Rosenbrock() {} virtual bool Evaluate(const double* parameters, double* cost, double* gradient) const { const double x = parameters[0]; const double y = parameters[1]; cost[0] = (1.0 - x) * (1.0 - x) + 100.0 * (y - x * x) * (y - x * x); if (gradient != NULL) { gradient[0] = -2.0 * (1.0 - x) - 200.0 * (y - x * x) * 2.0 * x; gradient[1] = 200.0 * (y - x * x); } return true; } virtual int NumParameters() const { return 2; } }; int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); // define the starting point for the optimization double parameters[2] = {-1.2, 0.0}; // set up global optimizer options only initialization // is need to accept the default options pallas::SimulatedAnnealing::Options options; // Increase the number of iterations // SA often requires many iterations to get // with 1 to 2 significant figures of the // optimal solution options.max_iterations = 1000; options.dwell_iterations = 1000; options.max_stagnant_iterations = 1000; // set a high initial temperature to allow // the SA algorithm to fully explore the // parameter space options.cooling_schedule_options.initial_temperature = 1000; // quit the optimization of cost gets within // 3 significant figures of global minimum options.minimum_cost = 0.001; // define custom step function which will bound the // randomized candidate solution in order to limit // the search and speed up convergence double upper_bounds [2] = {5, 5}; double lower_bounds [2] = {-5, -5}; unsigned int num_parameters = 2; double step_size = 0.1; pallas::scoped_ptr<pallas::StepFunction> step_function (new pallas::BoundedStepFunction(step_size, upper_bounds, lower_bounds, num_parameters)); options.set_step_function(step_function); // initialize a summary object to hold the // optimization details pallas::SimulatedAnnealing::Summary summary; // create a problem from your cost function pallas::GradientProblem problem(new Rosenbrock()); // solve the problem and store the optimal position // in parameters and the optimization details in // the summary pallas::Solve(options, problem, parameters, &summary); std::cout << summary.FullReport() << std::endl; std::cout << "Global minimum found at:" << std::endl; std::cout << "\tx: " << parameters[0] << "\ty: " << parameters[1] << std::endl; return 0; }
40.059829
109
0.650736
[ "object" ]
3aaedba3d423769b084589dbb545c3867438896c
11,414
cpp
C++
testing/adios2/bindings/C/TestBPWriteAggregateReadLocal.cpp
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
testing/adios2/bindings/C/TestBPWriteAggregateReadLocal.cpp
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
1
2020-01-15T15:07:21.000Z
2020-01-15T15:07:21.000Z
testing/adios2/bindings/C/TestBPWriteAggregateReadLocal.cpp
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Distributed under the OSI-approved Apache License, Version 2.0. See * accompanying file Copyright.txt for details. * * TestBPWriteAggregateReadLocal.cpp * * Created on: Jan 11, 2019 * Author: William F Godoy godoywf@ornl.gov */ #include <adios2_c.h> #ifdef ADIOS2_HAVE_MPI #include <mpi.h> #endif #include <gtest/gtest.h> #include <numeric> //std::iota #include <thread> void LocalAggregate1D(const std::string substreams) { // Each process would write a 1x8 array and all processes would // form a mpiSize * Nx 1D array const std::string fname("LocalAggregate1D_" + substreams + ".bp"); int mpiRank = 0, mpiSize = 1; // Number of steps constexpr size_t NSteps = 5; constexpr size_t Nx = 20; MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); std::vector<int32_t> inumbers(NSteps * Nx); std::vector<float> fnumbers(NSteps * Nx); adios2_adios *adiosH = adios2_init(MPI_COMM_WORLD, adios2_debug_mode_on); // writer { adios2_io *ioH = adios2_declare_io(adiosH, "TestIO"); size_t count[1]; count[0] = Nx; adios2_variable *variNumbers = adios2_define_variable(ioH, "ints", adios2_type_int32_t, 1, NULL, NULL, count, adios2_constant_dims_true); adios2_variable *varfNumbers = adios2_define_variable(ioH, "floats", adios2_type_float, 1, NULL, NULL, count, adios2_constant_dims_true); // TODO adios2_set_parameter(ioH, "CollectiveMetadata", "Off"); adios2_set_parameter(ioH, "Profile", "Off"); if (mpiSize > 1) { adios2_set_parameter(ioH, "substreams", substreams.c_str()); } adios2_engine *bpWriter = adios2_open(ioH, fname.c_str(), adios2_mode_write); adios2_step_status step_status; for (size_t i = 0; i < NSteps; ++i) { adios2_begin_step(bpWriter, adios2_step_mode_read, -1., &step_status); std::iota(inumbers.begin() + i * Nx, inumbers.begin() + i * Nx + Nx, mpiRank); const float randomStart = static_cast<float>(rand() % mpiSize); std::iota(fnumbers.begin() + i * Nx, fnumbers.begin() + i * Nx + Nx, randomStart); // if (mpiRank % 3 == 0) // { adios2_put(bpWriter, variNumbers, &inumbers[i * Nx], adios2_mode_sync); //} // if (mpiRank % 3 == 1) // { adios2_put(bpWriter, varfNumbers, &fnumbers[i * Nx], adios2_mode_sync); //} adios2_end_step(bpWriter); } adios2_close(bpWriter); bpWriter = NULL; } // Reader TODO, might need to generate metadata file // if (false) { adios2_io *ioH = adios2_declare_io(adiosH, "Reader"); adios2_engine *bpReader = adios2_open(ioH, fname.c_str(), adios2_mode_read); adios2_step_status step_status; while (true) { adios2_begin_step(bpReader, adios2_step_mode_read, -1, &step_status); if (step_status == adios2_step_status_end_of_stream) { break; } size_t currentStep; adios2_current_step(&currentStep, bpReader); adios2_variable *varInts = adios2_inquire_variable(ioH, "ints"); adios2_variable *varFloats = adios2_inquire_variable(ioH, "floats"); // if (mpiRank % 3 == 0) // { EXPECT_NE(varInts, nullptr); std::vector<int32_t> inVarInts(Nx); adios2_set_block_selection(varInts, mpiRank); adios2_get(bpReader, varInts, inVarInts.data(), adios2_mode_sync); for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarInts[i], inumbers[currentStep * Nx + i]); } //} // if (mpiRank % 3 == 1) // { EXPECT_NE(varFloats, nullptr); std::vector<float> inVarFloats(Nx); adios2_set_block_selection(varFloats, mpiRank); adios2_get(bpReader, varFloats, inVarFloats.data(), adios2_mode_sync); for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarFloats[i], fnumbers[currentStep * Nx + i]); } //} adios2_end_step(bpReader); } adios2_close(bpReader); bpReader = NULL; } adios2_finalize(adiosH); } void LocalAggregate1DBlock0(const std::string substreams) { // Each process would write a 1x8 array and all processes would // form a mpiSize * Nx 1D array const std::string fname("LocalAggregate1DSubFile_" + substreams + ".bp"); int mpiRank = 0, mpiSize = 1; // Number of steps constexpr size_t NSteps = 5; constexpr size_t Nx = 20; MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiSize); std::vector<int32_t> inumbers(NSteps * Nx); std::vector<float> fnumbers(NSteps * Nx); adios2_adios *adiosH = adios2_init(MPI_COMM_WORLD, adios2_debug_mode_on); // writer { adios2_io *ioH = adios2_declare_io(adiosH, "TestIO"); size_t count[1]; count[0] = Nx; adios2_variable *variNumbers = adios2_define_variable(ioH, "ints", adios2_type_int32_t, 1, NULL, NULL, count, adios2_constant_dims_true); adios2_variable *varfNumbers = adios2_define_variable(ioH, "floats", adios2_type_float, 1, NULL, NULL, count, adios2_constant_dims_true); // adios2_set_parameter(ioH, "CollectiveMetadata", "Off"); adios2_set_parameter(ioH, "Profile", "Off"); if (mpiSize > 1) { adios2_set_parameter(ioH, "substreams", substreams.c_str()); } adios2_engine *bpWriter = adios2_open(ioH, fname.c_str(), adios2_mode_write); adios2_step_status step_status; for (size_t i = 0; i < NSteps; ++i) { adios2_begin_step(bpWriter, adios2_step_mode_read, -1., &step_status); std::iota(inumbers.begin() + i * Nx, inumbers.begin() + i * Nx + Nx, mpiRank); const float randomStart = static_cast<float>(rand() % mpiSize); std::iota(fnumbers.begin() + i * Nx, fnumbers.begin() + i * Nx + Nx, randomStart); // if (mpiRank % 3 == 0) // { adios2_put(bpWriter, variNumbers, &inumbers[i * Nx], adios2_mode_sync); //} // if (mpiRank % 3 == 1) // { adios2_put(bpWriter, varfNumbers, &fnumbers[i * Nx], adios2_mode_sync); //} adios2_end_step(bpWriter); } adios2_close(bpWriter); bpWriter = NULL; } { // read block zero from collective, then compare to subfile read adios2_io *ioH = adios2_declare_io(adiosH, "Reader"); adios2_engine *bpReader = adios2_open(ioH, fname.c_str(), adios2_mode_read); // subfile read adios2_io *ioH0 = adios2_declare_io(adiosH, "Reader0"); const std::string fnameBP0 = fname + ".dir/" + fname + ".0"; adios2_engine *bpReader0 = adios2_open(ioH0, fnameBP0.c_str(), adios2_mode_read); adios2_step_status step_status; while (true) { adios2_begin_step(bpReader, adios2_step_mode_read, -1, &step_status); adios2_begin_step(bpReader0, adios2_step_mode_read, -1, &step_status); if (step_status == adios2_step_status_end_of_stream) { break; } size_t currentStep; adios2_current_step(&currentStep, bpReader0); adios2_variable *varInts = adios2_inquire_variable(ioH, "ints"); adios2_variable *varFloats = adios2_inquire_variable(ioH, "floats"); adios2_variable *varInts0 = adios2_inquire_variable(ioH0, "ints"); adios2_variable *varFloats0 = adios2_inquire_variable(ioH0, "floats"); EXPECT_NE(varInts, nullptr); EXPECT_NE(varInts0, nullptr); std::vector<int32_t> inVarInts(Nx); std::vector<int32_t> inVarInts0(Nx); adios2_set_block_selection(varInts, 0); adios2_get(bpReader, varInts, inVarInts.data(), adios2_mode_sync); adios2_set_block_selection(varInts0, 0); adios2_get(bpReader0, varInts0, inVarInts0.data(), adios2_mode_sync); for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarInts0[i], inVarInts[i]); } if (mpiRank == 0) { for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarInts0[i], inumbers[currentStep * Nx + i]); } } // floats EXPECT_NE(varFloats, nullptr); EXPECT_NE(varFloats0, nullptr); std::vector<float> inVarFloats(Nx); std::vector<float> inVarFloats0(Nx); adios2_set_block_selection(varFloats, 0); adios2_get(bpReader, varFloats, inVarFloats.data(), adios2_mode_sync); adios2_set_block_selection(varFloats0, 0); adios2_get(bpReader0, varFloats0, inVarFloats0.data(), adios2_mode_sync); for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarFloats[i], inVarFloats[i]); } if (mpiRank == 0) { for (size_t i = 0; i < Nx; ++i) { ASSERT_EQ(inVarFloats0[i], fnumbers[currentStep * Nx + i]); } } adios2_end_step(bpReader0); adios2_end_step(bpReader); } adios2_close(bpReader0); adios2_close(bpReader); bpReader0 = NULL; bpReader = NULL; } adios2_finalize(adiosH); } class BPWriteAggregateReadLocalTest : public ::testing::TestWithParam<std::string> { public: BPWriteAggregateReadLocalTest() = default; virtual void SetUp() {} virtual void TearDown() {} }; TEST_P(BPWriteAggregateReadLocalTest, Aggregate1D) { LocalAggregate1D(GetParam()); } TEST_P(BPWriteAggregateReadLocalTest, Aggregate1DBlock0) { LocalAggregate1DBlock0(GetParam()); } INSTANTIATE_TEST_CASE_P(Substreams, BPWriteAggregateReadLocalTest, ::testing::Values("1", "2", "3", "4")); int main(int argc, char **argv) { #ifdef ADIOS2_HAVE_MPI MPI_Init(nullptr, nullptr); #endif int result; ::testing::InitGoogleTest(&argc, argv); result = RUN_ALL_TESTS(); #ifdef ADIOS2_HAVE_MPI MPI_Finalize(); #endif return result; }
29.958005
80
0.550114
[ "vector" ]
3ab0339ee9696309e69764184f3344c7a80f13b7
32,206
cxx
C++
IO/VeraOut/vtkVeraOutReader.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
1
2021-10-03T16:47:04.000Z
2021-10-03T16:47:04.000Z
IO/VeraOut/vtkVeraOutReader.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
null
null
null
IO/VeraOut/vtkVeraOutReader.cxx
forestGzh/VTK
bc98327275bd5cfa95c5825f80a2755a458b6da8
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkVeraOutReader.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. =========================================================================*/ // .NAME vtkVeraOutReader - File reader for VERA OUT HDF5 format. #include "vtkVeraOutReader.h" // vtkCommonCore #include "vtkDataArray.h" #include "vtkDataArraySelection.h" #include "vtkDoubleArray.h" #include "vtkFloatArray.h" #include "vtkInformation.h" #include "vtkInformationDoubleVectorKey.h" #include "vtkInformationVector.h" #include "vtkIntArray.h" #include "vtkLongArray.h" #include "vtkLongLongArray.h" #include "vtkObjectFactory.h" #include "vtkShortArray.h" #include "vtkUnsignedCharArray.h" #include "vtkUnsignedIntArray.h" #include "vtkUnsignedShortArray.h" // vtkCommonExecutionModel #include "vtkStreamingDemandDrivenPipeline.h" // vtkCommonDataModel #include "vtkCellData.h" #include "vtkFieldData.h" #include "vtkRectilinearGrid.h" // vtkhdf5 #define H5_USE_16_API #include <vtk_hdf5.h> #include <numeric> #include <sstream> #include <vector> using namespace std; #define VERA_MAX_DIMENSION 6 #define DATASET_NAME_MAX_SIZE 1024 //***************************************************************************** class vtkVeraOutReader::Internals { public: Internals(vtkObject* owner) { this->Owner = owner; this->FileId = -1; this->NumberOfDimensions = 0; this->NeedCoreProcessing = true; this->APITCH = 20; // FIXME this->NASSX = 4; this->NASSY = 4; this->NPIN = 17; this->NAX = 4; this->APITCH = 20; this->SYMMETRY = 0; this->NUMBER_OF_STATES = 0; } // -------------------------------------------------------------------------- virtual ~Internals() { this->CloseFile(); } // -------------------------------------------------------------------------- void SetFileName(const char* filename) { std::string newFileName(filename ? filename : ""); ; if (newFileName != this->FileName) { this->FileName = filename; this->CloseFile(); // Reset any cache this->NUMBER_OF_STATES = 0; this->NeedCoreProcessing = true; this->CoreCellData.clear(); this->CellDataArraySelection->RemoveAllArrays(); } } // -------------------------------------------------------------------------- bool OpenFile() { if (this->FileId > -1) { // Already open, skip... return true; } hid_t fileAccessPropListID = H5Pcreate(H5P_FILE_ACCESS); if (fileAccessPropListID < 0) { vtkErrorWithObjectMacro(this->Owner, "Couldn't H5Pcreate"); return false; } herr_t err = H5Pset_fclose_degree(fileAccessPropListID, H5F_CLOSE_SEMI); if (err < 0) { vtkErrorWithObjectMacro(this->Owner, "Couldn't set file close access"); return false; } if ((this->FileId = H5Fopen(this->FileName.c_str(), H5F_ACC_RDONLY, fileAccessPropListID)) < 0) { vtkErrorWithObjectMacro( this->Owner, "Cannot be a VERA file (" << this->FileName.c_str() << ")"); return false; } H5Pclose(fileAccessPropListID); return true; } //---------------------------------------------------------------------------- void CloseFile() { if (this->FileId > -1) { H5Fclose(this->FileId); this->FileId = -1; } } //---------------------------------------------------------------------------- void LoadMetaData() { if (this->FileId == -1) { return; } this->ReadCore(); // Register state fields if (this->GetNumberOfTimeSteps()) { // Open group hid_t groupId = -1; if ((groupId = H5Gopen(this->FileId, "/STATE_0001")) < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't open Group /STATE_0001"); return; } H5G_info_t groupInfo; int status = H5Gget_info(groupId, &groupInfo); if (status < 0) { vtkErrorWithObjectMacro( this->Owner, "Can't get group info for /STATE_0001 (status: " << status << ")"); H5Gclose(groupId); return; } // Extract dataset names std::vector<std::string> datasetNames; char datasetName[DATASET_NAME_MAX_SIZE]; for (hsize_t idx = 0; idx < groupInfo.nlinks; idx++) { H5Lget_name_by_idx(groupId, ".", H5_INDEX_NAME, H5_ITER_INC, idx, datasetName, DATASET_NAME_MAX_SIZE, H5P_DEFAULT); datasetNames.push_back(datasetName); } H5Gclose(groupId); // Start processing datasets for (const std::string& dsName : datasetNames) { this->ReadDataSetDimensions("/STATE_0001", dsName.c_str()); if (this->NumberOfDimensions == 4 && this->Dimensions[0] == this->NPIN && this->Dimensions[1] == this->NPIN && this->Dimensions[2] == this->NAX && this->Dimensions[3] == this->NASS) { this->CellDataArraySelection->AddArray(dsName.c_str()); } else if (this->NumberOfDimensions == 1 && this->Dimensions[0] == 1) { this->FieldDataArraySelection->AddArray(dsName.c_str()); } } } } //---------------------------------------------------------------------------- int GetNumberOfTimeSteps() { if (this->NUMBER_OF_STATES) { return this->NUMBER_OF_STATES; } if (this->FileId == -1) { return 0; } // ---------------------------------- // Find out how many state we have // ---------------------------------- int count = 0; int status = 0; while (status >= 0) { count++; std::ostringstream groupName; groupName << "/STATE_" << std::setw(4) << std::setfill('0') << count; H5Eset_auto(NULL, NULL); status = H5Gget_objinfo(this->FileId, groupName.str().c_str(), 0, NULL); } // H5Eset_auto(NULL, NULL); this->NUMBER_OF_STATES = count ? count - 1 : 0; // ---------------------------------- return this->NUMBER_OF_STATES; } //---------------------------------------------------------------------------- bool ReadDataSetDimensions(const char* groupName, const char* datasetName) { if (this->FileId == -1) { return false; } // Open group hid_t groupId = -1; if ((groupId = H5Gopen(this->FileId, groupName)) < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't open group " << groupName); return false; } // Open dataset hid_t datasetId; if ((datasetId = H5Dopen(groupId, datasetName)) < 0) { H5Gclose(groupId); vtkErrorWithObjectMacro(this->Owner, "DataSet " << datasetName << " in group " << groupName << " don't want to open."); return false; } // Extract dataset dimensions hid_t spaceId = H5Dget_space(datasetId); H5Sget_simple_extent_dims(spaceId, this->Dimensions, nullptr); this->NumberOfDimensions = H5Sget_simple_extent_ndims(spaceId); // Close resources H5Sclose(spaceId); H5Dclose(datasetId); H5Gclose(groupId); return true; } //---------------------------------------------------------------------------- vtkDataArray* ReadDataSet(const char* groupName, const char* datasetName) { if (!this->ReadDataSetDimensions(groupName, datasetName)) { return nullptr; } vtkDataArray* arrayToReturn = nullptr; // Compute total size vtkIdType nbTuples = 1; for (hsize_t idx = 0; idx < this->NumberOfDimensions; idx++) { nbTuples *= this->Dimensions[idx]; } // Open group hid_t groupId = -1; if ((groupId = H5Gopen(this->FileId, groupName)) < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't open group " << groupName); return nullptr; } // Open dataset hid_t datasetId; if ((datasetId = H5Dopen(groupId, datasetName)) < 0) { vtkErrorWithObjectMacro(this->Owner, "DataSet " << datasetName << " in group " << groupName << " don't want to open."); H5Gclose(groupId); return nullptr; } // Extract data type hid_t tRawType = H5Dget_type(datasetId); hid_t dataType = H5Tget_native_type(tRawType, H5T_DIR_ASCEND); if (H5Tequal(dataType, H5T_NATIVE_FLOAT)) { arrayToReturn = vtkFloatArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); float* arrayPtr = static_cast<float*>(vtkArrayDownCast<vtkFloatArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_DOUBLE)) { arrayToReturn = vtkDoubleArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); double* arrayPtr = static_cast<double*>(vtkArrayDownCast<vtkDoubleArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_INT)) { arrayToReturn = vtkIntArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); int* arrayPtr = static_cast<int*>(vtkArrayDownCast<vtkIntArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_UINT)) { arrayToReturn = vtkUnsignedIntArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); unsigned int* arrayPtr = static_cast<unsigned int*>( vtkArrayDownCast<vtkUnsignedIntArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_SHORT)) { arrayToReturn = vtkShortArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); short* arrayPtr = static_cast<short*>(vtkArrayDownCast<vtkShortArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_USHORT)) { arrayToReturn = vtkUnsignedShortArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); unsigned short* arrayPtr = static_cast<unsigned short*>( vtkArrayDownCast<vtkUnsignedShortArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_UCHAR)) { arrayToReturn = vtkUnsignedCharArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); unsigned char* arrayPtr = static_cast<unsigned char*>( vtkArrayDownCast<vtkUnsignedCharArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_LONG)) { arrayToReturn = vtkLongArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); long* arrayPtr = static_cast<long*>(vtkArrayDownCast<vtkLongArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else if (H5Tequal(dataType, H5T_NATIVE_LLONG)) { arrayToReturn = vtkLongLongArray::New(); arrayToReturn->SetNumberOfTuples(nbTuples); long long* arrayPtr = static_cast<long long*>(vtkArrayDownCast<vtkLongLongArray>(arrayToReturn)->GetPointer(0)); H5Dread(datasetId, dataType, H5S_ALL, H5S_ALL, H5P_DEFAULT, arrayPtr); arrayPtr = nullptr; } else { vtkErrorWithObjectMacro(this->Owner, "Unknown HDF5 data type --- it is not FLOAT, " << "DOUBLE, INT, UNSIGNED INT, SHORT, UNSIGNED SHORT, " << "UNSIGNED CHAR, LONG, or LONG LONG."); } arrayToReturn->SetName(datasetName); // Close what we opened H5Tclose(dataType); // H5Tclose( tRawType ); H5Dclose(datasetId); H5Gclose(groupId); return arrayToReturn; } //---------------------------------------------------------------------------- vtkDataArray* CreatePinFieldArray(vtkDataArray* dataSource) { if (this->CoreMap == nullptr || dataSource == nullptr) { return nullptr; } vtkDataArray* outputField = dataSource->NewInstance(); outputField->SetNumberOfTuples(this->NASSX * this->NPIN * this->NASSY * this->NPIN * this->NAX); vtkIdType srcIndex = 0; for (hsize_t sj = 0; sj < this->NASSY; sj++) { for (hsize_t si = 0; si < this->NASSX; si++) { vtkIdType assembyId = this->CoreMap->GetTuple1(si * this->NASSX + sj) - 1; vtkIdType dstOffset = si * this->NPIN + sj * this->NASSX * this->NPIN * this->NPIN; for (hsize_t dk = 0; dk < this->NAX; dk++) { for (hsize_t dj = 0; dj < this->NPIN; dj++) { for (hsize_t di = 0; di < this->NPIN; di++) { if (assembyId < 0) { outputField->SetTuple1(dstOffset + di + (dj * this->NASSX * this->NPIN) + (dk * this->NASSX * this->NPIN * this->NASSY * this->NPIN), 0); } else { // Fortran ordering srcIndex = assembyId + dk * this->NASS + dj * this->NASS * this->NAX + di * this->NASS * this->NAX * this->NPIN; if (SYMMETRY == 4) { srcIndex = assembyId + dk * this->NASS; if (2 * si > this->NASSX) { srcIndex += di * this->NASS * this->NAX * this->NPIN; } else { srcIndex += (this->NPIN - di - 1) * this->NASS * this->NAX * this->NPIN; } if (2 * sj > this->NASSY) { srcIndex += dj * this->NASS * this->NAX; } else { srcIndex += (this->NPIN - dj - 1) * this->NASS * this->NAX; } } outputField->SetTuple1(dstOffset + di + (dj * this->NASSX * this->NPIN) + (dk * this->NASSX * this->NPIN * this->NASSY * this->NPIN), dataSource->GetTuple1(srcIndex)); } } } } } } return outputField; } //---------------------------------------------------------------------------- void AddDataSetNamesWithDimension( const char* groupName, hsize_t dimension, std::vector<std::string>& names) { // Open group hid_t groupId = -1; if ((groupId = H5Gopen(this->FileId, groupName)) < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't open group " << groupName); return; } H5G_info_t groupInfo; int status = H5Gget_info(groupId, &groupInfo); if (status < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't get group info for " << groupName); H5Gclose(groupId); return; } // Extract dataset names std::vector<std::string> datasetNames; char datasetName[DATASET_NAME_MAX_SIZE]; for (hsize_t idx = 0; idx < groupInfo.nlinks; idx++) { H5Lget_name_by_idx(groupId, ".", H5_INDEX_NAME, H5_ITER_INC, idx, datasetName, DATASET_NAME_MAX_SIZE, H5P_DEFAULT); datasetNames.push_back(datasetName); } // Start processing datasets for (const std::string& dsName : datasetNames) { // Open dataset hid_t datasetId; if ((datasetId = H5Dopen(groupId, dsName.c_str())) < 0) { vtkErrorWithObjectMacro(this->Owner, "DataSet " << dsName.c_str() << " in group " << groupName << " don't want to open."); continue; } // Extract dataset dimensions hid_t spaceId = H5Dget_space(datasetId); H5Sget_simple_extent_dims(spaceId, this->Dimensions, nullptr); this->NumberOfDimensions = H5Sget_simple_extent_ndims(spaceId); // Add name if condition is valid if (this->NumberOfDimensions == dimension) { names.push_back(dsName); } H5Sclose(spaceId); H5Dclose(datasetId); } H5Gclose(groupId); } //---------------------------------------------------------------------------- void ReadCore() { if (!this->NeedCoreProcessing) { return; } // Guard further reading if file name does not change.. this->NeedCoreProcessing = false; this->CoreCellData.clear(); // Local vars vtkDataArray* dataSource; vtkDataArray* outputCellArray; // -------------------------------------------------------------------------- // Global variables // -------------------------------------------------------------------------- // * NASSX – Maximum number of assemblies across the core horizontally in full symmetry // * NASSY – Maximum number of assemblies down the core vertically in full symmetry // * NPIN – Maximum number of fuel pins across a fuel assembly in the core. Assemblies are // assumed to be symmetric. // * NAX – Number of axial levels edited in the fuel // * NASS – Total number of fuel assemblies in the problem considering the symmetry of the // calculation. // -------------------------------------------------------------------------- this->ZCoordinates = this->ReadDataSet("/CORE", "axial_mesh"); this->NAX = this->Dimensions[0] - 1; this->ZCoordinates->Delete(); // Let the smart pointer hold the only ref this->CoreMap = this->ReadDataSet("/CORE", "core_map"); this->NASSX = this->Dimensions[0]; this->NASSY = this->Dimensions[1]; this->CoreMap->Delete(); // Let the smart pointer hold the only ref dataSource = this->ReadDataSet("/CORE", "core_sym"); this->SYMMETRY = dataSource->GetTuple1(0); dataSource->Delete(); // Just needed to extract the single value // ------------------------------------------ // Extract pin information // ------------------------------------------ std::vector<std::string> names; this->AddDataSetNamesWithDimension("/CORE", 4, names); for (const std::string& name : names) { dataSource = this->ReadDataSet("/CORE", name.c_str()); this->NPIN = this->Dimensions[0]; this->NASS = this->Dimensions[3]; outputCellArray = this->CreatePinFieldArray(dataSource); outputCellArray->SetName(dataSource->GetName()); this->CoreCellData.push_back(outputCellArray); outputCellArray->Delete(); dataSource->Delete(); } // ------------------------------------------ // DEBUG: std::cout << "============================" << std::endl; // DEBUG: std::cout << "NASSX " << this->NASSX << std::endl; // DEBUG: std::cout << "NASSY " << this->NASSY << std::endl; // DEBUG: std::cout << "NPIN " << this->NPIN << std::endl; // DEBUG: std::cout << "NAX " << this->NAX << std::endl; // DEBUG: std::cout << "NASS " << this->NASS << std::endl; // DEBUG: std::cout << "SYMMETRY " << this->SYMMETRY << std::endl; // DEBUG: std::cout << "============================" << std::endl; // ------------------------------------------ // X/Y Coordinates // ------------------------------------------ float axialStep = this->APITCH / (double)NPIN; this->XCoordinates->SetNumberOfTuples(NASSX * NPIN + 1); for (vtkIdType idx = 0; idx < this->XCoordinates->GetNumberOfTuples(); idx++) { this->XCoordinates->SetTuple1(idx, ((float)idx) * axialStep); } this->YCoordinates->SetNumberOfTuples(NASSY * NPIN + 1); for (vtkIdType idx = 0; idx < this->YCoordinates->GetNumberOfTuples(); idx++) { this->YCoordinates->SetTuple1(idx, ((float)idx) * axialStep); } // ------------------------------------------ // Fill cellData from core information // ------------------------------------------ outputCellArray = this->CoreMap->NewInstance(); outputCellArray->SetNumberOfTuples( this->NASSX * this->NPIN * this->NASSY * this->NPIN * this->NAX); outputCellArray->SetName("AssemblyID"); for (hsize_t sj = 0; sj < this->NASSY; sj++) { for (hsize_t si = 0; si < this->NASSX; si++) { vtkIdType srcIdx = si * this->NASSX + sj; // Fortran ordering vtkIdType dstOffset = si * this->NPIN + sj * this->NASSX * this->NPIN * this->NPIN; for (hsize_t dk = 0; dk < this->NAX; dk++) { for (hsize_t dj = 0; dj < this->NPIN; dj++) { for (hsize_t di = 0; di < this->NPIN; di++) { outputCellArray->SetTuple1(dstOffset + di + (dj * this->NASSX * this->NPIN) + (dk * this->NASSX * this->NPIN * this->NASSY * this->NPIN), this->CoreMap->GetTuple1(srcIdx)); } } } } } this->CoreCellData.push_back(outputCellArray); outputCellArray->Delete(); } //---------------------------------------------------------------------------- void InitializeWithCoreData(vtkRectilinearGrid* output) { // NoOp if already loaded this->ReadCore(); output->SetDimensions( this->NASSX * this->NPIN + 1, this->NASSY * this->NPIN + 1, this->NAX + 1); output->SetXCoordinates(this->XCoordinates); output->SetYCoordinates(this->YCoordinates); output->SetZCoordinates(this->ZCoordinates); for (const vtkSmartPointer<vtkDataArray>& cellArray : this->CoreCellData) { output->GetCellData()->AddArray(cellArray); } } //---------------------------------------------------------------------------- void AddStateData(vtkRectilinearGrid* output, vtkIdType timestep) { if (this->FileId == -1) { return; } // -------------------------------------------------------------------------- // STATE_0001 Group // STATE_0001/crit_boron Dataset {1} // STATE_0001/detector_response Dataset {49, 18} <------ SKIP/FIXME // STATE_0001/exposure Dataset {1} // STATE_0001/keff Dataset {1} // STATE_0001/pin_cladtemps Dataset {17, 17, 49, 56} // STATE_0001/pin_fueltemps Dataset {17, 17, 49, 56} // STATE_0001/pin_moddens Dataset {17, 17, 49, 56} // STATE_0001/pin_modtemps Dataset {17, 17, 49, 56} // STATE_0001/pin_powers Dataset {17, 17, 49, 56} // -------------------------------------------------------------------------- std::ostringstream stateGroupName; stateGroupName << "/STATE_" << std::setw(4) << std::setfill('0') << timestep; vtkDataArray* dataSource; vtkDataArray* outputCellArray; // Open group hid_t groupId = -1; if ((groupId = H5Gopen(this->FileId, stateGroupName.str().c_str())) < 0) { vtkErrorWithObjectMacro(this->Owner, "Can't open Group " << stateGroupName.str().c_str()); return; } H5G_info_t groupInfo; int status = H5Gget_info(groupId, &groupInfo); if (status < 0) { vtkErrorWithObjectMacro( this->Owner, "Can't get group info for " << stateGroupName.str().c_str()); return; } // Extract dataset names std::vector<std::string> datasetNames; char datasetName[DATASET_NAME_MAX_SIZE]; for (hsize_t idx = 0; idx < groupInfo.nlinks; idx++) { H5Lget_name_by_idx(groupId, ".", H5_INDEX_NAME, H5_ITER_INC, idx, datasetName, DATASET_NAME_MAX_SIZE, H5P_DEFAULT); datasetNames.push_back(datasetName); } H5Gclose(groupId); // Start processing datasets for (const std::string& dsName : datasetNames) { if (!(this->CellDataArraySelection->ArrayExists(dsName.c_str()) || this->FieldDataArraySelection->ArrayExists(dsName.c_str())) || !(this->CellDataArraySelection->ArrayIsEnabled(dsName.c_str()) || this->FieldDataArraySelection->ArrayIsEnabled(dsName.c_str()))) { continue; } dataSource = this->ReadDataSet(stateGroupName.str().c_str(), dsName.c_str()); if (dataSource) { if (this->NumberOfDimensions == 4 && this->Dimensions[0] == this->NPIN && this->Dimensions[1] == this->NPIN && this->Dimensions[2] == this->NAX && this->Dimensions[3] == this->NASS) { outputCellArray = this->CreatePinFieldArray(dataSource); outputCellArray->SetName(dsName.c_str()); output->GetCellData()->AddArray(outputCellArray); outputCellArray->Delete(); } else if (this->NumberOfDimensions == 1 && this->Dimensions[0] == 1) { // Add fields add FieldData output->GetFieldData()->AddArray(dataSource); } else { std::ostringstream message; message << "Invalid dimensions: "; for (hsize_t i = 0; i < this->NumberOfDimensions; i++) { message << this->Dimensions[i] << " "; } vtkDebugWithObjectMacro(this->Owner, << message.str()); } dataSource->Delete(); } } } //---------------------------------------------------------------------------- vtkNew<vtkDataArraySelection> CellDataArraySelection; vtkNew<vtkDataArraySelection> FieldDataArraySelection; private: hid_t FileId; std::string FileName; hsize_t NumberOfDimensions; hsize_t Dimensions[VERA_MAX_DIMENSION]; bool NeedCoreProcessing; double APITCH; hsize_t NASSX; hsize_t NASSY; hsize_t NAX; hsize_t NPIN; hsize_t NASS; vtkIdType SYMMETRY; vtkIdType NUMBER_OF_STATES; vtkNew<vtkFloatArray> XCoordinates; vtkNew<vtkFloatArray> YCoordinates; vtkObject* Owner; vtkSmartPointer<vtkDataArray> ZCoordinates; vtkSmartPointer<vtkDataArray> CoreMap; std::vector<vtkSmartPointer<vtkDataArray> > CoreCellData; }; //***************************************************************************** vtkStandardNewMacro(vtkVeraOutReader); //---------------------------------------------------------------------------- // Constructor for vtkVeraOutReader //---------------------------------------------------------------------------- vtkVeraOutReader::vtkVeraOutReader() { this->FileName = nullptr; this->NumberOfTimeSteps = 0; this->TimeSteps.clear(); this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); this->Internal = new Internals(this); } //---------------------------------------------------------------------------- // Destructor for vtkVeraOutReader //---------------------------------------------------------------------------- vtkVeraOutReader::~vtkVeraOutReader() { this->SetFileName(nullptr); delete this->Internal; this->Internal = nullptr; } //---------------------------------------------------------------------------- // Verify that the file exists, get dimension sizes and variables //---------------------------------------------------------------------------- int vtkVeraOutReader::RequestInformation( vtkInformation* reqInfo, vtkInformationVector** inVector, vtkInformationVector* outVector) { vtkDebugMacro(<< "In vtkVeraOutReader::RequestInformation" << endl); if (!this->Superclass::RequestInformation(reqInfo, inVector, outVector)) return 0; if (!this->FileName || this->FileName[0] == '\0') { vtkErrorMacro("No filename specified"); return 0; } vtkDebugMacro(<< "In vtkVeraOutReader::RequestInformation read filename okay" << endl); vtkInformation* outInfo = outVector->GetInformationObject(0); this->NumberOfTimeSteps = 0; this->Internal->SetFileName(this->FileName); if (this->Internal->OpenFile()) { this->NumberOfTimeSteps = this->Internal->GetNumberOfTimeSteps(); this->Internal->LoadMetaData(); this->Internal->CloseFile(); } this->TimeSteps.resize(this->NumberOfTimeSteps); std::iota(this->TimeSteps.begin(), this->TimeSteps.end(), 1.0); outInfo->Set( vtkStreamingDemandDrivenPipeline::TIME_STEPS(), &this->TimeSteps[0], this->NumberOfTimeSteps); double tRange[2]; tRange[0] = this->NumberOfTimeSteps ? this->TimeSteps[0] : 0; tRange[1] = this->NumberOfTimeSteps ? this->TimeSteps[this->NumberOfTimeSteps - 1] : 0; outInfo->Set(vtkStreamingDemandDrivenPipeline::TIME_RANGE(), tRange, 2); return 1; } //---------------------------------------------------------------------------- // Default method: Data is read into a vtkUnstructuredGrid //---------------------------------------------------------------------------- int vtkVeraOutReader::RequestData(vtkInformation* vtkNotUsed(reqInfo), vtkInformationVector** vtkNotUsed(inVector), vtkInformationVector* outVector) { if (!this->FileName || this->FileName[0] == '\0') { vtkErrorMacro("No filename specified"); return 0; } vtkDebugMacro(<< "In vtkVeraOutReader::RequestData" << endl); vtkInformation* outInfo = outVector->GetInformationObject(0); vtkRectilinearGrid* output = vtkRectilinearGrid::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); // -------------------------------------------------------------------------- // Time / State handling // -------------------------------------------------------------------------- vtkIdType requestedTimeStep = 0; auto timeKey = vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP(); if (outInfo->Has(timeKey)) { requestedTimeStep = outInfo->Get(timeKey); } // -------------------------------------------------------------------------- // Data handling // -------------------------------------------------------------------------- this->Internal->SetFileName(this->FileName); if (this->Internal->OpenFile()) { this->Internal->InitializeWithCoreData(output); this->Internal->AddStateData(output, requestedTimeStep); this->Internal->CloseFile(); } // -------------------------------------------------------------------------- vtkDebugMacro(<< "Out vtkVeraOutReader::RequestData" << endl); return 1; } //---------------------------------------------------------------------------- // Print self. //---------------------------------------------------------------------------- void vtkVeraOutReader::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "FileName: " << (this->FileName ? this->FileName : "NULL") << "\n"; } //---------------------------------------------------------------------------- // Cell Array Selection //---------------------------------------------------------------------------- vtkDataArraySelection* vtkVeraOutReader::GetCellDataArraySelection() const { return this->Internal->CellDataArraySelection; } //---------------------------------------------------------------------------- // Field Array Selection //---------------------------------------------------------------------------- vtkDataArraySelection* vtkVeraOutReader::GetFieldDataArraySelection() const { return this->Internal->FieldDataArraySelection; } //---------------------------------------------------------------------------- // MTime //---------------------------------------------------------------------------- vtkMTimeType vtkVeraOutReader::GetMTime() { vtkMTimeType mTime = this->Superclass::GetMTime(); vtkMTimeType cellMTime = this->Internal->CellDataArraySelection->GetMTime(); vtkMTimeType fieldMTime = this->Internal->FieldDataArraySelection->GetMTime(); mTime = ( cellMTime > mTime ? cellMTime : mTime ); mTime = ( fieldMTime > mTime ? fieldMTime : mTime ); return mTime; }
33.099692
100
0.54732
[ "vector" ]
3ab0f992ee6eb173fd0457109ee6c7feede62fbc
2,901
cpp
C++
dev/Gems/GraphModel/Code/Source/Model/Connection.cpp
BenjaminHCheung/lumberyard
f875f9634ebb128d1bbb5334720596e19cb6db54
[ "AML" ]
6
2018-01-21T14:07:01.000Z
2020-03-13T17:57:26.000Z
dev/Gems/GraphModel/Code/Source/Model/Connection.cpp
BenjaminHCheung/lumberyard
f875f9634ebb128d1bbb5334720596e19cb6db54
[ "AML" ]
null
null
null
dev/Gems/GraphModel/Code/Source/Model/Connection.cpp
BenjaminHCheung/lumberyard
f875f9634ebb128d1bbb5334720596e19cb6db54
[ "AML" ]
6
2020-06-04T04:21:02.000Z
2021-06-22T17:09:27.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // AZ #include <AzCore/PlatformDef.h> #include <AzCore/RTTI/BehaviorContext.h> #include <AzCore/Serialization/EditContext.h> // Graph Model #include <GraphModel/Model/Connection.h> #include <GraphModel/Model/Node.h> #include <GraphModel/Model/Graph.h> namespace GraphModel { Connection::Connection(GraphPtr graph, SlotPtr sourceSlot, SlotPtr targetSlot) : GraphElement(graph) , m_sourceSlot(sourceSlot) , m_targetSlot(targetSlot) { AZ_Assert(sourceSlot->SupportsConnections(), "sourceSlot type does not support connections to other slots"); AZ_Assert(targetSlot->SupportsConnections(), "targetSlot type does not support connections to other slots"); const NodeId sourceNodeId = sourceSlot->GetParentNode()->GetId(); const NodeId targetNodeId = targetSlot->GetParentNode()->GetId(); m_sourceEndpoint = AZStd::make_pair(sourceNodeId, sourceSlot->GetSlotId()); m_targetEndpoint = AZStd::make_pair(targetNodeId, targetSlot->GetSlotId()); } void Connection::PostLoadSetup(GraphPtr graph) { m_graph = graph; m_sourceSlot = azrtti_cast<Slot*>(graph->FindSlot(m_sourceEndpoint)); m_targetSlot = azrtti_cast<Slot*>(graph->FindSlot(m_targetEndpoint)); } void Connection::Reflect(AZ::ReflectContext* context) { AZ::SerializeContext* serializeContext = azrtti_cast<AZ::SerializeContext*>(context); if (serializeContext) { serializeContext->Class<Connection>() ->Version(0) ->Field("m_sourceEndpoint", &Connection::m_sourceEndpoint) ->Field("m_targetEndpoint", &Connection::m_targetEndpoint) ; } } NodePtr Connection::GetSourceNode() const { return GetSourceSlot()->GetParentNode(); } NodePtr Connection::GetTargetNode() const { return GetTargetSlot()->GetParentNode(); } SlotPtr Connection::GetSourceSlot() const { return m_sourceSlot.lock(); } SlotPtr Connection::GetTargetSlot() const { return m_targetSlot.lock(); } const Endpoint& Connection::GetSourceEndpoint() const { return m_sourceEndpoint; } const Endpoint& Connection::GetTargetEndpoint() const { return m_targetEndpoint; } } // namespace GraphModel
31.879121
116
0.68011
[ "model" ]
3ab30b4c527ec3acd8124373fe9e9832578c6d54
4,674
cpp
C++
Engine/src/Razix/Core/OS/VFS.cpp
Divya899/Razix
64bea79190f0873f33844a94e32347a352783949
[ "Apache-2.0" ]
null
null
null
Engine/src/Razix/Core/OS/VFS.cpp
Divya899/Razix
64bea79190f0873f33844a94e32347a352783949
[ "Apache-2.0" ]
null
null
null
Engine/src/Razix/Core/OS/VFS.cpp
Divya899/Razix
64bea79190f0873f33844a94e32347a352783949
[ "Apache-2.0" ]
null
null
null
#include "rzxpch.h" #include "VFS.h" #include "Razix/Core/Log.h" #include "Razix/Core/SplashScreen.h" #include "Razix/Core/OS/FileSystem.h" #include "Razix/Utilities/StringUtilities.h" namespace Razix { VFS* VFS::s_Instance = nullptr; void VFS::StartUp() { RAZIX_CORE_INFO("Starting Up Virtual File Sytem"); Razix::SplashScreen::Get().SetLogString("Starting VFS..."); /// Instance is automatically created once the system is Started Up // TODO: Move this to explicit lazy singleton instantiation as a member in Engine class s_Instance = new VFS(); } void VFS::ShutDown() { RAZIX_CORE_ERROR("Shutting Down Virtual File System"); delete s_Instance; } void VFS::Mount(const std::string& virtualPath, const std::string& physicalPath) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); m_MountPoints[virtualPath].push_back(physicalPath); } void VFS::UnMount(const std::string& path) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); m_MountPoints[path].clear(); } bool VFS::ResolvePhysicalPath(const std::string& virtualPath, std::string& outPhysicalPath, bool folder /*= false*/) { // Check if it's the absolute path, if not resolve the virtual path if (!(virtualPath[0] == '/' && virtualPath[1] == '/')) { outPhysicalPath = virtualPath; return folder ? FileSystem::FolderExists(virtualPath) : FileSystem::FileExists(virtualPath); } // Break the path by '/' and get the list of directories of the path to search static std::string delimiter = "/"; std::vector<std::string> dirs = Utilities::SplitString(virtualPath, delimiter); const std::string& virtualDir = dirs.front(); // If it is the last directory it's the path itself if (m_MountPoints.find(virtualDir) == m_MountPoints.end() || m_MountPoints[virtualDir].empty()) { outPhysicalPath = virtualPath; return folder ? FileSystem::FolderExists(virtualPath) : FileSystem::FileExists(virtualPath); } // Find the new path from the mount points using the virtual directories const std::string remainder = virtualPath.substr(virtualDir.size() + 2, virtualPath.size() - virtualDir.size()); for (const std::string& physicalPath : m_MountPoints[virtualDir]) { const std::string newPath = physicalPath + remainder; if (folder ? FileSystem::FolderExists(newPath) : FileSystem::FileExists(newPath)) { outPhysicalPath = newPath; return true; } } return false; } bool VFS::AbsolutePathToVFS(const std::string& absolutePath, std::string& outVirtualPath, bool folder /*= false*/) { // Find the corresponding virtual path from the mount points using the complete file path for (auto const& [key, val] : m_MountPoints) { for (auto& vfsPath : val) { if (absolutePath.find(vfsPath) != std::string::npos) { std::string newPath = absolutePath; std::string newPartPath = "//" + key; newPath.replace(0, vfsPath.length(), newPartPath); outVirtualPath = newPath; return true; } } } outVirtualPath = absolutePath; return false; } uint8_t* VFS::ReadFile(const std::string& path) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); std::string physicalPath; return ResolvePhysicalPath(path, physicalPath) ? FileSystem::ReadFile(physicalPath) : nullptr; } std::string VFS::ReadTextFile(const std::string& path) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); std::string physicalPath; return ResolvePhysicalPath(path, physicalPath) ? FileSystem::ReadTextFile(physicalPath) : nullptr; } bool VFS::WriteFile(const std::string& path, uint8_t* buffer) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); std::string physicalPath; return ResolvePhysicalPath(path, physicalPath) ? FileSystem::WriteFile(physicalPath, buffer) : false; } bool VFS::WriteTextFile(const std::string& path, const std::string& text) { RAZIX_ASSERT(s_Instance, "VFS was not Started Up properly"); std::string physicalPath; return ResolvePhysicalPath(path, physicalPath) ? FileSystem::WriteTextFile(physicalPath, text) : false; } }
37.392
120
0.629012
[ "vector" ]
3ab6091a75a387f44810bd5d95386b252e34c8e1
4,766
cpp
C++
Tutorials/Tools/shader_manager.cpp
pribault/RadeonRays_SDK
b9bda1fcdb806c5f0f157b17d473daa5f45e3ce1
[ "MIT" ]
344
2017-05-05T11:16:01.000Z
2021-11-22T10:57:53.000Z
Tutorials/Tools/shader_manager.cpp
pribault/RadeonRays_SDK
b9bda1fcdb806c5f0f157b17d473daa5f45e3ce1
[ "MIT" ]
65
2017-05-15T12:20:23.000Z
2020-03-08T10:05:31.000Z
Tutorials/Tools/shader_manager.cpp
pribault/RadeonRays_SDK
b9bda1fcdb806c5f0f157b17d473daa5f45e3ce1
[ "MIT" ]
107
2017-05-06T23:18:44.000Z
2022-01-31T07:23:34.000Z
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 "shader_manager.h" #include <vector> #include <string> #include <stdexcept> #include <fstream> static void LoadFileContents(std::string const& name, std::vector<char>& contents, bool binary = false) { std::ifstream in(name, std::ios::in | (std::ios_base::openmode)(binary?std::ios::binary : 0)); if (in) { contents.clear(); std::streamoff beg = in.tellg(); in.seekg(0, std::ios::end); std::streamoff fileSize = in.tellg() - beg; in.seekg(0, std::ios::beg); contents.resize(static_cast<unsigned>(fileSize)); in.read(&contents[0], fileSize); } else { throw std::runtime_error("Cannot read the contents of a file"); } } static GLuint CompileShader(std::vector<GLchar> const& shader_source, GLenum type) { GLuint shader = glCreateShader(type); GLint len = static_cast<GLint>(shader_source.size()); GLchar const* source_array = &shader_source[0]; glShaderSource(shader, 1, &source_array, &len); glCompileShader(shader); GLint result = GL_TRUE; glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if(result == GL_FALSE) { std::vector<char> log; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len); log.resize(len); glGetShaderInfoLog(shader, len, &result, &log[0]); glDeleteShader(shader); throw std::runtime_error(std::string(log.begin(), log.end())); return 0; } return shader; } ShaderManager::ShaderManager() { } ShaderManager::~ShaderManager() { for (auto citer = shadercache_.cbegin(); citer != shadercache_.cend(); ++citer) { glDeleteProgram(citer->second); } } GLuint ShaderManager::CompileProgram(std::string const& name) { std::string vsname = name + ".vsh"; std::string fsname = name + ".fsh"; // Need to wrap the shader program here to be exception-safe std::vector<GLchar> sourcecode; LoadFileContents(vsname, sourcecode); GLuint vertex_shader = CompileShader(sourcecode, GL_VERTEX_SHADER); /// This part is not exception safe: /// if the VS compilation succeeded /// and PS compilation fails then VS object will leak /// fix this by wrapping the shaders into a class LoadFileContents(fsname, sourcecode); GLuint frag_shader = CompileShader(sourcecode, GL_FRAGMENT_SHADER); GLuint program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, frag_shader); glDeleteShader(vertex_shader); glDeleteShader(frag_shader); glLinkProgram(program); GLint result = GL_TRUE; glGetProgramiv(program, GL_LINK_STATUS, &result); if(result == GL_FALSE) { GLint length = 0; std::vector<char> log; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &length); log.resize(length); glGetProgramInfoLog(program, length, &result, &log[0]); glDeleteProgram(program); throw std::runtime_error(std::string(log.begin(), log.end())); } return program; } GLuint ShaderManager::GetProgram(std::string const& name) { auto iter = shadercache_.find(name); if (iter != shadercache_.end()) { return iter->second; } else { GLuint program = CompileProgram(name); shadercache_[name] = program; return program; } }
28.710843
103
0.642677
[ "object", "vector" ]
3ab9b118743fe8dc1db16e4359a5388eeaac51b8
5,478
hpp
C++
src/cpp/subprocess/basic_types.hpp
merly-ai/subprocess
bddef925a19a8b1035799bfd5a2163311750f4f4
[ "MIT" ]
null
null
null
src/cpp/subprocess/basic_types.hpp
merly-ai/subprocess
bddef925a19a8b1035799bfd5a2163311750f4f4
[ "MIT" ]
null
null
null
src/cpp/subprocess/basic_types.hpp
merly-ai/subprocess
bddef925a19a8b1035799bfd5a2163311750f4f4
[ "MIT" ]
null
null
null
#pragma once #ifdef _WIN32 #define NOMINMAX #include <windows.h> #else #include <unistd.h> #endif #include <map> #include <stdexcept> #include <string> #include <vector> #include <csignal> // Fucking stdout, stderr, stdin are macros. So instead of stdout,... // we will use cin, cout, cerr as variable names namespace subprocess { // ssize_t is not a standard type and not supported in MSVC typedef intptr_t ssize_t; #ifdef _WIN32 /** True if on windows platform. This constant is useful so you can use regular if statements instead of ifdefs and have both branches compile therebye reducing chance of compiler error on a different platform. */ constexpr bool kIsWin32 = true; #else constexpr bool kIsWin32 = false; #endif /* windows doesnt'h have all of these. The numeric values I hope are standardized. Posix specifies the number in the standard so most systems should be fine. */ /** Signals to send. they start with P because SIGX are macros, P stands for Posix as these values are as defined by Posix. */ enum SigNum { PSIGHUP = 1, PSIGINT = SIGINT, PSIGQUIT = 3, PSIGILL = SIGILL, PSIGTRAP = 5, PSIGABRT = SIGABRT, PSIGIOT = 6, PSIGBUS = 7, PSIGFPE = SIGFPE, PSIGKILL = 9, PSIGUSR1 = 10, PSIGSEGV = SIGSEGV, PSIGUSR2 = 12, PSIGPIPE = 13, PSIGALRM = 14, PSIGTERM = SIGTERM, PSIGSTKFLT = 16, PSIGCHLD = 17, PSIGCONT = 18, PSIGSTOP = 19, PSIGTSTP = 20, PSIGTTIN = 21, PSIGTTOU = 22, PSIGURG = 23, PSIGXCPU = 24, PSIGXFSZ = 25, PSIGVTALRM = 26, PSIGPROF = 27, PSIGWINCH = 28, PSIGIO = 29 }; #ifndef _WIN32 typedef int PipeHandle; typedef ::pid_t pid_t; /** The path seperator for PATH environment variable. */ constexpr char kPathDelimiter = ':'; // to please windows we can't have this be a constexpr and be standard c++ /** The value representing an invalid pipe */ const PipeHandle kBadPipeValue = (PipeHandle)-1; #else typedef HANDLE PipeHandle; typedef DWORD pid_t; constexpr char kPathDelimiter = ';'; const PipeHandle kBadPipeValue = INVALID_HANDLE_VALUE; #endif constexpr int kStdInValue = 0; constexpr int kStdOutValue = 1; constexpr int kStdErrValue = 2; /** The value representing an invalid exit code possible for a process. */ constexpr int kBadReturnCode = -1000; typedef std::vector<std::string> CommandLine; typedef std::map<std::string, std::string> EnvMap; /** Redirect destination */ enum class PipeOption : int { inherit, ///< Inherits current process handle cout, ///< Redirects to stdout cerr, ///< redirects to stderr /** Redirects to provided pipe. You can open /dev/null. Pipe handle that you specify will be made inheritable and closed automatically. */ specific, pipe, ///< Redirects to a new handle created for you. close ///< Troll the child by providing a closed pipe. }; struct SubprocessError : std::runtime_error { using std::runtime_error::runtime_error; }; struct OSError : SubprocessError { using SubprocessError::SubprocessError; }; struct CommandNotFoundError : SubprocessError { using SubprocessError::SubprocessError; }; // when the API for spawning a process fails. I don't know if this ever // happens in practice. struct SpawnError : OSError { using OSError::OSError; }; struct TimeoutExpired : SubprocessError { using SubprocessError::SubprocessError; /** The command that was running */ CommandLine command; /** The specified timeout */ double timeout; /** Captured stdout */ std::string cout; /** captured stderr */ std::string cerr; }; struct CalledProcessError : SubprocessError { using SubprocessError::SubprocessError; // credit for documentation is from python docs. They say it simply // and well. /** Exit status of the child process. If the process exited due to a signal, this will be the negative signal number. */ int returncode; /** Command used to spawn the child process */ CommandLine cmd; /** stdout output if it was captured. */ std::string cout; /** stderr output if it was captured. */ std::string cerr; }; /** Details about a completed process. */ struct CompletedProcess { /** The args used for the process. This includes the first first arg which is the command/executable itself. */ CommandLine args; /** negative number -N means it was terminated by signal N. */ int returncode = -1; /** Captured stdout */ std::string cout; /** Captured stderr */ std::string cerr; explicit operator bool() const { return returncode == 0; } }; namespace details { void throw_os_error(const char* function, int errno_code); } }
30.265193
79
0.59602
[ "vector" ]
3ac4bf9534c6d9eb33f2c6885cdb6eeb17f361fb
1,969
cpp
C++
ZOJ/1610/16718396_AC_40ms_524kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
ZOJ/1610/16718396_AC_40ms_524kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
ZOJ/1610/16718396_AC_40ms_524kB.cpp
BakaErii/ACM_Collection
d368b15c7f1c84472424d5e61e5ebc667f589025
[ "WTFPL" ]
null
null
null
/** * @author Moe_Sakiya sakiya@tun.moe * @date 2018-10-29 14:53:32 * */ #include <iostream> #include <string> #include <algorithm> #include <set> #include <map> #include <vector> #include <stack> #include <queue> #include <cstdio> #include <cstring> #include <cstdlib> #include <cmath> #define leftSon left,mid,curr<<1 #define rightSon mid+1,right,curr<<1|1 using namespace std; const int maxN = 10005; int arrCol[maxN << 2]; int num[maxN]; int getCol[maxN]; void pushDown(int curr) { if (arrCol[curr] != -1) { arrCol[curr << 1] = arrCol[curr]; arrCol[curr << 1 | 1] = arrCol[curr]; arrCol[curr] = -1; } return; } void updateSection(int leftSection, int rightSection, int value, int left, int right, int curr) { int mid = (left + right) >> 1; if (leftSection <= left && right <= rightSection) { arrCol[curr] = value; return; } pushDown(curr); if (leftSection <= mid) updateSection(leftSection, rightSection, value, leftSon); if (mid < rightSection) updateSection(leftSection, rightSection, value, rightSon); return; } void querySection(int left, int right, int curr) { int mid = (left + right) >> 1; if (arrCol[curr] != -1) { for (int i = left; i <= right; i++) getCol[i] = arrCol[curr]; return; } if (left < right && arrCol[curr] == -1) { querySection(leftSon); querySection(rightSon); } return; } int main(void) { ios::sync_with_stdio(false); cin.tie(NULL); int n, l, r, v; while (~scanf("%d", &n)) { //INIT memset(num, 0, sizeof(num)); memset(arrCol, -1, sizeof(arrCol)); memset(getCol, -1, sizeof(getCol)); for (int i = 0; i < n; i++) { scanf("%d %d %d", &l, &r, &v); updateSection(l + 1, r, v, 1, 8000, 1); } querySection(1, 8000, 1); if (getCol[0] != -1) num[getCol[0]]++; for(int i=1;i<=8000;i++) if(getCol[i]!=-1&&getCol[i]!=getCol[i-1]) num[getCol[i]]++; for(int i=0;i<=8000;i++) if(num[i]!=0) printf("%d %d\n",i,num[i]); printf("\n"); } return 0; }
20.946809
97
0.611478
[ "vector" ]
3ac7855e402d58b5fb71eb121acb064e3fc0fe29
4,475
cc
C++
base/android/jni_array_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2018-11-24T07:58:44.000Z
2019-02-22T21:02:46.000Z
base/android/jni_array_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
base/android/jni_array_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/android/jni_array.h" #include "base/android/jni_android.h" #include "base/android/scoped_java_ref.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { namespace android { TEST(JniArray, BasicConversions) { const uint8 kBytes[] = { 0, 1, 2, 3 }; const size_t kLen = arraysize(kBytes); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jbyteArray> bytes = ToJavaByteArray(env, kBytes, kLen); ASSERT_TRUE(bytes.obj()); std::vector<uint8> vec(5); JavaByteArrayToByteVector(env, bytes.obj(), &vec); EXPECT_EQ(4U, vec.size()); EXPECT_EQ(std::vector<uint8>(kBytes, kBytes + kLen), vec); AppendJavaByteArrayToByteVector(env, bytes.obj(), &vec); EXPECT_EQ(8U, vec.size()); } void CheckLongConversion( JNIEnv* env, const int64* long_array, const size_t len, const ScopedJavaLocalRef<jlongArray>& longs) { ASSERT_TRUE(longs.obj()); jsize java_array_len = env->GetArrayLength(longs.obj()); ASSERT_EQ(static_cast<jsize>(len), java_array_len); jlong value; for (size_t i = 0; i < len; ++i) { env->GetLongArrayRegion(longs.obj(), i, 1, &value); ASSERT_EQ(long_array[i], value); } } TEST(JniArray, LongConversions) { const int64 kLongs[] = { 0, 1, -1, kint64min, kint64max}; const size_t kLen = arraysize(kLongs); JNIEnv* env = AttachCurrentThread(); CheckLongConversion(env, kLongs, kLen, ToJavaLongArray(env, kLongs, kLen)); const std::vector<int64> vec(kLongs, kLongs + kLen); CheckLongConversion(env, kLongs, kLen, ToJavaLongArray(env, vec)); } TEST(JniArray, JavaIntArrayToIntVector) { const int kInts[] = {0, 1, -1}; const size_t kLen = arraysize(kInts); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jintArray> jints(env, env->NewIntArray(kLen)); ASSERT_TRUE(jints.obj()); for (size_t i = 0; i < kLen; ++i) { jint j = static_cast<jint>(kInts[i]); env->SetIntArrayRegion(jints.obj(), i, 1, &j); ASSERT_FALSE(HasException(env)); } std::vector<int> ints; JavaIntArrayToIntVector(env, jints.obj(), &ints); ASSERT_EQ(static_cast<jsize>(ints.size()), env->GetArrayLength(jints.obj())); jint value; for (size_t i = 0; i < kLen; ++i) { env->GetIntArrayRegion(jints.obj(), i, 1, &value); ASSERT_EQ(ints[i], value); } } TEST(JniArray, JavaFloatArrayToFloatVector) { const float kFloats[] = {0.0, 0.5, -0.5}; const size_t kLen = arraysize(kFloats); JNIEnv* env = AttachCurrentThread(); ScopedJavaLocalRef<jfloatArray> jfloats(env, env->NewFloatArray(kLen)); ASSERT_TRUE(jfloats.obj()); for (size_t i = 0; i < kLen; ++i) { jfloat j = static_cast<jfloat>(kFloats[i]); env->SetFloatArrayRegion(jfloats.obj(), i, 1, &j); ASSERT_FALSE(HasException(env)); } std::vector<float> floats; JavaFloatArrayToFloatVector(env, jfloats.obj(), &floats); ASSERT_EQ(static_cast<jsize>(floats.size()), env->GetArrayLength(jfloats.obj())); jfloat value; for (size_t i = 0; i < kLen; ++i) { env->GetFloatArrayRegion(jfloats.obj(), i, 1, &value); ASSERT_EQ(floats[i], value); } } TEST(JniArray, JavaArrayOfByteArrayToStringVector) { const int kMaxItems = 50; JNIEnv* env = AttachCurrentThread(); // Create a byte[][] object. ScopedJavaLocalRef<jclass> byte_array_clazz(env, env->FindClass("[B")); ASSERT_TRUE(byte_array_clazz.obj()); ScopedJavaLocalRef<jobjectArray> array( env, env->NewObjectArray(kMaxItems, byte_array_clazz.obj(), NULL)); ASSERT_TRUE(array.obj()); // Create kMaxItems byte buffers. char text[16]; for (int i = 0; i < kMaxItems; ++i) { snprintf(text, sizeof text, "%d", i); ScopedJavaLocalRef<jbyteArray> byte_array = ToJavaByteArray( env, reinterpret_cast<uint8*>(text), static_cast<size_t>(strlen(text))); ASSERT_TRUE(byte_array.obj()); env->SetObjectArrayElement(array.obj(), i, byte_array.obj()); ASSERT_FALSE(HasException(env)); } // Convert to std::vector<std::string>, check the content. std::vector<std::string> vec; JavaArrayOfByteArrayToStringVector(env, array.obj(), &vec); EXPECT_EQ(static_cast<size_t>(kMaxItems), vec.size()); for (int i = 0; i < kMaxItems; ++i) { snprintf(text, sizeof text, "%d", i); EXPECT_STREQ(text, vec[i].c_str()); } } } // namespace android } // namespace base
30.033557
79
0.682905
[ "object", "vector" ]
3ac97d92515f8c465019cd412d80294fea50ca11
18,062
cxx
C++
VirtualReality/qSlicerVirtualRealityModuleWidget.cxx
KitwareMedical/SlicerOpenVR
e40e0b118f38ccd88b9e8a2bd619f06fbf544b84
[ "Apache-2.0" ]
5
2017-10-17T13:29:01.000Z
2018-01-21T06:36:15.000Z
VirtualReality/qSlicerVirtualRealityModuleWidget.cxx
KitwareMedical/SlicerOpenVR
e40e0b118f38ccd88b9e8a2bd619f06fbf544b84
[ "Apache-2.0" ]
19
2017-10-17T13:18:35.000Z
2018-02-06T23:34:20.000Z
VirtualReality/qSlicerVirtualRealityModuleWidget.cxx
KitwareMedical/SlicerOpenVR
e40e0b118f38ccd88b9e8a2bd619f06fbf544b84
[ "Apache-2.0" ]
9
2017-09-27T19:40:19.000Z
2018-01-17T00:12:07.000Z
/*============================================================================== Program: 3D Slicer Portions (c) Copyright Brigham and Women's Hospital (BWH) All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // Qt includes #include <QDebug> // SlicerQt includes #include "qSlicerVirtualRealityModuleWidget.h" #include "ui_qSlicerVirtualRealityModuleWidget.h" // CTK includes #include "ctkDoubleSpinBox.h" // MRML includes #include "vtkMRMLScene.h" // VirtualReality includes #include "qSlicerVirtualRealityModule.h" #include "qMRMLVirtualRealityView.h" #include "vtkMRMLVirtualRealityViewNode.h" #include "vtkMRMLVirtualRealityViewDisplayableManagerFactory.h" #include "vtkSlicerVirtualRealityLogic.h" //----------------------------------------------------------------------------- /// \ingroup Slicer_QtModules_ExtensionTemplate class qSlicerVirtualRealityModuleWidgetPrivate: public Ui_qSlicerVirtualRealityModuleWidget { public: qSlicerVirtualRealityModuleWidgetPrivate(); }; //----------------------------------------------------------------------------- // qSlicerVirtualRealityModuleWidgetPrivate methods //----------------------------------------------------------------------------- qSlicerVirtualRealityModuleWidgetPrivate::qSlicerVirtualRealityModuleWidgetPrivate() { } //----------------------------------------------------------------------------- // qSlicerVirtualRealityModuleWidget methods //----------------------------------------------------------------------------- qSlicerVirtualRealityModuleWidget::qSlicerVirtualRealityModuleWidget(QWidget* _parent) : Superclass(_parent) , d_ptr(new qSlicerVirtualRealityModuleWidgetPrivate) { } //----------------------------------------------------------------------------- qSlicerVirtualRealityModuleWidget::~qSlicerVirtualRealityModuleWidget() { } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setup() { Q_D(qSlicerVirtualRealityModuleWidget); d->setupUi(this); this->Superclass::setup(); connect(d->ConnectCheckBox, SIGNAL(toggled(bool)), this, SLOT(setVirtualRealityConnected(bool))); connect(d->RenderingEnabledCheckBox, SIGNAL(toggled(bool)), this, SLOT(setVirtualRealityActive(bool))); connect(d->TwoSidedLightingCheckBox, SIGNAL(toggled(bool)), this, SLOT(setTwoSidedLighting(bool))); connect(d->BackLightsCheckBox, SIGNAL(toggled(bool)), this, SLOT(setBackLights(bool))); connect(d->ControllerModelsVisibleCheckBox, SIGNAL(toggled(bool)), this, SLOT(setControllerModelsVisible(bool))); connect(d->LighthousesVisibleCheckBox, SIGNAL(toggled(bool)), this, SLOT(setTrackingReferenceModelsVisible(bool))); connect(d->ReferenceViewNodeComboBox, SIGNAL(currentNodeChanged(vtkMRMLNode*)), this, SLOT(setReferenceViewNode(vtkMRMLNode*))); connect(d->UpdateViewFromReferenceViewCameraButton, SIGNAL(clicked()), this, SLOT(updateViewFromReferenceViewCamera())); connect(d->DesiredUpdateRateSlider, SIGNAL(valueChanged(double)), this, SLOT(onDesiredUpdateRateChanged(double))); connect(d->MotionSensitivitySlider, SIGNAL(valueChanged(double)), this, SLOT(onMotionSensitivityChanged(double))); connect(d->MagnificationSlider, SIGNAL(valueChanged(double)), this, SLOT(onMagnificationChanged(double))); connect(d->MotionSpeedSlider, SIGNAL(valueChanged(double)), this, SLOT(onMotionSpeedChanged(double))); connect(d->ControllerTransformsUpdateCheckBox, SIGNAL(toggled(bool)), this, SLOT(setControllerTransformsUpdate(bool))); connect(d->HMDTransformCheckBox, SIGNAL(toggled(bool)), this, SLOT(setHMDTransformUpdate(bool))); connect(d->TrackerTransformsCheckBox, SIGNAL(toggled(bool)), this, SLOT(setTrackerTransformsUpdate(bool))); // Make magnification label same width as motion sensitivity spinbox ctkDoubleSpinBox* motionSpeedSpinBox = d->MotionSpeedSlider->findChild<ctkDoubleSpinBox*>("SpinBox"); d->MagnificationValueLabel->setMinimumWidth(motionSpeedSpinBox->sizeHint().width()); this->updateWidgetFromMRML(); // If virtual reality logic is modified it indicates that the view node may changed qvtkConnect(logic(), vtkCommand::ModifiedEvent, this, SLOT(updateWidgetFromMRML())); } //-------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::updateWidgetFromMRML() { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); bool wasBlocked = d->ConnectCheckBox->blockSignals(true); d->ConnectCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetVisibility()); d->ConnectCheckBox->blockSignals(wasBlocked); QString errorText; if (vrViewNode && vrViewNode->HasError()) { errorText = vrViewNode->GetError().c_str(); } d->ConnectionStatusLabel->setText(errorText); wasBlocked = d->RenderingEnabledCheckBox->blockSignals(true); d->RenderingEnabledCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetActive()); d->RenderingEnabledCheckBox->blockSignals(wasBlocked); wasBlocked = d->DesiredUpdateRateSlider->blockSignals(true); d->DesiredUpdateRateSlider->setValue(vrViewNode != nullptr ? vrViewNode->GetDesiredUpdateRate() : 0); d->DesiredUpdateRateSlider->setEnabled(vrViewNode != nullptr); d->DesiredUpdateRateSlider->blockSignals(wasBlocked); wasBlocked = d->MagnificationSlider->blockSignals(true); d->MagnificationSlider->setValue(vrViewNode != nullptr ? this->getPowerFromMagnification(vrViewNode->GetMagnification()) : 1.0); d->MagnificationValueLabel->setText(vrViewNode != nullptr ? QString("%1x").arg(vrViewNode->GetMagnification(), 3, 'f', 2) : "10.0"); d->MagnificationSlider->setEnabled(vrViewNode != nullptr); d->MagnificationSlider->blockSignals(wasBlocked); wasBlocked = d->MotionSensitivitySlider->blockSignals(true); d->MotionSensitivitySlider->setValue(vrViewNode != nullptr ? vrViewNode->GetMotionSensitivity() * 100.0 : 0); d->MotionSensitivitySlider->setEnabled(vrViewNode != nullptr); d->MotionSensitivitySlider->blockSignals(wasBlocked); wasBlocked = d->MotionSpeedSlider->blockSignals(true); d->MotionSpeedSlider->setValue(vrViewNode != nullptr ? vrViewNode->GetMotionSpeed() : 1.6666); d->MotionSpeedSlider->setEnabled(vrViewNode != nullptr); d->MotionSpeedSlider->blockSignals(wasBlocked); wasBlocked = d->TwoSidedLightingCheckBox->blockSignals(true); d->TwoSidedLightingCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetTwoSidedLighting()); d->TwoSidedLightingCheckBox->setEnabled(vrViewNode != nullptr); d->TwoSidedLightingCheckBox->blockSignals(wasBlocked); wasBlocked = d->BackLightsCheckBox->blockSignals(true); d->BackLightsCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetBackLights()); d->BackLightsCheckBox->setEnabled(vrViewNode != nullptr); d->BackLightsCheckBox->blockSignals(wasBlocked); wasBlocked = d->ControllerModelsVisibleCheckBox->blockSignals(true); d->ControllerModelsVisibleCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetControllerModelsVisible()); d->ControllerModelsVisibleCheckBox->setEnabled(vrViewNode != nullptr); d->ControllerModelsVisibleCheckBox->blockSignals(wasBlocked); wasBlocked = d->LighthousesVisibleCheckBox->blockSignals(true); d->LighthousesVisibleCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetLighthouseModelsVisible()); d->LighthousesVisibleCheckBox->setEnabled(vrViewNode != nullptr); d->LighthousesVisibleCheckBox->blockSignals(wasBlocked); wasBlocked = d->ReferenceViewNodeComboBox->blockSignals(true); d->ReferenceViewNodeComboBox->setCurrentNode(vrViewNode != nullptr ? vrViewNode->GetReferenceViewNode() : nullptr); d->ReferenceViewNodeComboBox->blockSignals(wasBlocked); d->ReferenceViewNodeComboBox->setEnabled(vrViewNode != nullptr); wasBlocked = d->ControllerTransformsUpdateCheckBox->blockSignals(true); d->ControllerTransformsUpdateCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetControllerTransformsUpdate()); d->ControllerTransformsUpdateCheckBox->setEnabled(vrViewNode != nullptr); d->ControllerTransformsUpdateCheckBox->blockSignals(wasBlocked); wasBlocked = d->HMDTransformCheckBox->blockSignals(true); d->HMDTransformCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetHMDTransformUpdate()); d->HMDTransformCheckBox->setEnabled(vrViewNode != nullptr); d->HMDTransformCheckBox->blockSignals(wasBlocked); wasBlocked = d->TrackerTransformsCheckBox->blockSignals(true); d->TrackerTransformsCheckBox->setChecked(vrViewNode != nullptr && vrViewNode->GetTrackerTransformUpdate()); d->TrackerTransformsCheckBox->setEnabled(vrViewNode != nullptr); d->TrackerTransformsCheckBox->blockSignals(wasBlocked); d->UpdateViewFromReferenceViewCameraButton->setEnabled(vrViewNode != nullptr && vrViewNode->GetReferenceViewNode() != nullptr); } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setVirtualRealityConnected(bool connect) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vrLogic->SetVirtualRealityConnected(connect); } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setVirtualRealityActive(bool activate) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vrLogic->SetVirtualRealityActive(activate); } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setTwoSidedLighting(bool active) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetTwoSidedLighting(active); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setBackLights(bool active) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetBackLights(active); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setControllerModelsVisible(bool visible) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetControllerModelsVisible(visible); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setTrackingReferenceModelsVisible(bool visible) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetLighthouseModelsVisible(visible); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setReferenceViewNode(vtkMRMLNode* node) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vtkMRMLViewNode* referenceViewNode = vtkMRMLViewNode::SafeDownCast(node); vrViewNode->SetAndObserveReferenceViewNode(referenceViewNode); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::updateViewFromReferenceViewCamera() { Q_D(qSlicerVirtualRealityModuleWidget); qSlicerVirtualRealityModule* vrModule = dynamic_cast<qSlicerVirtualRealityModule*>(this->module()); if (!vrModule) { return; } qMRMLVirtualRealityView* vrView = vrModule->viewWidget(); if (!vrView) { return; } vrView->updateViewFromReferenceViewCamera(); } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::onDesiredUpdateRateChanged(double fps) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetDesiredUpdateRate(fps); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::onMotionSensitivityChanged(double percent) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetMotionSensitivity(percent * 0.01); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::onMotionSpeedChanged(double speedMps) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetMotionSpeed(speedMps); } } //---------------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::onMagnificationChanged(double powerOfTen) { Q_D(qSlicerVirtualRealityModuleWidget); double magnification = this->getMagnificationFromPower(powerOfTen); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetMagnification(magnification); } d->MagnificationValueLabel->setText(QString("%1x").arg(magnification, 3, 'f', 2)); } //---------------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::onPhysicalToWorldMatrixModified() { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { double magnification = vrViewNode->GetMagnification(); bool wasBlocked = d->MagnificationSlider->blockSignals(true); d->MagnificationSlider->setValue(this->getPowerFromMagnification(magnification)); d->MagnificationSlider->blockSignals(wasBlocked); d->MagnificationValueLabel->setText(QString("%1x").arg(magnification, 3, 'f', 2)); } } //---------------------------------------------------------------------------------- double qSlicerVirtualRealityModuleWidget::getMagnificationFromPower(double powerOfTen) { if (powerOfTen < -2.0) { powerOfTen = -2.0; } else if (powerOfTen > 2.0) { powerOfTen = 2.0; } return pow(10.0, powerOfTen); } //---------------------------------------------------------------------------------- double qSlicerVirtualRealityModuleWidget::getPowerFromMagnification(double magnification) { if (magnification < 0.01) { magnification = 0.01; } else if (magnification > 100.0) { magnification = 100.0; } return log10(magnification); } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setControllerTransformsUpdate(bool active) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetControllerTransformsUpdate(active); } } //----------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setHMDTransformUpdate(bool active) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetHMDTransformUpdate(active); } } //---------------------------------------------------------------------------- void qSlicerVirtualRealityModuleWidget::setTrackerTransformsUpdate(bool active) { Q_D(qSlicerVirtualRealityModuleWidget); vtkSlicerVirtualRealityLogic* vrLogic = vtkSlicerVirtualRealityLogic::SafeDownCast(this->logic()); vtkMRMLVirtualRealityViewNode* vrViewNode = vrLogic->GetVirtualRealityViewNode(); if (vrViewNode) { vrViewNode->SetTrackerTransformUpdate(active); } }
42.599057
130
0.69051
[ "3d" ]
3acbda1df623aeb360dc93ae9cd71ab833191115
9,201
cpp
C++
esp32/components/rpg/rpg.cpp
nsec/nsec16
7c012abac54a4f7627da27dce38b0370918b1717
[ "MIT" ]
25
2017-12-22T18:49:30.000Z
2021-11-09T11:59:42.000Z
esp32/components/rpg/rpg.cpp
nsec/nsec16
7c012abac54a4f7627da27dce38b0370918b1717
[ "MIT" ]
6
2018-10-01T19:27:51.000Z
2021-05-30T21:28:02.000Z
esp32/components/rpg/rpg.cpp
nsec/nsec16
7c012abac54a4f7627da27dce38b0370918b1717
[ "MIT" ]
2
2019-03-22T03:15:30.000Z
2020-11-05T19:39:57.000Z
#include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "rpg.h" #include "rpg_const.h" #include "rpg_control.h" #include "rpg/ChestObject.h" #include "rpg/Coordinates.h" #include "rpg/KonamiHandler.h" #include "rpg/Scene.h" #include "rpg/characters/CharacterAngela.h" #include "rpg/characters/CharacterAristocrate.h" #include "rpg/characters/CharacterCharles.h" #include "rpg/characters/CharacterChloe.h" #include "rpg/characters/CharacterDancer.h" #include "rpg/characters/CharacterDog.h" #include "rpg/characters/CharacterDuck.h" #include "rpg/characters/CharacterFarmer.h" #include "rpg/characters/CharacterFil.h" #include "rpg/characters/CharacterFisherman.h" #include "rpg/characters/CharacterMerchant.h" #include "rpg/characters/CharacterMonk.h" #include "rpg/characters/CharacterOldman.h" #include "rpg/characters/CharacterOldwoman.h" #include "rpg/characters/CharacterPunk.h" #include "rpg/characters/CharacterRed.h" #include "rpg/characters/CharacterRetailer.h" #include "rpg/characters/CharacterSailor.h" #include "rpg/characters/CharacterSoldier.h" #include "rpg/characters/CharacterVijay.h" #include "rpg/characters/CharacterYue.h" #include "rpg/characters/MainCharacter.h" #include "rpg/data/BlockedDataReader.h" #include "challenges_screen.h" #include "graphics.h" #include "infoscreen.h" #include "menu.h" #include "save.h" void run_main_scene(void) { rpg::Scene scene{"main", rpg::GlobalCoordinates::xy(1200, 1200)}; rpg::data::BlockedDataReader blocked_data_reader{ "main", rpg::GlobalCoordinates::xy(1200, 1200)}; rpg::MainCharacter mc{}; mc.set_blocked_data_reader(blocked_data_reader); scene.add_character(&mc); rpg::CharacterAngela character_angela{}; character_angela.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_angela); rpg::CharacterAristocrate character_aristocrate{}; character_aristocrate.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_aristocrate); rpg::CharacterCharles character_charles{}; scene.add_character(&character_charles); rpg::CharacterChloe character_chloe{}; character_chloe.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_chloe); rpg::CharacterDancer character_dancer{}; character_dancer.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_dancer); rpg::CharacterDog character_dog{}; character_dog.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_dog); rpg::CharacterDuck character_duck{}; character_duck.set_max_distance(40, 1); scene.add_character(&character_duck); rpg::CharacterFarmer character_farmer{}; character_farmer.set_blocked_data_reader(blocked_data_reader); character_farmer.set_max_distance(180, 100); scene.add_character(&character_farmer); rpg::CharacterFil character_fil{}; character_fil.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_fil); rpg::CharacterFisherman character_fisherman{}; scene.add_character(&character_fisherman); rpg::CharacterMerchant character_merchant{}; character_merchant.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_merchant); rpg::CharacterMonk character_monk{}; character_monk.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_monk); rpg::CharacterOldman character_oldman{}; scene.add_character(&character_oldman); rpg::CharacterOldwoman character_oldwoman{}; character_oldwoman.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_oldwoman); rpg::CharacterPunk character_punk{}; character_punk.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_punk); rpg::CharacterRed character_red{}; character_red.set_blocked_data_reader(blocked_data_reader); character_red.set_max_distance(150, 240); scene.add_character(&character_red); rpg::CharacterRetailer character_retailer{}; character_retailer.set_blocked_data_reader(blocked_data_reader); character_retailer.set_max_distance(40, 1); scene.add_character(&character_retailer); rpg::CharacterSailor character_sailor{}; character_sailor.set_blocked_data_reader(blocked_data_reader); character_sailor.set_max_distance(18, 72); scene.add_character(&character_sailor); rpg::CharacterSoldier character_solider1{}, character_solider2{}; character_solider1.set_blocked_data_reader(blocked_data_reader); character_solider2.set_blocked_data_reader(blocked_data_reader); character_solider1.set_max_distance(90, 48); character_solider2.set_max_distance(30, 100); scene.add_character(&character_solider1); scene.add_character(&character_solider2); rpg::CharacterVijay character_vijay{}; character_vijay.set_blocked_data_reader(blocked_data_reader); scene.add_character(&character_vijay); rpg::CharacterYue character_yue{}; character_yue.set_blocked_data_reader(blocked_data_reader); character_yue.set_max_distance(120, 120); scene.add_character(&character_yue); scene.get_viewport().move(rpg::GlobalCoordinates::xy(935, 611)); mc.move(rpg::GlobalCoordinates::xy(1084, 712)); character_angela.move_initial(rpg::GlobalCoordinates::xy(120, 210)); character_aristocrate.move_initial(rpg::GlobalCoordinates::xy(760, 680)); character_charles.move_initial(rpg::GlobalCoordinates::xy(105, 745)); character_chloe.move_initial(rpg::GlobalCoordinates::xy(450, 313)); character_dancer.move_initial(rpg::GlobalCoordinates::xy(740, 477)); character_dog.move_initial(rpg::GlobalCoordinates::xy(262, 474)); character_duck.move_initial(rpg::GlobalCoordinates::xy(589, 542)); character_farmer.move_initial(rpg::GlobalCoordinates::xy(938, 140)); character_fil.move_initial(rpg::GlobalCoordinates::xy(460, 720)); character_fisherman.move_initial(rpg::GlobalCoordinates::xy(970, 1100)); character_merchant.move_initial(rpg::GlobalCoordinates::xy(570, 700)); character_monk.move_initial(rpg::GlobalCoordinates::xy(265, 1057)); character_oldman.move_initial(rpg::GlobalCoordinates::xy(975, 753)); character_oldwoman.move_initial(rpg::GlobalCoordinates::xy(250, 111)); character_punk.move_initial(rpg::GlobalCoordinates::xy(24, 768)); character_red.move_initial(rpg::GlobalCoordinates::xy(648, 805)); character_retailer.move_initial(rpg::GlobalCoordinates::xy(550, 615)); character_sailor.move_initial(rpg::GlobalCoordinates::xy(1017, 826)); character_solider1.move_initial(rpg::GlobalCoordinates::xy(590, 1080)); character_solider2.move_initial(rpg::GlobalCoordinates::xy(705, 1135)); character_vijay.move_initial(rpg::GlobalCoordinates::xy(616, 1010)); character_yue.move_initial(rpg::GlobalCoordinates::xy(660, 125)); rpg::ChestObject chest_island{rpg::SceneObjectIdentity::chest_island, rpg::GlobalCoordinates::tile(48, 48), Save::save_data.chest_opened_island}; scene.add_scene_object(&chest_island); rpg::ChestObject chest_konami{rpg::SceneObjectIdentity::chest_konami, rpg::GlobalCoordinates::tile(0, 1), Save::save_data.chest_opened_konami}; scene.add_scene_object(&chest_konami); rpg::ChestObject chest_welcome{rpg::SceneObjectIdentity::chest_welcome, rpg::GlobalCoordinates::tile(41, 26), Save::save_data.chest_opened_welcome}; scene.add_scene_object(&chest_welcome); rpg::KonamiHandler konami_handler{scene, blocked_data_reader}; rpg::RpgControlDevice control_device{}; control_device.scene = &scene; while (true) { rpg_control_take(control_device); scene.get_viewport().mark_for_full_refresh(); scene.render(); if (control_device.exit_action == rpg::ControlExitAction::konami_code) { konami_handler.patch(); continue; } // Scene fade out effect. graphics_fadeout_display_buffer(40); graphics_update_display(); for (int i = 0; i <= 13; ++i) { graphics_fadeout_display_buffer(20); graphics_update_display(); } switch (control_device.exit_action) { case rpg::ControlExitAction::badge_info: infoscreen_display_badgeinfo(); break; case rpg::ControlExitAction::hall_of_fame: infoscreen_display_halloffame(); break; case rpg::ControlExitAction::menu_led: menu::display_led_settings(); break; case rpg::ControlExitAction::menu_sound: menu::display_sound_settings(); break; case rpg::ControlExitAction::menu_wifi: menu::display_wifi_settings(); break; case rpg::ControlExitAction::reverse_challenge: challenges_screen_display(); break; default: break; } } }
38.822785
80
0.734159
[ "render" ]
3acd1b2b9a7d377fee4f28d25ec214f64b521bb4
136,734
cpp
C++
v3d_main/terafly/src/control/CViewer.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
v3d_main/terafly/src/control/CViewer.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
v3d_main/terafly/src/control/CViewer.cpp
hanchuan/vaa3d_external
d6381572dec4079705ac5d3e39c9556b50472403
[ "MIT" ]
null
null
null
//------------------------------------------------------------------------------------------------ // Copyright (c) 2012 Alessandro Bria and Giulio Iannello (University Campus Bio-Medico of Rome). // All rights reserved. //------------------------------------------------------------------------------------------------ /******************************************************************************************************************************************************************************************* * LICENSE NOTICE ******************************************************************************************************************************************************************************************** * By downloading/using/running/editing/changing any portion of codes in this package you agree to this license. If you do not agree to this license, do not download/use/run/edit/change * this code. ******************************************************************************************************************************************************************************************** * 1. This material is free for non-profit research, but needs a special license for any commercial purpose. Please contact Alessandro Bria at a.bria@unicas.it or Giulio Iannello at * g.iannello@unicampus.it for further details. * 2. You agree to appropriately cite this work in your related studies and publications. * * Bria, A., et al., (2012) "Stitching Terabyte-sized 3D Images Acquired in Confocal Ultramicroscopy", Proceedings of the 9th IEEE International Symposium on Biomedical Imaging. * Bria, A., Iannello, G., "A Tool for Fast 3D Automatic Stitching of Teravoxel-sized Datasets", submitted on July 2012 to IEEE Transactions on Information Technology in Biomedicine. * * 3. This material is provided by the copyright holders (Alessandro Bria and Giulio Iannello), University Campus Bio-Medico and contributors "as is" and any express or implied war- * ranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the * copyright owners, University Campus Bio-Medico, 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;reasonable royalties; or business interruption) however caused and on any theory of liabil- * ity, 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. * 4. Neither the name of University Campus Bio-Medico of Rome, nor Alessandro Bria and Giulio Iannello, may be used to endorse or promote products derived from this software without * specific prior written permission. ********************************************************************************************************************************************************************************************/ /****************** * CHANGELOG * ******************* * 2016-05-31. Alessandro. @FIXED missing hidden neuron segments. * 2014-11-17. Alessandro. @FIXED "duplicated annotations" bug * 2014-11-17. Alessandro. @ADDED 'anoV0', ..., 'anoD1' VOI annotation (global) coordinates as object members in order to fix "duplicated annotations" bug */ #include "CViewer.h" #include "v3dr_mainwindow.h" #include "CVolume.h" #include "CAnnotations.h" #include "CImageUtils.h" #include "COperation.h" #include "../presentation/PMain.h" #include "../presentation/PLog.h" #include "../presentation/PAnoToolBar.h" #include "../presentation/PDialogProofreading.h" #include "renderer.h" #include "renderer_gl1.h" #include "v3dr_colormapDialog.h" #include "V3Dsubclasses.h" #include "QUndoMarkerCreate.h" #include "QUndoMarkerDelete.h" #include "QUndoMarkerDeleteROI.h" #include "v3d_application.h" using namespace tf; CViewer* CViewer::first = 0; CViewer* CViewer::last = 0; CViewer* CViewer::current = 0; int CViewer::nInstances = 0; int CViewer::nTotalInstances = 0; int CViewer::newViewerOperationID = 0; void CViewer::show() { /**/tf::debug(tf::LEV1, 0, __itm__current__function__); PMain* pMain = PMain::getInstance(); QElapsedTimer timer; timer.start(); try { // open tri-view window (and hiding it asap) this->window = V3D_env->newImageWindow(QString(title.c_str())); this->triViewWidget = (XFormWidget*)window; triViewWidget->setWindowState(Qt::WindowMinimized); Image4DSimple* image = new Image4DSimple(); image->setFileName(title.c_str()); image->setData(imgData, volH1-volH0, volV1-volV0, volD1-volD0, nchannels*(volT1-volT0+1), V3D_UINT8); image->setTDim(volT1-volT0+1); image->setTimePackType(TIME_PACK_C); V3D_env->setImage(window, image); // create 3D view window with postponed show() XFormWidget *w = V3dApplication::getMainWindow()->validateImageWindow(window); w->doImage3DView(true, 0, -1, -1,-1, -1, -1,-1, false); view3DWidget = (V3dR_GLWidget*)(V3D_env->getView3DControl(window)); if(!view3DWidget->getiDrawExternalParameter()) QMessageBox::critical(pMain,QObject::tr("Error"), QObject::tr("Unable to get iDrawExternalParameter from Vaa3D's V3dR_GLWidget"),QObject::tr("Ok")); window3D = view3DWidget->getiDrawExternalParameter()->window3D; // disable progress bar (for faster 3D viewer updates) view3DWidget->setShowProgressBar(false); // start 3D visualization with Vaa3D display controls hidden (or inherit from previous viewer) if(!prev || prev->window3D->displayControlsHidden) window3D->hideDisplayControls(); // remove TeraFly's toolbar from previous viewer (if any) and add to this viewer int tab_selected = PMain::getInstance()->tabs->currentIndex(); if(prev) { prev->window3D->centralLayout->takeAt(0); PAnoToolBar::instance()->setParent(0); PMain::getInstance()->tabs->removeTab(1); } window3D->centralLayout->insertWidget(0, PAnoToolBar::instance()); // @ADDED Vaa3D-controls-within-TeraFly feature. window3D->hideDisplayControlsButton->setVisible(false); window3D->centralLayout->takeAt(3); QWidget* vaa3d_controls = new QWidget(); QVBoxLayout* vaa3d_controls_layout = new QVBoxLayout(); vaa3d_controls_layout->addWidget(window3D->tabOptions); vaa3d_controls_layout->addWidget(window3D->toolBtnGroup); vaa3d_controls_layout->addWidget(window3D->tabCutPlane); vaa3d_controls_layout->addWidget(window3D->tabRotZoom); vaa3d_controls->setLayout(vaa3d_controls_layout); PMain::getInstance()->tabs->insertTab(1, vaa3d_controls, "Vaa3D controls"); PMain::getInstance()->tabs->setCurrentIndex(tab_selected); // also reset undo/redo (which are referred to this viewer) PAnoToolBar::instance()->buttonUndo->setEnabled(false); PAnoToolBar::instance()->buttonRedo->setEnabled(false); // re-arrange viewer's layout window3D->centralLayout->setSpacing(0); window3D->centralLayout->insertSpacing(2, 10); window3D->centralLayout->insertSpacing(4, 10); window3D->centralLayout->setContentsMargins(10,5,5,10); // set fixed size that fills available screen space // window3D->resize(qApp->desktop()->availableGeometry().width()-PMain::getInstance()->width(), PMain::getInstance()->height()); // resize according to persistent settings window3D->resize(CSettings::instance()->getViewerWidth(), CSettings::instance()->getViewerWidth()); // show 3D viewer window3D->show(); // install the event filter on the 3D renderer and on the 3D window view3DWidget->installEventFilter(this); window3D->installEventFilter(this); window3D->timeSlider->installEventFilter(this); // time slider: disconnect Vaa3D event handlers and set the complete (virtual) time range disconnect(view3DWidget, SIGNAL(changeVolumeTimePoint(int)), window3D->timeSlider, SLOT(setValue(int))); disconnect(window3D->timeSlider, SIGNAL(valueChanged(int)), view3DWidget, SLOT(setVolumeTimePoint(int))); window3D->timeSlider->setMinimum(0); window3D->timeSlider->setMaximum(CImport::instance()->getTDim()-1); // if the previous explorer window exists if(prev) { // apply the same color map only if it differs from the previous one Renderer_gl2* prev_renderer = (Renderer_gl2*)(prev->view3DWidget->getRenderer()); Renderer_gl2* curr_renderer = (Renderer_gl2*)(view3DWidget->getRenderer()); bool changed_cmap = false; for(int k=0; k<3; k++) { RGBA8* prev_cmap = prev_renderer->colormap[k]; RGBA8* curr_cmap = curr_renderer->colormap[k]; for(int i=0; i<256; i++) { if(curr_cmap[i].i != prev_cmap[i].i) changed_cmap = true; curr_cmap[i] = prev_cmap[i]; } } if(changed_cmap) curr_renderer->applyColormapToImage(); //positioning the current 3D window exactly at the previous window position QPoint location = prev->pos(); resize(prev->window3D->size()); move(location); //hiding both tri-view and 3D view prev->window3D->setVisible(false); //prev->triViewWidget->setVisible(false); //---- Alessandro 2013-09-04 fixed: this causes Vaa3D's setCurHiddenSelectedWindow() to fail prev->view3DWidget->setCursor(Qt::ArrowCursor); //registrating views: ---- Alessandro 2013-04-18 fixed: determining unique triple of rotation angles and assigning absolute rotation float ratio = CImport::instance()->getVolume(volResIndex)->getDIM_D()/CImport::instance()->getVolume(prev->volResIndex)->getDIM_D(); view3DWidget->setZoom(prev->view3DWidget->zoom()/ratio); prev->view3DWidget->absoluteRotPose(); view3DWidget->doAbsoluteRot(prev->view3DWidget->xRot(), prev->view3DWidget->yRot(), prev->view3DWidget->zRot()); // 5D data: select the same time frame (if available) if(CImport::instance()->is5D()) { int prev_s = prev->window3D->timeSlider->value(); if(prev_s < volT0 || prev_s > volT1) window3D->timeSlider->setValue(volT0); else window3D->timeSlider->setValue(prev_s); view3DWidget->setVolumeTimePoint(window3D->timeSlider->value()-volT0); } //sync widgets syncWindows(prev->window3D, window3D); //storing annotations done in the previous view and loading annotations of the current view prev->storeAnnotations(); prev->clearAnnotations(); this->loadAnnotations(); } //otherwise this is the lowest resolution window else { //registrating the current window as the first window of the multiresolution explorer windows chain CViewer::first = this; // update annotation space updateAnnotationSpace(); //centering the current 3D window and the plugin's window int screen_height = qApp->desktop()->availableGeometry().height(); int screen_width = qApp->desktop()->availableGeometry().width(); int window_x = (screen_width - (window3D->width() + pMain->width()))/2; int window_y = (screen_height - window3D->height()) / 2; window3D->move(window_x, window_y); } //registrating the current window as the last and current window of the multiresolution explorer windows chain CViewer::last = this; CViewer::current = this; //selecting the current resolution in the PMain GUI and disabling previous resolutions pMain->resolution_cbox->setCurrentIndex(volResIndex); for(int i=0; i<pMain->resolution_cbox->count(); i++) { // Get the index of the value to disable QModelIndex index = pMain->resolution_cbox->model()->index(i,0); // These are the effective 'disable/enable' flags QVariant v1(Qt::NoItemFlags); QVariant v2(Qt::ItemIsSelectable | Qt::ItemIsEnabled); //the magic if(i<volResIndex) pMain->resolution_cbox->model()->setData( index, v1, Qt::UserRole -1); else pMain->resolution_cbox->model()->setData( index, v2, Qt::UserRole -1); } pMain->gradientBar->setStep(volResIndex); pMain->gradientBar->update(); //disabling translate buttons if needed if(!pMain->isPRactive()) { pMain->traslYneg->setEnabled(volV0 > 0); pMain->traslYpos->setEnabled(volV1 < CImport::instance()->getVolume(volResIndex)->getDIM_V()); pMain->traslXneg->setEnabled(volH0 > 0); pMain->traslXpos->setEnabled(volH1 < CImport::instance()->getVolume(volResIndex)->getDIM_H()); pMain->traslZneg->setEnabled(volD0 > 0); pMain->traslZpos->setEnabled(volD1 < CImport::instance()->getVolume(volResIndex)->getDIM_D()); pMain->traslTneg->setEnabled(volT0 > 0); pMain->traslTpos->setEnabled(volT1 < CImport::instance()->getVolume(volResIndex)->getDIM_T()-1); } //setting min, max and value of PMain GUI VOI's widgets /**/tf::debug(tf::LEV2, tf::strprintf("Vaa3D cut is set to V[%d,%d], H[%d,%d], D[%d,%d]", view3DWidget->yCut0(), view3DWidget->yCut1(), view3DWidget->xCut0(), view3DWidget->xCut1(), view3DWidget->zCut0(), view3DWidget->zCut1()).c_str(), __itm__current__function__); pMain->V0_sbox->setMinimum(coord2global<int>(view3DWidget->yCut0(), iim::vertical, true, -1, true, false, __itm__current__function__) +1); pMain->V0_sbox->setValue(pMain->V0_sbox->minimum()); pMain->V1_sbox->setMaximum(coord2global<int>(view3DWidget->yCut1()+1, iim::vertical, true, -1, true, false, __itm__current__function__)); pMain->V1_sbox->setValue(pMain->V1_sbox->maximum()); pMain->H0_sbox->setMinimum(coord2global<int>(view3DWidget->xCut0(), iim::horizontal,true, -1, true, false, __itm__current__function__) +1); pMain->H0_sbox->setValue(pMain->H0_sbox->minimum()); pMain->H1_sbox->setMaximum(coord2global<int>(view3DWidget->xCut1()+1, iim::horizontal,true, -1, true, false, __itm__current__function__)); pMain->H1_sbox->setValue(pMain->H1_sbox->maximum()); pMain->D0_sbox->setMinimum(coord2global<int>(view3DWidget->zCut0(), iim::depth, true, -1, true, false, __itm__current__function__) +1); pMain->D0_sbox->setValue(pMain->D0_sbox->minimum()); pMain->D1_sbox->setMaximum(coord2global<int>(view3DWidget->zCut1()+1, iim::depth, true, -1, true, false, __itm__current__function__)); pMain->D1_sbox->setValue(pMain->D1_sbox->maximum()); /**/tf::debug(tf::LEV2, tf::strprintf("sbox set to V[%d,%d], H[%d,%d], D[%d,%d]", pMain->V0_sbox->minimum(), pMain->V1_sbox->maximum(), pMain->H0_sbox->minimum(), pMain->H1_sbox->maximum(), pMain->D0_sbox->minimum(), pMain->D1_sbox->maximum()).c_str(), __itm__current__function__); if(pMain->frameCoord->isEnabled()) { pMain->T0_sbox->setText(QString::number(volT0+1)); pMain->T1_sbox->setText(QString::number(volT1+1)); } //signal connections connect(view3DWidget, SIGNAL(changeXCut0(int)), this, SLOT(Vaa3D_changeXCut0(int))); connect(view3DWidget, SIGNAL(changeXCut1(int)), this, SLOT(Vaa3D_changeXCut1(int))); connect(view3DWidget, SIGNAL(changeYCut0(int)), this, SLOT(Vaa3D_changeYCut0(int))); connect(view3DWidget, SIGNAL(changeYCut1(int)), this, SLOT(Vaa3D_changeYCut1(int))); connect(view3DWidget, SIGNAL(changeZCut0(int)), this, SLOT(Vaa3D_changeZCut0(int))); connect(view3DWidget, SIGNAL(changeZCut1(int)), this, SLOT(Vaa3D_changeZCut1(int))); connect(window3D->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(Vaa3D_changeTSlider(int))); //connect(view3DWidget, SIGNAL(xRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //connect(view3DWidget, SIGNAL(yRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //connect(view3DWidget, SIGNAL(zRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); connect(pMain->refSys, SIGNAL(mouseReleased()), this, SLOT(PMain_rotationchanged())); connect(pMain->V0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV0sbox(int))); connect(pMain->V1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV1sbox(int))); connect(pMain->H0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH0sbox(int))); connect(pMain->H1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH1sbox(int))); connect(pMain->D0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD0sbox(int))); connect(pMain->D1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD1sbox(int))); disconnect(window3D->zoomSlider, SIGNAL(valueChanged(int)), view3DWidget, SLOT(setZoom(int))); connect(window3D->zoomSlider, SIGNAL(valueChanged(int)), this, SLOT(setZoom(int))); //changing window flags (disabling minimize/maximize buttons) // ---- Alessandro 2013-04-22 fixed: this causes (somehow) window3D not to respond correctly to the move() method // window3D->setWindowFlags(Qt::Tool // | Qt::WindowTitleHint // | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint | Qt::WindowCloseButtonHint); this->window3D->raise(); this->window3D->activateWindow(); this->window3D->show(); // updating reference system if(!pMain->isPRactive()) pMain->refSys->setDims(volH1-volH0+1, volV1-volV0+1, volD1-volD0+1); this->view3DWidget->updateGL(); // if omitted, Vaa3D_rotationchanged somehow resets rotation to 0,0,0 Vaa3D_rotationchanged(0); // saving subvol spinboxes state ---- Alessandro 2013-04-23: not sure if this is really needed saveSubvolSpinboxState(); // refresh annotation toolbar PAnoToolBar::instance()->refreshTools(); // update curve aspect pMain->curveAspectChanged(); // update marker size pMain->markersSizeSpinBoxChanged(pMain->markersSizeSpinBox->value()); // update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); } catch(RuntimeException &ex) { QMessageBox::critical(pMain,QObject::tr("Error"), (std::string(ex.what())+"\nsource: " + ex.getSource()).c_str(),QObject::tr("Ok")); pMain->closeVolume(); } catch(const char* error) { QMessageBox::critical(pMain,QObject::tr("Error"), QObject::tr(error),QObject::tr("Ok")); pMain->closeVolume(); } catch(...) { QMessageBox::critical(pMain,QObject::tr("Error"), QObject::tr("Unknown error occurred"),QObject::tr("Ok")); pMain->closeVolume(); } if(prev) PLog::instance()->appendOperation(new NewViewerOperation(QString("Opened view ").append(title.c_str()).toStdString(), tf::GPU, timer.elapsed())); else PLog::instance()->appendOperation(new ImportOperation( "Opened first viewer", tf::GPU, timer.elapsed())); } CViewer::CViewer(V3DPluginCallback2 *_V3D_env, int _resIndex, tf::uint8 *_imgData, int _volV0, int _volV1, int _volH0, int _volH1, int _volD0, int _volD1, int _volT0, int _volT1, int _nchannels, CViewer *_prev, int _slidingViewerBlockID /* = -1 */): QWidget() { /**/tf::debug(tf::LEV1, strprintf("_resIndex = %d, _V0 = %d, _V1 = %d, _H0 = %d, _H1 = %d, _D0 = %d, _D1 = %d, _T0 = %d, _T1 = %d, _nchannels = %d", _resIndex, _volV0, _volV1, _volH0, _volH1, _volD0, _volD1, _volT0, _volT1, _nchannels).c_str(), __itm__current__function__); //initializations ID = nTotalInstances++; resetZoomHistory(); isActive = isReady = false; this->V3D_env = _V3D_env; this->prev = _prev; this->next = 0; this->volResIndex = _resIndex; this->volV0 = _volV0; this->volV1 = _volV1; this->volH0 = _volH0; this->volH1 = _volH1; this->volD0 = _volD0; this->volD1 = _volD1; this->volT0 = _volT0; this->volT1 = _volT1; this->anoV0 = this->anoV1 = this->anoH0 = this->anoH1 = this->anoD0 = this->anoD1 = -1; this->nchannels = _nchannels; this->toBeClosed = false; this->imgData = _imgData; this->isReady = false; this->waitingForData = false; this->has_double_clicked = false; char ctitle[1024]; sprintf(ctitle, "ID(%d), Res(%d x %d x %d),Volume X=[%d,%d], Y=[%d,%d], Z=[%d,%d], T=[%d,%d], %d channels", ID, CImport::instance()->getVolume(volResIndex)->getDIM_H(), CImport::instance()->getVolume(volResIndex)->getDIM_V(), CImport::instance()->getVolume(volResIndex)->getDIM_D(), volH0+1, volH1, volV0+1, volV1, volD0+1, volD1, volT0, volT1, nchannels); this->title = ctitle; sprintf(ctitle, "ID(%d), Res{%d}, Vol{[%d,%d) [%d,%d) [%d,%d) [%d,%d]}", ID, volResIndex, volH0, volH1, volV0, volV1, volD0, volD1, volT0, volT1); this->titleShort = ctitle; V0_sbox_min = V0_sbox_val = V1_sbox_max = V1_sbox_val = H0_sbox_min = H0_sbox_val = H1_sbox_max = H1_sbox_val = D0_sbox_min = D0_sbox_val = D1_sbox_max = D1_sbox_val = T0_sbox_min = T0_sbox_val = T1_sbox_max = T1_sbox_val = -1; slidingViewerBlockID = _slidingViewerBlockID; forceZoomIn = false; try { //making prev (if exist) the last view and checking that it belongs to a lower resolution if(prev) { prev->makeLastView(); if(prev->volResIndex > volResIndex) throw RuntimeException("in CViewer(): attempting to break the ascending order of resolution history. This feature is not supported yet."); } //check that the number of instantiated objects does not exceed the number of available resolutions nInstances++; /**/tf::debug(tf::LEV3, strprintf("nInstances++, nInstances = %d", nInstances).c_str(), __itm__current__function__); if(nInstances > CImport::instance()->getResolutions() +1) throw RuntimeException(QString("in CViewer(): exceeded the maximum number of views opened at the same time.\n\nPlease signal this issue to developers.").toStdString().c_str()); //deactivating previous window and activating the current one if(prev) { prev->view3DWidget->removeEventFilter(prev); prev->window3D->removeEventFilter(prev); prev->window3D->timeSlider->removeEventFilter(this); prev->resetZoomHistory(); prev->setActive(false); } setActive(true); } catch(RuntimeException &ex) { QMessageBox::critical(PMain::getInstance(),QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok")); PMain::getInstance()->closeVolume(); } catch(const char* error) { QMessageBox::critical(PMain::getInstance(),QObject::tr("Error"), QObject::tr(error),QObject::tr("Ok")); PMain::getInstance()->closeVolume(); } catch(...) { QMessageBox::critical(PMain::getInstance(),QObject::tr("Error"), QObject::tr("Unknown error occurred"),QObject::tr("Ok")); PMain::getInstance()->closeVolume(); } /**/tf::debug(tf::LEV1, "Object successfully constructed", __itm__current__function__); } CViewer::~CViewer() { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); // decouple TeraFly's toolbar from Vaa3D 3D viewer (only if required) if(PAnoToolBar::instance()->parent() == window3D) { window3D->centralLayout->takeAt(0); PAnoToolBar::instance()->setParent(0); } // remove the event filter from the 3D renderer and from the 3D window isActive = false; view3DWidget->removeEventFilter(this); window3D->removeEventFilter(this); window3D->timeSlider->removeEventFilter(this); // CLOSE 3D window (solution #1) //QMessageBox::information(0, "info", strprintf("calling close3Dwindow").c_str()); //if(!CImport::instance()->is5D()) //V3D_env->close3DWindow(window); //this causes crash on 5D data when scrolling time slider, but is OK in all the other cases // CLOSE 3D window (solution #2) // view3DWidget->close(); //this causes crash when makeLastView is called on a very long chain of opened windows // window3D->postClose(); // CLOSE 3D window (solution #3) // @fixed by Alessandro on 2014-04-11: this seems the only way to close the 3D window w/o (randomly) causing TeraFly to crash // @update by Alessandro on 2014-07-15: this causes random crash in "Proofreading" mode, but is ok on 5D data (even in "Proofediting mode"!) // @update by Alessandro on 2014-07-21: this ALWAYS works on Windows. Still has to be tested on other platforms. POST_EVENT(window3D, QEvent::Close); // this OK //close 2D window triViewWidget->close(); //decreasing the number of instantiated objects nInstances--; /**/tf::debug(tf::LEV1, strprintf("title = %s, nInstances--, nInstances = %d", titleShort.c_str(), nInstances).c_str(), __itm__current__function__); /**/tf::debug(tf::LEV1, strprintf("title = %s, object successfully DESTROYED", titleShort.c_str()).c_str(), __itm__current__function__); } /********************************************************************************** * Filters events generated by the 3D rendering window <view3DWidget> * We're interested to intercept these events to provide many useful ways to explore * the 3D volume at different resolutions without changing Vaa3D code. ***********************************************************************************/ bool CViewer::eventFilter(QObject *object, QEvent *event) { try { //ignoring all events when window is not active if(!isActive) { //printf("Ignoring event from CViewer[%s] cause it's not active\n", title.c_str()); event->ignore(); return true; } //updating zoom factor history zoomHistoryPushBack(view3DWidget->zoom()); /******************** INTERCEPTING ZOOMING CHANGES ************************* Zoom-in and zoom-out changes generated by the current 3D renderer are inter- cepted to switch to the higher/lower resolution. ***************************************************************************/ //---- Alessandro 2013-04-25: triggering zoom-in is now Vaa3D responsibility //if (object == view3DWidget && event->type() == QEvent::Wheel) { // if(next && //the next resolution exists // isZoomDerivativePos() && //zoom derivative is positive // view3DWidget->zoom() > 130 -PMain::instance()->zoomSensitivity->value()) //zoom-in threshold reached // { // //printf("Switching to the next view zoom={%d, %d, %d, %d}\n", zoomHistory[0], zoomHistory[1], zoomHistory[2], zoomHistory[3]); // setActive(false); // resetZoomHistory(); // next->restoreViewerFrom(this); // event->ignore(); // return true; // } // else if(prev && //the previous resolution exists !toBeClosed && //the current resolution does not have to be closed isZoomDerivativeNeg() && //zoom derivative is negative view3DWidget->zoom() < PMain::getInstance()->zoomOutSens->value()) //zoom-out threshold reached { // if window is not ready for "switch view" events, reset zoom-out and ignore this event if(!isReady) { resetZoomHistory(); return false; } else { setActive(false); resetZoomHistory(); prev->restoreViewerFrom(this); return true; } } } /******************** REDIRECTING MOUSE-WHEEL EVENTS ************************* Mouse-wheel events are redirected to the customized wheelEvent handler ***************************************************************************/ if ((object == view3DWidget || object == window3D) && event->type() == QEvent::Wheel) { QWheelEvent* wheelEvt = (QWheelEvent*)event; myV3dR_GLWidget::cast(view3DWidget)->wheelEventO(wheelEvt); return true; } /****************** INTERCEPTING MOUSE CLICK EVENTS *********************** Mouse click events are intercepted for handling annotations tools ***************************************************************************/ if (object == view3DWidget && event->type() == QEvent::MouseButtonPress) { QMouseEvent* mouseEvt = (QMouseEvent*)event; if(mouseEvt->button() == Qt::RightButton && PAnoToolBar::instance()->buttonMarkerDelete->isChecked()) { deleteMarkerAt(mouseEvt->x(), mouseEvt->y()); return true; } else if(mouseEvt->button() == Qt::RightButton && PAnoToolBar::instance()->buttonMarkerCreate->isChecked()) { createMarkerAt(mouseEvt->x(), mouseEvt->y()); return true; } else if(mouseEvt->button() == Qt::RightButton && PAnoToolBar::instance()->buttonMarkerCreate2->isChecked()) { createMarker2At(mouseEvt->x(), mouseEvt->y()); return true; } // ignore Vaa3D-right-click-popup marker create operations else if(mouseEvt->button() == Qt::RightButton) { view3DWidget->getRenderer()->hitPoint(mouseEvt->x(), mouseEvt->y()); Renderer::SelectMode mode = view3DWidget->getRenderer()->selectMode; bool addMarker = static_cast<Renderer_gl1*>(view3DWidget->getRenderer())->b_addthismarker; if((mode == Renderer::smMarkerCreate1 && addMarker) || (mode == Renderer::smMarkerCreate2 && addMarker) || (mode == Renderer::smMarkerCreate3 && addMarker) || mode == Renderer::smMarkerCreate1Curve) { QMessageBox::information(0, "This feature has been disabled", "This feature has been disabled by the developers of TeraFly.\n\n" "Please use the TeraFly's annotation toolbar to perform this action."); PAnoToolBar::instance()->buttonMarkerCreateChecked(false); PAnoToolBar::instance()->buttonMarkerCreate2Checked(false); } event->ignore(); return true; } return false; } /****************** INTERCEPTING MOUSE RELEASE EVENTS ********************** Mouse release events are intercepted for... ***************************************************************************/ if (object == view3DWidget && event->type() == QEvent::MouseButtonRelease) { // ...and emitting a Vaa3D rotation changed event this->Vaa3D_rotationchanged(0); return false; } /****************** INTERCEPTING DOUBLE CLICK EVENTS *********************** Double click events are intercepted to switch to the higher resolution. ***************************************************************************/ if (object == view3DWidget && event->type() == QEvent::MouseButtonDblClick) { if(PMain::getInstance()->isPRactive()) { QMessageBox::information(this->window3D, "Warning", "TeraFly is running in \"Proofreading\" mode. All TeraFly's' navigation features are disabled. " "Please terminate the \"Proofreading\" mode and try again."); return true; } // set double click flag has_double_clicked = true; QMouseEvent* mouseEvt = (QMouseEvent*)event; XYZ point = getRenderer3DPoint(mouseEvt->x(), mouseEvt->y()); newViewer(point.x, point.y, point.z, volResIndex+1, volT0, volT1); return true; } /******************** INTERCEPTING KEYPRESS EVENTS ************************ Double click events are intercepted to switch to the higher resolution. ***************************************************************************/ if (object == window3D && event->type() == 6) { QKeyEvent* key_evt = (QKeyEvent*)event; if(key_evt->key() == Qt::Key_Return) PMain::getInstance()->PRblockSpinboxEditingFinished(); } /****************** INTERCEPTING TIME SLIDER EVENTS ************************ Time slider events are intercepted to navigate through the entire time range ***************************************************************************/ if (object == window3D->timeSlider && // event from Vaa3D time slider ( event->type() == QEvent::MouseButtonRelease || // mouse release event event->type() == QEvent::Wheel)) // mouse scroll event { Vaa3D_changeTSlider(window3D->timeSlider->value(), true); return false; } /***************** INTERCEPTING WINDOW CLOSE EVENTS *********************** Close events are intercepted to switch to the lower resolution, if avail- able. Otherwise, the plugin is closed. ***************************************************************************/ else if(object == window3D && event->type()==QEvent::Close) { if(!toBeClosed) { PMain::getInstance()->closeVolume(); event->ignore(); return true; } } /************ INTERCEPTING WINDOW MOVING/RESIZING EVENTS ****************** Window moving and resizing events are intercepted to let PMain's position be syncronized with the explorer. ***************************************************************************/ else if(object == window3D && (event->type() == QEvent::Move || event->type() == QEvent::Resize)) { alignToRight(PMain::getInstance(), event); return true; } /************* INTERCEPTING WINDOW STATE CHANGES EVENTS ******************* Window state changes events are intercepted to let PMain's position be syn- cronized with the explorer. ***************************************************************************/ else if(object == window3D && event->type() == QEvent::WindowStateChange) { alignToRight(PMain::getInstance(), event); return true; } return false; } catch(RuntimeException &ex) { QMessageBox::critical(PMain::getInstance(),QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok")); return false; } } /********************************************************************************* * Receive data (and metadata) from <CVolume> throughout the loading process **********************************************************************************/ void CViewer::receiveData( tf::uint8* data, // data (any dimension) integer_array data_s, // data start coordinates along X, Y, Z, C, t integer_array data_c, // data count along X, Y, Z, C, t QWidget *dest, // address of the listener bool finished, // whether the loading operation is terminated tf::RuntimeException* ex /* = 0*/, // exception (optional) qint64 elapsed_time /* = 0 */, // elapsed time (optional) QString op_dsc /* = ""*/, // operation descriptor (optional) int step /* = 0 */) // step number (optional) { /**/tf::debug(tf::LEV1, strprintf("title = %s, data_s = {%s}, data_c = {%s}, finished = %s", titleShort.c_str(), !data_s.empty() ? strprintf("%d,%d,%d,%d,%d", data_s[0], data_s[1], data_s[2], data_s[3], data_s[4]).c_str() : "", !data_c.empty() ? strprintf("%d,%d,%d,%d,%d", data_c[0], data_c[1], data_c[2], data_c[3], data_c[4]).c_str() : "", finished ? "true" : "false").c_str(), __itm__current__function__); char message[1000]; CVolume* cVolume = CVolume::instance(); //if an exception has occurred, showing a message error if(ex) QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex->what()),QObject::tr("Ok")); else if(dest == this) { try { QElapsedTimer timer; // PREVIEW+STREAMING mode only: copy loaded data if(cVolume->getStreamingSteps() != 0) { // update IO time PLog::instance()->appendOperation(new NewViewerOperation(op_dsc.toStdString(), tf::IO, elapsed_time)); // copy loaded data into Vaa3D viewer timer.start(); uint32 img_dims[5] = {volH1-volH0, volV1-volV0, volD1-volD0, nchannels, volT1-volT0+1}; uint32 img_offset[5] = {data_s[0]-volH0, data_s[1]-volV0, data_s[2]-volD0, 0, data_s[4]-volT0 }; uint32 new_img_dims[5] = {data_c[0], data_c[1], data_c[2], data_c[3], data_c[4] }; uint32 new_img_offset[5] = {0, 0, 0, 0, 0 }; uint32 new_img_count[5] = {data_c[0], data_c[1], data_c[2], data_c[3], data_c[4] }; CImageUtils::copyVOI(data, new_img_dims, new_img_offset, new_img_count, view3DWidget->getiDrawExternalParameter()->image4d->getRawData(), img_dims, img_offset); qint64 elapsedTime = timer.elapsed(); // release memory delete[] data; // update log sprintf(message, "Streaming %d/%d: Copied block X=[%d, %d) Y=[%d, %d) Z=[%d, %d) T=[%d, %d] to resolution %d", step, cVolume->getStreamingSteps(), cVolume->getVoiH0(), cVolume->getVoiH1(), cVolume->getVoiV0(), cVolume->getVoiV1(), cVolume->getVoiD0(), cVolume->getVoiD1(), cVolume->getVoiT0(), cVolume->getVoiT1(), cVolume->getVoiResIndex()); PLog::instance()->appendOperation(new NewViewerOperation(message, tf::CPU, elapsedTime)); } // if 5D data, update selected time frame if(CImport::instance()->is5D()) view3DWidget->setVolumeTimePoint(window3D->timeSlider->value()-volT0); PMain::getInstance()->frameCoord->setText(strprintf("t = %d/%d", window3D->timeSlider->value()+1, CImport::instance()->getTDim()).c_str()); // PREVIEW+STREAMING mode only: update image data if(cVolume->getStreamingSteps() != 0) { /**/tf::debug(tf::LEV1, strprintf("title = %s: update image data", titleShort.c_str()).c_str(), __itm__current__function__); timer.restart(); view3DWidget->updateImageData(); sprintf(message, "Streaming %d/%d: Block X=[%d, %d) Y=[%d, %d) Z=[%d, %d) T=[%d, %d] rendered into view %s", step, cVolume->getStreamingSteps(), cVolume->getVoiH0(), cVolume->getVoiH1(), cVolume->getVoiV0(), cVolume->getVoiV1(), cVolume->getVoiD0(), cVolume->getVoiD1(), cVolume->getVoiT0(), cVolume->getVoiT1(), title.c_str()); PLog::instance()->appendOperation(new NewViewerOperation(message, tf::GPU, timer.elapsed())); } // operations to be performed when all image data have been loaded if(finished) { // disconnect from data producer disconnect(CVolume::instance(), SIGNAL(sendData(tf::uint8*,tf::integer_array,tf::integer_array,QWidget*,bool,tf::RuntimeException*,qint64,QString,int)), this, SLOT(receiveData(tf::uint8*,tf::integer_array,tf::integer_array,QWidget*,bool,tf::RuntimeException*,qint64,QString,int))); // reset TeraFly's GUI PMain::getInstance()->resetGUI(); // exit from "waiting for 5D data" state, if previously set if(this->waitingForData) this->setWaitingForData(false); // reset the cursor window3D->setCursor(Qt::ArrowCursor); view3DWidget->setCursor(Qt::ArrowCursor); //---- Alessandro 2013-09-28 fixed: processing pending events related trasl* buttons (previously deactivated) prevents the user from // triggering multiple traslations at the same time. //---- Alessandro 2014-01-26 fixed: processEvents() is no longer needed, since the trasl* button slots have been made safer and do not // trigger any action when the the current window is not active (or has to be closed) //QApplication::processEvents(); /**/tf::debug(tf::LEV3, strprintf("title = %s: reactivating directional shifts", titleShort.c_str()).c_str(), __itm__current__function__); PMain::getInstance()->traslXneg->setActive(true); PMain::getInstance()->traslXpos->setActive(true); PMain::getInstance()->traslYneg->setActive(true); PMain::getInstance()->traslYpos->setActive(true); PMain::getInstance()->traslZneg->setActive(true); PMain::getInstance()->traslZpos->setActive(true); PMain::getInstance()->traslTneg->setActive(true); PMain::getInstance()->traslTpos->setActive(true); /**/tf::debug(tf::LEV3, strprintf("title = %s: directional shifts successfully reactivated", titleShort.c_str()).c_str(), __itm__current__function__); //current window is now ready for user input isReady = true; //saving elapsed time to log if(prev) { /**/tf::debug(tf::LEV3, strprintf("title = %s: saving elapsed time to log", titleShort.c_str()).c_str(), __itm__current__function__); PLog::instance()->appendOperation(new NewViewerOperation(tf::strprintf("Successfully generated view %s", title.c_str()), tf::ALL_COMPS, prev->newViewerTimer.elapsed())); } // refresh annotation toolbar PAnoToolBar::instance()->refreshTools(); } } catch(RuntimeException &ex) { QMessageBox::critical(PMain::getInstance(),QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok")); PMain::getInstance()->resetGUI(); isReady = true; } } // QMessageBox::information(0, "Stop", "Wait..."); /**/tf::debug(tf::LEV3, "method terminated", __itm__current__function__); } /********************************************************************************** * Generates a new view using the given coordinates. * Called by the current <CViewer> when the user zooms in and the higher res- * lution has to be loaded. ***********************************************************************************/ void CViewer::newViewer(int x, int y, int z, //can be either the VOI's center (default) or the VOI's ending point (see x0,y0,z0) int resolution, //resolution index of the view requested int t0, int t1, //time frames selection int dx/*=-1*/, int dy/*=-1*/, int dz/*=-1*/, //VOI [x-dx,x+dx), [y-dy,y+dy), [z-dz,z+dz), [t0, t1] int x0/*=-1*/, int y0/*=-1*/, int z0/*=-1*/, //VOI [x0, x), [y0, y), [z0, z), [t0, t1] bool auto_crop /* = true */, //whether to crop the VOI to the max dims bool scale_coords /* = true */, //whether to scale VOI coords to the target res int sliding_viewer_block_ID /* = -1 */) //block ID in "Sliding viewer" mode { /**/tf::debug(tf::LEV1, strprintf("title = %s, x = %d, y = %d, z = %d, res = %d, dx = %d, dy = %d, dz = %d, x0 = %d, y0 = %d, z0 = %d, t0 = %d, t1 = %d, auto_crop = %s, scale_coords = %s, sliding_viewer_block_ID = %d", titleShort.c_str(), x, y, z, resolution, dx, dy, dz, x0, y0, z0, t0, t1, auto_crop ? "true" : "false", scale_coords ? "true" : "false", sliding_viewer_block_ID).c_str(), __itm__current__function__); // check precondition #1: active window if(!isActive || toBeClosed) { QMessageBox::warning(0, "Unexpected behaviour", "Precondition check \"!isActive || toBeClosed\" failed. Please contact the developers"); return; } // check precondition #2: valid resolution if(resolution >= CImport::instance()->getResolutions()) resolution = volResIndex; // check precondition #3: window ready for "newView" events if( !isReady ) { tf::warning("precondition (!isReady) not met. Aborting newView", __itm__current__function__); return; } // deactivate current window and processing all pending events setActive(false); QApplication::processEvents(); // after processEvents(), it might be that this windows is no longer valid, then terminating if(toBeClosed) return; // restart timer (measures the time needed to switch to a new view) newViewerTimer.restart(); // create new macro-group for NewViewerOperation tf::NewViewerOperation::newGroup(); try { // set GUI to waiting state QElapsedTimer timer; timer.start(); PMain& pMain = *(PMain::getInstance()); pMain.progressBar->setEnabled(true); pMain.progressBar->setMinimum(0); pMain.progressBar->setMaximum(0); pMain.statusBar->showMessage("Switching view..."); view3DWidget->setCursor(Qt::BusyCursor); window3D->setCursor(Qt::BusyCursor); pMain.setCursor(Qt::BusyCursor); // scale VOI coordinates to the reference system of the target resolution if(scale_coords) { float ratioX = static_cast<float>(CImport::instance()->getVolume(resolution)->getDIM_H())/CImport::instance()->getVolume(volResIndex)->getDIM_H(); float ratioY = static_cast<float>(CImport::instance()->getVolume(resolution)->getDIM_V())/CImport::instance()->getVolume(volResIndex)->getDIM_V(); float ratioZ = static_cast<float>(CImport::instance()->getVolume(resolution)->getDIM_D())/CImport::instance()->getVolume(volResIndex)->getDIM_D(); x = coord2global<int>(x, iim::horizontal, true, resolution, false, false, __itm__current__function__); y = coord2global<int>(y, iim::vertical, true, resolution, false, false, __itm__current__function__); z = coord2global<int>(z, iim::depth, true, resolution, false, false, __itm__current__function__); if(x0 != -1) x0 = coord2global<int>(x0, iim::horizontal, true, resolution, false, false, __itm__current__function__); else dx = dx == -1 ? std::numeric_limits<int>::max() : static_cast<int>(dx*ratioX+0.5f); if(y0 != -1) y0 = coord2global<int>(y0, iim::vertical, true, resolution, false, false, __itm__current__function__); else dy = dy == -1 ? std::numeric_limits<int>::max() : static_cast<int>(dy*ratioY+0.5f); if(z0 != -1) z0 = coord2global<int>(z0, iim::depth, true, resolution, false, false, __itm__current__function__); else dz = dz == -1 ? std::numeric_limits<int>::max() : static_cast<int>(dz*ratioZ+0.5f); } // adjust time size so as to use all the available frames set by the user if(CImport::instance()->is5D() && ((t1 - t0 +1) != pMain.Tdim_sbox->value())) { t1 = t0 + (pMain.Tdim_sbox->value()-1); /**/tf::debug(tf::LEV1, strprintf("mismatch between |[t0,t1]| (%d) and max T dims (%d), adjusting it to [%d,%d]", t1-t0+1, pMain.Tdim_sbox->value(), t0, t1).c_str(), __itm__current__function__); } // crop VOI if its larger than the maximum allowed if(auto_crop) { // modality #1: VOI = [x-dx,x+dx), [y-dy,y+dy), [z-dz,z+dz), [t0, t1] if(dx != -1 && dy != -1 && dz != -1) { /**/tf::debug(tf::LEV3, strprintf("title = %s, cropping bbox dims from (%d,%d,%d) t[%d,%d] to...", titleShort.c_str(), dx, dy, dz, t0, t1).c_str(), __itm__current__function__); dx = std::min(dx, round(pMain.Hdim_sbox->value()/2.0f)); dy = std::min(dy, round(pMain.Vdim_sbox->value()/2.0f)); dz = std::min(dz, round(pMain.Ddim_sbox->value()/2.0f)); t0 = std::max(0, std::min(t0,CImport::instance()->getVolume(volResIndex)->getDIM_T()-1)); t1 = std::max(0, std::min(t1,CImport::instance()->getVolume(volResIndex)->getDIM_T()-1)); if(CImport::instance()->is5D() && (t1-t0+1 > pMain.Tdim_sbox->value())) t1 = t0 + pMain.Tdim_sbox->value(); if(CImport::instance()->is5D() && (t1 >= CImport::instance()->getTDim()-1)) t0 = t1 - (pMain.Tdim_sbox->value()-1); if(CImport::instance()->is5D() && (t0 == 0)) t1 = pMain.Tdim_sbox->value()-1; /**/tf::debug(tf::LEV3, strprintf("title = %s, ...to (%d,%d,%d)", titleShort.c_str(), dx, dy, dz).c_str(), __itm__current__function__); } // modality #2: VOI = [x0, x), [y0, y), [z0, z), [t0, t1] else { /**/tf::debug(tf::LEV3, strprintf("title = %s, cropping bbox dims from [%d,%d) [%d,%d) [%d,%d) [%d,%d] to...", titleShort.c_str(), x0, x, y0, y, z0, z, t0, t1).c_str(), __itm__current__function__); if(x - x0 > pMain.Hdim_sbox->value()) { float margin = ( (x - x0) - pMain.Hdim_sbox->value() )/2.0f ; x = round(x - margin); x0 = round(x0 + margin); } if(y - y0 > pMain.Vdim_sbox->value()) { float margin = ( (y - y0) - pMain.Vdim_sbox->value() )/2.0f ; y = round(y - margin); y0 = round(y0 + margin); } if(z - z0 > pMain.Ddim_sbox->value()) { float margin = ( (z - z0) - pMain.Ddim_sbox->value() )/2.0f ; z = round(z - margin); z0 = round(z0 + margin); } t0 = std::max(0, std::min(t0,CImport::instance()->getVolume(volResIndex)->getDIM_T()-1)); t1 = std::max(0, std::min(t1,CImport::instance()->getVolume(volResIndex)->getDIM_T()-1)); if(CImport::instance()->is5D() && (t1-t0+1 > pMain.Tdim_sbox->value())) t1 = t0 + pMain.Tdim_sbox->value(); if(CImport::instance()->is5D() && (t1 >= CImport::instance()->getTDim()-1)) t0 = t1 - (pMain.Tdim_sbox->value()-1); if(CImport::instance()->is5D() && (t0 == 0)) t1 = pMain.Tdim_sbox->value()-1; /**/tf::debug(tf::LEV3, strprintf("title = %s, ...to [%d,%d) [%d,%d) [%d,%d) [%d,%d]", titleShort.c_str(), x0, x, y0, y, z0, z, t0, t1).c_str(), __itm__current__function__); } } // ask CVolume to check (and correct) for a valid VOI CVolume* cVolume = CVolume::instance(); try { if(dx != -1 && dy != -1 && dz != -1) cVolume->setVoi(0, resolution, y-dy, y+dy, x-dx, x+dx, z-dz, z+dz, t0, t1); else cVolume->setVoi(0, resolution, y0, y, x0, x, z0, z, t0, t1); } catch(RuntimeException &ex) { /**/tf::warning(strprintf("Exception thrown when setting VOI: \"%s\". Aborting newView", ex.what()).c_str(), __itm__current__function__); setActive(true); view3DWidget->setCursor(Qt::ArrowCursor); window3D->setCursor(Qt::ArrowCursor); PMain::getInstance()->resetGUI(); return; } // save the state of PMain GUI VOI's widgets saveSubvolSpinboxState(); // disconnect current window from GUI's listeners and event filters disconnect(view3DWidget, SIGNAL(changeXCut0(int)), this, SLOT(Vaa3D_changeXCut0(int))); disconnect(view3DWidget, SIGNAL(changeXCut1(int)), this, SLOT(Vaa3D_changeXCut1(int))); disconnect(view3DWidget, SIGNAL(changeYCut0(int)), this, SLOT(Vaa3D_changeYCut0(int))); disconnect(view3DWidget, SIGNAL(changeYCut1(int)), this, SLOT(Vaa3D_changeYCut1(int))); disconnect(view3DWidget, SIGNAL(changeZCut0(int)), this, SLOT(Vaa3D_changeZCut0(int))); disconnect(view3DWidget, SIGNAL(changeZCut1(int)), this, SLOT(Vaa3D_changeZCut1(int))); disconnect(window3D->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(Vaa3D_changeTSlider(int))); //disconnect(view3DWidget, SIGNAL(xRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //disconnect(view3DWidget, SIGNAL(yRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //disconnect(view3DWidget, SIGNAL(zRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); disconnect(PMain::getInstance()->refSys, SIGNAL(mouseReleased()), this, SLOT(PMain_rotationchanged())); disconnect(PMain::getInstance()->V0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV0sbox(int))); disconnect(PMain::getInstance()->V1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV1sbox(int))); disconnect(PMain::getInstance()->H0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH0sbox(int))); disconnect(PMain::getInstance()->H1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH1sbox(int))); disconnect(PMain::getInstance()->D0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD0sbox(int))); disconnect(PMain::getInstance()->D1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD1sbox(int))); view3DWidget->removeEventFilter(this); window3D->removeEventFilter(this); window3D->timeSlider->removeEventFilter(this); // PREVIEW+STREAMING mode - obtain low res data from current window to be displayed in a new window while the user waits for the new high res data if(CSettings::instance()->getPreviewMode()) { // get low res data timer.restart(); int voiH0m=0, voiH1m=0, voiV0m=0, voiV1m=0,voiD0m=0, voiD1m=0, voiT0m=0, voiT1m=0; int rVoiH0 = CVolume::scaleCoord<int>(cVolume->getVoiH0(), resolution, volResIndex, iim::horizontal, true); int rVoiH1 = CVolume::scaleCoord<int>(cVolume->getVoiH1(), resolution, volResIndex, iim::horizontal, true); int rVoiV0 = CVolume::scaleCoord<int>(cVolume->getVoiV0(), resolution, volResIndex, iim::vertical, true); int rVoiV1 = CVolume::scaleCoord<int>(cVolume->getVoiV1(), resolution, volResIndex, iim::vertical, true); int rVoiD0 = CVolume::scaleCoord<int>(cVolume->getVoiD0(), resolution, volResIndex, iim::depth, true); int rVoiD1 = CVolume::scaleCoord<int>(cVolume->getVoiD1(), resolution, volResIndex, iim::depth, true); uint8* lowresData = getVOI(rVoiH0, rVoiH1, rVoiV0, rVoiV1, rVoiD0, rVoiD1, cVolume->getVoiT0(), cVolume->getVoiT1(), cVolume->getVoiH1()-cVolume->getVoiH0(), cVolume->getVoiV1()-cVolume->getVoiV0(), cVolume->getVoiD1()-cVolume->getVoiD0(), voiH0m, voiH1m, voiV0m, voiV1m,voiD0m, voiD1m, voiT0m, voiT1m); std::string message = tf::strprintf("Block X=[%d, %d) Y=[%d, %d) Z=[%d, %d) T[%d, %d] loaded from view %s, black-filled region is " "X=[%d, %d) Y=[%d, %d) Z=[%d, %d) T[%d, %d]", rVoiH0, rVoiH1, rVoiV0, rVoiV1, rVoiD0, rVoiD1, cVolume->getVoiT0(), cVolume->getVoiT1(), title.c_str(), voiH0m, voiH1m, voiV0m, voiV1m,voiD0m, voiD1m, voiT0m, voiT1m); PLog::instance()->appendOperation(new NewViewerOperation(message, tf::CPU, timer.elapsed())); // create new window this->next = new CViewer(V3D_env, resolution, lowresData, cVolume->getVoiV0(), cVolume->getVoiV1(), cVolume->getVoiH0(), cVolume->getVoiH1(), cVolume->getVoiD0(), cVolume->getVoiD1(), cVolume->getVoiT0(), cVolume->getVoiT1(), nchannels, this, sliding_viewer_block_ID); // update CVolume with the request of the actual missing VOI along t and the current selected frame cVolume->setVoiT(voiT0m, voiT1m, window3D->timeSlider->value()); // set the number of streaming steps cVolume->setStreamingSteps(PMain::getInstance()->debugStreamingStepsSBox->value()); // connect new window to data producer cVolume->setSource(next); connect(CVolume::instance(), SIGNAL(sendData(tf::uint8*,tf::integer_array,tf::integer_array,QWidget*,bool,tf::RuntimeException*,qint64,QString,int)), next, SLOT(receiveData(tf::uint8*,tf::integer_array,tf::integer_array,QWidget*,bool,tf::RuntimeException*,qint64,QString,int)), Qt::QueuedConnection); // lock updateGraphicsInProgress mutex on this thread (i.e. the GUI thread or main queue event thread) /**/tf::debug(tf::LEV3, strprintf("Waiting for updateGraphicsInProgress mutex").c_str(), __itm__current__function__); /**/ updateGraphicsInProgress.lock(); /**/tf::debug(tf::LEV3, strprintf("Access granted from updateGraphicsInProgress mutex").c_str(), __itm__current__function__); // update status bar message pMain.statusBar->showMessage("Loading image data..."); // load new data in a separate thread. When done, the "receiveData" method of the new window will be called cVolume->start(); // meanwhile, show the new window with preview data next->show(); // enter "waiting for 5D data" state, if possible next->setWaitingForData(true); //if the resolution of the loaded voi is the same of the current one, this window will be closed if(resolution == volResIndex) this->close(); // unlock updateGraphicsInProgress mutex /**/tf::debug(tf::LEV3, strprintf("updateGraphicsInProgress.unlock()").c_str(), __itm__current__function__); /**/ updateGraphicsInProgress.unlock(); } // DIRECT mode - just wait for image data to be loaded and THEN create the new window else { // set the number of streaming steps to 0 cVolume->setStreamingSteps(0); // load data and instance new viewer this->next = new CViewer(V3D_env, resolution, CVolume::instance()->loadData(), cVolume->getVoiV0(), cVolume->getVoiV1(), cVolume->getVoiH0(), cVolume->getVoiH1(), cVolume->getVoiD0(), cVolume->getVoiD1(), cVolume->getVoiT0(), cVolume->getVoiT1(), nchannels, this, sliding_viewer_block_ID); // show new viewer next->show(); // update new viewer as all data have been received next->receiveData(0,tf::integer_array(),tf::integer_array(), next, true); // if new viewer has the same resolution, this window has to be closed if(resolution == volResIndex) this->close(); } } catch(RuntimeException &ex) { QMessageBox::critical(this,QObject::tr("Error"), QObject::tr(ex.what()),QObject::tr("Ok")); PMain::getInstance()->resetGUI(); } } //safely close this viewer void CViewer::close() { /**/tf::debug(tf::LEV2, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); if(prev) { prev->newViewerTimer = newViewerTimer; prev->next = next; next->prev = prev; } else { next->prev = 0; CViewer::first = next; } this->toBeClosed = true; delete this; } /********************************************************************************** * Resizes the given image subvolume in a newly allocated array using the fastest * achievable scaling method. The image currently shown is used as data source. ***********************************************************************************/ tf::uint8* CViewer::getVOI(int x0, int x1, // VOI [x0, x1) in the local reference sys int y0, int y1, // VOI [y0, y1) in the local reference sys int z0, int z1, // VOI [z0, z1) in the local reference sys int t0, int t1, // VOI [t0, t1] in the local reference sys int xDimInterp, // interpolated VOI dimension along X int yDimInterp, // interpolated VOI dimension along Y int zDimInterp, // interpolated VOI dimension along Z int& x0m, int& x1m, // black-filled VOI [x0m, x1m) in the local rfsys int& y0m, int& y1m, // black-filled VOI [y0m, y1m) in the local rfsys int& z0m, int& z1m, // black-filled VOI [z0m, z1m) in the local rfsys int& t0m, int& t1m) // black-filled VOI [t0m, t1m] in the local rfsys throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, x0 = %d, x1 = %d, y0 = %d, y1 = %d, z0 = %d, z1 = %d, t0 = %d, t1 = %d, xDim = %d, yDim = %d, zDim = %d", titleShort.c_str(), x0, x1, y0, y1, z0, z1, t0, t1, xDimInterp, yDimInterp, zDimInterp).c_str(), __itm__current__function__); // allocate image data and initializing to zero (black) /**/tf::debug(tf::LEV3, "Allocate image data", __itm__current__function__); tf::sint64 img_dim = static_cast<size_t>(xDimInterp) * yDimInterp * zDimInterp * nchannels * (t1-t0+1); uint8* img = new uint8[img_dim]; for(uint8* img_p = img; img_p-img < img_dim; img_p++) *img_p=0; // compute actual VOI that can be copied, i.e. that intersects with the image currently displayed /**/tf::debug(tf::LEV3, "Compute intersection VOI", __itm__current__function__); QRect XRectDisplayed(QPoint(volH0, 0), QPoint(volH1, 1)); QRect YRectDisplayed(QPoint(volV0, 0), QPoint(volV1, 1)); QRect ZRectDisplayed(QPoint(volD0, 0), QPoint(volD1, 1)); QRect TRectDisplayed(QPoint(volT0, 0), QPoint(volT1, 1)); QRect XRectVOI(QPoint(x0, 0), QPoint(x1, 1)); QRect YRectVOI(QPoint(y0, 0), QPoint(y1, 1)); QRect ZRectVOI(QPoint(z0, 0), QPoint(z1, 1)); QRect TRectVOI(QPoint(t0, 0), QPoint(t1, 1)); QRect XRectIntersect = XRectDisplayed.intersected(XRectVOI); QRect YRectIntersect = YRectDisplayed.intersected(YRectVOI); QRect ZRectIntersect = ZRectDisplayed.intersected(ZRectVOI); QRect TRectIntersect = TRectDisplayed.intersected(TRectVOI); int x0a = XRectIntersect.left(); int x1a = XRectIntersect.right(); int y0a = YRectIntersect.left(); int y1a = YRectIntersect.right(); int z0a = ZRectIntersect.left(); int z1a = ZRectIntersect.right(); int t0a = TRectIntersect.left(); int t1a = TRectIntersect.right(); /**/tf::debug(tf::LEV3, strprintf("title = %s, available voi is [%d, %d) [%d, %d) [%d, %d) [%d, %d]", titleShort.c_str(), x0a, x1a, y0a, y1a, z0a, z1a, t0a, t1a).c_str(), __itm__current__function__); // compute missing VOI. If copyable VOI is empty, returning the black-initialized image if(x1a - x0a <= 0 || y1a - y0a <= 0 || z1a - z0a <= 0 || t1a - t0a < 0) { x0m = x0; x1m = x1; y0m = y0; y1m = y1; z0m = z0; z1m = z1; t0m = t0; t1m = t1; return img; } else { x0m = x0; // not yet supported (@TODO) x1m = x1; // not yet supported (@TODO) y0m = y0; // not yet supported (@TODO) y1m = y1; // not yet supported (@TODO) z0m = z0; // not yet supported (@TODO) z1m = z1; // not yet supported (@TODO) // if all data is available along XYZ, trying to speed up loading along T by requesting only the missing frames if( x0 == x0a && x1 == x1a && y0 == y0a && y1 == y1a && z0 == z0a && z1 == z1a) { // check for intersection contained in the VOI (if it does, optimized VOI loading is disabled) if(t0 == t0a && t1 == t1a) // missing piece is along X,Y,Z { t0m = t0; t1m = t1; } else if(volT1 == t1a) { t0m = t1a+1; t1m = t1; tf::debug(LEV3, strprintf("missing piece along T is [%d,%d]", t0m, t1m).c_str(), __itm__current__function__); } else if(volT0 == t0a) { t0m = t0; t1m = t0a-1; tf::debug(LEV3, strprintf("missing piece along T is [%d,%d]", t0m, t1m).c_str(), __itm__current__function__); } else { t0m = t1a; t1m = t1; tf::warning(strprintf("internal intersection detected, [%d,%d] is within [%d,%d], disabling optimized VOI loading", t0a, t1a, volT0, volT1).c_str(), __itm__current__function__); } } else { t0m = t0; t1m = t1; } } //fast scaling by pixel replication // - NOTE: interpolated image is allowed to be slightly larger (or even smaller) than the source image resulting after scaling. if( ( (xDimInterp % (x1-x0) <= 1) || (xDimInterp % (x1-x0+1) <= 1) || (xDimInterp % (x1-x0-1) <= 1)) && ( (yDimInterp % (y1-y0) <= 1) || (yDimInterp % (y1-y0+1) <= 1) || (yDimInterp % (y1-y0-1) <= 1)) && ( (zDimInterp % (z1-z0) <= 1) || (zDimInterp % (z1-z0+1) <= 1) || (zDimInterp % (z1-z0-1) <= 1))) { //checking for uniform scaling along the three axes uint scalx = static_cast<uint>(static_cast<float>(xDimInterp) / (x1-x0) +0.5f); uint scaly = static_cast<uint>(static_cast<float>(yDimInterp) / (y1-y0) +0.5f); uint scalz = static_cast<uint>(static_cast<float>(zDimInterp) / (z1-z0) +0.5f); if(scalx != scaly || scaly != scalz || scalx != scalz) { uint scaling = std::min(std::min(scalx, scaly), scalz); tf::warning(strprintf("Fast nonuniform scaling not supported: requested scaling along X,Y,Z is {%d, %d, %d}, but will perform %d", scalx, scaly, scalz, scaling).c_str()); scalx = scaly = scalz = scaling; } uint32 buf_data_dims[5] = {volH1-volH0, volV1-volV0, volD1-volD0, nchannels, volT1-volT0+1}; uint32 img_dims[5] = {xDimInterp, yDimInterp, zDimInterp, nchannels, t1-t0+1}; uint32 buf_data_offset[5] = {x0a-volH0, y0a-volV0, z0a-volD0, 0, t0a-volT0}; uint32 img_offset[5] = {x0a-x0, y0a-y0, z0a-z0, 0, t0a-t0}; uint32 buf_data_count[5] = {x1a-x0a, y1a-y0a, z1a-z0a, 0, t1a-t0a+1}; CImageUtils::copyVOI(view3DWidget->getiDrawExternalParameter()->image4d->getRawData(), buf_data_dims, buf_data_offset, buf_data_count, img, img_dims, img_offset, scalx); } //interpolation else tf::warning("Interpolation of the pre-buffered image not yet implemented"); return img; } /********************************************************************************** * Returns the maximum intensity projection of the given VOI in a newly allocated * array. Data is taken from the currently displayed image. ***********************************************************************************/ tf::uint8* CViewer::getMIP(int x0, int x1, // VOI [x0, x1) in the local reference sys int y0, int y1, // VOI [y0, y1) in the local reference sys int z0, int z1, // VOI [z0, z1) in the local reference sys int t0 /* = -1 */, int t1 /* = -1 */, // VOI [t0, t1] in the local reference sys tf::direction dir /* = z */, bool to_BGRA /* = false */, //true if mip data must be stored into BGRA format tf::uint8 alpha /* = 255 */) //alpha transparency used if to_BGRA is true throw (tf::RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, x0 = %d, x1 = %d, y0 = %d, y1 = %d, z0 = %d, z1 = %d, t0 = %d, t1 = %d, dir = %d, to_BGRA = %s, alpha = %d", titleShort.c_str(), x0, x1, y0, y1, z0, z1, t0, t1, dir, to_BGRA ? "true" : "false", alpha).c_str(), __itm__current__function__); if(t0 == -1) t0 = volT0; if(t1 == -1) t1 = volT1; uint32 img_dims[5] = {volH1-volH0, volV1-volV0, volD1-volD0, nchannels, volT1-volT0+1}; uint32 img_offset[5] = {x0 -volH0, y0 -volV0, z0 -volD0, 0, t0-volT0}; uint32 img_count[5] = {x1 -x0, y1 -y0, z1 -z0, 0, t1-t0+1}; return CImageUtils::mip(view3DWidget->getiDrawExternalParameter()->image4d->getRawData(), img_dims, img_offset, img_count, dir, to_BGRA, alpha); } /********************************************************************************** * Makes the current view the last one by deleting (and deallocting) its subsequent * views. ***********************************************************************************/ void CViewer::makeLastView() throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); if(CViewer::current != this) throw RuntimeException(QString("in CViewer::makeLastView(): this view is not the current one, thus can't be made the last view").toStdString().c_str()); while(CViewer::last != this) { CViewer::last = CViewer::last->prev; CViewer::last->next->toBeClosed = true; delete CViewer::last->next; CViewer::last->next = 0; } } /********************************************************************************** * Saves/restore the state of PMain spinboxes for subvolume selection ***********************************************************************************/ void CViewer::saveSubvolSpinboxState() { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); PMain& pMain = *(PMain::getInstance()); V0_sbox_min = pMain.V0_sbox->minimum(); V1_sbox_max = pMain.V1_sbox->maximum(); H0_sbox_min = pMain.H0_sbox->minimum(); H1_sbox_max = pMain.H1_sbox->maximum(); D0_sbox_min = pMain.D0_sbox->minimum(); D1_sbox_max = pMain.D1_sbox->maximum(); // T0_sbox_min = pMain.T0_sbox->minimum(); // T1_sbox_max = pMain.T1_sbox->maximum(); V0_sbox_val = pMain.V0_sbox->value(); V1_sbox_val = pMain.V1_sbox->value(); H0_sbox_val = pMain.H0_sbox->value(); H1_sbox_val = pMain.H1_sbox->value(); D0_sbox_val = pMain.D0_sbox->value(); D1_sbox_val = pMain.D1_sbox->value(); if(pMain.frameCoord->isEnabled()) { T0_sbox_val = pMain.T0_sbox->text().toInt()-1; T1_sbox_val = pMain.T1_sbox->text().toInt()-1; } } void CViewer::restoreSubvolSpinboxState() { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); PMain& pMain = *(PMain::getInstance()); pMain.V0_sbox->setMinimum(V0_sbox_min); pMain.V1_sbox->setMaximum(V1_sbox_max); pMain.H0_sbox->setMinimum(H0_sbox_min); pMain.H1_sbox->setMaximum(H1_sbox_max); pMain.D0_sbox->setMinimum(D0_sbox_min); pMain.D1_sbox->setMaximum(D1_sbox_max); // pMain.T0_sbox->setMinimum(T0_sbox_min); // pMain.T1_sbox->setMaximum(T1_sbox_max); pMain.V0_sbox->setValue(V0_sbox_val); pMain.V1_sbox->setValue(V1_sbox_val); pMain.H0_sbox->setValue(H0_sbox_val); pMain.H1_sbox->setValue(H1_sbox_val); pMain.D0_sbox->setValue(D0_sbox_val); pMain.D1_sbox->setValue(D1_sbox_val); if(pMain.frameCoord->isEnabled()) { pMain.T0_sbox->setText(QString::number(T0_sbox_val+1)); pMain.T1_sbox->setText(QString::number(T1_sbox_val+1)); } } /********************************************************************************** * Annotations are stored/loaded to/from the <CAnnotations> object ***********************************************************************************/ void CViewer::storeAnnotations() throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); QElapsedTimer timer; // 2014-11-17. Alessandro. @FIXED "duplicated annotations" bug // use the same annotation VOI that was set for ::loadAnnotations at current explorer creation /**/tf::debug(tf::LEV3, strprintf("use annotation VOI X[%d,%d), Y[%d,%d), Z[%d,%d)", anoH0, anoH1, anoV0, anoV1, anoD0, anoD1).c_str(), __itm__current__function__); interval_t x_range(anoH0, anoH1); interval_t y_range(anoV0, anoV1); interval_t z_range(anoD0, anoD1); // begin new macro group of AnnotationOperation //if(triViewWidget->getImageData()->listLandmarks.empty() == false || V3D_env->getSWC(this->window).listNeuron.empty() == false) tf::AnnotationOperation::newGroup(); /********************************************************************************** * MARKERS ***********************************************************************************/ //storing edited markers QList<LocationSimple> markers = triViewWidget->getImageData()->listLandmarks; if(!markers.empty()) { // 2015-04-15. Alessandro. @FIXED: excluding hidden markers is no more needed (and no more correct) since the // load/store annotation VOIs are now the same (see fix of 2014-11-17). // @fixed by Alessandro on 2014-07-21: excluding hidden markers from store operation timer.start(); // QList<LocationSimple>::iterator it = markers.begin(); // while (it != markers.end()) // { // if (is_outside((*it).x, (*it).y, (*it).z)) // { // #ifdef terafly_enable_debug_annotations // tf::debug(tf::LEV3, strprintf("(%.0f, %.0f, %.0f) excluded from store operation because it is a hidden marker", it->x, it->y, it->z).c_str(), 0, true); // #endif // it = markers.erase(it); // } // else // ++it; // } // PLog::instance()->appendOperation(new AnnotationOperation(QString("store annotations: exclude hidden landmarks, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); //converting local coordinates into global coordinates timer.restart(); for(int i=0; i<markers.size(); i++) { markers[i].x = coord2global<float>(markers[i].x, iim::horizontal, false, -1, false, false, __itm__current__function__); markers[i].y = coord2global<float>(markers[i].y, iim::vertical, false, -1, false, false, __itm__current__function__); markers[i].z = coord2global<float>(markers[i].z, iim::depth, false, -1, false, false, __itm__current__function__); } PLog::instance()->appendOperation(new AnnotationOperation(QString("store annotations: convert landmark coordinates, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); //storing markers timer.restart(); CAnnotations::getInstance()->addLandmarks(x_range, y_range, z_range, markers); PLog::instance()->appendOperation(new AnnotationOperation(QString("store annotations: store landmarks in the octree, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); } /********************************************************************************** * CURVES ***********************************************************************************/ // @FIXED missing hidden neuron segments by Alessandro on 2016-05-31. std::vector<bool> activeNeuronSegments; if(view3DWidget->getiDrawExternalParameter() && view3DWidget->getiDrawExternalParameter()->image4d) { My4DImage* curImg = view3DWidget->getiDrawExternalParameter()->image4d; for (int i=0; i<curImg->tracedNeuron.seg.size(); i++) { activeNeuronSegments.push_back(curImg->tracedNeuron.seg[i].on); curImg->tracedNeuron.seg[i].on = true; } curImg->update_3drenderer_neuron_view(view3DWidget, static_cast<Renderer_gl1*>(view3DWidget->getRenderer())); } else tf::warning("Cannot store hidden neuron segments: cannot retrieve image4D from current 3D widget"); //storing edited curves NeuronTree nt = this->V3D_env->getSWC(this->window); if(!nt.listNeuron.empty()) { //converting local coordinates into global coordinates timer.restart(); for(int i=0; i<nt.listNeuron.size(); i++) { /* @debug */ //printf("%d(%d) [(%.0f,%.0f,%.0f) ->", nt.listNeuron[i].n, nt.listNeuron[i].pn, nt.listNeuron[i].x, nt.listNeuron[i].y, nt.listNeuron[i].z); nt.listNeuron[i].x = coord2global<float>(nt.listNeuron[i].x, iim::horizontal, false, -1, false, false, __itm__current__function__); nt.listNeuron[i].y = coord2global<float>(nt.listNeuron[i].y, iim::vertical, false, -1, false, false, __itm__current__function__); nt.listNeuron[i].z = coord2global<float>(nt.listNeuron[i].z, iim::depth, false, -1, false, false, __itm__current__function__); /* @debug */ //printf("(%.0f,%.0f,%.0f)] ", nt.listNeuron[i].x, nt.listNeuron[i].y, nt.listNeuron[i].z); } PLog::instance()->appendOperation(new AnnotationOperation(QString("store annotations: convert curve nodes coordinates, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); /* @debug */ //printf("\n"); //storing curves timer.restart(); CAnnotations::getInstance()->addCurves(x_range, y_range, z_range, nt); PLog::instance()->appendOperation(new AnnotationOperation(QString("store annotations: store curves in the octree, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); } // @FIXED missing hidden neuron segments by Alessandro on 2016-05-31. if(view3DWidget->getiDrawExternalParameter() && view3DWidget->getiDrawExternalParameter()->image4d) { My4DImage* curImg = view3DWidget->getiDrawExternalParameter()->image4d; for (int i=0; i<curImg->tracedNeuron.seg.size(); i++) curImg->tracedNeuron.seg[i].on = activeNeuronSegments[i]; curImg->update_3drenderer_neuron_view(view3DWidget, static_cast<Renderer_gl1*>(view3DWidget->getRenderer())); } } void CViewer::clearAnnotations() throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); //clearing previous annotations (useful when this view has been already visited) V3D_env->getHandleNeuronTrees_Any3DViewer(window3D)->clear(); QList<LocationSimple> vaa3dMarkers; V3D_env->setLandmark(window, vaa3dMarkers); // V3D_env->setSWC(window, vaa3dCurves); V3D_env->pushObjectIn3DWindow(window); view3DWidget->enableMarkerLabel(false); view3DWidget->getRenderer()->endSelectMode(); } void CViewer::deleteSelectedMarkers() throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); if(PAnoToolBar::instance()->buttonMarkerRoiDelete->isChecked()) { // associate selected image markers to vaa3d markers and delete QList<LocationSimple> vaa3dMarkers = V3D_env->getLandmark(window); QList<LocationSimple> deletedMarkers; QList<ImageMarker> &listMarker = static_cast<Renderer_gl1*>(view3DWidget->getRenderer())->listMarker; for (QList<ImageMarker>::iterator it = listMarker.begin(); it!= listMarker.end(); it++) { if (it->selected && !CAnnotations::isMarkerOutOfRendererBounds(*it, *this)) { for(QList<LocationSimple>::iterator jt = vaa3dMarkers.begin(); jt != vaa3dMarkers.end();) { if(jt->x == it->x && jt->y == it->y && jt->z == it->z) { deletedMarkers.push_back(*jt); jt = vaa3dMarkers.erase(jt); break; } else ++jt; } it->selected = false; } } // set new markers V3D_env->setLandmark(window, vaa3dMarkers); V3D_env->pushObjectIn3DWindow(window); // update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); // add Undo action undoStack.beginMacro("delete markers"); undoStack.push(new QUndoMarkerDeleteROI(this, deletedMarkers)); undoStack.endMacro(); PAnoToolBar::instance()->buttonUndo->setEnabled(true); // need to refresh annotation tools as this Vaa3D's action resets the Vaa3D annotation mode PAnoToolBar::instance()->refreshTools(); } } void CViewer::createMarkerAt(int x, int y) throw (tf::RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, point = (%x, %y)", titleShort.c_str(), x, y).c_str(), __itm__current__function__); view3DWidget->getRenderer()->hitPen(x, y); QList<LocationSimple> vaa3dMarkers = V3D_env->getLandmark(window); undoStack.beginMacro("create marker"); undoStack.push(new QUndoMarkerCreate(this, vaa3dMarkers.back())); undoStack.endMacro(); PAnoToolBar::instance()->buttonUndo->setEnabled(true); // all markers have the same color when they are created vaa3dMarkers.back().color = CImageUtils::vaa3D_color(0,0,255); V3D_env->setLandmark(window, vaa3dMarkers); V3D_env->pushObjectIn3DWindow(window); //update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); } void CViewer::createMarker2At(int x, int y) throw (tf::RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, point = (%x, %y)", titleShort.c_str(), x, y).c_str(), __itm__current__function__); view3DWidget->getRenderer()->hitPen(x, y); static bool every_two_clicks_flag = true; every_two_clicks_flag = !every_two_clicks_flag; if(every_two_clicks_flag) { QList<LocationSimple> vaa3dMarkers = V3D_env->getLandmark(window); undoStack.beginMacro("create marker"); undoStack.push(new QUndoMarkerCreate(this, vaa3dMarkers.back())); undoStack.endMacro(); PAnoToolBar::instance()->buttonUndo->setEnabled(true); // all markers have the same color when they are created vaa3dMarkers.back().color = CImageUtils::vaa3D_color(0,0,255); V3D_env->setLandmark(window, vaa3dMarkers); V3D_env->pushObjectIn3DWindow(window); //update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); // start another operation PAnoToolBar::instance()->buttonMarkerCreate2Checked(true); } } void CViewer::deleteMarkerAt(int x, int y, QList<LocationSimple>* deletedMarkers /* = 0 */) throw (tf::RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, point = (%x, %y)", titleShort.c_str(), x, y).c_str(), __itm__current__function__); // select marker (if any) at the clicked location view3DWidget->getRenderer()->selectObj(x,y, false); // search for the selected markers vector<int> vaa3dMarkers_tbd; QList<LocationSimple> vaa3dMarkers = V3D_env->getLandmark(window); QList <ImageMarker> imageMarkers = static_cast<Renderer_gl1*>(view3DWidget->getRenderer())->listMarker; for(int i=0; i<imageMarkers.size(); i++) { if(imageMarkers[i].selected) { for(int j=0; j<vaa3dMarkers.size(); j++) if(vaa3dMarkers[j].x == imageMarkers[i].x && vaa3dMarkers[j].y == imageMarkers[i].y && vaa3dMarkers[j].z == imageMarkers[i].z && !CAnnotations::isMarkerOutOfRendererBounds(vaa3dMarkers[j], *this)) vaa3dMarkers_tbd.push_back(j); } } // remove selected markers for(int i=0; i<vaa3dMarkers_tbd.size(); i++) { if(deletedMarkers) deletedMarkers->push_back(vaa3dMarkers[vaa3dMarkers_tbd[i]]); else { undoStack.beginMacro("delete marker"); undoStack.push(new QUndoMarkerDelete(this, vaa3dMarkers[vaa3dMarkers_tbd[i]])); undoStack.endMacro(); PAnoToolBar::instance()->buttonUndo->setEnabled(true); } vaa3dMarkers.removeAt(vaa3dMarkers_tbd[i]); } // set new markers V3D_env->setLandmark(window, vaa3dMarkers); V3D_env->pushObjectIn3DWindow(window); // end select mode view3DWidget->getRenderer()->endSelectMode(); //update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); } void CViewer::updateAnnotationSpace() throw (tf::RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); //computing the current volume range in the highest resolution image space /**/tf::debug(tf::LEV3, strprintf("computing the current volume range in the highest resolution image space").c_str(), __itm__current__function__); int highestResIndex = CImport::instance()->getResolutions()-1; int voiV0 = CVolume::scaleCoord<int>(volV0, volResIndex, highestResIndex, iim::vertical, true); int voiV1 = CVolume::scaleCoord<int>(volV1, volResIndex, highestResIndex, iim::vertical, true); int voiH0 = CVolume::scaleCoord<int>(volH0, volResIndex, highestResIndex, iim::horizontal, true); int voiH1 = CVolume::scaleCoord<int>(volH1, volResIndex, highestResIndex, iim::horizontal, true); int voiD0 = CVolume::scaleCoord<int>(volD0, volResIndex, highestResIndex, iim::depth, true); int voiD1 = CVolume::scaleCoord<int>(volD1, volResIndex, highestResIndex, iim::depth, true); interval_t x_range(voiH0, voiH1); interval_t y_range(voiV0, voiV1); interval_t z_range(voiD0, voiD1); // set volume range to infinite if unlimited space annotation option is active if(PMain::getInstance()->spaceSizeUnlimited->isChecked() && this == CViewer::first) { // unlimited annotation VOI is used only in the first view (whole image) so as to include out-of-bounds annotation objects x_range.start = y_range.start = z_range.start = 0; x_range.end = y_range.end = z_range.end = std::numeric_limits<int>::max(); } else if(this != CViewer::first) { // for subsequent views (i.e., higher resolutions at certain VOIs), the actual annotation VOI is enlarged by 100% // to enable the "Show/hide markers around the displayed ROI" function in the annotation toolbar int vmPerc = 100; int vmX = (x_range.end - x_range.start)*(vmPerc/100.0f)/2; int vmY = (y_range.end - y_range.start)*(vmPerc/100.0f)/2; int vmZ = (z_range.end - z_range.start)*(vmPerc/100.0f)/2; x_range.start = std::max(0, x_range.start - vmX); x_range.end += vmX; y_range.start = std::max(0, y_range.start - vmY); y_range.end += vmY; z_range.start = std::max(0, z_range.start - vmZ); z_range.end += vmZ; } // @FIXED "duplicated annotations" bug by Alessandro on 2014-17-11. Annotation VOI +100% enlargment is the source of "duplicated annotations" bug because // this creates an asymmetry between loading annotations in the displayed VOI (which is done with +100% enlargment) and saving annotations // from the displayed VOI (which is done w/o +100% enlargment !!!) // Then, we save the actual annotation VOI in object members and use those at saving time. anoV0 = y_range.start; anoV1 = y_range.end; anoH0 = x_range.start; anoH1 = x_range.end; anoD0 = z_range.start; anoD1 = z_range.end; /**/tf::debug(tf::LEV3, strprintf("store annotation VOI X[%d,%d), Y[%d,%d), Z[%d,%d)", anoH0, anoH1, anoV0, anoV1, anoD0, anoD1).c_str(), __itm__current__function__); } void CViewer::loadAnnotations() throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); // where to put vaa3d annotations QList<LocationSimple> vaa3dMarkers; NeuronTree vaa3dCurves; // to measure elapsed time QElapsedTimer timer; // clearing previous annotations (useful when this view has been already visited) /**/tf::debug(tf::LEV3, strprintf("clearing previous annotations").c_str(), __itm__current__function__); V3D_env->getHandleNeuronTrees_Any3DViewer(window3D)->clear(); //obtaining the annotations within the current window updateAnnotationSpace(); interval_t x_range(anoH0, anoH1); interval_t y_range(anoV0, anoV1); interval_t z_range(anoD0, anoD1); /**/tf::debug(tf::LEV3, strprintf("obtaining the annotations within the current window").c_str(), __itm__current__function__); CAnnotations::getInstance()->findLandmarks(x_range, y_range, z_range, vaa3dMarkers); CAnnotations::getInstance()->findCurves(x_range, y_range, z_range, vaa3dCurves.listNeuron); //converting global coordinates to local coordinates timer.restart(); /**/tf::debug(tf::LEV3, strprintf("converting global coordinates to local coordinates").c_str(), __itm__current__function__); for(int i=0; i<vaa3dMarkers.size(); i++) { vaa3dMarkers[i].x = coord2local<float>(vaa3dMarkers[i].x, iim::horizontal, false); vaa3dMarkers[i].y = coord2local<float>(vaa3dMarkers[i].y, iim::vertical, false); vaa3dMarkers[i].z = coord2local<float>(vaa3dMarkers[i].z, iim::depth, false); } /* @debug */ //printf("\n\ngoing to insert in Vaa3D the curve points "); for(int i=0; i<vaa3dCurves.listNeuron.size(); i++) { /* @debug */ //printf("%d(%d) [(%.0f,%.0f,%.0f) ->", vaa3dCurves.listNeuron[i].n, vaa3dCurves.listNeuron[i].pn, vaa3dCurves.listNeuron[i].x, vaa3dCurves.listNeuron[i].y, vaa3dCurves.listNeuron[i].z); vaa3dCurves.listNeuron[i].x = coord2local<float>(vaa3dCurves.listNeuron[i].x, iim::horizontal, false); vaa3dCurves.listNeuron[i].y = coord2local<float>(vaa3dCurves.listNeuron[i].y, iim::vertical, false); vaa3dCurves.listNeuron[i].z = coord2local<float>(vaa3dCurves.listNeuron[i].z, iim::depth, false); /* @debug */ //printf("(%.0f,%.0f,%.0f)] ", vaa3dCurves.listNeuron[i].x, vaa3dCurves.listNeuron[i].y, vaa3dCurves.listNeuron[i].z); } vaa3dCurves.color.r = 0; vaa3dCurves.color.g = 0; vaa3dCurves.color.b = 0; vaa3dCurves.color.a = 0; PLog::instance()->appendOperation(new AnnotationOperation(QString("load annotations: convert coordinates, view ").append(title.c_str()).toStdString(), tf::CPU, timer.elapsed())); /* @debug */ //printf("\n\n"); //assigning annotations /**/tf::debug(tf::LEV3, strprintf("assigning annotations").c_str(), __itm__current__function__); timer.restart(); V3D_env->setLandmark(window, vaa3dMarkers); V3D_env->setSWC(window, vaa3dCurves); V3D_env->pushObjectIn3DWindow(window); view3DWidget->enableMarkerLabel(false); view3DWidget->getRenderer()->endSelectMode(); //end curve editing mode QList<NeuronTree>* listNeuronTree = static_cast<Renderer_gl1*>(view3DWidget->getRenderer())->getHandleNeuronTrees(); for (int i=0; i<listNeuronTree->size(); i++) (*listNeuronTree)[i].editable = false; //090928 view3DWidget->updateTool(); view3DWidget->update(); //update visible markers PAnoToolBar::instance()->buttonMarkerRoiViewChecked(PAnoToolBar::instance()->buttonMarkerRoiView->isChecked()); PLog::instance()->appendOperation(new AnnotationOperation(QString("load annotations: push objects into view ").append(title.c_str()).toStdString(), tf::GPU, timer.elapsed())); } /********************************************************************************** * Restores the current view from the given (neighboring) view. * Called by the next(prev) <CViewer> when the user zooms out(in) and the * lower(higher) resoolution has to be reestabilished. ***********************************************************************************/ void CViewer::restoreViewerFrom(CViewer* source) throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, source->title = %s", titleShort.c_str(), source->titleShort.c_str()).c_str(), __itm__current__function__); // begin new group for RestoreViewerOperation tf::RestoreViewerOperation::newGroup(); QElapsedTimer timer; timer.start(); if(source) { //signal disconnections source->disconnect(source->view3DWidget, SIGNAL(changeXCut0(int)), source, SLOT(Vaa3D_changeXCut0(int))); source->disconnect(source->view3DWidget, SIGNAL(changeXCut1(int)), source, SLOT(Vaa3D_changeXCut1(int))); source->disconnect(source->view3DWidget, SIGNAL(changeYCut0(int)), source, SLOT(Vaa3D_changeYCut0(int))); source->disconnect(source->view3DWidget, SIGNAL(changeYCut1(int)), source, SLOT(Vaa3D_changeYCut1(int))); source->disconnect(source->view3DWidget, SIGNAL(changeZCut0(int)), source, SLOT(Vaa3D_changeZCut0(int))); source->disconnect(source->view3DWidget, SIGNAL(changeZCut1(int)), source, SLOT(Vaa3D_changeZCut1(int))); source->connect(source->window3D->timeSlider, SIGNAL(valueChanged(int)), source, SLOT(Vaa3D_changeTSlider(int))); //source->disconnect(source->view3DWidget, SIGNAL(xRotationChanged(int)), source, SLOT(Vaa3D_rotationchanged(int))); //source->disconnect(source->view3DWidget, SIGNAL(yRotationChanged(int)), source, SLOT(Vaa3D_rotationchanged(int))); //source->disconnect(source->view3DWidget, SIGNAL(zRotationChanged(int)), source, SLOT(Vaa3D_rotationchanged(int))); source->disconnect(PMain::getInstance()->refSys, SIGNAL(mouseReleased()), source, SLOT(PMain_rotationchanged())); source->disconnect(PMain::getInstance()->V0_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeV0sbox(int))); source->disconnect(PMain::getInstance()->V1_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeV1sbox(int))); source->disconnect(PMain::getInstance()->H0_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeH0sbox(int))); source->disconnect(PMain::getInstance()->H1_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeH1sbox(int))); source->disconnect(PMain::getInstance()->D0_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeD0sbox(int))); source->disconnect(PMain::getInstance()->D1_sbox, SIGNAL(valueChanged(int)), source, SLOT(PMain_changeD1sbox(int))); source->view3DWidget->removeEventFilter(source); source->window3D->removeEventFilter(source); window3D->timeSlider->removeEventFilter(source); //saving source spinbox state source->saveSubvolSpinboxState(); //activating current view setActive(true); //registrating views: ---- Alessandro 2013-04-18 fixed: determining unique triple of rotation angles and assigning absolute rotation source->view3DWidget->absoluteRotPose(); view3DWidget->doAbsoluteRot(source->view3DWidget->xRot(), source->view3DWidget->yRot(), source->view3DWidget->zRot()); //setting zoom only if user has zoomed in if(source->volResIndex < volResIndex) { float ratio = CImport::instance()->getVolume(volResIndex)->getDIM_D()/CImport::instance()->getVolume(source->volResIndex)->getDIM_D(); view3DWidget->setZoom(source->view3DWidget->zoom()/ratio); } if(source->volResIndex > volResIndex) { // float ratio = CImport::instance()->getVolume(volResIndex)->getDIM_D()/CImport::instance()->getVolume(source->volResIndex)->getDIM_D(); if(this != first) view3DWidget->setZoom(16); else view3DWidget->setZoom(30); } //showing current view (with triViewWidget minimized) triViewWidget->setWindowState(Qt::WindowMinimized); //positioning the current 3D window exactly at the <source> window position QPoint location = source->window3D->pos(); resize(source->window3D->size()); move(location); //hiding <source> source->window3D->setVisible(false); //source->triViewWidget->setVisible(false); //---- Alessandro 2013-09-04 fixed: this causes Vaa3D's setCurHiddenSelectedWindow() to fail source->view3DWidget->setCursor(Qt::ArrowCursor); //applying the same color map only if it differs from the source one Renderer_gl2* source_renderer = (Renderer_gl2*)(source->view3DWidget->getRenderer()); Renderer_gl2* curr_renderer = (Renderer_gl2*)(view3DWidget->getRenderer()); bool changed_cmap = false; for(int k=0; k<3; k++) { RGBA8* source_cmap = source_renderer->colormap[k]; RGBA8* curr_cmap = curr_renderer->colormap[k]; for(int i=0; i<256; i++) { if(curr_cmap[i].i != source_cmap[i].i) changed_cmap = true; curr_cmap[i] = source_cmap[i]; } } if(changed_cmap) curr_renderer->applyColormapToImage(); //storing annotations done in the source view source->storeAnnotations(); source->clearAnnotations(); //registrating the current window as the current window of the multiresolution explorer windows chain CViewer::current = this; //selecting the current resolution in the PMain GUI and disabling previous resolutions PMain* pMain = PMain::getInstance(); pMain->resolution_cbox->setCurrentIndex(volResIndex); for(int i=0; i<pMain->resolution_cbox->count(); i++) { // Get the index of the value to disable QModelIndex index = pMain->resolution_cbox->model()->index(i,0); // These are the effective 'disable/enable' flags QVariant v1(Qt::NoItemFlags); QVariant v2(Qt::ItemIsSelectable | Qt::ItemIsEnabled); //the magic if(i<volResIndex) pMain->resolution_cbox->model()->setData( index, v1, Qt::UserRole -1); else pMain->resolution_cbox->model()->setData( index, v2, Qt::UserRole -1); } pMain->gradientBar->setStep(volResIndex); pMain->gradientBar->update(); //restoring min, max and value of PMain GUI VOI's widgets restoreSubvolSpinboxState(); //disabling translate buttons if needed pMain->traslYneg->setEnabled(volV0 > 0); pMain->traslYpos->setEnabled(volV1 < CImport::instance()->getVolume(volResIndex)->getDIM_V()); pMain->traslXneg->setEnabled(volH0 > 0); pMain->traslXpos->setEnabled(volH1 < CImport::instance()->getVolume(volResIndex)->getDIM_H()); pMain->traslZneg->setEnabled(volD0 > 0); pMain->traslZpos->setEnabled(volD1 < CImport::instance()->getVolume(volResIndex)->getDIM_D()); pMain->traslTneg->setEnabled(volT0 > 0); pMain->traslTpos->setEnabled(volT1 < CImport::instance()->getVolume(volResIndex)->getDIM_T()-1); //signal connections connect(view3DWidget, SIGNAL(changeXCut0(int)), this, SLOT(Vaa3D_changeXCut0(int))); connect(view3DWidget, SIGNAL(changeXCut1(int)), this, SLOT(Vaa3D_changeXCut1(int))); connect(view3DWidget, SIGNAL(changeYCut0(int)), this, SLOT(Vaa3D_changeYCut0(int))); connect(view3DWidget, SIGNAL(changeYCut1(int)), this, SLOT(Vaa3D_changeYCut1(int))); connect(view3DWidget, SIGNAL(changeZCut0(int)), this, SLOT(Vaa3D_changeZCut0(int))); connect(view3DWidget, SIGNAL(changeZCut1(int)), this, SLOT(Vaa3D_changeZCut1(int))); connect(window3D->timeSlider, SIGNAL(valueChanged(int)), this, SLOT(Vaa3D_changeTSlider(int))); //connect(view3DWidget, SIGNAL(xRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //connect(view3DWidget, SIGNAL(yRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //connect(view3DWidget, SIGNAL(zRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); connect(PMain::getInstance()->refSys, SIGNAL(mouseReleased()), this, SLOT(PMain_rotationchanged())); connect(PMain::getInstance()->V0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV0sbox(int))); connect(PMain::getInstance()->V1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV1sbox(int))); connect(PMain::getInstance()->H0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH0sbox(int))); connect(PMain::getInstance()->H1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH1sbox(int))); connect(PMain::getInstance()->D0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD0sbox(int))); connect(PMain::getInstance()->D1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD1sbox(int))); view3DWidget->installEventFilter(this); window3D->installEventFilter(this); window3D->timeSlider->installEventFilter(this); //loading annotations of the current view this->loadAnnotations(); // 5D data: select the same time frame (if available) if(CImport::instance()->is5D()) { int source_s = source->window3D->timeSlider->value(); if(source_s < volT0 || source_s > volT1) window3D->timeSlider->setValue(volT0); else window3D->timeSlider->setValue(source_s); view3DWidget->setVolumeTimePoint(window3D->timeSlider->value()-volT0); } //sync widgets syncWindows(source->window3D, window3D); // remove TeraFly's toolbar from source viewer and add to this viewer source->window3D->centralLayout->takeAt(0); PAnoToolBar::instance()->setParent(0); window3D->centralLayout->insertWidget(0, PAnoToolBar::instance()); // also reset undo/redo (which are referred to the source viewer) PAnoToolBar::instance()->buttonUndo->setEnabled(false); PAnoToolBar::instance()->buttonRedo->setEnabled(false); source->undoStack.clear(); this->undoStack.clear(); // @ADDED Vaa3D-controls-within-TeraFly feature. int tab_selected = PMain::getInstance()->tabs->currentIndex(); PMain::getInstance()->tabs->removeTab(1); QWidget* vaa3d_controls = new QWidget(); QVBoxLayout* vaa3d_controls_layout = new QVBoxLayout(); vaa3d_controls_layout->addWidget(window3D->tabOptions); vaa3d_controls_layout->addWidget(window3D->toolBtnGroup); vaa3d_controls_layout->addWidget(window3D->tabCutPlane); vaa3d_controls_layout->addWidget(window3D->tabRotZoom); vaa3d_controls->setLayout(vaa3d_controls_layout); PMain::getInstance()->tabs->insertTab(1, vaa3d_controls, "Vaa3D controls"); PMain::getInstance()->tabs->setCurrentIndex(tab_selected); //showing window this->window3D->raise(); this->window3D->activateWindow(); this->window3D->show(); // update reference system dimension if(!PMain::getInstance()->isPRactive()) PMain::getInstance()->refSys->setDims(volH1-volH0+1, volV1-volV0+1, volD1-volD0+1); // refresh annotation toolbar PAnoToolBar::instance()->refreshTools(); //current windows now gets ready to user input isReady = true; } PLog::instance()->appendOperation(new RestoreViewerOperation(strprintf("Restored viewer %d from viewer %d", ID, source->ID), tf::ALL_COMPS, timer.elapsed())); } /********************************************************************************** * Returns the most likely 3D point in the image that the user is pointing on the * renderer at the given location. * This is based on the Vaa3D 3D point selection with one mouse click. ***********************************************************************************/ XYZ CViewer::getRenderer3DPoint(int x, int y) throw (RuntimeException) { /**/tf::debug(tf::LEV1, strprintf("title = %s, x = %d, y = %d", titleShort.c_str(), x, y).c_str(), __itm__current__function__); //view3DWidget->getRenderer()->selectObj(x,y, false); return myRenderer_gl1::cast(static_cast<Renderer_gl1*>(view3DWidget->getRenderer()))->get3DPoint(x, y); // Renderer_gl1* rend = static_cast<Renderer_gl1*>(view3DWidget->getRenderer()); // XYZ p = rend->selectPosition(x, y); // printf("\n\npoint = (%.0f, %.0f, %.0f)\n\n", p.x, p.y, p.z); // return p; } /********************************************************************************** * method (indirectly) invoked by Vaa3D to propagate VOI's coordinates ***********************************************************************************/ void CViewer::invokedFromVaa3D(v3d_imaging_paras* params /* = 0 */) { if(!isActive || toBeClosed) return; if(params) /**/tf::debug(tf::LEV1, strprintf("title = %s, params = [%d-%d] x [%d-%d] x [%d-%d]", titleShort.c_str(), params->xs, params->xe, params->ys, params->ye, params->zs, params->ze).c_str(), __itm__current__function__); else /**/tf::debug(tf::LEV1, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); //--- Alessandro 04/09/2013: added precondition checks to solve a bug which causes invokedFromVaa3D to be called without the customStructPointer available // in Vaa3D. This happens because Vaa3D someway bypasses TeraFly for handling the zoomin-in with mouse scroll or because TeraFly // does not correctly disconnects Vaa3D from the setZoom slots as a new view is created. v3d_imaging_paras* roi = 0; if(params) roi = params; else if(view3DWidget->getiDrawExternalParameter() && view3DWidget->getiDrawExternalParameter()->image4d && view3DWidget->getiDrawExternalParameter()->image4d->getCustomStructPointer() ) roi = static_cast<v3d_imaging_paras*>(view3DWidget->getiDrawExternalParameter()->image4d->getCustomStructPointer()); if(!roi) { /**/tf::warning(strprintf("title = %s, Unable to get customStructPointer from Vaa3D V3dR_GLWidget. Aborting invokedFromVaa3D()", titleShort.c_str()).c_str(), __itm__current__function__); return; } if(params == 0) /**/tf::debug(tf::LEV3, strprintf("title = %s, Vaa3D ROI is [%d-%d] x [%d-%d] x [%d-%d]", titleShort.c_str(), roi->xs, roi->xe, roi->ys, roi->ye, roi->zs, roi->ze).c_str(), __itm__current__function__); //--- Alessandro 23/04/2014: after several bug fixes, it seems this bug does not occur anymore //--- Alessandro 24/08/2013: to prevent the plugin to crash at the deepest resolution when the plugin is invoked by Vaa3D // if(volResIndex == CImport::instance()->getResolutions()-1) // { // QMessageBox::warning(this, "Warning", "Vaa3D-invoked actions at the highest resolution have been temporarily removed. " // "Please use different operations such as \"Double-click zoom-in\" or \"Traslate\"."); // return; // } //retrieving ROI infos propagated by Vaa3D int roiCenterX = roi->xe-(roi->xe-roi->xs)/2; int roiCenterY = roi->ye-(roi->ye-roi->ys)/2; int roiCenterZ = roi->ze-(roi->ze-roi->zs)/2; // otherwise before continue, check "Proofreading" mode is not active if(PMain::getInstance()->isPRactive()) { QMessageBox::information(this->window3D, "Warning", "TeraFly is running in \"Proofreading\" mode. All TeraFly's' navigation features are disabled. " "Please terminate the \"Proofreading\" mode and try again."); return; } // zoom-in around marker or ROI triggers a new window else if(roi->ops_type == 1 && !forceZoomIn) newViewer(roi->xe, roi->ye, roi->ze, volResIndex+1, volT0, volT1, -1, -1, -1, roi->xs, roi->ys, roi->zs); // zoom-in with mouse scroll up may trigger a new window if caching is not possible else if(roi->ops_type == 2 || forceZoomIn) { // reset forceZoomIn if(forceZoomIn) forceZoomIn = false; if(volResIndex != CImport::instance()->getResolutions()-1 && // do nothing if highest resolution has been reached ( isZoomDerivativePos() || has_double_clicked)) // accept zoom-in only when zoom factor derivative is positive or user has double clicked { // reset double click status has_double_clicked = false; //trying caching if next view exists if(next) { //converting Vaa3D VOI local coordinates to TeraFly coordinates of the next resolution float gXS = coord2global<float>(static_cast<float>(roi->xs), iim::horizontal, false, next->volResIndex, false, true, __itm__current__function__); float gXE = coord2global<float>(static_cast<float>(roi->xe), iim::horizontal, false, next->volResIndex, false, true, __itm__current__function__); float gYS = coord2global<float>(static_cast<float>(roi->ys), iim::vertical, false, next->volResIndex, false, true, __itm__current__function__); float gYE = coord2global<float>(static_cast<float>(roi->ye), iim::vertical, false, next->volResIndex, false, true, __itm__current__function__); float gZS = coord2global<float>(static_cast<float>(roi->zs), iim::depth, false, next->volResIndex, false, true, __itm__current__function__); float gZE = coord2global<float>(static_cast<float>(roi->ze), iim::depth, false, next->volResIndex, false, true, __itm__current__function__); QRectF gXRect(QPointF(gXS, 0), QPointF(gXE, 1)); QRectF gYRect(QPointF(gYS, 0), QPointF(gYE, 1)); QRectF gZRect(QPointF(gZS, 0), QPointF(gZE, 1)); //obtaining the actual requested VOI under the existing constraints (i.e., maximum view dimensions) /**/tf::debug(tf::LEV3, strprintf("title = %s, requested voi is [%.0f, %.0f] x [%.0f, %.0f] x [%.0f, %.0f]...BUT", titleShort.c_str(), gXS, gXE, gYS, gYE, gZS, gZE).c_str(), __itm__current__function__); if(gXE-gXS > PMain::getInstance()->Hdim_sbox->value()) { float center = gXS+(gXE-gXS)/2; gXS = center - PMain::getInstance()->Hdim_sbox->value()/2; gXE = center + PMain::getInstance()->Hdim_sbox->value()/2; } if(gYE-gYS > PMain::getInstance()->Vdim_sbox->value()) { float center = gYS+(gYE-gYS)/2; gYS = center - PMain::getInstance()->Vdim_sbox->value()/2; gYE = center + PMain::getInstance()->Vdim_sbox->value()/2; } if(gZE-gZS > PMain::getInstance()->Ddim_sbox->value()) { float center = gZS+(gZE-gZS)/2; gZS = center - PMain::getInstance()->Ddim_sbox->value()/2; gZE = center + PMain::getInstance()->Ddim_sbox->value()/2; } /**/tf::debug(tf::LEV3, strprintf("title = %s, ...BUT actual requested VOI became [%.0f, %.0f] x [%.0f, %.0f] x [%.0f, %.0f]", titleShort.c_str(), gXS, gXE, gYS, gYE, gZS, gZE).c_str(), __itm__current__function__); //obtaining coordinates of the cached resolution float gXScached = static_cast<float>(next->volH0); float gXEcached = static_cast<float>(next->volH1); float gYScached = static_cast<float>(next->volV0); float gYEcached = static_cast<float>(next->volV1); float gZScached = static_cast<float>(next->volD0); float gZEcached = static_cast<float>(next->volD1); QRectF gXRectCached(QPoint(gXScached, 0), QPoint(gXEcached, 1)); QRectF gYRectCached(QPoint(gYScached, 0), QPoint(gYEcached, 1)); QRectF gZRectCached(QPoint(gZScached, 0), QPoint(gZEcached, 1)); //computing intersection volume and Vaa3D VOI coverage factor float intersectionX = gXRect.intersected(gXRectCached).width(); float intersectionY = gYRect.intersected(gYRectCached).width(); float intersectionZ = gZRect.intersected(gZRectCached).width(); float intersectionVol = intersectionX*intersectionY*intersectionZ; float voiVol = (gXE-gXS)*(gYE-gYS)*(gZE-gZS); float cachedVol = (gXEcached-gXScached)*(gYEcached-gYScached)*(gZEcached-gZScached); float coverageFactor = voiVol != 0 ? intersectionVol/voiVol : 0; /**/tf::debug(tf::LEV3, strprintf("title = %s, actual requested voi is [%.0f, %.0f] x [%.0f, %.0f] x [%.0f, %.0f] and cached is [%.0f, %.0f] x [%.0f, %.0f] x [%.0f, %.0f]", titleShort.c_str(), gXS, gXE, gYS, gYE, gZS, gZE, gXScached, gXEcached, gYScached, gYEcached, gZScached, gZEcached).c_str(), __itm__current__function__); /**/tf::debug(tf::LEV3, strprintf("title = %s,intersection is %.0f x %.0f x %.0f with coverage factor = %.2f ", titleShort.c_str(), intersectionX, intersectionY, intersectionZ, coverageFactor).c_str(), __itm__current__function__); //if Vaa3D VOI is covered for the selected percentage by the existing cached volume, just restoring its view if((coverageFactor >= PMain::getInstance()->cacheSens->value()/100.0f) && isReady) { setActive(false); resetZoomHistory(); next->restoreViewerFrom(this); } //otherwise invoking a new view else newViewer(roiCenterX, roiCenterY, roiCenterZ, volResIndex+1, volT0, volT1, static_cast<int>((roi->xe-roi->xs)/2.0f+0.5f), static_cast<int>((roi->ye-roi->ys)/2.0f+0.5f), static_cast<int>((roi->ze-roi->zs)/2.0f+0.5f)); } else newViewer(roiCenterX, roiCenterY, roiCenterZ, volResIndex+1, volT0, volT1, static_cast<int>((roi->xe-roi->xs)/2.0f+0.5f), static_cast<int>((roi->ye-roi->ys)/2.0f+0.5f), static_cast<int>((roi->ze-roi->zs)/2.0f+0.5f)); } else /**/tf::debug(tf::LEV3, strprintf("title = %s, ignoring Vaa3D mouse scroll up zoom-in", titleShort.c_str()).c_str(), __itm__current__function__); } else QMessageBox::critical(this,QObject::tr("Error"), QObject::tr("in CViewer::Vaa3D_selectedROI(): unsupported (or unset) operation type"),QObject::tr("Ok")); } /********************************************************************************** * Linked to volume cut scrollbars of Vaa3D widget containing the 3D renderer. * This implements the syncronization Vaa3D-->TeraManager of subvolume selection. ***********************************************************************************/ void CViewer::Vaa3D_changeYCut0(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->V0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV0sbox(int))); PMain::getInstance()->V0_sbox->setValue(coord2global<int>(s, iim::vertical, true, -1, true, false, __itm__current__function__)+1); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->V0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV0sbox(int))); } void CViewer::Vaa3D_changeYCut1(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->V1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV1sbox(int))); PMain::getInstance()->V1_sbox->setValue(coord2global<int>(s+1, iim::vertical, true, -1, true, false, __itm__current__function__)); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->V1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeV1sbox(int))); } void CViewer::Vaa3D_changeXCut0(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->H0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH0sbox(int))); PMain::getInstance()->H0_sbox->setValue(coord2global<int>(s, iim::horizontal, true, -1, true, false, __itm__current__function__)+1); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->H0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH0sbox(int))); } void CViewer::Vaa3D_changeXCut1(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->H1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH1sbox(int))); PMain::getInstance()->H1_sbox->setValue(coord2global<int>(s+1, iim::horizontal, true, -1, true, false, __itm__current__function__)); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->H1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeH1sbox(int))); } void CViewer::Vaa3D_changeZCut0(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->D0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD0sbox(int))); PMain::getInstance()->D0_sbox->setValue(coord2global<int>(s, iim::depth, true, -1, true, false, __itm__current__function__)+1); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->D0_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD0sbox(int))); } void CViewer::Vaa3D_changeZCut1(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(PMain::getInstance()->D1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD1sbox(int))); PMain::getInstance()->D1_sbox->setValue(coord2global<int>(s+1, iim::depth, true, -1, true, false, __itm__current__function__)); PDialogProofreading::instance()->updateBlocks(0); connect(PMain::getInstance()->D1_sbox, SIGNAL(valueChanged(int)), this, SLOT(PMain_changeD1sbox(int))); } void CViewer::Vaa3D_changeTSlider(int s, bool editingFinished /* = false */) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV3, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif if(isActive && // window is visible isReady && // window is ready for user input !toBeClosed && // window is not going to be destroyed view3DWidget && // Vaa3D renderer has been instantiated CImport::instance()->is5D()) // data is 5D type { // change current frame coordinate PMain::getInstance()->frameCoord->setText(strprintf("t = %d/%d", s+1, CImport::instance()->getTDim()).c_str()); // if frame is out of the displayed range if(s < volT0 || s > volT1) { // PREVIEW+STREAMING mode only if(CSettings::instance()->getPreviewMode()) { // enter "waiting for 5D data" state setWaitingForData(true, true); // display message informing the user that something will happen if he/she confirms the operation PMain::getInstance()->statusBar->showMessage(strprintf("Ready to jump at time frame %d/%d", s, CImport::instance()->getTDim()-1).c_str()); } // if user operation is confirmed, then switching view if(editingFinished) newViewer( (volH1-volH0)/2, (volV1-volV0)/2, (volD1-volD0)/2, volResIndex, s-PMain::getInstance()->Tdim_sbox->value()/2, s+PMain::getInstance()->Tdim_sbox->value()/2); } // if frame is within the displayed range else { // exit from "waiting for 5D data" state (if previously set) setWaitingForData(false, true); // display default message PMain::getInstance()->statusBar->showMessage("Ready."); // display selected frame view3DWidget->setVolumeTimePoint(s-volT0); } } } /********************************************************************************** * Linked to PMain GUI VOI's widgets. * This implements the syncronization TeraManager-->Vaa3D of subvolume selection. ***********************************************************************************/ void CViewer::PMain_changeV0sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeYCut0(int)), this, SLOT(Vaa3D_changeYCut0(int))); view3DWidget->setYCut0(coord2local<int>(s, iim::vertical, true, true)); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeYCut0(int)), this, SLOT(Vaa3D_changeYCut0(int))); } void CViewer::PMain_changeV1sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeYCut1(int)), this, SLOT(Vaa3D_changeYCut1(int))); view3DWidget->setYCut1(coord2local<int>(s+1, iim::vertical, true, true)-1); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeYCut1(int)), this, SLOT(Vaa3D_changeYCut1(int))); } void CViewer::PMain_changeH0sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeXCut0(int)), this, SLOT(Vaa3D_changeXCut0(int))); view3DWidget->setXCut0(coord2local<int>(s, iim::horizontal, true, true)); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeXCut0(int)), this, SLOT(Vaa3D_changeXCut0(int))); } void CViewer::PMain_changeH1sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeXCut1(int)), this, SLOT(Vaa3D_changeXCut1(int))); view3DWidget->setXCut1(coord2local<int>(s+1, iim::horizontal, true, true)-1); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeXCut1(int)), this, SLOT(Vaa3D_changeXCut1(int))); } void CViewer::PMain_changeD0sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeZCut0(int)), this, SLOT(Vaa3D_changeZCut0(int))); view3DWidget->setZCut0(coord2local<int>(s, iim::depth, true, true)); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeZCut0(int)), this, SLOT(Vaa3D_changeZCut0(int))); } void CViewer::PMain_changeD1sbox(int s) { #ifdef terafly_enable_debug_max_level /**/tf::debug(tf::LEV_MAX, strprintf("title = %s, s = %d", title.c_str(), s).c_str(), __itm__current__function__); #endif disconnect(view3DWidget, SIGNAL(changeZCut1(int)), this, SLOT(Vaa3D_changeZCut1(int))); view3DWidget->setZCut1(coord2local<int>(s+1, iim::depth, true, true)-1); PDialogProofreading::instance()->updateBlocks(0); connect(view3DWidget, SIGNAL(changeZCut1(int)), this, SLOT(Vaa3D_changeZCut1(int))); } /********************************************************************************** * Alignes the given widget to the right of the current window ***********************************************************************************/ void CViewer::alignToRight(QWidget* widget, QEvent *evt) { /**/tf::debug(tf::LEV3, strprintf("title = %s", titleShort.c_str()).c_str(), __itm__current__function__); if(evt->type() == QEvent::Resize) { QResizeEvent* revt = static_cast<QResizeEvent*>(evt); CSettings::instance()->setViewerHeight(revt->size().height()); CSettings::instance()->setViewerWidth(revt->size().width()); CSettings::instance()->writeSettings(); } // update height widget->setFixedSize(widget->width(), window3D->height()); widget->move(window3D->x()+window3D->width(), window3D->y()); } /********************************************************************************** * Linked to PMain GUI QGLRefSys widget. * This implements the syncronization Vaa3D-->TeraFly of rotations. ***********************************************************************************/ void CViewer::Vaa3D_rotationchanged(int s) { if(isActive && !toBeClosed) { // printf("disconnect\n"); // disconnect(view3DWidget, SIGNAL(xRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); // disconnect(view3DWidget, SIGNAL(yRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); // disconnect(view3DWidget, SIGNAL(zRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); //printf("view3DWidget->absoluteRotPose()\n"); //QMessageBox::information(0, "Test", "view3DWidget->absoluteRotPose()"); //view3DWidget->updateGL(); view3DWidget->absoluteRotPose(); //printf("PMain::getInstance()->refSys\n"); QGLRefSys* refsys = PMain::getInstance()->refSys; //printf(" refsys->setXRotation(view3DWidget->xRot())\n"); refsys->setXRotation(view3DWidget->xRot()); //printf(" refsys->setXRotation(view3DWidget->yRot())\n"); refsys->setYRotation(view3DWidget->yRot()); //printf(" refsys->setXRotation(view3DWidget->zRot())\n"); refsys->setZRotation(view3DWidget->zRot()); //view3DWidget->doAbsoluteRot(view3DWidget->xRot(), view3DWidget->yRot(), view3DWidget->zRot()); // printf("connect\n"); // connect(view3DWidget, SIGNAL(xRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); // connect(view3DWidget, SIGNAL(yRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); // connect(view3DWidget, SIGNAL(zRotationChanged(int)), this, SLOT(Vaa3D_rotationchanged(int))); } } void CViewer::PMain_rotationchanged() { if(isActive && !toBeClosed) { QGLRefSys* refsys = PMain::getInstance()->refSys; view3DWidget->doAbsoluteRot(refsys->getXRot(), refsys->getYRot(), refsys->getZRot()); } } /********************************************************************************** * Linked to Vaa3D renderer slider ***********************************************************************************/ void CViewer::setZoom(int z) { /**/tf::debug(tf::LEV3, strprintf("title = %s, zoom = %d", titleShort.c_str(), z).c_str(), __itm__current__function__); //QMessageBox::information(this, "asd", QString("zoom ") + QString::number(z)); myV3dR_GLWidget::cast(view3DWidget)->setZoomO(z); } /********************************************************************************** * Syncronizes widgets from <src> to <dst> ***********************************************************************************/ void CViewer::syncWindows(V3dR_MainWindow* src, V3dR_MainWindow* dst) { /**/tf::debug(tf::LEV1, strprintf("src->title = %s, dst->title = %s", src->getDataTitle().toStdString().c_str(), dst->getDataTitle().toStdString().c_str()).c_str(), __itm__current__function__); //syncronizing volume display controls dst->checkBox_channelR->setChecked(src->checkBox_channelR->isChecked()); dst->checkBox_channelG->setChecked(src->checkBox_channelG->isChecked()); dst->checkBox_channelB->setChecked(src->checkBox_channelB->isChecked()); dst->checkBox_volCompress->setChecked(src->checkBox_volCompress->isChecked()); dst->dispType_maxip->setChecked(src->dispType_maxip->isChecked()); dst->dispType_minip->setChecked(src->dispType_minip->isChecked()); dst->dispType_alpha->setChecked(src->dispType_alpha->isChecked()); dst->dispType_cs3d->setChecked(src->dispType_cs3d->isChecked()); dst->zthicknessBox->setValue(src->zthicknessBox->value()); dst->comboBox_channel->setCurrentIndex(src->comboBox_channel->currentIndex()); dst->transparentSlider->setValue(src->transparentSlider->value()); dst->fcutSlider->setValue(src->fcutSlider->value()); if(dst->displayControlsHidden != src->displayControlsHidden) dst->hideDisplayControls(); //syncronizing other controls dst->checkBox_displayAxes->setChecked(src->checkBox_displayAxes->isChecked()); dst->checkBox_displayBoundingBox->setChecked(src->checkBox_displayBoundingBox->isChecked()); dst->checkBox_OrthoView->setChecked(src->checkBox_OrthoView->isChecked()); //propagating skeleton mode and line width dst->getGLWidget()->getRenderer()->lineType = src->getGLWidget()->getRenderer()->lineType; dst->getGLWidget()->getRenderer()->lineWidth = src->getGLWidget()->getRenderer()->lineWidth; } /********************************************************************************** * Change to "waiting" state (i.e., when image data are to be loaded or are loading) ***********************************************************************************/ void CViewer::setWaitingForData(bool wait, bool pre_wait /* = false */) { /**/tf::debug(tf::LEV3, strprintf("title = %s, wait = %s, pre_wait = %s, this->waitingForData = %s", title.c_str(), wait ? "true" : "false", pre_wait ? "true" : "false", waitingForData ? "true" : "false").c_str(), __itm__current__function__); if(wait != this->waitingForData) { PMain& pMain = *(PMain::getInstance()); this->waitingForData = wait; if(waitingForData) { // change GUI appearance QPalette palette = pMain.frameCoord->palette(); palette.setColor(QPalette::Base, QColor(255, 255, 181)); palette.setColor(QPalette::Background, QColor(255, 255, 181)); pMain.frameCoord->setPalette(palette); pMain.setPalette(palette); window3D->setPalette(palette); // disable time bar if(!pre_wait) window3D->timeSlider->setEnabled(false); } else { // change GUI appearance pMain.frameCoord->setPalette(QApplication::palette( PMain::getInstance()->frameCoord )); pMain.setPalette(QApplication::palette( PMain::getInstance() )); window3D->setPalette(QApplication::palette( window3D )); // re-enable the time bar if(!pre_wait) window3D->timeSlider->setEnabled(true); } } } /********************************************************************************** * Change current Vaa3D's rendered cursor ***********************************************************************************/ void CViewer::setCursor(const QCursor& cur, bool renderer_only /* = false */) { /**/tf::debug(tf::LEV3, 0, __itm__current__function__); if(CViewer::current) { CViewer::current->window3D->setCursor(cur); CViewer::current->view3DWidget->setCursor(cur); } }
52.529389
312
0.594666
[ "object", "vector", "model", "3d" ]
3ada196f92a5071111eb87f677953ddb10dc09a6
3,039
cpp
C++
src/build/boc-shell/expression_visitor.cpp
jdmclark/gorc
a03d6a38ab7684860c418dd3d2e77cbe6a6d9fc8
[ "Apache-2.0" ]
97
2015-02-24T05:09:24.000Z
2022-01-23T12:08:22.000Z
src/build/boc-shell/expression_visitor.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
8
2015-03-27T23:03:23.000Z
2020-12-21T02:34:33.000Z
src/build/boc-shell/expression_visitor.cpp
annnoo/gorc
1889b4de6380c30af6c58a8af60ecd9c816db91d
[ "Apache-2.0" ]
10
2016-03-24T14:32:50.000Z
2021-11-13T02:38:53.000Z
#include "expression_visitor.hpp" #include "argument_visitor.hpp" #include "program_visitor.hpp" #include "symbols.hpp" #include "stack.hpp" #include "log/log.hpp" #include "utility/zip.hpp" gorc::shvalue gorc::expression_visitor::visit(argument_expression &e) const { return ast_visit(argument_visitor(), e.value); } gorc::shvalue gorc::expression_visitor::visit(unary_expression &e) const { auto sub_value = ast_visit(expression_visitor(), *e.value); switch(e.op) { case unary_operator::logical_not: return shvalue_from_boolean(!shvalue_to_boolean(sub_value)); // LCOV_EXCL_START } // Not coverable LOG_FATAL("unhandled unary operator"); // LCOV_EXCL_STOP } gorc::shvalue gorc::expression_visitor::visit(infix_expression &e) const { auto left_value = ast_visit(expression_visitor(), *e.left); auto right_value = ast_visit(expression_visitor(), *e.right); switch(e.op) { case infix_operator::equal: return shvalue_from_boolean(left_value == right_value); case infix_operator::not_equal: return shvalue_from_boolean(left_value != right_value); case infix_operator::cons: { shvalue rv = left_value; std::copy(right_value.begin(), right_value.end(), std::back_inserter(rv)); return rv; } // LCOV_EXCL_START } // Not coverable LOG_FATAL("unhandled infix operator"); // LCOV_EXCL_STOP } gorc::shvalue gorc::expression_visitor::visit(nil_expression &) const { return shvalue(); } gorc::shvalue gorc::expression_visitor::visit(call_expression &e) const { // Try for a builtin first auto builtin_ptr = get_builtin(e.name->value); if(builtin_ptr.has_value()) { auto &builtin = *builtin_ptr.get_value(); if(builtin.args != e.arguments->elements.size()) { LOG_FATAL(format("builtin '%s' expected %d arguments, found %d") % e.name->value % builtin.args % e.arguments->elements.size()); } std::vector<shvalue> args; for(auto const &arg : e.arguments->elements) { args.push_back(ast_visit(expression_visitor(), *arg)); } return builtin.code(args); } auto &fn_node = get_function(e.name->value); if(fn_node.arguments->elements.size() != e.arguments->elements.size()) { LOG_FATAL(format("function '%s' expected %d arguments, found %d") % e.name->value % fn_node.arguments->elements.size() % e.arguments->elements.size()); } scoped_stack_frame fn_stack; for(auto arg : zip(fn_node.arguments->elements, e.arguments->elements)) { create_variable(std::get<0>(arg)->value, ast_visit(expression_visitor(), *std::get<1>(arg))); } program_visitor pv; ast_visit(pv, *fn_node.code); if(pv.return_value.has_value()) { return pv.return_value.get_value(); } else { return shvalue(); } }
27.378378
86
0.634748
[ "vector" ]
3adb9b00d6215108baa62a74347a50f7ea99bd77
7,090
hpp
C++
source/grid_utils.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
15
2020-07-31T23:06:09.000Z
2022-01-13T18:05:33.000Z
source/grid_utils.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
137
2020-08-13T23:32:17.000Z
2021-10-16T04:00:40.000Z
source/grid_utils.hpp
mmore500/pipe-profile
861babd819909d1bda5e933269e7bc64018272d6
[ "MIT" ]
3
2020-08-09T01:52:03.000Z
2020-10-02T02:13:47.000Z
#pragma once #include <algorithm> #include <cstdlib> #include <random> #include <string> #include <thread> #include <vector> #ifdef PP_USE_OMP #include <omp.h> #endif #include "../third-party/Empirical/include/emp/data/DataFile.hpp" #include "../third-party/Empirical/include/emp/tools/keyname_utils.hpp" #include "uitsl/chrono/CoarseClock.hpp" #include "uitsl/concurrent/ConcurrentTimeoutBarrier.hpp" #include "uitsl/concurrent/Gatherer.hpp" #include "uitsl/countdown/Counter.hpp" #include "uitsl/countdown/Timer.hpp" #include "uitsl/debug/safe_cast.hpp" #include "uitsl/debug/safe_compare.hpp" #include "uitsl/math/math_utils.hpp" #include "uitsl/mpi/mpi_init_utils.hpp" #include "uitsl/parallel/ThreadIbarrierFactory.hpp" #include "uitsl/parallel/ThreadTeam.hpp" #include "uitsl/polyfill/barrier.hpp" #include "uitsl/polyfill/latch.hpp" #include "uit/fixtures/Conduit.hpp" #include "netuit/arrange/RingTopologyFactory.hpp" #include "netuit/mesh/Mesh.hpp" #include "chunk_utils.hpp" #include "config_utils.hpp" #include "State.hpp" #include "Tile.hpp" grid_t make_grid(const config_t & cfg) { emp::vector<uit::Inlet<Spec>> inlets; emp::vector<uit::Outlet<Spec>> outlets; const size_t grid_size = cfg.at("grid_size"); const size_t num_threads = cfg.at("num_threads"); netuit::Mesh<Spec> mesh{ netuit::RingTopologyFactory{}(grid_size * uitsl::get_nprocs()), uitsl::AssignContiguously<uitsl::thread_id_t>{num_threads, grid_size} }; grid_t grid; netuit::Mesh<Spec>::submesh_t submesh{ mesh.GetSubmesh() }; for (const auto & node : submesh) { grid.push_back( Tile( node.GetInput(0), node.GetOutput(0) ) ); } for (size_t i = 0; i < grid_size; ++i) { grid[i].next = &grid[uitsl::circular_index(i, grid_size , 1)]; grid[i].prev = &grid[uitsl::circular_index(i, grid_size, -1)]; grid[i].id = i; } return grid; } void initialize_grid(grid_t & grid) { const std::array<State, 2> states{'_', 'O'}; for (size_t i = 0; i < grid.size(); ++i) { grid[i].SetState(states[i % states.size()]); } } double run_grid(grid_t & grid, const config_t & cfg) { emp::vector<chunk_t> chunks( make_chunks( grid, cfg.at("num_chunks") ) ); initialize_grid(grid); const size_t num_updates = cfg.at("num_updates"); const size_t num_seconds = cfg.at("num_seconds"); const size_t verbose = cfg.at("verbose"); const size_t resistance = cfg.at("resistance"); const size_t num_threads = cfg.at("num_threads"); const size_t use_omp = cfg.at("use_omp"); const size_t synchronous = cfg.at("synchronous"); const size_t shuffle_tile_evaluation = cfg.at("shuffle_tile_evaluation"); const size_t checkout_memory = cfg.at("checkout_memory"); const auto task_step = [=](chunk_t chunk){ update_chunk(chunk, verbose, shuffle_tile_evaluation, resistance); }; std::latch latch{uitsl::safe_cast<std::ptrdiff_t>(num_threads)}; std::barrier barrier{uitsl::safe_cast<std::ptrdiff_t>(num_threads)}; uitsl::ThreadIbarrierFactory factory{ num_threads }; uitsl::Gatherer<int> gatherer(MPI_INT); const auto task_sequence = [&](chunk_t source){ emp_assert(!use_omp); auto chunk = checkout_memory ? checkout_chunk(source) : source; uitsl::Timer<std::chrono::seconds, uitsl::CoarseClock> timer{ std::chrono::seconds{num_seconds} }; uitsl::Counter counter{num_updates}; // synchronize once after thread creation and MPI spinup if (!synchronous) { latch.arrive_and_wait(); MPI_Barrier(MPI_COMM_WORLD); } while (!counter.IsComplete() && !timer.IsComplete()) { task_step(chunk); // synchronize after each step if (synchronous) { const uitsl::ThreadIbarrier thread_barrier{ factory.MakeBarrier() }; uitsl::ConcurrentTimeoutBarrier{ thread_barrier, timer }; } counter.Step(); } if (checkout_memory) checkin_chunk(source, chunk); gatherer.Put(uitsl::safe_cast<int>( counter.GetElapsed() / ( num_seconds ?: std::chrono::duration_cast<std::chrono::duration<double>>( timer.GetElapsed() ).count() ?: 1 ) )); }; const auto omp_sync = [task_step, num_updates, &chunks](){ #ifdef PP_USE_OMP const size_t num_chunks = chunks.size(); for (size_t update = 0; update < num_updates; ++update) { #pragma omp parallel for for (size_t i = 0; i < num_chunks; ++i) task_step(chunks[i]); } } #endif }; const auto omp_async = [task_step, &chunks](){ #ifdef PP_USE_OMP const size_t num_chunks = chunks.size(); #pragma omp parallel { // attempt to ensure synchonous thread initialization #pragma omp barrier #pragma omp for for (size_t i = 0; i < num_chunks; ++i) task_step(chunks[i]); } #endif }; const auto std_run = [&](){ uitsl::ThreadTeam team; for (auto chunk : chunks) { team.Add([chunk, task_sequence](){ task_sequence(chunk); }); } team.Join(); }; if (use_omp) { if (synchronous) omp_sync(); else omp_async(); } else std_run(); const auto productivities = gatherer.Gather(); return productivities ? std::accumulate( std::begin(*productivities), std::end(*productivities), 0.0 ) / productivities->size() : -1.0; } void audit_grid( const grid_t & grid, const config_t& cfg, const size_t nanoseconds ) { std::unordered_map<std::string, std::string> descriptors{ {"title", "audit"}, {"nanoseconds", emp::to_string(nanoseconds)}, {"ext", ".csv"} }; std::transform( std::begin(cfg), std::end(cfg), std::inserter(descriptors, std::begin(descriptors)), [](const auto & pair){ const auto & [key, value] = pair; return std::pair<std::string, std::string>{key, emp::to_string(value)}; } ); emp::DataFile datafile( emp::keyname::pack(descriptors) ); size_t tile; datafile.AddVar<size_t>(tile, "Tile"); size_t attempted_write_count; datafile.AddVar<size_t>(attempted_write_count, "Attempted Write Count"); size_t blocked_write_count; datafile.AddVar<size_t>(blocked_write_count, "Blocked Write Count"); size_t dropped_write_count; datafile.AddVar<size_t>(dropped_write_count, "Dropped Write Count"); size_t read_count; datafile.AddVar<size_t>(read_count, "Read Count"); size_t read_revision_count; datafile.AddVar<size_t>(read_revision_count, "Read Revision Count"); size_t net_flux; datafile.AddVar<size_t>(net_flux, "Net Flux"); datafile.PrintHeaderKeys(); for (tile = 0; tile < grid.size(); ++tile) { const auto & which = grid[tile]; attempted_write_count = which.GetNumPutsAttempted(); blocked_write_count = which.GetNumPutsThatBlocked(); dropped_write_count = which.GetNumDroppedPuts(); read_count = which.GetNumReadsPerformed(); read_revision_count = which.GetReadRevisionCount(); net_flux = which.GetNetFluxThroughDuct(); datafile.Update(); } }
24.703833
77
0.667983
[ "mesh", "vector", "transform" ]
3adcd70d4b8a08064a4f275d58dd4e8d9cacb205
5,811
cpp
C++
Engine/Bindings/GLShaderBindings.cpp
Kepler-Br/AdvancedRaymarching
108e515edad39df52e81bee9b3f2e777c99c9de2
[ "MIT" ]
null
null
null
Engine/Bindings/GLShaderBindings.cpp
Kepler-Br/AdvancedRaymarching
108e515edad39df52e81bee9b3f2e777c99c9de2
[ "MIT" ]
null
null
null
Engine/Bindings/GLShaderBindings.cpp
Kepler-Br/AdvancedRaymarching
108e515edad39df52e81bee9b3f2e777c99c9de2
[ "MIT" ]
null
null
null
#include "GLShaderBindings.h" #include <iostream> #include <glm/gtc/type_ptr.hpp> #include "../Incapsulated/GLError.h" #include "../Exceptions/ShaderErrorException.h" void GLShaderBindings::printGLShaderLogIfAny(GLuint shaderId) { GLint logLength = 0; GLchar *log; glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength); GLError::throwExceptionIfGLError("printGLShaderLogIfAny glGetShaderiv"); if (logLength == 0) return; log = new GLchar[logLength]; glGetShaderInfoLog(shaderId, logLength, &logLength, log); GLError::throwExceptionIfGLError("printGLShaderLogIfAny glGetShaderInfoLog"); std::cout << log << std::endl; delete log; } void GLShaderBindings::deleteProgram(GLuint shaderProgramPointer) { glDeleteProgram(shaderProgramPointer); GLError::throwExceptionIfGLError("glDeleteProgram"); } GLuint GLShaderBindings::createProgram() { GLuint shaderProgram; shaderProgram = glCreateProgram(); if (shaderProgram == 0) throw GLErrorException("glCreateProgram returned 0."); return shaderProgram; } void GLShaderBindings::useProgram(const GLuint shaderProgramPointer) { glUseProgram(shaderProgramPointer); GLError::throwExceptionIfGLError("glUseProgram"); } GLuint GLShaderBindings::createShader(const GLenum shaderType) { const GLuint shader = glCreateShader(shaderType); if (shader == 0) throw GLErrorException("glCreateShader shader object pointer is zero."); GLError::throwExceptionIfGLError("glCreateShader"); return shader; } void GLShaderBindings::uploadSource(const GLuint shaderObjectPointer, const std::string &source) { const char *cSource = source.c_str(); glShaderSource(shaderObjectPointer, 1, &cSource, nullptr); GLError::throwExceptionIfGLError("glShaderSource"); } void GLShaderBindings::compileShader(GLuint shaderObjectPointer, GLenum shaderType) { GLint success = GL_FALSE; glCompileShader(shaderObjectPointer); GLError::throwExceptionIfGLError("glCompileShader"); glGetShaderiv(shaderObjectPointer, GL_COMPILE_STATUS, &success); GLError::throwExceptionIfGLError("glGetShaderiv"); if (success == GL_FALSE) { GLShaderBindings::printGLShaderLogIfAny(shaderObjectPointer); if (shaderType == GL_FRAGMENT_SHADER) throw ShaderErrorException("Cannot compile fragment shader."); else if (shaderType == GL_VERTEX_SHADER) throw ShaderErrorException("Cannot compile vertex shader."); else throw ShaderErrorException("Cannot compile UNK shader."); } } void GLShaderBindings::attachShader(const GLuint shaderProgramPointer, const GLuint shaderPointer, const GLenum shaderType) { glAttachShader(shaderProgramPointer, shaderPointer); if (shaderType == GL_VERTEX_SHADER) GLError::throwExceptionIfGLError("glAttachShader vertex"); else if (shaderType == GL_FRAGMENT_SHADER) GLError::throwExceptionIfGLError("glAttachShader fragment"); GLError::throwExceptionIfGLError("glAttachShader other"); } void GLShaderBindings::deleteShader(const GLuint shaderObjectPointer, const GLenum shaderType) { glDeleteShader(shaderObjectPointer); if (shaderType == GL_VERTEX_SHADER) GLError::throwExceptionIfGLError("glDeleteShader vertex"); else if (shaderType == GL_FRAGMENT_SHADER) GLError::throwExceptionIfGLError("glDeleteShader fragment"); else GLError::throwExceptionIfGLError("glDeleteShader UNK"); } void GLShaderBindings::linkProgram(const GLuint shaderProgramPointer) { GLint isLinked = 1; glLinkProgram(shaderProgramPointer); GLError::throwExceptionIfGLError("glLinkProgram"); glGetProgramiv(shaderProgramPointer, GL_LINK_STATUS, &isLinked); if (isLinked == GL_FALSE) { GLShaderBindings::printGLShaderLogIfAny(shaderProgramPointer); throw ShaderErrorException("Shader link failure."); } } GLuint GLShaderBindings::getAttributeLocation(const GLuint shaderProgramPointer, const std::string &attributeName) { const GLint attributeLocation = glGetAttribLocation(shaderProgramPointer, attributeName.c_str()); if (attributeLocation == -1) throw GLErrorException("glGetAttribLocation returned -1."); GLError::throwExceptionIfGLError("glGetAttribLocation"); return attributeLocation; } GLuint GLShaderBindings::getUniformLocation(const GLuint shaderProgramPointer, const std::string &uniformName) { const GLint uniformLocation = glGetUniformLocation(shaderProgramPointer, uniformName.c_str()); if (uniformLocation == -1) throw GLErrorException("glGetUniformLocation returned -1."); GLError::throwExceptionIfGLError("glGetUniformLocation"); return uniformLocation; } void GLShaderBindings::setUniform(const GLint uniformPointer, const GLint value) { glUniform1i(uniformPointer, value); GLError::throwExceptionIfGLError("Cannot set value(GLint) from undefined uniform location"); } void GLShaderBindings::setUniform(const GLint uniformPointer, const GLfloat value) { glUniform1f(uniformPointer, value); GLError::throwExceptionIfGLError("Cannot set value(GLfloat) from undefined uniform location"); } void GLShaderBindings::setUniform(const GLint uniformPointer, const GLdouble value) { glUniform1d(uniformPointer, value); GLError::throwExceptionIfGLError("Cannot set value(GLdouble) from undefined uniform location"); } void GLShaderBindings::setUniformMatrix4(const GLint uniformPointer, const glm::mat4 &value, const GLboolean shouldTranspose) { static const GLsizei matricesCount = 1; glUniformMatrix4fv(uniformPointer, matricesCount, shouldTranspose, glm::value_ptr(value)); GLError::throwExceptionIfGLError("Cannot set value(glm::mat4) from undefined uniform location"); }
36.093168
125
0.759938
[ "object" ]