text
stringlengths
54
60.6k
<commit_before>#include "logging.hh" #include "nixexpr.hh" #include "util.hh" #include <gtest/gtest.h> namespace nix { /* ---------------------------------------------------------------------------- * logEI * --------------------------------------------------------------------------*/ TEST(logEI, catpuresBasicProperties) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { throw TestError("an error for testing purposes"); } catch (Error &e) { testing::internal::CaptureStderr(); logger->logEI(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(),"\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError ------------------------------------ error-unit-test\x1B[0m\nan error for testing purposes\n"); } } TEST(logEI, appendingHintsToPreviousError) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto e = Error("initial error"); throw TestError(e.info()); } catch (Error &e) { ErrorInfo ei = e.info(); ei.hint = hintfmt("%s; subsequent error message.", normaltxt(e.info().hint ? e.info().hint->str() : "")); testing::internal::CaptureStderr(); logger->logEI(ei); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError ------------------------------------ error-unit-test\x1B[0m\n\x1B[33;1m\x1B[0minitial error\x1B[0m; subsequent error message.\n"); } } TEST(logEI, picksUpSysErrorExitCode) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto x = readFile(-1); } catch (SysError &e) { testing::internal::CaptureStderr(); logError(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- SysError ------------------------------------- error-unit-test\x1B[0m\n\x1B[33;1m\x1B[0mstatting file\x1B[0m: \x1B[33;1mBad file descriptor\x1B[0m\n"); } } TEST(logEI, loggingErrorOnInfoLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlInfo, .name = "Info name", .description = "Info description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1minfo:\x1B[0m\x1B[34;1m --- Info name ------------------------------------- error-unit-test\x1B[0m\nInfo description\n"); } TEST(logEI, loggingErrorOnTalkativeLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlTalkative, .name = "Talkative name", .description = "Talkative description", }); auto str = testing::internal::GetCapturedStderr(); // XXX: why is this the empty string? ASSERT_STREQ(str.c_str(), ""); } TEST(logEI, loggingErrorOnChattyLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlChatty, .name = "Chatty name", .description = "Talkative description", }); auto str = testing::internal::GetCapturedStderr(); // XXX: why is this the empty string? ASSERT_STREQ(str.c_str(), ""); } TEST(logEI, loggingErrorOnDebugLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlDebug, .name = "Debug name", .description = "Debug description", }); auto str = testing::internal::GetCapturedStderr(); // XXX: why is this the empty string? ASSERT_STREQ(str.c_str(), ""); } TEST(logEI, loggingErrorOnVomitLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlVomit, .name = "Vomit name", .description = "Vomit description", }); auto str = testing::internal::GetCapturedStderr(); // XXX: why is this the empty string? ASSERT_STREQ(str.c_str(), ""); } /* ---------------------------------------------------------------------------- * logError * --------------------------------------------------------------------------*/ TEST(logError, logErrorWithoutHintOrCode) { testing::internal::CaptureStderr(); logError({ .name = "name", .description = "error description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- name ----------------------------------------- error-unit-test\x1B[0m\nerror description\n"); } TEST(logError, logErrorWithPreviousAndNextLinesOfCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .description = "error with code lines", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13), .prevLineOfCode = "previous line of code", .errLineOfCode = "this is the problem line of code", .nextLineOfCode = "next line of code", }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nerror with code lines\n\n 39| previous line of code\n 40| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 41| next line of code\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithoutLinesOfCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .description = "error without any code lines.", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13) }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nerror without any code lines.\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithOnlyHintAndName) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .hint = hintfmt("hint %1%", "only"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13) }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nhint \x1B[33;1monly\x1B[0m\n"); } /* ---------------------------------------------------------------------------- * logWarning * --------------------------------------------------------------------------*/ TEST(logWarning, logWarningWithNameDescriptionAndHint) { testing::internal::CaptureStderr(); logWarning({ .name = "name", .description = "error description", .hint = hintfmt("there was a %1%", "warning"), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- name --------------------------------------- error-unit-test\x1B[0m\nerror description\n\nthere was a \x1B[33;1mwarning\x1B[0m\n"); } TEST(logWarning, logWarningWithFileLineNumAndCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logWarning({ .name = "warning name", .description = "warning description", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13), .prevLineOfCode = std::nullopt, .errLineOfCode = "this is the problem line of code", .nextLineOfCode = std::nullopt }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- warning name ------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nwarning description\n\n 40| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } } <commit_msg>set verbosity levels<commit_after>#include "logging.hh" #include "nixexpr.hh" #include "util.hh" #include <gtest/gtest.h> namespace nix { /* ---------------------------------------------------------------------------- * logEI * --------------------------------------------------------------------------*/ TEST(logEI, catpuresBasicProperties) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { throw TestError("an error for testing purposes"); } catch (Error &e) { testing::internal::CaptureStderr(); logger->logEI(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(),"\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError ------------------------------------ error-unit-test\x1B[0m\nan error for testing purposes\n"); } } TEST(logEI, appendingHintsToPreviousError) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto e = Error("initial error"); throw TestError(e.info()); } catch (Error &e) { ErrorInfo ei = e.info(); ei.hint = hintfmt("%s; subsequent error message.", normaltxt(e.info().hint ? e.info().hint->str() : "")); testing::internal::CaptureStderr(); logger->logEI(ei); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- TestError ------------------------------------ error-unit-test\x1B[0m\n\x1B[33;1m\x1B[0minitial error\x1B[0m; subsequent error message.\n"); } } TEST(logEI, picksUpSysErrorExitCode) { MakeError(TestError, Error); ErrorInfo::programName = std::optional("error-unit-test"); try { auto x = readFile(-1); } catch (SysError &e) { testing::internal::CaptureStderr(); logError(e.info()); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- SysError ------------------------------------- error-unit-test\x1B[0m\n\x1B[33;1m\x1B[0mstatting file\x1B[0m: \x1B[33;1mBad file descriptor\x1B[0m\n"); } } TEST(logEI, loggingErrorOnInfoLevel) { testing::internal::CaptureStderr(); logger->logEI({ .level = lvlInfo, .name = "Info name", .description = "Info description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1minfo:\x1B[0m\x1B[34;1m --- Info name ------------------------------------- error-unit-test\x1B[0m\nInfo description\n"); } TEST(logEI, loggingErrorOnTalkativeLevel) { verbosity = lvlTalkative; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlTalkative, .name = "Talkative name", .description = "Talkative description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mtalk:\x1B[0m\x1B[34;1m --- Talkative name -------------------------------- error-unit-test\x1B[0m\nTalkative description\n"); } TEST(logEI, loggingErrorOnChattyLevel) { verbosity = lvlChatty; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlChatty, .name = "Chatty name", .description = "Talkative description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mchat:\x1B[0m\x1B[34;1m --- Chatty name ----------------------------------- error-unit-test\x1B[0m\nTalkative description\n"); } TEST(logEI, loggingErrorOnDebugLevel) { verbosity = lvlDebug; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlDebug, .name = "Debug name", .description = "Debug description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mdebug:\x1B[0m\x1B[34;1m --- Debug name ----------------------------------- error-unit-test\x1B[0m\nDebug description\n"); } TEST(logEI, loggingErrorOnVomitLevel) { verbosity = lvlVomit; testing::internal::CaptureStderr(); logger->logEI({ .level = lvlVomit, .name = "Vomit name", .description = "Vomit description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[32;1mvomit:\x1B[0m\x1B[34;1m --- Vomit name ----------------------------------- error-unit-test\x1B[0m\nVomit description\n"); } /* ---------------------------------------------------------------------------- * logError * --------------------------------------------------------------------------*/ TEST(logError, logErrorWithoutHintOrCode) { testing::internal::CaptureStderr(); logError({ .name = "name", .description = "error description", }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- name ----------------------------------------- error-unit-test\x1B[0m\nerror description\n"); } TEST(logError, logErrorWithPreviousAndNextLinesOfCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .description = "error with code lines", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13), .prevLineOfCode = "previous line of code", .errLineOfCode = "this is the problem line of code", .nextLineOfCode = "next line of code", }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nerror with code lines\n\n 39| previous line of code\n 40| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n 41| next line of code\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithoutLinesOfCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .description = "error without any code lines.", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13) }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nerror without any code lines.\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } TEST(logError, logErrorWithOnlyHintAndName) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logError({ .name = "error name", .hint = hintfmt("hint %1%", "only"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13) }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[31;1merror:\x1B[0m\x1B[34;1m --- error name ----------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nhint \x1B[33;1monly\x1B[0m\n"); } /* ---------------------------------------------------------------------------- * logWarning * --------------------------------------------------------------------------*/ TEST(logWarning, logWarningWithNameDescriptionAndHint) { testing::internal::CaptureStderr(); logWarning({ .name = "name", .description = "error description", .hint = hintfmt("there was a %1%", "warning"), }); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- name --------------------------------------- error-unit-test\x1B[0m\nerror description\n\nthere was a \x1B[33;1mwarning\x1B[0m\n"); } TEST(logWarning, logWarningWithFileLineNumAndCode) { SymbolTable testTable; auto problem_file = testTable.create("myfile.nix"); testing::internal::CaptureStderr(); logWarning({ .name = "warning name", .description = "warning description", .hint = hintfmt("this hint has %1% templated %2%!!", "yellow", "values"), .nixCode = NixCode { .errPos = Pos(problem_file, 40, 13), .prevLineOfCode = std::nullopt, .errLineOfCode = "this is the problem line of code", .nextLineOfCode = std::nullopt }}); auto str = testing::internal::GetCapturedStderr(); ASSERT_STREQ(str.c_str(), "\x1B[33;1mwarning:\x1B[0m\x1B[34;1m --- warning name ------------------------------- error-unit-test\x1B[0m\nin file: \x1B[34;1mmyfile.nix (40:13)\x1B[0m\n\nwarning description\n\n 40| this is the problem line of code\n | \x1B[31;1m^\x1B[0m\n\nthis hint has \x1B[33;1myellow\x1B[0m templated \x1B[33;1mvalues\x1B[0m!!\n"); } } <|endoftext|>
<commit_before>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __LINUX_ROUTING_HANDLE_HPP__ #define __LINUX_ROUTING_HANDLE_HPP__ #include <stdint.h> #include <netlink/route/tc.h> namespace routing { // The Linux kernel Traffic Control (TC) uses handles to uniqely // identify the queueing disciplines (qdiscs), classes and filters // attached to a network interface. The most common type of handle is // identified by primary and secondary device numbers (sometimes // called major and minor numbers) and written as primary:secondary. // Handles provide the mechanism by which TC classes, qdiscs and // filters can be connected together to create complex network traffic // policing policies. class Handle { public: explicit constexpr Handle(uint32_t _handle) : handle(_handle) {} constexpr Handle(uint16_t primary, uint16_t secondary) : handle((((uint32_t) primary) << 16) + secondary) {} // NOTE: This is used to construct a classid. The higher 16 bits of // the given 'parent' will be the primary and the lower 16 bits is // specified by the given 'id'. constexpr Handle(const Handle& parent, uint16_t id) : handle((((uint32_t) parent.primary()) << 16) + id) {} constexpr bool operator == (const Handle& that) const { return handle == that.handle; } constexpr bool operator != (const Handle& that) const { return handle != that.handle; } constexpr uint16_t primary() const { return handle >> 16; } constexpr uint16_t secondary() const { return handle & 0x0000ffff; } constexpr uint32_t get() const { return handle; } protected: uint32_t handle; }; // Packets flowing from the device driver to the network stack are // called ingress traffic, and packets flowing from the network stack // to the device driver are called egress traffic (shown below). // // +---------+ // | Network | // | Stack | // |---------| // | eth0 | // +---------+ // ^ | // Ingress | | Egress // | | // -------+ +------> // // The root handles for both ingress and egress are immutable. constexpr Handle EGRESS_ROOT = Handle(TC_H_ROOT); constexpr Handle INGRESS_ROOT = Handle(TC_H_INGRESS); } // namespace routing { #endif // __LINUX_ROUTING_HANDLE_HPP__ <commit_msg>Added output stream operation for handle to use in port_mapping.cpp.<commit_after>/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __LINUX_ROUTING_HANDLE_HPP__ #define __LINUX_ROUTING_HANDLE_HPP__ #include <stdint.h> #include <ostream> #include <netlink/route/tc.h> namespace routing { // The Linux kernel Traffic Control (TC) uses handles to uniqely // identify the queueing disciplines (qdiscs), classes and filters // attached to a network interface. The most common type of handle is // identified by primary and secondary device numbers (sometimes // called major and minor numbers) and written as primary:secondary. // Handles provide the mechanism by which TC classes, qdiscs and // filters can be connected together to create complex network traffic // policing policies. class Handle { public: explicit constexpr Handle(uint32_t _handle) : handle(_handle) {} constexpr Handle(uint16_t primary, uint16_t secondary) : handle((((uint32_t) primary) << 16) + secondary) {} // NOTE: This is used to construct a classid. The higher 16 bits of // the given 'parent' will be the primary and the lower 16 bits is // specified by the given 'id'. constexpr Handle(const Handle& parent, uint16_t id) : handle((((uint32_t) parent.primary()) << 16) + id) {} constexpr bool operator == (const Handle& that) const { return handle == that.handle; } constexpr bool operator != (const Handle& that) const { return handle != that.handle; } constexpr uint16_t primary() const { return handle >> 16; } constexpr uint16_t secondary() const { return handle & 0x0000ffff; } constexpr uint32_t get() const { return handle; } protected: uint32_t handle; }; inline std::ostream& operator << (std::ostream& out, const Handle& handle) { out << std::hex << handle.primary() << ":" << handle.secondary() << std::dec; return out; } // Packets flowing from the device driver to the network stack are // called ingress traffic, and packets flowing from the network stack // to the device driver are called egress traffic (shown below). // // +---------+ // | Network | // | Stack | // |---------| // | eth0 | // +---------+ // ^ | // Ingress | | Egress // | | // -------+ +------> // // The root handles for both ingress and egress are immutable. constexpr Handle EGRESS_ROOT = Handle(TC_H_ROOT); constexpr Handle INGRESS_ROOT = Handle(TC_H_INGRESS); } // namespace routing { #endif // __LINUX_ROUTING_HANDLE_HPP__ <|endoftext|>
<commit_before>#include <map> // ignore unused parameters in LLVM libraries #if (__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include <llvm/IR/Value.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Constants.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Module.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/raw_ostream.h> #if (__clang__) #pragma clang diagnostic pop // ignore -Wunused-parameter #else #pragma GCC diagnostic pop #endif #include "llvm/LLVMNode.h" #include "llvm/LLVMDependenceGraph.h" #include "llvm/llvm-utils.h" #include "llvm/analysis/PointsTo/PointsTo.h" #include "ReachingDefinitions/ReachingDefinitions.h" #include "DefUse.h" #include "analysis/PointsTo/PointerSubgraph.h" #include "analysis/DFS.h" using dg::analysis::rd::LLVMReachingDefinitions; using dg::analysis::rd::RDNode; using namespace llvm; /// -------------------------------------------------- // Add def-use edges /// -------------------------------------------------- namespace dg { static void handleInstruction(const Instruction *Inst, LLVMNode *node) { LLVMDependenceGraph *dg = node->getDG(); for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) { LLVMNode *op = dg->getNode(*I); if (op) op->addDataDependence(node); } } static void addReturnEdge(LLVMNode *callNode, LLVMDependenceGraph *subgraph) { // FIXME we may loose some accuracy here and // this edges causes that we'll go into subprocedure // even with summary edges if (!callNode->isVoidTy()) subgraph->getExit()->addDataDependence(callNode); } LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg, LLVMReachingDefinitions *rd, LLVMPointerAnalysis *pta, bool assume_pure_funs) : analysis::DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), analysis::DATAFLOW_INTERPROCEDURAL), dg(dg), RD(rd), PTA(pta), DL(new DataLayout(dg->getModule())), assume_pure_functions(assume_pure_funs) { assert(PTA && "Need points-to information"); assert(RD && "Need reaching definitions"); } void LLVMDefUseAnalysis::handleInlineAsm(LLVMNode *callNode) { CallInst *CI = cast<CallInst>(callNode->getValue()); LLVMDependenceGraph *dg = callNode->getDG(); // the last operand is the asm itself, so iterate only to e - 1 for (unsigned i = 0, e = CI->getNumOperands(); i < e - 1; ++i) { Value *opVal = CI->getOperand(i); if (!opVal->getType()->isPointerTy()) continue; LLVMNode *opNode = dg->getNode(opVal->stripInBoundsOffsets()); if (!opNode) { // FIXME: ConstantExpr llvmutils::printerr("WARN: unhandled inline asm operand: ", opVal); continue; } assert(opNode && "Do not have an operand for inline asm"); // if nothing else, this call at least uses the operands opNode->addDataDependence(callNode); } } void LLVMDefUseAnalysis::handleIntrinsicCall(LLVMNode *callNode, CallInst *CI) { static std::set<Instruction *> warnings; IntrinsicInst *I = cast<IntrinsicInst>(CI); Value *dest, *src = nullptr; switch (I->getIntrinsicID()) { case Intrinsic::memmove: case Intrinsic::memcpy: dest = I->getOperand(0); src = I->getOperand(1); break; case Intrinsic::memset: dest = I->getOperand(0); break; case Intrinsic::vastart: dest = I->getOperand(0); break; case Intrinsic::vaend: case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: case Intrinsic::trap: case Intrinsic::bswap: case Intrinsic::prefetch: case Intrinsic::objectsize: // nothing to be done, direct def-use edges // will be added later return; case Intrinsic::stacksave: case Intrinsic::stackrestore: if (warnings.insert(CI).second) llvmutils::printerr("WARN: stack save/restore not implemented", CI); return; default: I->dump(); assert(0 && "DEF-USE: Unhandled intrinsic call"); handleUndefinedCall(callNode, CI); return; } // we must have dest set assert(dest); // these functions touch the memory of the pointers addDataDependence(callNode, CI, dest, UNKNOWN_OFFSET /* FIXME */); if (src) addDataDependence(callNode, CI, src, UNKNOWN_OFFSET /* FIXME */); } void LLVMDefUseAnalysis::handleUndefinedCall(LLVMNode *callNode, CallInst *CI) { if (assume_pure_functions) return; // the function is undefined - add the top-level dependencies and // also assume that this function use all the memory that is passed // via the pointers for (int e = CI->getNumArgOperands(), i = 0; i < e; ++i) { if (auto pts = PTA->getPointsTo(CI->getArgOperand(i))) { // the passed memory may be used in the undefined // function on the unknown offset addDataDependence(callNode, CI, pts, UNKNOWN_OFFSET); } } } void LLVMDefUseAnalysis::handleCallInst(LLVMNode *node) { CallInst *CI = cast<CallInst>(node->getKey()); if (CI->isInlineAsm()) { handleInlineAsm(node); return; } Function *func = dyn_cast<Function>(CI->getCalledValue()->stripPointerCasts()); if (func) { if (func->isIntrinsic() && !isa<DbgInfoIntrinsic>(CI)) { handleIntrinsicCall(node, CI); return; } // for realloc, we need to make it data dependent on the // memory it reallocates, since that is the memory it copies if (func->size() == 0) { const char *name = func->getName().data(); if (strcmp(name, "realloc") == 0) { addDataDependence(node, CI, CI->getOperand(0), UNKNOWN_OFFSET /* FIXME */); } else if (strcmp(name, "malloc") == 0 || strcmp(name, "calloc") == 0 || strcmp(name, "alloca") == 0) { // we do not want to do anything for the memory // allocation functions } else { handleUndefinedCall(node, CI); } // the function is undefined, so do not even try to // add the edges from return statements return; } } // add edges from the return nodes of subprocedure // to the call (if the call returns something) for (LLVMDependenceGraph *subgraph : node->getSubgraphs()) addReturnEdge(node, subgraph); } // Add data dependence edges from all memory location that may write // to memory pointed by 'pts' to 'node' void LLVMDefUseAnalysis::addUnknownDataDependence(LLVMNode *node, PSNode *pts) { // iterate over all nodes from ReachingDefinitions Subgraph. It is faster than // going over all llvm nodes and querying the pointer to analysis for (auto& it : RD->getNodesMap()) { RDNode *rdnode = it.second; // only STORE may be a definition site if (rdnode->getType() != analysis::rd::RDNodeType::STORE) continue; llvm::Value *rdVal = rdnode->getUserData<llvm::Value>(); // artificial node? if (!rdVal) continue; // does this store define some value that is in pts? for (const analysis::rd::DefSite& ds : rdnode->getDefines()) { llvm::Value *llvmVal = ds.target->getUserData<llvm::Value>(); // is this an artificial node? if (!llvmVal) continue; // if these two sets have an over-lap, we must add the data dependence for (const auto& ptr : pts->pointsTo) if (ptr.target->getUserData<llvm::Value>() == llvmVal) { addDataDependence(node, rdVal); } } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, llvm::Value *rdval) { LLVMNode *rdnode = dg->getNode(rdval); if (!rdnode) { // that means that the value is not from this graph. // We need to add interprocedural edge llvm::Function *F = llvm::cast<llvm::Instruction>(rdval)->getParent()->getParent(); LLVMNode *entryNode = dg->getGlobalNode(F); assert(entryNode && "Don't have built function"); // get the graph where the node lives LLVMDependenceGraph *graph = entryNode->getDG(); assert(graph != dg && "Cannot find a node"); rdnode = graph->getNode(rdval); if (!rdnode) { llvmutils::printerr("ERROR: DG has not val: ", rdval); return; } } assert(rdnode); rdnode->addDataDependence(node); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, RDNode *rd) { llvm::Value *rdval = rd->getUserData<llvm::Value>(); assert(rdval && "RDNode has not set the coresponding value"); addDataDependence(node, rdval); } // \param mem current reaching definitions point void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, PSNode *pts, RDNode *mem, uint64_t size) { using namespace dg::analysis; static std::set<const llvm::Value *> reported_mappings; for (const pta::Pointer& ptr : pts->pointsTo) { if (!ptr.isValid()) continue; llvm::Value *llvmVal = ptr.target->getUserData<llvm::Value>(); assert(llvmVal && "Don't have Value in PSNode"); RDNode *val = RD->getNode(llvmVal); if(!val) { if (reported_mappings.insert(llvmVal).second) llvmutils::printerr("DEF-USE: no information for: ", llvmVal); // XXX: shouldn't we set val to unknown location now? continue; } std::set<RDNode *> defs; // Get even reaching definitions for UNKNOWN_MEMORY. // Since those can be ours definitions, we must add them always mem->getReachingDefinitions(rd::UNKNOWN_MEMORY, UNKNOWN_OFFSET, UNKNOWN_OFFSET, defs); if (!defs.empty()) { for (RDNode *rd : defs) { assert(!rd->isUnknown() && "Unknown memory defined at unknown location?"); addDataDependence(node, rd); } defs.clear(); } mem->getReachingDefinitions(val, ptr.offset, size, defs); if (defs.empty()) { llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(llvmVal); if (!GV || !GV->hasInitializer()) { static std::set<const llvm::Value *> reported; if (reported.insert(llvmVal).second) { llvm::errs() << "No reaching definition for: " << *llvmVal << " off: " << *ptr.offset << "\n"; } } continue; } // add data dependence for (RDNode *rd : defs) { if (rd->isUnknown()) { // we don't know what definitions reach this node, // se we must add data dependence to all possible // write to this memory addUnknownDataDependence(node, pts); // we can bail out, since we have added all break; } addDataDependence(node, rd); } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ const llvm::Value *ptrOp, uint64_t size) { // get points-to information for the operand PSNode *pts = PTA->getPointsTo(ptrOp); //assert(pts && "Don't have points-to information for LoadInst"); if (!pts) { llvmutils::printerr("ERROR: No points-to: ", ptrOp); return; } addDataDependence(node, where, pts, size); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ PSNode *pts, /* what memory */ uint64_t size) { using namespace dg::analysis; // get the node from reaching definition where we have // all the reaching definitions RDNode *mem = RD->getMapping(where); if(!mem) { llvmutils::printerr("ERROR: Don't have mapping: ", where); return; } // take every memory the load inst can use and get the // reaching definition addDataDependence(node, pts, mem, size); } static uint64_t getAllocatedSize(llvm::Type *Ty, const llvm::DataLayout *DL) { // Type can be i8 *null or similar if (!Ty->isSized()) return UNKNOWN_OFFSET; return DL->getTypeAllocSize(Ty); } void LLVMDefUseAnalysis::handleLoadInst(llvm::LoadInst *Inst, LLVMNode *node) { using namespace dg::analysis; uint64_t size = getAllocatedSize(Inst->getType(), DL); addDataDependence(node, Inst, Inst->getPointerOperand(), size); } bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node, LLVMNode *prev) { Value *val = node->getKey(); (void) prev; if (LoadInst *Inst = dyn_cast<LoadInst>(val)) { handleLoadInst(Inst, node); } else if (isa<CallInst>(val)) { handleCallInst(node); /*} else if (StoreInst *Inst = dyn_cast<StoreInst>(val)) { handleStoreInst(Inst, node);*/ } /* just add direct def-use edges to every instruction */ if (Instruction *Inst = dyn_cast<Instruction>(val)) handleInstruction(Inst, node); // we will run only once return false; } } // namespace dg <commit_msg>llvm def-use: use getMemAllocationFunc<commit_after>#include <map> // ignore unused parameters in LLVM libraries #if (__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #endif #include <llvm/IR/Value.h> #include <llvm/IR/Instruction.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/IntrinsicInst.h> #include <llvm/IR/Constants.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/Module.h> #include <llvm/IR/DataLayout.h> #include <llvm/Support/raw_ostream.h> #if (__clang__) #pragma clang diagnostic pop // ignore -Wunused-parameter #else #pragma GCC diagnostic pop #endif #include "llvm/LLVMNode.h" #include "llvm/LLVMDependenceGraph.h" #include "llvm/llvm-utils.h" #include "llvm/analysis/PointsTo/PointsTo.h" #include "ReachingDefinitions/ReachingDefinitions.h" #include "DefUse.h" #include "analysis/PointsTo/PointerSubgraph.h" #include "analysis/DFS.h" using dg::analysis::rd::LLVMReachingDefinitions; using dg::analysis::rd::RDNode; using namespace llvm; /// -------------------------------------------------- // Add def-use edges /// -------------------------------------------------- namespace dg { static void handleInstruction(const Instruction *Inst, LLVMNode *node) { LLVMDependenceGraph *dg = node->getDG(); for (auto I = Inst->op_begin(), E = Inst->op_end(); I != E; ++I) { LLVMNode *op = dg->getNode(*I); if (op) op->addDataDependence(node); } } static void addReturnEdge(LLVMNode *callNode, LLVMDependenceGraph *subgraph) { // FIXME we may loose some accuracy here and // this edges causes that we'll go into subprocedure // even with summary edges if (!callNode->isVoidTy()) subgraph->getExit()->addDataDependence(callNode); } LLVMDefUseAnalysis::LLVMDefUseAnalysis(LLVMDependenceGraph *dg, LLVMReachingDefinitions *rd, LLVMPointerAnalysis *pta, bool assume_pure_funs) : analysis::DataFlowAnalysis<LLVMNode>(dg->getEntryBB(), analysis::DATAFLOW_INTERPROCEDURAL), dg(dg), RD(rd), PTA(pta), DL(new DataLayout(dg->getModule())), assume_pure_functions(assume_pure_funs) { assert(PTA && "Need points-to information"); assert(RD && "Need reaching definitions"); } void LLVMDefUseAnalysis::handleInlineAsm(LLVMNode *callNode) { CallInst *CI = cast<CallInst>(callNode->getValue()); LLVMDependenceGraph *dg = callNode->getDG(); // the last operand is the asm itself, so iterate only to e - 1 for (unsigned i = 0, e = CI->getNumOperands(); i < e - 1; ++i) { Value *opVal = CI->getOperand(i); if (!opVal->getType()->isPointerTy()) continue; LLVMNode *opNode = dg->getNode(opVal->stripInBoundsOffsets()); if (!opNode) { // FIXME: ConstantExpr llvmutils::printerr("WARN: unhandled inline asm operand: ", opVal); continue; } assert(opNode && "Do not have an operand for inline asm"); // if nothing else, this call at least uses the operands opNode->addDataDependence(callNode); } } void LLVMDefUseAnalysis::handleIntrinsicCall(LLVMNode *callNode, CallInst *CI) { static std::set<Instruction *> warnings; IntrinsicInst *I = cast<IntrinsicInst>(CI); Value *dest, *src = nullptr; switch (I->getIntrinsicID()) { case Intrinsic::memmove: case Intrinsic::memcpy: dest = I->getOperand(0); src = I->getOperand(1); break; case Intrinsic::memset: dest = I->getOperand(0); break; case Intrinsic::vastart: dest = I->getOperand(0); break; case Intrinsic::vaend: case Intrinsic::lifetime_start: case Intrinsic::lifetime_end: case Intrinsic::trap: case Intrinsic::bswap: case Intrinsic::prefetch: case Intrinsic::objectsize: // nothing to be done, direct def-use edges // will be added later return; case Intrinsic::stacksave: case Intrinsic::stackrestore: if (warnings.insert(CI).second) llvmutils::printerr("WARN: stack save/restore not implemented", CI); return; default: I->dump(); assert(0 && "DEF-USE: Unhandled intrinsic call"); handleUndefinedCall(callNode, CI); return; } // we must have dest set assert(dest); // these functions touch the memory of the pointers addDataDependence(callNode, CI, dest, UNKNOWN_OFFSET /* FIXME */); if (src) addDataDependence(callNode, CI, src, UNKNOWN_OFFSET /* FIXME */); } void LLVMDefUseAnalysis::handleUndefinedCall(LLVMNode *callNode, CallInst *CI) { if (assume_pure_functions) return; // the function is undefined - add the top-level dependencies and // also assume that this function use all the memory that is passed // via the pointers for (int e = CI->getNumArgOperands(), i = 0; i < e; ++i) { if (auto pts = PTA->getPointsTo(CI->getArgOperand(i))) { // the passed memory may be used in the undefined // function on the unknown offset addDataDependence(callNode, CI, pts, UNKNOWN_OFFSET); } } } void LLVMDefUseAnalysis::handleCallInst(LLVMNode *node) { CallInst *CI = cast<CallInst>(node->getKey()); if (CI->isInlineAsm()) { handleInlineAsm(node); return; } Function *func = dyn_cast<Function>(CI->getCalledValue()->stripPointerCasts()); if (func) { if (func->isIntrinsic() && !isa<DbgInfoIntrinsic>(CI)) { handleIntrinsicCall(node, CI); return; } // for realloc, we need to make it data dependent on the // memory it reallocates, since that is the memory it copies if (func->size() == 0) { using dg::MemAllocationFuncs; MemAllocationFuncs type = getMemAllocationFunc(func); if (type == MemAllocationFuncs::REALLOC) { addDataDependence(node, CI, CI->getOperand(0), UNKNOWN_OFFSET /* FIXME */); } else if (type == MemAllocationFuncs::NONEMEM) { handleUndefinedCall(node, CI); }// else { // we do not want to do anything for the memory // allocation functions // } // the function is undefined, so do not even try to // add the edges from return statements return; } } // add edges from the return nodes of subprocedure // to the call (if the call returns something) for (LLVMDependenceGraph *subgraph : node->getSubgraphs()) addReturnEdge(node, subgraph); } // Add data dependence edges from all memory location that may write // to memory pointed by 'pts' to 'node' void LLVMDefUseAnalysis::addUnknownDataDependence(LLVMNode *node, PSNode *pts) { // iterate over all nodes from ReachingDefinitions Subgraph. It is faster than // going over all llvm nodes and querying the pointer to analysis for (auto& it : RD->getNodesMap()) { RDNode *rdnode = it.second; // only STORE may be a definition site if (rdnode->getType() != analysis::rd::RDNodeType::STORE) continue; llvm::Value *rdVal = rdnode->getUserData<llvm::Value>(); // artificial node? if (!rdVal) continue; // does this store define some value that is in pts? for (const analysis::rd::DefSite& ds : rdnode->getDefines()) { llvm::Value *llvmVal = ds.target->getUserData<llvm::Value>(); // is this an artificial node? if (!llvmVal) continue; // if these two sets have an over-lap, we must add the data dependence for (const auto& ptr : pts->pointsTo) if (ptr.target->getUserData<llvm::Value>() == llvmVal) { addDataDependence(node, rdVal); } } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, llvm::Value *rdval) { LLVMNode *rdnode = dg->getNode(rdval); if (!rdnode) { // that means that the value is not from this graph. // We need to add interprocedural edge llvm::Function *F = llvm::cast<llvm::Instruction>(rdval)->getParent()->getParent(); LLVMNode *entryNode = dg->getGlobalNode(F); assert(entryNode && "Don't have built function"); // get the graph where the node lives LLVMDependenceGraph *graph = entryNode->getDG(); assert(graph != dg && "Cannot find a node"); rdnode = graph->getNode(rdval); if (!rdnode) { llvmutils::printerr("ERROR: DG has not val: ", rdval); return; } } assert(rdnode); rdnode->addDataDependence(node); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, RDNode *rd) { llvm::Value *rdval = rd->getUserData<llvm::Value>(); assert(rdval && "RDNode has not set the coresponding value"); addDataDependence(node, rdval); } // \param mem current reaching definitions point void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, PSNode *pts, RDNode *mem, uint64_t size) { using namespace dg::analysis; static std::set<const llvm::Value *> reported_mappings; for (const pta::Pointer& ptr : pts->pointsTo) { if (!ptr.isValid()) continue; llvm::Value *llvmVal = ptr.target->getUserData<llvm::Value>(); assert(llvmVal && "Don't have Value in PSNode"); RDNode *val = RD->getNode(llvmVal); if(!val) { if (reported_mappings.insert(llvmVal).second) llvmutils::printerr("DEF-USE: no information for: ", llvmVal); // XXX: shouldn't we set val to unknown location now? continue; } std::set<RDNode *> defs; // Get even reaching definitions for UNKNOWN_MEMORY. // Since those can be ours definitions, we must add them always mem->getReachingDefinitions(rd::UNKNOWN_MEMORY, UNKNOWN_OFFSET, UNKNOWN_OFFSET, defs); if (!defs.empty()) { for (RDNode *rd : defs) { assert(!rd->isUnknown() && "Unknown memory defined at unknown location?"); addDataDependence(node, rd); } defs.clear(); } mem->getReachingDefinitions(val, ptr.offset, size, defs); if (defs.empty()) { llvm::GlobalVariable *GV = llvm::dyn_cast<llvm::GlobalVariable>(llvmVal); if (!GV || !GV->hasInitializer()) { static std::set<const llvm::Value *> reported; if (reported.insert(llvmVal).second) { llvm::errs() << "No reaching definition for: " << *llvmVal << " off: " << *ptr.offset << "\n"; } } continue; } // add data dependence for (RDNode *rd : defs) { if (rd->isUnknown()) { // we don't know what definitions reach this node, // se we must add data dependence to all possible // write to this memory addUnknownDataDependence(node, pts); // we can bail out, since we have added all break; } addDataDependence(node, rd); } } } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ const llvm::Value *ptrOp, uint64_t size) { // get points-to information for the operand PSNode *pts = PTA->getPointsTo(ptrOp); //assert(pts && "Don't have points-to information for LoadInst"); if (!pts) { llvmutils::printerr("ERROR: No points-to: ", ptrOp); return; } addDataDependence(node, where, pts, size); } void LLVMDefUseAnalysis::addDataDependence(LLVMNode *node, const llvm::Value *where, /* in CFG */ PSNode *pts, /* what memory */ uint64_t size) { using namespace dg::analysis; // get the node from reaching definition where we have // all the reaching definitions RDNode *mem = RD->getMapping(where); if(!mem) { llvmutils::printerr("ERROR: Don't have mapping: ", where); return; } // take every memory the load inst can use and get the // reaching definition addDataDependence(node, pts, mem, size); } static uint64_t getAllocatedSize(llvm::Type *Ty, const llvm::DataLayout *DL) { // Type can be i8 *null or similar if (!Ty->isSized()) return UNKNOWN_OFFSET; return DL->getTypeAllocSize(Ty); } void LLVMDefUseAnalysis::handleLoadInst(llvm::LoadInst *Inst, LLVMNode *node) { using namespace dg::analysis; uint64_t size = getAllocatedSize(Inst->getType(), DL); addDataDependence(node, Inst, Inst->getPointerOperand(), size); } bool LLVMDefUseAnalysis::runOnNode(LLVMNode *node, LLVMNode *prev) { Value *val = node->getKey(); (void) prev; if (LoadInst *Inst = dyn_cast<LoadInst>(val)) { handleLoadInst(Inst, node); } else if (isa<CallInst>(val)) { handleCallInst(node); /*} else if (StoreInst *Inst = dyn_cast<StoreInst>(val)) { handleStoreInst(Inst, node);*/ } /* just add direct def-use edges to every instruction */ if (Instruction *Inst = dyn_cast<Instruction>(val)) handleInstruction(Inst, node); // we will run only once return false; } } // namespace dg <|endoftext|>
<commit_before>#include <stan/math/rev/mat.hpp> #include <stan/math/rev/mat/fun/typedefs.hpp> #include <gtest/gtest.h> #include <vector> #if defined(STAN_OPENCL) && !defined(STAN_OPENCL_NOCACHE) #include <CL/cl.hpp> #endif TEST(AgradPartialsVari, OperandsAndPartialsScal) { using stan::math::operands_and_partials; using stan::math::var; double d1; operands_and_partials<double> o3(d1); EXPECT_EQ(5, sizeof(o3)); var v1 = var(0.0); std::vector<var> v_stdvec; v_stdvec.push_back(v1); operands_and_partials<var> o4(v1); o4.edge1_.partials_[0] += 10.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); } TEST(AgradPartialsVari, OperandsAndPartialsVec) { using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; vector_d d_vec(4); operands_and_partials<vector_d> o3(d_vec); EXPECT_EQ(6, sizeof(o3)); vector_v v_vec(4); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_vec << v1, v2, v3, v4; std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<vector_v> o4(v_vec); o4.edge1_.partials_[0] += 10.0; o4.edge1_.partials_[1] += 20.0; o4.edge1_.partials_[2] += 30.0; o4.edge1_.partials_[3] += 40.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsStdVec) { using stan::math::operands_and_partials; using stan::math::var; std::vector<double> d_vec(4); operands_and_partials<std::vector<double> > o3(d_vec); EXPECT_EQ(5, sizeof(o3)); std::vector<var> v_vec; var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_vec.push_back(v1); v_vec.push_back(v2); v_vec.push_back(v3); v_vec.push_back(v4); operands_and_partials<std::vector<var> > o4(v_vec); o4.edge1_.partials_[0] += 10.0; o4.edge1_.partials_[1] += 20.0; o4.edge1_.partials_[2] += 30.0; o4.edge1_.partials_[3] += 40.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_vec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsMat) { using stan::math::matrix_d; using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; matrix_d d_mat(2, 2); d_mat << 10.0, 20.0, 30.0, 40.0; operands_and_partials<matrix_d> o3(d_mat); EXPECT_EQ(6, sizeof(o3)); matrix_v v_mat(2, 2); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_mat << v1, v2, v3, v4; std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<matrix_v> o4(v_mat); o4.edge1_.partials_ += d_mat; o4.edge1_.partials_vec_[1] += d_mat; // Should affect the same vars as the call above o4.edge1_.partials_vec_[27] += d_mat; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(30.0, grad[0]); EXPECT_FLOAT_EQ(60.0, grad[1]); EXPECT_FLOAT_EQ(90.0, grad[2]); EXPECT_FLOAT_EQ(120.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsMatMultivar) { using stan::math::matrix_d; using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; matrix_d d_mat(2, 2); d_mat << 10.0, 20.0, 30.0, 40.0; std::vector<matrix_d> d_mat_vec; d_mat_vec.push_back(d_mat); operands_and_partials<std::vector<matrix_d> > o3(d_mat_vec); EXPECT_EQ(5, sizeof(o3)); matrix_v v_mat1(2, 2); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_mat1 << v1, v2, v3, v4; matrix_v v_mat2(2, 2); var v5 = var(0.1); var v6 = var(1.1); var v7 = var(2.1); var v8 = var(3.1); v_mat2 << v5, v6, v7, v8; std::vector<matrix_v> v_mat_vec; v_mat_vec.push_back(v_mat1); v_mat_vec.push_back(v_mat2); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); v_stdvec.push_back(v5); v_stdvec.push_back(v6); v_stdvec.push_back(v7); v_stdvec.push_back(v8); operands_and_partials<std::vector<matrix_v> > o4(v_mat_vec); o4.edge1_.partials_vec_[0] += d_mat; // Should NOT affect the same vars as the call above o4.edge1_.partials_vec_[1] += d_mat; o4.edge1_.partials_vec_[1] += d_mat; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); EXPECT_FLOAT_EQ(20.0, grad[4]); EXPECT_FLOAT_EQ(40.0, grad[5]); EXPECT_FLOAT_EQ(60.0, grad[6]); EXPECT_FLOAT_EQ(80.0, grad[7]); } TEST(AgradPartialsVari, OperandsAndPartialsMultivar) { using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; std::vector<vector_d> d_vec_vec(2); vector_d d_vec1(2); d_vec1 << 10.0, 20.0; vector_d d_vec2(2); d_vec2 << 30.0, 40.0; d_vec_vec.push_back(d_vec1); d_vec_vec.push_back(d_vec2); operands_and_partials<std::vector<vector_d> > o3(d_vec_vec); EXPECT_EQ(5, sizeof(o3)); vector_v v_vec1(2); var v1 = var(0.0); var v2 = var(1.0); v_vec1 << v1, v2; vector_v v_vec2(2); var v3 = var(2.0); var v4 = var(3.0); v_vec2 << v3, v4; std::vector<vector_v> v_vec; v_vec.push_back(v_vec1); v_vec.push_back(v_vec2); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<std::vector<vector_v> > o4(v_vec); o4.edge1_.partials_vec_[0] += d_vec1; o4.edge1_.partials_vec_[1] += d_vec2; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } // XXX Test mixed - operands_and_partials<std::vector<matrix_v>, // vector_d, vector_v> TEST(AgradPartialsVari, OperandsAndPartialsMultivarMixed) { using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; std::vector<vector_d> d_vec_vec(2); vector_d d_vec1(2); d_vec1 << 10.0, 20.0; vector_d d_vec2(2); d_vec2 << 30.0, 40.0; d_vec_vec.push_back(d_vec1); d_vec_vec.push_back(d_vec2); vector_v v_vec1(2); var v1 = var(0.0); var v2 = var(1.0); v_vec1 << v1, v2; vector_v v_vec2(2); var v3 = var(2.0); var v4 = var(3.0); v_vec2 << v3, v4; std::vector<vector_v> v_vec; v_vec.push_back(v_vec1); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<std::vector<vector_v>, std::vector<vector_d>, vector_v> o4(v_vec, d_vec_vec, v_vec2); o4.edge1_.partials_vec_[0] += d_vec1; o4.edge3_.partials_vec_[0] += d_vec2; #if defined(STAN_OPENCL) && !defined(STAN_OPENCL_NOCACHE) EXPECT_EQ(2 * sizeof(d_vec1) + 6 * sizeof(&v_vec) - sizeof(cl::Buffer), sizeof(o4)); #else // 2 partials stdvecs, 4 pointers to edges, 2 pointers to operands // vecs EXPECT_EQ(2 * sizeof(d_vec1) + 6 * sizeof(&v_vec), sizeof(o4)); #endif std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); // when given vector_d in place of vector_v all expressions must // still compile operands_and_partials<std::vector<vector_v>, std::vector<vector_d>, vector_d> o5(v_vec, d_vec_vec, d_vec2); o5.edge1_.partials_vec_[0] += d_vec1; if (false) { // the test here is to make things compile as this pattern to // if-out things when terms are const is used in our functions o5.edge3_.partials_vec_[0] += vector_d(); o5.edge3_.partials_vec_[0] -= vector_d(); o5.edge3_.partials_vec_[0](0) = 0; } // the same needs to work for the nested case operands_and_partials<std::vector<vector_d>, std::vector<vector_d>, vector_v> o6(d_vec_vec, d_vec_vec, v_vec2); if (false) { // the test here is to make things compile as this pattern to // if-out things when terms are const is used in our functions o6.edge1_.partials_vec_[0] += d_vec1; } o6.edge3_.partials_vec_[0] += d_vec2; } <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0 (tags/google/stable/2017-11-14)<commit_after>#include <stan/math/rev/mat.hpp> #include <stan/math/rev/mat/fun/typedefs.hpp> #include <gtest/gtest.h> #include <vector> #if defined(STAN_OPENCL) && !defined(STAN_OPENCL_NOCACHE) #include <CL/cl.hpp> #endif TEST(AgradPartialsVari, OperandsAndPartialsScal) { using stan::math::operands_and_partials; using stan::math::var; double d1; operands_and_partials<double> o3(d1); EXPECT_EQ(5, sizeof(o3)); var v1 = var(0.0); std::vector<var> v_stdvec; v_stdvec.push_back(v1); operands_and_partials<var> o4(v1); o4.edge1_.partials_[0] += 10.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); } TEST(AgradPartialsVari, OperandsAndPartialsVec) { using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; vector_d d_vec(4); operands_and_partials<vector_d> o3(d_vec); EXPECT_EQ(6, sizeof(o3)); vector_v v_vec(4); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_vec << v1, v2, v3, v4; std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<vector_v> o4(v_vec); o4.edge1_.partials_[0] += 10.0; o4.edge1_.partials_[1] += 20.0; o4.edge1_.partials_[2] += 30.0; o4.edge1_.partials_[3] += 40.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsStdVec) { using stan::math::operands_and_partials; using stan::math::var; std::vector<double> d_vec(4); operands_and_partials<std::vector<double> > o3(d_vec); EXPECT_EQ(5, sizeof(o3)); std::vector<var> v_vec; var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_vec.push_back(v1); v_vec.push_back(v2); v_vec.push_back(v3); v_vec.push_back(v4); operands_and_partials<std::vector<var> > o4(v_vec); o4.edge1_.partials_[0] += 10.0; o4.edge1_.partials_[1] += 20.0; o4.edge1_.partials_[2] += 30.0; o4.edge1_.partials_[3] += 40.0; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_vec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsMat) { using stan::math::matrix_d; using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; matrix_d d_mat(2, 2); d_mat << 10.0, 20.0, 30.0, 40.0; operands_and_partials<matrix_d> o3(d_mat); EXPECT_EQ(6, sizeof(o3)); matrix_v v_mat(2, 2); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_mat << v1, v2, v3, v4; std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<matrix_v> o4(v_mat); o4.edge1_.partials_ += d_mat; o4.edge1_.partials_vec_[1] += d_mat; // Should affect the same vars as the call above o4.edge1_.partials_vec_[27] += d_mat; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(30.0, grad[0]); EXPECT_FLOAT_EQ(60.0, grad[1]); EXPECT_FLOAT_EQ(90.0, grad[2]); EXPECT_FLOAT_EQ(120.0, grad[3]); } TEST(AgradPartialsVari, OperandsAndPartialsMatMultivar) { using stan::math::matrix_d; using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; matrix_d d_mat(2, 2); d_mat << 10.0, 20.0, 30.0, 40.0; std::vector<matrix_d> d_mat_vec; d_mat_vec.push_back(d_mat); operands_and_partials<std::vector<matrix_d> > o3(d_mat_vec); EXPECT_EQ(5, sizeof(o3)); matrix_v v_mat1(2, 2); var v1 = var(0.0); var v2 = var(1.0); var v3 = var(2.0); var v4 = var(3.0); v_mat1 << v1, v2, v3, v4; matrix_v v_mat2(2, 2); var v5 = var(0.1); var v6 = var(1.1); var v7 = var(2.1); var v8 = var(3.1); v_mat2 << v5, v6, v7, v8; std::vector<matrix_v> v_mat_vec; v_mat_vec.push_back(v_mat1); v_mat_vec.push_back(v_mat2); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); v_stdvec.push_back(v5); v_stdvec.push_back(v6); v_stdvec.push_back(v7); v_stdvec.push_back(v8); operands_and_partials<std::vector<matrix_v> > o4(v_mat_vec); o4.edge1_.partials_vec_[0] += d_mat; // Should NOT affect the same vars as the call above o4.edge1_.partials_vec_[1] += d_mat; o4.edge1_.partials_vec_[1] += d_mat; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); EXPECT_FLOAT_EQ(20.0, grad[4]); EXPECT_FLOAT_EQ(40.0, grad[5]); EXPECT_FLOAT_EQ(60.0, grad[6]); EXPECT_FLOAT_EQ(80.0, grad[7]); } TEST(AgradPartialsVari, OperandsAndPartialsMultivar) { using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; std::vector<vector_d> d_vec_vec(2); vector_d d_vec1(2); d_vec1 << 10.0, 20.0; vector_d d_vec2(2); d_vec2 << 30.0, 40.0; d_vec_vec.push_back(d_vec1); d_vec_vec.push_back(d_vec2); operands_and_partials<std::vector<vector_d> > o3(d_vec_vec); EXPECT_EQ(5, sizeof(o3)); vector_v v_vec1(2); var v1 = var(0.0); var v2 = var(1.0); v_vec1 << v1, v2; vector_v v_vec2(2); var v3 = var(2.0); var v4 = var(3.0); v_vec2 << v3, v4; std::vector<vector_v> v_vec; v_vec.push_back(v_vec1); v_vec.push_back(v_vec2); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<std::vector<vector_v> > o4(v_vec); o4.edge1_.partials_vec_[0] += d_vec1; o4.edge1_.partials_vec_[1] += d_vec2; std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); } // XXX Test mixed - operands_and_partials<std::vector<matrix_v>, // vector_d, vector_v> TEST(AgradPartialsVari, OperandsAndPartialsMultivarMixed) { using stan::math::matrix_v; using stan::math::operands_and_partials; using stan::math::var; using stan::math::vector_d; using stan::math::vector_v; std::vector<vector_d> d_vec_vec(2); vector_d d_vec1(2); d_vec1 << 10.0, 20.0; vector_d d_vec2(2); d_vec2 << 30.0, 40.0; d_vec_vec.push_back(d_vec1); d_vec_vec.push_back(d_vec2); vector_v v_vec1(2); var v1 = var(0.0); var v2 = var(1.0); v_vec1 << v1, v2; vector_v v_vec2(2); var v3 = var(2.0); var v4 = var(3.0); v_vec2 << v3, v4; std::vector<vector_v> v_vec; v_vec.push_back(v_vec1); std::vector<var> v_stdvec; v_stdvec.push_back(v1); v_stdvec.push_back(v2); v_stdvec.push_back(v3); v_stdvec.push_back(v4); operands_and_partials<std::vector<vector_v>, std::vector<vector_d>, vector_v> o4(v_vec, d_vec_vec, v_vec2); o4.edge1_.partials_vec_[0] += d_vec1; o4.edge3_.partials_vec_[0] += d_vec2; #if defined(STAN_OPENCL) && !defined(STAN_OPENCL_NOCACHE) EXPECT_EQ(2 * sizeof(d_vec1) + 6 * sizeof(&v_vec) - sizeof(cl::Buffer), sizeof(o4)); #else // 2 partials stdvecs, 4 pointers to edges, 2 pointers to operands // vecs EXPECT_EQ(2 * sizeof(d_vec1) + 6 * sizeof(&v_vec), sizeof(o4)); #endif std::vector<double> grad; var v = o4.build(10.0); v.grad(v_stdvec, grad); EXPECT_FLOAT_EQ(10.0, v.val()); EXPECT_FLOAT_EQ(10.0, grad[0]); EXPECT_FLOAT_EQ(20.0, grad[1]); EXPECT_FLOAT_EQ(30.0, grad[2]); EXPECT_FLOAT_EQ(40.0, grad[3]); // when given vector_d in place of vector_v all expressions must // still compile operands_and_partials<std::vector<vector_v>, std::vector<vector_d>, vector_d> o5(v_vec, d_vec_vec, d_vec2); o5.edge1_.partials_vec_[0] += d_vec1; if (false) { // the test here is to make things compile as this pattern to // if-out things when terms are const is used in our functions o5.edge3_.partials_vec_[0] += vector_d(); o5.edge3_.partials_vec_[0] -= vector_d(); o5.edge3_.partials_vec_[0](0) = 0; } // the same needs to work for the nested case operands_and_partials<std::vector<vector_d>, std::vector<vector_d>, vector_v> o6(d_vec_vec, d_vec_vec, v_vec2); if (false) { // the test here is to make things compile as this pattern to // if-out things when terms are const is used in our functions o6.edge1_.partials_vec_[0] += d_vec1; } o6.edge3_.partials_vec_[0] += d_vec2; } <|endoftext|>
<commit_before>#include <qtest.h> #include <QtDeclarative/qmlcomponent.h> #include <QtDeclarative/qmlengine.h> class MyQmlObject : public QObject { Q_OBJECT Q_PROPERTY(bool trueProperty READ trueProperty) Q_PROPERTY(bool falseProperty READ falseProperty) Q_PROPERTY(QString stringProperty READ stringProperty WRITE setStringProperty NOTIFY stringChanged) public: MyQmlObject(): m_methodCalled(false), m_methodIntCalled(false) {} bool trueProperty() const { return true; } bool falseProperty() const { return false; } QString stringProperty() const { return m_string; } void setStringProperty(const QString &s) { if (s == m_string) return; m_string = s; emit stringChanged(); } bool methodCalled() const { return m_methodCalled; } bool methodIntCalled() const { return m_methodIntCalled; } QString string() const { return m_string; } signals: void basicSignal(); void argumentSignal(int a, QString b, qreal c); void stringChanged(); public slots: void method() { m_methodCalled = true; } void method(int a) { if(a == 163) m_methodIntCalled = true; } void setString(const QString &s) { m_string = s; } private: friend class tst_qmlbindengine; bool m_methodCalled; bool m_methodIntCalled; QString m_string; }; QML_DECLARE_TYPE(MyQmlObject); QML_DEFINE_TYPE(MyQmlObject,MyQmlObject); class MyQmlContainer : public QObject { Q_OBJECT Q_PROPERTY(QList<MyQmlContainer*>* children READ children) public: MyQmlContainer() {} QList<MyQmlContainer*> *children() { return &m_children; } private: QList<MyQmlContainer*> m_children; }; QML_DECLARE_TYPE(MyQmlContainer); QML_DEFINE_TYPE(MyQmlContainer,MyQmlContainer); class tst_qmlbindengine : public QObject { Q_OBJECT public: tst_qmlbindengine() {} private slots: void boolPropertiesEvaluateAsBool(); void methods(); void signalAssignment(); void bindingLoop(); private: QmlEngine engine; }; void tst_qmlbindengine::boolPropertiesEvaluateAsBool() { { QmlComponent component(&engine, "MyQmlObject { stringProperty: trueProperty?'pass':'fail' }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->stringProperty(), QLatin1String("pass")); } { QmlComponent component(&engine, "MyQmlObject { stringProperty: falseProperty?'fail':'pass' }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->stringProperty(), QLatin1String("pass")); } } void tst_qmlbindengine::signalAssignment() { { QmlComponent component(&engine, "MyQmlObject { onBasicSignal: setString('pass') }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->string(), QString()); emit object->basicSignal(); QCOMPARE(object->string(), QString("pass")); } { QmlComponent component(&engine, "MyQmlObject { onArgumentSignal: setString('pass ' + a + ' ' + b + ' ' + c) }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->string(), QString()); emit object->argumentSignal(19, "Hello world!", 10.3); QCOMPARE(object->string(), QString("pass 19 Hello world! 10.3")); } } void tst_qmlbindengine::methods() { { QmlComponent component(&engine, "MyQmlObject { id: MyObject; onBasicSignal: MyObject.method() }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), false); emit object->basicSignal(); QCOMPARE(object->methodCalled(), true); QCOMPARE(object->methodIntCalled(), false); } { QmlComponent component(&engine, "MyQmlObject { id: MyObject; onBasicSignal: MyObject.method(163) }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), false); emit object->basicSignal(); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), true); } } #include <QDebug> void tst_qmlbindengine::bindingLoop() { QmlComponent component(&engine, "MyQmlContainer { children : [ "\ "MyQmlObject { id: Object1; stringProperty: \"hello\" + Object2.stringProperty }, "\ "MyQmlObject { id: Object2; stringProperty: \"hello\" + Object1.stringProperty } ] }"); //### ignoreMessage doesn't seem to work here //QTest::ignoreMessage(QtWarningMsg, "QML MyQmlObject (unknown location): Binding loop detected for property \"stringProperty\""); QObject *object = component.create(); QVERIFY(object != 0); } QTEST_MAIN(tst_qmlbindengine) #include "tst_qmlbindengine.moc" <commit_msg>Add context property test<commit_after>#include <qtest.h> #include <QtDeclarative/qmlcomponent.h> #include <QtDeclarative/qmlengine.h> #include <QtDeclarative/qmlexpression.h> #include <QtDeclarative/qmlcontext.h> class MyQmlObject : public QObject { Q_OBJECT Q_PROPERTY(bool trueProperty READ trueProperty) Q_PROPERTY(bool falseProperty READ falseProperty) Q_PROPERTY(QString stringProperty READ stringProperty WRITE setStringProperty NOTIFY stringChanged) public: MyQmlObject(): m_methodCalled(false), m_methodIntCalled(false) {} bool trueProperty() const { return true; } bool falseProperty() const { return false; } QString stringProperty() const { return m_string; } void setStringProperty(const QString &s) { if (s == m_string) return; m_string = s; emit stringChanged(); } bool methodCalled() const { return m_methodCalled; } bool methodIntCalled() const { return m_methodIntCalled; } QString string() const { return m_string; } signals: void basicSignal(); void argumentSignal(int a, QString b, qreal c); void stringChanged(); public slots: void method() { m_methodCalled = true; } void method(int a) { if(a == 163) m_methodIntCalled = true; } void setString(const QString &s) { m_string = s; } private: friend class tst_qmlbindengine; bool m_methodCalled; bool m_methodIntCalled; QString m_string; }; QML_DECLARE_TYPE(MyQmlObject); QML_DEFINE_TYPE(MyQmlObject,MyQmlObject); class MyQmlContainer : public QObject { Q_OBJECT Q_PROPERTY(QList<MyQmlContainer*>* children READ children) public: MyQmlContainer() {} QList<MyQmlContainer*> *children() { return &m_children; } private: QList<MyQmlContainer*> m_children; }; QML_DECLARE_TYPE(MyQmlContainer); QML_DEFINE_TYPE(MyQmlContainer,MyQmlContainer); class tst_qmlbindengine : public QObject { Q_OBJECT public: tst_qmlbindengine() {} private slots: void boolPropertiesEvaluateAsBool(); void methods(); void signalAssignment(); void bindingLoop(); void contextPropertiesTriggerReeval(); private: QmlEngine engine; }; void tst_qmlbindengine::boolPropertiesEvaluateAsBool() { { QmlComponent component(&engine, "MyQmlObject { stringProperty: trueProperty?'pass':'fail' }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->stringProperty(), QLatin1String("pass")); } { QmlComponent component(&engine, "MyQmlObject { stringProperty: falseProperty?'fail':'pass' }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->stringProperty(), QLatin1String("pass")); } } void tst_qmlbindengine::signalAssignment() { { QmlComponent component(&engine, "MyQmlObject { onBasicSignal: setString('pass') }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->string(), QString()); emit object->basicSignal(); QCOMPARE(object->string(), QString("pass")); } { QmlComponent component(&engine, "MyQmlObject { onArgumentSignal: setString('pass ' + a + ' ' + b + ' ' + c) }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->string(), QString()); emit object->argumentSignal(19, "Hello world!", 10.3); QCOMPARE(object->string(), QString("pass 19 Hello world! 10.3")); } } void tst_qmlbindengine::methods() { { QmlComponent component(&engine, "MyQmlObject { id: MyObject; onBasicSignal: MyObject.method() }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), false); emit object->basicSignal(); QCOMPARE(object->methodCalled(), true); QCOMPARE(object->methodIntCalled(), false); } { QmlComponent component(&engine, "MyQmlObject { id: MyObject; onBasicSignal: MyObject.method(163) }"); MyQmlObject *object = qobject_cast<MyQmlObject *>(component.create()); QVERIFY(object != 0); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), false); emit object->basicSignal(); QCOMPARE(object->methodCalled(), false); QCOMPARE(object->methodIntCalled(), true); } } void tst_qmlbindengine::bindingLoop() { QmlComponent component(&engine, "MyQmlContainer { children : [ "\ "MyQmlObject { id: Object1; stringProperty: \"hello\" + Object2.stringProperty }, "\ "MyQmlObject { id: Object2; stringProperty: \"hello\" + Object1.stringProperty } ] }"); //### ignoreMessage doesn't seem to work here //QTest::ignoreMessage(QtWarningMsg, "QML MyQmlObject (unknown location): Binding loop detected for property \"stringProperty\""); QObject *object = component.create(); QVERIFY(object != 0); } class MyExpression : public QmlExpression { public: MyExpression(QmlContext *ctxt, const QString &expr) : QmlExpression(ctxt, expr, 0), changed(false) { } bool changed; }; void tst_qmlbindengine::contextPropertiesTriggerReeval() { QmlContext context(engine.rootContext()); context.setContextProperty("testProp", QVariant(1)); MyExpression expr(&context, "testProp + 1"); QCOMPARE(expr.changed, false); QCOMPARE(expr.value(), QVariant(2)); context.setContextProperty("testProp", QVariant(2)); QCOMPARE(expr.changed, true); QCOMPARE(expr.value(), QVariant(3)); } QTEST_MAIN(tst_qmlbindengine) #include "tst_qmlbindengine.moc" <|endoftext|>
<commit_before>/** \file undistort.cc Apply Lensfun corrections to a PNM file in place. This means, the original file is overwritten. The command line parameters are: - path to the PNM file - x coordinate of top left corner - y coordinate of top left corner - x coordinate of top right corner - y coordinate of top right corner - x coordinate of bottom left corner - y coordinate of bottom left corner - x coordinate of bottom right corner - y coordinate of bottom right corner All coordinates are pixel coordinates, with the top left of the image the origin. The corners must be the corners of a perfect rectangle which was taken a picture of, e.g. a sheet of paper. These are used for the perspective correction as well as the rotation, so that the edges of the rectangle are parellel to the image borders. The program returns the position and the dimensions of the rectangle <b>in the output image</b> to stdout in JSON format: \code{.json} [x₀, y₀, width, height] \endcode Here, x₀ and y₀ are the coordinates of the top left corner, and width and height are the dimensions of the rectangle. This program does not apply colour corrections such as vignetting correction, as those are handled by kamscan.py using flat field images. */ #include <fstream> #include <vector> #include <iterator> #include <iostream> #include <string> #include <algorithm> #include <cmath> #include "lensfun.h" /** Class for bitmap data. In case of 2 bytes per channel, network byte order is assumed. */ class Image { public: Image(int width, int height, int channel_size, int channels); Image() {}; Image(const Image &image); /** Get the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(int x, int y, int channel); /** Get the channel intensity at a certian coordinate. The coordinates are floats and may contain fractions. In this case, the intensity is calculated using bilinear interpolation between the four pixels around this coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(float x, float y, int channel); /** Set the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \param value raw integer value of the intensity of this channel at this position */ void set(int x, int y, int channel, int value); /** Determine the channel descriptions. This is used by Lensfun internally and necessary if you want to apply colour corrections, e.g. vignetting correction. \return the components of each pixel */ int components(); /** Determine the pixel format à la Lensfun. It is derived from channel_size. \return the pixel format as it is needed by Lensfun */ lfPixelFormat pixel_format(); int width, height; ///< width and height of the image in pixels int channels; ///< number of channels; may be 1 (greyscale) or 3 (RGB) /** the raw data (1:1 dump of the PNM content, without header) */ std::vector<unsigned char> data; private: friend std::istream& operator>>(std::istream &inputStream, Image &other); friend std::ostream& operator<<(std::ostream &outputStream, const Image &other); int channel_size; ///< width of one channel in bytes; may be 1 or 2 }; Image::Image(int width, int height, int channel_size, int channels) : width(width), height(height), channel_size(channel_size), channels(channels) { data.resize(width * height * channel_size * channels); } Image::Image(const Image &image) : width(image.width), height(image.height), channel_size(image.channel_size), channels(image.channels) { } int Image::get(int x, int y, int channel) { if (x < 0 || x >= width || y < 0 || y >= height) return 0; int position = channel_size * (channels * (y * width + x) + channel); int result = static_cast<int>(data[position]); if (channel_size == 2) result = (result << 8) + static_cast<int>(data[position + 1]); return result; } int Image::get(float x, float y, int channel) { float dummy; int x0 = static_cast<int>(x); int y0 = static_cast<int>(y); float i0 = static_cast<float>(get(x0, y0, channel)); float i1 = static_cast<float>(get(x0 + 1, y0, channel)); float i2 = static_cast<float>(get(x0, y0 + 1, channel)); float i3 = static_cast<float>(get(x0 + 1, y0 + 1, channel)); float fraction_x = std::modf(x, &dummy); float i01 = (1 - fraction_x) * i0 + fraction_x * i1; float i23 = (1 - fraction_x) * i2 + fraction_x * i3; float fraction_y = std::modf(y, &dummy); return static_cast<int>(std::round((1 - fraction_y) * i01 + fraction_y * i23)); } void Image::set(int x, int y, int channel, int value) { if (x >= 0 && x < width && y >= 0 && y < height) { int position = channel_size * (channels * (y * width + x) + channel); if (channel_size == 1) data[position] = static_cast<unsigned char>(value); else if (channel_size == 2) { data[position] = static_cast<unsigned char>(value >> 8); data[position + 1] = static_cast<unsigned char>(value & 256); } } } int Image::components() { switch (channels) { case 1: return LF_CR_1(INTENSITY); case 3: return LF_CR_3(RED, GREEN, BLUE); default: throw std::runtime_error("Invalid value of 'channels'."); } } lfPixelFormat Image::pixel_format() { switch (channel_size) { case 1: return LF_PF_U8; case 2: return LF_PF_U16; default: throw std::runtime_error("Invalid value of 'channel_size'."); } } std::istream& operator>>(std::istream &inputStream, Image &other) { std::string magic_number; int maximum_color_value; inputStream >> magic_number; if (magic_number == "P5") other.channels = 1; else if (magic_number == "P6") other.channels = 3; else throw std::runtime_error("Invalid input file. Must start with 'P5' or 'P6'."); inputStream >> other.width >> other.height >> maximum_color_value; inputStream.get(); // skip the trailing white space switch (maximum_color_value) { case 255: other.channel_size = 1; break; case 65535: other.channel_size = 2; break; default: throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535."); } size_t size = other.width * other.height * other.channel_size * other.channels; other.data.resize(size); inputStream.read(reinterpret_cast<char*>(other.data.data()), size); return inputStream; } std::ostream& operator<<(std::ostream &outputStream, const Image &other) { outputStream << (other.channels == 3 ? "P6" : "P5") << "\n" << other.width << " " << other.height << "\n" << (other.channel_size == 1 ? "255" : "65535") << "\n"; outputStream.write(reinterpret_cast<const char*>(other.data.data()), other.data.size()); return outputStream; } int main(int argc, char* argv[]) { if (argc != 10) { std::cerr << "You must give path to input file as well as all four corner coordinates.\n"; return -1; } lfDatabase ldb; if (ldb.Load() != LF_NO_ERROR) { std::cerr << "Database could not be loaded\n"; return -1; } const lfCamera *camera; const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7"); if (cameras && !cameras[1]) camera = cameras[0]; else { std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n"; lf_free(cameras); return -1; } lf_free(cameras); const lfLens *lens; const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS (kamscan)"); if (lenses && !lenses[1]) { lens = lenses[0]; } else if (!lenses) { std::cerr << "Cannot find lens in database\n"; lf_free(lenses); return -1; } else { std::cerr << "Lens name ambiguous\n"; } lf_free(lenses); Image image; { std::ifstream file(argv[1], std::ios::binary); file >> image; } lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format()); lfModifier pc_coord_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); lfModifier back_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); if (!modifier.EnableDistortionCorrection(lens, 50) || !back_modifier.EnableDistortionCorrection(lens, 50) || !pc_coord_modifier.EnableDistortionCorrection(lens, 50)) { std::cerr << "Failed to activate undistortion\n"; return -1; } if (image.channels == 3) if (!modifier.EnableTCACorrection(lens, 50)) { std::cerr << "Failed to activate un-TCA\n"; return -1; } std::vector<float> x, y; x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[6])); y.push_back(std::stof(argv[7])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); x.push_back(std::stof(argv[8])); y.push_back(std::stof(argv[9])); x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); std::vector<float> x_undist, y_undist; for (int i = 0; i < x.size(); i++) { float result[2]; pc_coord_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x_undist.push_back(result[0]); y_undist.push_back(result[1]); } if (!modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0) || !back_modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0)) { std::cerr << "Failed to activate perspective correction\n"; return -1; } std::vector<float> res(image.width * image.height * 2 * image.channels); if (image.channels == 3) modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data()); else modifier.ApplyGeometryDistortion(0, 0, image.width, image.height, res.data()); Image new_image = image; for (int x = 0; x < image.width; x++) for (int y = 0; y < image.height; y++) { int position = 2 * image.channels * (y * image.width + x); float source_x_R = res[position]; float source_y_R = res[position + 1]; new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0)); if (image.channels == 3) { float source_x_G = res[position + 2]; float source_y_G = res[position + 3]; float source_x_B = res[position + 4]; float source_y_B = res[position + 5]; new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1)); new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2)); } } std::ofstream file(argv[1], std::ios::binary); file << new_image; for (int i = 0; i < 4; i++) { float result[2]; back_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x[i] = result[0]; y[i] = result[1]; } std::cout << "[" << std::min(x[0], x[2]) << ", " << std::min(y[0], y[1]) << ", " << std::max(x[1], x[3]) - std::min(x[0], x[2]) << ", " << std::max(y[2], y[3]) - std::min(y[0], y[1]) << "]\n"; return 0; } <commit_msg>Added notice that undistort only works for the Sony E 50mm f/1.8 OSS.<commit_after>/** \file undistort.cc Apply Lensfun corrections to a PNM file in place. This means, the original file is overwritten. The command line parameters are: - path to the PNM file - x coordinate of top left corner - y coordinate of top left corner - x coordinate of top right corner - y coordinate of top right corner - x coordinate of bottom left corner - y coordinate of bottom left corner - x coordinate of bottom right corner - y coordinate of bottom right corner All coordinates are pixel coordinates, with the top left of the image the origin. The corners must be the corners of a perfect rectangle which was taken a picture of, e.g. a sheet of paper. These are used for the perspective correction as well as the rotation, so that the edges of the rectangle are parellel to the image borders. The program returns the position and the dimensions of the rectangle <b>in the output image</b> to stdout in JSON format: \code{.json} [x₀, y₀, width, height] \endcode Here, x₀ and y₀ are the coordinates of the top left corner, and width and height are the dimensions of the rectangle. This program does not apply colour corrections such as vignetting correction, as those are handled by kamscan.py using flat field images. \b Important: This program has my lens hardcoded into it, the 50mm f/1.8 OSS for the Sony E mount. It was necessary to make a special calibration for the finite distance to the subject. Lensfun contains corrections for focus at infinity. */ #include <fstream> #include <vector> #include <iterator> #include <iostream> #include <string> #include <algorithm> #include <cmath> #include "lensfun.h" /** Class for bitmap data. In case of 2 bytes per channel, network byte order is assumed. */ class Image { public: Image(int width, int height, int channel_size, int channels); Image() {}; Image(const Image &image); /** Get the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(int x, int y, int channel); /** Get the channel intensity at a certian coordinate. The coordinates are floats and may contain fractions. In this case, the intensity is calculated using bilinear interpolation between the four pixels around this coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \return raw integer value of the intensity of this channel at this position */ int get(float x, float y, int channel); /** Set the channel intensity at a certian coordinate. \param x x coordinate \param y y coordinate \param channel index of the channel (for greyscale, it is always zero; for RGB, it is 0, 1, or 2) \param value raw integer value of the intensity of this channel at this position */ void set(int x, int y, int channel, int value); /** Determine the channel descriptions. This is used by Lensfun internally and necessary if you want to apply colour corrections, e.g. vignetting correction. \return the components of each pixel */ int components(); /** Determine the pixel format à la Lensfun. It is derived from channel_size. \return the pixel format as it is needed by Lensfun */ lfPixelFormat pixel_format(); int width, height; ///< width and height of the image in pixels int channels; ///< number of channels; may be 1 (greyscale) or 3 (RGB) /** the raw data (1:1 dump of the PNM content, without header) */ std::vector<unsigned char> data; private: friend std::istream& operator>>(std::istream &inputStream, Image &other); friend std::ostream& operator<<(std::ostream &outputStream, const Image &other); int channel_size; ///< width of one channel in bytes; may be 1 or 2 }; Image::Image(int width, int height, int channel_size, int channels) : width(width), height(height), channel_size(channel_size), channels(channels) { data.resize(width * height * channel_size * channels); } Image::Image(const Image &image) : width(image.width), height(image.height), channel_size(image.channel_size), channels(image.channels) { } int Image::get(int x, int y, int channel) { if (x < 0 || x >= width || y < 0 || y >= height) return 0; int position = channel_size * (channels * (y * width + x) + channel); int result = static_cast<int>(data[position]); if (channel_size == 2) result = (result << 8) + static_cast<int>(data[position + 1]); return result; } int Image::get(float x, float y, int channel) { float dummy; int x0 = static_cast<int>(x); int y0 = static_cast<int>(y); float i0 = static_cast<float>(get(x0, y0, channel)); float i1 = static_cast<float>(get(x0 + 1, y0, channel)); float i2 = static_cast<float>(get(x0, y0 + 1, channel)); float i3 = static_cast<float>(get(x0 + 1, y0 + 1, channel)); float fraction_x = std::modf(x, &dummy); float i01 = (1 - fraction_x) * i0 + fraction_x * i1; float i23 = (1 - fraction_x) * i2 + fraction_x * i3; float fraction_y = std::modf(y, &dummy); return static_cast<int>(std::round((1 - fraction_y) * i01 + fraction_y * i23)); } void Image::set(int x, int y, int channel, int value) { if (x >= 0 && x < width && y >= 0 && y < height) { int position = channel_size * (channels * (y * width + x) + channel); if (channel_size == 1) data[position] = static_cast<unsigned char>(value); else if (channel_size == 2) { data[position] = static_cast<unsigned char>(value >> 8); data[position + 1] = static_cast<unsigned char>(value & 256); } } } int Image::components() { switch (channels) { case 1: return LF_CR_1(INTENSITY); case 3: return LF_CR_3(RED, GREEN, BLUE); default: throw std::runtime_error("Invalid value of 'channels'."); } } lfPixelFormat Image::pixel_format() { switch (channel_size) { case 1: return LF_PF_U8; case 2: return LF_PF_U16; default: throw std::runtime_error("Invalid value of 'channel_size'."); } } std::istream& operator>>(std::istream &inputStream, Image &other) { std::string magic_number; int maximum_color_value; inputStream >> magic_number; if (magic_number == "P5") other.channels = 1; else if (magic_number == "P6") other.channels = 3; else throw std::runtime_error("Invalid input file. Must start with 'P5' or 'P6'."); inputStream >> other.width >> other.height >> maximum_color_value; inputStream.get(); // skip the trailing white space switch (maximum_color_value) { case 255: other.channel_size = 1; break; case 65535: other.channel_size = 2; break; default: throw std::runtime_error("Invalid PPM file: Maximum color value must be 255 or 65535."); } size_t size = other.width * other.height * other.channel_size * other.channels; other.data.resize(size); inputStream.read(reinterpret_cast<char*>(other.data.data()), size); return inputStream; } std::ostream& operator<<(std::ostream &outputStream, const Image &other) { outputStream << (other.channels == 3 ? "P6" : "P5") << "\n" << other.width << " " << other.height << "\n" << (other.channel_size == 1 ? "255" : "65535") << "\n"; outputStream.write(reinterpret_cast<const char*>(other.data.data()), other.data.size()); return outputStream; } int main(int argc, char* argv[]) { if (argc != 10) { std::cerr << "You must give path to input file as well as all four corner coordinates.\n"; return -1; } lfDatabase ldb; if (ldb.Load() != LF_NO_ERROR) { std::cerr << "Database could not be loaded\n"; return -1; } const lfCamera *camera; const lfCamera **cameras = ldb.FindCamerasExt(NULL, "NEX-7"); if (cameras && !cameras[1]) camera = cameras[0]; else { std::cerr << "Cannot find unique camera in database. " << sizeof(cameras) << " cameras found.\n"; lf_free(cameras); return -1; } lf_free(cameras); const lfLens *lens; const lfLens **lenses = ldb.FindLenses(camera, NULL, "E 50mm f/1.8 OSS (kamscan)"); if (lenses && !lenses[1]) { lens = lenses[0]; } else if (!lenses) { std::cerr << "Cannot find lens in database\n"; lf_free(lenses); return -1; } else { std::cerr << "Lens name ambiguous\n"; } lf_free(lenses); Image image; { std::ifstream file(argv[1], std::ios::binary); file >> image; } lfModifier modifier(camera->CropFactor, image.width, image.height, image.pixel_format()); lfModifier pc_coord_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); lfModifier back_modifier(camera->CropFactor, image.width, image.height, image.pixel_format(), true); if (!modifier.EnableDistortionCorrection(lens, 50) || !back_modifier.EnableDistortionCorrection(lens, 50) || !pc_coord_modifier.EnableDistortionCorrection(lens, 50)) { std::cerr << "Failed to activate undistortion\n"; return -1; } if (image.channels == 3) if (!modifier.EnableTCACorrection(lens, 50)) { std::cerr << "Failed to activate un-TCA\n"; return -1; } std::vector<float> x, y; x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[6])); y.push_back(std::stof(argv[7])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); x.push_back(std::stof(argv[8])); y.push_back(std::stof(argv[9])); x.push_back(std::stof(argv[2])); y.push_back(std::stof(argv[3])); x.push_back(std::stof(argv[4])); y.push_back(std::stof(argv[5])); std::vector<float> x_undist, y_undist; for (int i = 0; i < x.size(); i++) { float result[2]; pc_coord_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x_undist.push_back(result[0]); y_undist.push_back(result[1]); } if (!modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0) || !back_modifier.EnablePerspectiveCorrection(lens, 50, x_undist.data(), y_undist.data(), 6, 0)) { std::cerr << "Failed to activate perspective correction\n"; return -1; } std::vector<float> res(image.width * image.height * 2 * image.channels); if (image.channels == 3) modifier.ApplySubpixelGeometryDistortion(0, 0, image.width, image.height, res.data()); else modifier.ApplyGeometryDistortion(0, 0, image.width, image.height, res.data()); Image new_image = image; for (int x = 0; x < image.width; x++) for (int y = 0; y < image.height; y++) { int position = 2 * image.channels * (y * image.width + x); float source_x_R = res[position]; float source_y_R = res[position + 1]; new_image.set(x, y, 0, image.get(source_x_R, source_y_R, 0)); if (image.channels == 3) { float source_x_G = res[position + 2]; float source_y_G = res[position + 3]; float source_x_B = res[position + 4]; float source_y_B = res[position + 5]; new_image.set(x, y, 1, image.get(source_x_G, source_y_G, 1)); new_image.set(x, y, 2, image.get(source_x_B, source_y_B, 2)); } } std::ofstream file(argv[1], std::ios::binary); file << new_image; for (int i = 0; i < 4; i++) { float result[2]; back_modifier.ApplyGeometryDistortion(x[i], y[i], 1, 1, result); x[i] = result[0]; y[i] = result[1]; } std::cout << "[" << std::min(x[0], x[2]) << ", " << std::min(y[0], y[1]) << ", " << std::max(x[1], x[3]) - std::min(x[0], x[2]) << ", " << std::max(y[2], y[3]) - std::min(y[0], y[1]) << "]\n"; return 0; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <kcpolydb.h> long estimate_a(long *pack) { return ( 4 + pack[0] * 8 + 4 + 1 + pack[1] * 8 * 5 + 4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 + 4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 + 4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 + 4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6 ); } long estimate_b(long *pack) { return ( 4 + pack[0] * 9 + 4 + 1 + pack[1] * 9 * 5 + 4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 + 4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 + 4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 + 4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6 ); } int main(int argc, char **argv) { if (argc <= 1) { std::cout << "Usage: stat <dbfile.kct>" << std::endl; return 1; } kyotocabinet::TreeDB db; if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER)) { std::cout << "Could not open database." << std::endl; return 2; } std::auto_ptr<kyotocabinet::TreeDB::Cursor> cur(db.cursor()); cur->jump(); std::string key, value; long pack[] = {0, 0, 0, 0, 0, 0}; while (cur->get(&key, &value, true)) { if (value.size() == 8) { pack[0]++; } else { pack[value.at(0)]++; } } for (int i = 0; i < 5; i++) { std::cout << "Pack format " << i << ": " << pack[i] << " nodes " << std::endl; } std::cout << "Unique positions: " << (pack[0] + pack[1] + pack[2] + pack[3] + pack[4] + pack[5]) << std::endl; std::cout << std::endl; std::cout << "Scheme A: " << estimate_a(pack) << " bytes" << std::endl; std::cout << "Scheme B: " << estimate_b(pack) << " bytes" << std::endl; std::cout << "B/A: " << ((double)estimate_b(pack)/estimate_a(pack)) << std::endl; return 0; } <commit_msg>Show progress<commit_after>#include <iostream> #include <string> #include <kcpolydb.h> long estimate_a(long *pack) { return ( 4 + pack[0] * 8 + 4 + 1 + pack[1] * 8 * 5 + 4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 + 4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 + 4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 + 4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6 ); } long estimate_b(long *pack) { return ( 4 + pack[0] * 9 + 4 + 1 + pack[1] * 9 * 5 + 4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 + 4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 + 4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 + 4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6 ); } int main(int argc, char **argv) { if (argc <= 1) { std::cout << "Usage: stat <dbfile.kct>" << std::endl; return 1; } kyotocabinet::TreeDB db; if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER)) { std::cout << "Could not open database." << std::endl; return 2; } std::auto_ptr<kyotocabinet::TreeDB::Cursor> cur(db.cursor()); cur->jump(); std::string key, value; long pack[] = {0, 0, 0, 0, 0, 0}; long total = 0; std::cout << "Scanning ..." << std::endl; while (cur->get(&key, &value, true)) { total++; if (value.size() == 8) { pack[0]++; } else { pack[value.at(0)]++; } if (total % 50000 == 0) { std::cerr << "."; } } std::cerr << std::endl; for (int i = 0; i < 5; i++) { std::cout << "Pack format " << i << ": " << pack[i] << " nodes " << std::endl; } std::cout << "Unique positions: " << total << std::endl; std::cout << std::endl; std::cout << "Scheme A: " << estimate_a(pack) << " bytes" << std::endl; std::cout << "Scheme B: " << estimate_b(pack) << " bytes" << std::endl; std::cout << "B/A: " << ((double)estimate_b(pack)/estimate_a(pack)) << std::endl; return 0; } <|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "maemotoolchain.h" #include "maemoglobal.h" #include "maemomanager.h" #include "maemoqtversion.h" #include "qt4projectmanagerconstants.h" #include "qtversionmanager.h" #include <projectexplorer/gccparser.h> #include <projectexplorer/headerpath.h> #include <projectexplorer/toolchainmanager.h> #include <utils/environment.h> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> namespace Qt4ProjectManager { namespace Internal { static const char *const MAEMO_QT_VERSION_KEY = "Qt4ProjectManager.Maemo.QtVersion"; // -------------------------------------------------------------------------- // MaemoToolChain // -------------------------------------------------------------------------- MaemoToolChain::MaemoToolChain(bool autodetected) : ProjectExplorer::GccToolChain(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID), autodetected), m_qtVersionId(-1) { updateId(); } MaemoToolChain::MaemoToolChain(const MaemoToolChain &tc) : ProjectExplorer::GccToolChain(tc), m_qtVersionId(tc.m_qtVersionId) { } MaemoToolChain::~MaemoToolChain() { } QString MaemoToolChain::typeName() const { return MaemoToolChainFactory::tr("Maemo GCC"); } ProjectExplorer::Abi MaemoToolChain::targetAbi() const { return m_targetAbi; } QString MaemoToolChain::mkspec() const { return QString(); // always use default } bool MaemoToolChain::isValid() const { return GccToolChain::isValid() && m_qtVersionId >= 0 && m_targetAbi.isValid(); } bool MaemoToolChain::canClone() const { return false; } void MaemoToolChain::addToEnvironment(Utils::Environment &env) const { BaseQtVersion *v = QtVersionManager::instance()->version(m_qtVersionId); if (!v) return; const QString maddeRoot = MaemoGlobal::maddeRoot(v->qmakeCommand()); // put this into environment to make pkg-config stuff work env.prependOrSet(QLatin1String("SYSROOT_DIR"), QDir::toNativeSeparators(sysroot())); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madbin") .arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madlib") .arg(maddeRoot))); env.prependOrSet(QLatin1String("PERL5LIB"), QDir::toNativeSeparators(QString("%1/madlib/perl5").arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin").arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin") .arg(MaemoGlobal::targetRoot(v->qmakeCommand())))); const QString manglePathsKey = QLatin1String("GCCWRAPPER_PATHMANGLE"); if (!env.hasKey(manglePathsKey)) { const QStringList pathsToMangle = QStringList() << QLatin1String("/lib") << QLatin1String("/opt") << QLatin1String("/usr"); env.set(manglePathsKey, QString()); foreach (const QString &path, pathsToMangle) env.appendOrSet(manglePathsKey, path, QLatin1String(":")); } } QString MaemoToolChain::sysroot() const { BaseQtVersion *v = QtVersionManager::instance()->version(m_qtVersionId); if (!v) return QString(); if (m_sysroot.isEmpty()) { QFile file(QDir::cleanPath(MaemoGlobal::targetRoot(v->qmakeCommand())) + QLatin1String("/information")); if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&file); while (!stream.atEnd()) { const QString &line = stream.readLine().trimmed(); const QStringList &list = line.split(QLatin1Char(' ')); if (list.count() > 1 && list.at(0) == QLatin1String("sysroot")) m_sysroot = MaemoGlobal::maddeRoot(v->qmakeCommand()) + QLatin1String("/sysroots/") + list.at(1); } } } return m_sysroot; } bool MaemoToolChain::operator ==(const ProjectExplorer::ToolChain &tc) const { if (!ToolChain::operator ==(tc)) return false; const MaemoToolChain *tcPtr = static_cast<const MaemoToolChain *>(&tc); return m_qtVersionId == tcPtr->m_qtVersionId; } ProjectExplorer::ToolChainConfigWidget *MaemoToolChain::configurationWidget() { return new MaemoToolChainConfigWidget(this); } QVariantMap MaemoToolChain::toMap() const { QVariantMap result = GccToolChain::toMap(); result.insert(QLatin1String(MAEMO_QT_VERSION_KEY), m_qtVersionId); return result; } bool MaemoToolChain::fromMap(const QVariantMap &data) { if (!GccToolChain::fromMap(data)) return false; m_qtVersionId = data.value(QLatin1String(MAEMO_QT_VERSION_KEY), -1).toInt(); return isValid(); } void MaemoToolChain::setQtVersionId(int id) { if (id < 0) { m_targetAbi = ProjectExplorer::Abi(); m_qtVersionId = -1; updateId(); // Will trigger toolChainUpdated()! return; } MaemoQtVersion *version = dynamic_cast<MaemoQtVersion *>(QtVersionManager::instance()->version(id)); Q_ASSERT(version); ProjectExplorer::Abi::OSFlavor flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor; if (version->osVersion() == MaemoDeviceConfig::Maemo5) flavour = ProjectExplorer::Abi::MaemoLinuxFlavor; else if (version->osVersion() == MaemoDeviceConfig::Maemo6) flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor; else if (version->osVersion() == MaemoDeviceConfig::Meego) flavour = ProjectExplorer::Abi::MeegoLinuxFlavor; else return; m_qtVersionId = id; Q_ASSERT(version->qtAbis().count() == 1); m_targetAbi = version->qtAbis().at(0); updateId(); // Will trigger toolChainUpdated()! setDisplayName(MaemoToolChainFactory::tr("Maemo GCC for %1").arg(version->displayName())); } int MaemoToolChain::qtVersionId() const { return m_qtVersionId; } void MaemoToolChain::updateId() { setId(QString::fromLatin1("%1:%2.%3").arg(Constants::MAEMO_TOOLCHAIN_ID) .arg(m_qtVersionId).arg(debuggerCommand())); } // -------------------------------------------------------------------------- // MaemoToolChainConfigWidget // -------------------------------------------------------------------------- MaemoToolChainConfigWidget::MaemoToolChainConfigWidget(MaemoToolChain *tc) : ProjectExplorer::ToolChainConfigWidget(tc) { QVBoxLayout *layout = new QVBoxLayout(this); QLabel *label = new QLabel; BaseQtVersion *v = QtVersionManager::instance()->version(tc->qtVersionId()); Q_ASSERT(v); label->setText(tr("<html><head/><body><table>" "<tr><td>Path to MADDE:</td><td>%1</td></tr>" "<tr><td>Path to MADDE target:</td><td>%2</td></tr>" "<tr><td>Debugger:</td/><td>%3</td></tr></body></html>") .arg(QDir::toNativeSeparators(MaemoGlobal::maddeRoot(v->qmakeCommand())), QDir::toNativeSeparators(MaemoGlobal::targetRoot(v->qmakeCommand())), QDir::toNativeSeparators(tc->debuggerCommand()))); layout->addWidget(label); } void MaemoToolChainConfigWidget::apply() { // nothing to do! } void MaemoToolChainConfigWidget::discard() { // nothing to do! } bool MaemoToolChainConfigWidget::isDirty() const { return false; } // -------------------------------------------------------------------------- // MaemoToolChainFactory // -------------------------------------------------------------------------- MaemoToolChainFactory::MaemoToolChainFactory() : ProjectExplorer::ToolChainFactory() { } QString MaemoToolChainFactory::displayName() const { return tr("Maemo GCC"); } QString MaemoToolChainFactory::id() const { return QLatin1String(Constants::MAEMO_TOOLCHAIN_ID); } QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::autoDetect() { QtVersionManager *vm = QtVersionManager::instance(); connect(vm, SIGNAL(qtVersionsChanged(QList<int>)), this, SLOT(handleQtVersionChanges(QList<int>))); QList<int> versionList; foreach (BaseQtVersion *v, vm->versions()) versionList.append(v->uniqueId()); return createToolChainList(versionList); } void MaemoToolChainFactory::handleQtVersionChanges(const QList<int> &changes) { ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance(); QList<ProjectExplorer::ToolChain *> tcList = createToolChainList(changes); foreach (ProjectExplorer::ToolChain *tc, tcList) tcm->registerToolChain(tc); } QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::createToolChainList(const QList<int> &changes) { ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance(); QtVersionManager *vm = QtVersionManager::instance(); QList<ProjectExplorer::ToolChain *> result; foreach (int i, changes) { BaseQtVersion *v = vm->version(i); if (!v) { // remove tool chain: QList<ProjectExplorer::ToolChain *> toRemove; foreach (ProjectExplorer::ToolChain *tc, tcm->toolChains()) { if (!tc->id().startsWith(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID))) continue; MaemoToolChain *mTc = static_cast<MaemoToolChain *>(tc); if (mTc->qtVersionId() == i) toRemove.append(mTc); } foreach (ProjectExplorer::ToolChain *tc, toRemove) tcm->deregisterToolChain(tc); } else if (MaemoQtVersion *mqv = dynamic_cast<MaemoQtVersion *>(v)) { // add tool chain: MaemoToolChain *mTc = new MaemoToolChain(true); mTc->setQtVersionId(i); QString target = "Maemo 5"; if (v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID)) target = "Maemo 6"; else if (v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID)) target = "Meego"; mTc->setDisplayName(tr("%1 GCC (%2)").arg(target).arg(MaemoGlobal::maddeRoot(mqv->qmakeCommand()))); mTc->setCompilerPath(MaemoGlobal::targetRoot(mqv->qmakeCommand()) + QLatin1String("/bin/gcc")); mTc->setDebuggerCommand(ProjectExplorer::ToolChainManager::instance()->defaultDebugger(mqv->qtAbis().at(0))); if (mTc->debuggerCommand().isEmpty()) mTc->setDebuggerCommand(MaemoGlobal::targetRoot(mqv->qmakeCommand()) + QLatin1String("/bin/gdb")); result.append(mTc); } } return result; } } // namespace Internal } // namespace Qt4ProjectManager <commit_msg>Maemo: Fix possible assert<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at [email protected]. ** **************************************************************************/ #include "maemotoolchain.h" #include "maemoglobal.h" #include "maemomanager.h" #include "maemoqtversion.h" #include "qt4projectmanagerconstants.h" #include "qtversionmanager.h" #include <projectexplorer/gccparser.h> #include <projectexplorer/headerpath.h> #include <projectexplorer/toolchainmanager.h> #include <utils/environment.h> #include <QtCore/QDir> #include <QtCore/QFileInfo> #include <QtGui/QLabel> #include <QtGui/QVBoxLayout> namespace Qt4ProjectManager { namespace Internal { static const char *const MAEMO_QT_VERSION_KEY = "Qt4ProjectManager.Maemo.QtVersion"; // -------------------------------------------------------------------------- // MaemoToolChain // -------------------------------------------------------------------------- MaemoToolChain::MaemoToolChain(bool autodetected) : ProjectExplorer::GccToolChain(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID), autodetected), m_qtVersionId(-1) { updateId(); } MaemoToolChain::MaemoToolChain(const MaemoToolChain &tc) : ProjectExplorer::GccToolChain(tc), m_qtVersionId(tc.m_qtVersionId) { } MaemoToolChain::~MaemoToolChain() { } QString MaemoToolChain::typeName() const { return MaemoToolChainFactory::tr("Maemo GCC"); } ProjectExplorer::Abi MaemoToolChain::targetAbi() const { return m_targetAbi; } QString MaemoToolChain::mkspec() const { return QString(); // always use default } bool MaemoToolChain::isValid() const { return GccToolChain::isValid() && m_qtVersionId >= 0 && m_targetAbi.isValid(); } bool MaemoToolChain::canClone() const { return false; } void MaemoToolChain::addToEnvironment(Utils::Environment &env) const { BaseQtVersion *v = QtVersionManager::instance()->version(m_qtVersionId); if (!v) return; const QString maddeRoot = MaemoGlobal::maddeRoot(v->qmakeCommand()); // put this into environment to make pkg-config stuff work env.prependOrSet(QLatin1String("SYSROOT_DIR"), QDir::toNativeSeparators(sysroot())); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madbin") .arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/madlib") .arg(maddeRoot))); env.prependOrSet(QLatin1String("PERL5LIB"), QDir::toNativeSeparators(QString("%1/madlib/perl5").arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin").arg(maddeRoot))); env.prependOrSetPath(QDir::toNativeSeparators(QString("%1/bin") .arg(MaemoGlobal::targetRoot(v->qmakeCommand())))); const QString manglePathsKey = QLatin1String("GCCWRAPPER_PATHMANGLE"); if (!env.hasKey(manglePathsKey)) { const QStringList pathsToMangle = QStringList() << QLatin1String("/lib") << QLatin1String("/opt") << QLatin1String("/usr"); env.set(manglePathsKey, QString()); foreach (const QString &path, pathsToMangle) env.appendOrSet(manglePathsKey, path, QLatin1String(":")); } } QString MaemoToolChain::sysroot() const { BaseQtVersion *v = QtVersionManager::instance()->version(m_qtVersionId); if (!v) return QString(); if (m_sysroot.isEmpty()) { QFile file(QDir::cleanPath(MaemoGlobal::targetRoot(v->qmakeCommand())) + QLatin1String("/information")); if (file.exists() && file.open(QIODevice::ReadOnly | QIODevice::Text)) { QTextStream stream(&file); while (!stream.atEnd()) { const QString &line = stream.readLine().trimmed(); const QStringList &list = line.split(QLatin1Char(' ')); if (list.count() > 1 && list.at(0) == QLatin1String("sysroot")) m_sysroot = MaemoGlobal::maddeRoot(v->qmakeCommand()) + QLatin1String("/sysroots/") + list.at(1); } } } return m_sysroot; } bool MaemoToolChain::operator ==(const ProjectExplorer::ToolChain &tc) const { if (!ToolChain::operator ==(tc)) return false; const MaemoToolChain *tcPtr = static_cast<const MaemoToolChain *>(&tc); return m_qtVersionId == tcPtr->m_qtVersionId; } ProjectExplorer::ToolChainConfigWidget *MaemoToolChain::configurationWidget() { return new MaemoToolChainConfigWidget(this); } QVariantMap MaemoToolChain::toMap() const { QVariantMap result = GccToolChain::toMap(); result.insert(QLatin1String(MAEMO_QT_VERSION_KEY), m_qtVersionId); return result; } bool MaemoToolChain::fromMap(const QVariantMap &data) { if (!GccToolChain::fromMap(data)) return false; m_qtVersionId = data.value(QLatin1String(MAEMO_QT_VERSION_KEY), -1).toInt(); return isValid(); } void MaemoToolChain::setQtVersionId(int id) { if (id < 0) { m_targetAbi = ProjectExplorer::Abi(); m_qtVersionId = -1; updateId(); // Will trigger toolChainUpdated()! return; } MaemoQtVersion *version = dynamic_cast<MaemoQtVersion *>(QtVersionManager::instance()->version(id)); Q_ASSERT(version); ProjectExplorer::Abi::OSFlavor flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor; if (version->osVersion() == MaemoDeviceConfig::Maemo5) flavour = ProjectExplorer::Abi::MaemoLinuxFlavor; else if (version->osVersion() == MaemoDeviceConfig::Maemo6) flavour = ProjectExplorer::Abi::HarmattanLinuxFlavor; else if (version->osVersion() == MaemoDeviceConfig::Meego) flavour = ProjectExplorer::Abi::MeegoLinuxFlavor; else return; m_qtVersionId = id; Q_ASSERT(version->qtAbis().count() == 1); m_targetAbi = version->qtAbis().at(0); updateId(); // Will trigger toolChainUpdated()! setDisplayName(MaemoToolChainFactory::tr("Maemo GCC for %1").arg(version->displayName())); } int MaemoToolChain::qtVersionId() const { return m_qtVersionId; } void MaemoToolChain::updateId() { setId(QString::fromLatin1("%1:%2.%3").arg(Constants::MAEMO_TOOLCHAIN_ID) .arg(m_qtVersionId).arg(debuggerCommand())); } // -------------------------------------------------------------------------- // MaemoToolChainConfigWidget // -------------------------------------------------------------------------- MaemoToolChainConfigWidget::MaemoToolChainConfigWidget(MaemoToolChain *tc) : ProjectExplorer::ToolChainConfigWidget(tc) { QVBoxLayout *layout = new QVBoxLayout(this); QLabel *label = new QLabel; BaseQtVersion *v = QtVersionManager::instance()->version(tc->qtVersionId()); Q_ASSERT(v); label->setText(tr("<html><head/><body><table>" "<tr><td>Path to MADDE:</td><td>%1</td></tr>" "<tr><td>Path to MADDE target:</td><td>%2</td></tr>" "<tr><td>Debugger:</td/><td>%3</td></tr></body></html>") .arg(QDir::toNativeSeparators(MaemoGlobal::maddeRoot(v->qmakeCommand())), QDir::toNativeSeparators(MaemoGlobal::targetRoot(v->qmakeCommand())), QDir::toNativeSeparators(tc->debuggerCommand()))); layout->addWidget(label); } void MaemoToolChainConfigWidget::apply() { // nothing to do! } void MaemoToolChainConfigWidget::discard() { // nothing to do! } bool MaemoToolChainConfigWidget::isDirty() const { return false; } // -------------------------------------------------------------------------- // MaemoToolChainFactory // -------------------------------------------------------------------------- MaemoToolChainFactory::MaemoToolChainFactory() : ProjectExplorer::ToolChainFactory() { } QString MaemoToolChainFactory::displayName() const { return tr("Maemo GCC"); } QString MaemoToolChainFactory::id() const { return QLatin1String(Constants::MAEMO_TOOLCHAIN_ID); } QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::autoDetect() { QtVersionManager *vm = QtVersionManager::instance(); connect(vm, SIGNAL(qtVersionsChanged(QList<int>)), this, SLOT(handleQtVersionChanges(QList<int>))); QList<int> versionList; foreach (BaseQtVersion *v, vm->versions()) versionList.append(v->uniqueId()); return createToolChainList(versionList); } void MaemoToolChainFactory::handleQtVersionChanges(const QList<int> &changes) { ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance(); QList<ProjectExplorer::ToolChain *> tcList = createToolChainList(changes); foreach (ProjectExplorer::ToolChain *tc, tcList) tcm->registerToolChain(tc); } QList<ProjectExplorer::ToolChain *> MaemoToolChainFactory::createToolChainList(const QList<int> &changes) { ProjectExplorer::ToolChainManager *tcm = ProjectExplorer::ToolChainManager::instance(); QtVersionManager *vm = QtVersionManager::instance(); QList<ProjectExplorer::ToolChain *> result; foreach (int i, changes) { BaseQtVersion *v = vm->version(i); if (!v || !v->isValid()) { // remove tool chain: QList<ProjectExplorer::ToolChain *> toRemove; foreach (ProjectExplorer::ToolChain *tc, tcm->toolChains()) { if (!tc->id().startsWith(QLatin1String(Constants::MAEMO_TOOLCHAIN_ID))) continue; MaemoToolChain *mTc = static_cast<MaemoToolChain *>(tc); if (mTc->qtVersionId() == i) toRemove.append(mTc); } foreach (ProjectExplorer::ToolChain *tc, toRemove) tcm->deregisterToolChain(tc); } else if (MaemoQtVersion *mqv = dynamic_cast<MaemoQtVersion *>(v)) { // add tool chain: MaemoToolChain *mTc = new MaemoToolChain(true); mTc->setQtVersionId(i); QString target = "Maemo 5"; if (v->supportsTargetId(Constants::HARMATTAN_DEVICE_TARGET_ID)) target = "Maemo 6"; else if (v->supportsTargetId(Constants::MEEGO_DEVICE_TARGET_ID)) target = "Meego"; mTc->setDisplayName(tr("%1 GCC (%2)").arg(target).arg(MaemoGlobal::maddeRoot(mqv->qmakeCommand()))); mTc->setCompilerPath(MaemoGlobal::targetRoot(mqv->qmakeCommand()) + QLatin1String("/bin/gcc")); mTc->setDebuggerCommand(ProjectExplorer::ToolChainManager::instance()->defaultDebugger(mqv->qtAbis().at(0))); if (mTc->debuggerCommand().isEmpty()) mTc->setDebuggerCommand(MaemoGlobal::targetRoot(mqv->qmakeCommand()) + QLatin1String("/bin/gdb")); result.append(mTc); } } return result; } } // namespace Internal } // namespace Qt4ProjectManager <|endoftext|>
<commit_before>/* * display_visibility_manager.cpp * * Created on: Aug 27, 2012 * Author: gossow */ #include "display_group_visibility_property.h" #include "rviz/properties/bool_property.h" #include "rviz/display_context.h" #include "rviz/bit_allocator.h" #include "rviz/display.h" #include "rviz/display_group.h" namespace rviz { DisplayGroupVisibilityProperty::DisplayGroupVisibilityProperty( uint32_t vis_bit, DisplayGroup* display_group, Display* parent_display, const QString& name, bool default_value, const QString& description, Property* parent, const char *changed_slot, QObject* receiver ) : DisplayVisibilityProperty( vis_bit, display_group, name, default_value, description, parent, changed_slot, receiver ) , display_group_(display_group) , parent_display_(parent_display) { connect( display_group, SIGNAL( displayAdded( rviz::Display* ) ), this, SLOT( onDisplayAdded( rviz::Display* ) )); connect( display_group, SIGNAL( displayRemoved( rviz::Display* ) ), this, SLOT( onDisplayRemoved( rviz::Display* ) )); for( int i = 0; i < display_group->numDisplays(); i++ ) { rviz::Display* display = display_group->getDisplayAt( i ); if ( display != parent ) { onDisplayAdded( display ); } } } void DisplayGroupVisibilityProperty::update() { DisplayVisibilityProperty::update(); std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.begin(); for( ; it != disp_vis_props_.end(); it++ ) { it->second->update(); } } void DisplayGroupVisibilityProperty::sortDisplayList() { // remove and re-add everything in our property list // in the same order as it appears in the display group for( int i = 0; i < display_group_->numDisplays(); i++ ) { rviz::Display* display = display_group_->getDisplayAt( i ); std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.find( display ); if ( it != disp_vis_props_.end() ) { takeChild( it->second ); addChild( it->second ); } } } void DisplayGroupVisibilityProperty::onDisplayAdded( Display* display ) { DisplayGroup* display_group = qobject_cast<DisplayGroup*>( display ); DisplayVisibilityProperty* vis_prop; if( display_group ) { vis_prop = new DisplayGroupVisibilityProperty( vis_bit_, display_group, parent_display_, "", true, "Uncheck to hide everything in this Display Group", this ); } else { vis_prop = new DisplayVisibilityProperty( vis_bit_, display, "", true, "Show or hide this Display", this ); } disp_vis_props_[ display ] = vis_prop; sortDisplayList(); } void DisplayGroupVisibilityProperty::onDisplayRemoved( Display* display ) { std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.find( display ); if ( it != disp_vis_props_.end() ) { Property* child = takeChild( it->second ); child->setParent( NULL ); delete child; disp_vis_props_.erase( display ); } } DisplayGroupVisibilityProperty::~DisplayGroupVisibilityProperty() { } } <commit_msg>bugfix in visibility property: don't show parent display in list<commit_after>/* * display_visibility_manager.cpp * * Created on: Aug 27, 2012 * Author: gossow */ #include "display_group_visibility_property.h" #include "rviz/properties/bool_property.h" #include "rviz/display_context.h" #include "rviz/bit_allocator.h" #include "rviz/display.h" #include "rviz/display_group.h" namespace rviz { DisplayGroupVisibilityProperty::DisplayGroupVisibilityProperty( uint32_t vis_bit, DisplayGroup* display_group, Display* parent_display, const QString& name, bool default_value, const QString& description, Property* parent, const char *changed_slot, QObject* receiver ) : DisplayVisibilityProperty( vis_bit, display_group, name, default_value, description, parent, changed_slot, receiver ) , display_group_(display_group) , parent_display_(parent_display) { connect( display_group, SIGNAL( displayAdded( rviz::Display* ) ), this, SLOT( onDisplayAdded( rviz::Display* ) )); connect( display_group, SIGNAL( displayRemoved( rviz::Display* ) ), this, SLOT( onDisplayRemoved( rviz::Display* ) )); for( int i = 0; i < display_group->numDisplays(); i++ ) { rviz::Display* display = display_group->getDisplayAt( i ); if ( display != parent_display ) { onDisplayAdded( display ); } } } void DisplayGroupVisibilityProperty::update() { DisplayVisibilityProperty::update(); std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.begin(); for( ; it != disp_vis_props_.end(); it++ ) { it->second->update(); } } void DisplayGroupVisibilityProperty::sortDisplayList() { // remove and re-add everything in our property list // in the same order as it appears in the display group for( int i = 0; i < display_group_->numDisplays(); i++ ) { rviz::Display* display = display_group_->getDisplayAt( i ); std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.find( display ); if ( it != disp_vis_props_.end() ) { takeChild( it->second ); addChild( it->second ); } } } void DisplayGroupVisibilityProperty::onDisplayAdded( Display* display ) { DisplayGroup* display_group = qobject_cast<DisplayGroup*>( display ); DisplayVisibilityProperty* vis_prop; if( display_group ) { vis_prop = new DisplayGroupVisibilityProperty( vis_bit_, display_group, parent_display_, "", true, "Uncheck to hide everything in this Display Group", this ); } else { vis_prop = new DisplayVisibilityProperty( vis_bit_, display, "", true, "Show or hide this Display", this ); } disp_vis_props_[ display ] = vis_prop; sortDisplayList(); } void DisplayGroupVisibilityProperty::onDisplayRemoved( Display* display ) { std::map<rviz::Display*, DisplayVisibilityProperty*>::iterator it = disp_vis_props_.find( display ); if ( it != disp_vis_props_.end() ) { Property* child = takeChild( it->second ); child->setParent( NULL ); delete child; disp_vis_props_.erase( display ); } } DisplayGroupVisibilityProperty::~DisplayGroupVisibilityProperty() { } } <|endoftext|>
<commit_before>/** * @file Reactor.cpp * * A zero-dimensional reactor */ // Copyright 2001 California Institute of Technology #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "Reactor.h" #include "../CVode.h" #include "FlowDevice.h" #include "Wall.h" namespace Cantera { doublereal quadInterp(doublereal x0, doublereal* x, doublereal* y); Reactor::Reactor() : ReactorBase(), FuncEval(), m_kin(0), m_integ(0), m_temp_atol(1.e-11), m_maxstep(0.0), m_vdot(0.0), m_Q(0.0), m_emis(0.0), m_h(0.0), m_area(1.0), m_ext_temp(0.0), m_ext_temp4(0.0), m_kv(0.0), m_p0(OneAtm), m_rtol(1.e-9), m_trad_set(false), m_chem(true), m_energy(true) { m_integ = new CVodeInt; // use backward differencing, with a full Jacobian computed // numerically, and use a Newton linear iterator m_integ->setMethod(BDF_Method); m_integ->setProblemType(DENSE + NOJAC); m_integ->setIterator(Newton_Iter); } // overloaded method of FuncEval. Called by the integrator to // get the initial conditions. void Reactor::getInitialConditions(double t0, size_t leny, double* y) { m_init = true; if (m_mix == 0) { cout << "Error: reactor is empty." << endl; return; } m_time = t0; // total mass doublereal mass = m_mix->density() * m_vol; // set components y + 2 ... y + K + 1 to the // mass M_k of each species m_mix->getMassFractions(leny-2, y+2); scale(y + 2, y + m_nsp + 2, y + 2, mass); // set the first component to the total internal // energy y[0] = m_thermo->intEnergy_mass() * mass; // set the second component to the total volume y[1] = m_vol; } /** * Must be called before calling method 'advance' */ void Reactor::initialize(doublereal t0) { m_mix->restoreState(m_state); m_sdot.resize(m_nsp, 0.0); m_atol.resize(m_nsp + 2); fill(m_atol.begin(), m_atol.end(), 1.e-15); m_integ->setTolerances(m_rtol, neq(), m_atol.begin()); m_integ->setMaxStep(m_maxstep); m_integ->initialize(t0, *this); m_enthalpy = m_thermo->enthalpy_mass(); m_pressure = m_thermo->pressure(); m_intEnergy = m_thermo->intEnergy_mass(); m_init = true; } void Reactor::updateState(doublereal* y) { phase_t& mix = *m_mix; // define for readability // The components of y are the total internal energy, // the total volume, and the mass of each species. // Set the mass fractions and density of the mixture. doublereal u = y[0]; m_vol = y[1]; doublereal* mss = y + 2; doublereal mass = accumulate(y+2, y+2+m_nsp, 0.0); m_mix->setMassFractions(mss); m_mix->setDensity(mass/m_vol); doublereal temp = temperature(); mix.setTemperature(temp); if (m_energy) { doublereal u_mass = u/mass; // specific int. energy doublereal delta; do { delta = -(m_thermo->intEnergy_mass() - u_mass)/m_thermo->cv_mass(); temp += delta; mix.setTemperature(temp); } while (fabs(delta) > m_temp_atol); } mix.setTemperature(temp); m_state[0] = temp; // save parameters needed by other connected reactors m_enthalpy = m_thermo->enthalpy_mass(); m_pressure = m_thermo->pressure(); m_intEnergy = m_thermo->intEnergy_mass(); } /** * Called by the integrator to evaluate ydot given y at time 'time'. */ void Reactor::eval(doublereal time, doublereal* y, doublereal* ydot) { int i; m_time = time; updateState(y); // synchronize the reactor state with y m_vdot = 0.0; m_Q = 0.0; // compute wall terms doublereal vdot; for (i = 0; i < m_nwalls; i++) { vdot = m_lr[i]*m_wall[i]->vdot(time); m_vdot += vdot; m_Q += m_lr[i]*m_wall[i]->Q(time); } // volume equation ydot[1] = m_vdot; /* species equations * Equation is: * \dot M_k = \hat W_k \dot\omega_k + \dot m_{in} Y_{k,in} * - \dot m_{out} Y_{k} + A \dot s_k. */ const doublereal* mw = m_mix->molecularWeights().begin(); int n; m_kin->getNetProductionRates(ydot+2); // "omega dot" for (n = 0; n < m_nsp; n++) { ydot[n+2] *= m_vol; // moles/s/m^3 -> moles/s // ydot[n+2] += m_sdot[n]; ydot[n+2] *= mw[n]; } /** * Energy equation. * \dot U = -P\dot V + A \dot q + \dot m_{in} h_{in} * - \dot m_{out} h. */ if (m_energy) { ydot[0] = - m_thermo->pressure() * m_vdot - m_Q; } else { ydot[0] = 0.0; } // add terms for open system if (m_open) { const doublereal* mf = m_mix->massFractions(); doublereal enthalpy = m_thermo->enthalpy_mass(); // outlets int n; doublereal mdot_out; for (i = 0; i < m_nOutlets; i++) { mdot_out = m_outlet[i]->massFlowRate(); for (n = 0; n < m_nsp; n++) { ydot[2+n] -= mdot_out * mf[n]; } ydot[0] -= mdot_out * enthalpy; } // inlets doublereal mdot_in; for (i = 0; i < m_nInlets; i++) { mdot_in = m_inlet[i]->massFlowRate(); for (n = 0; n < m_nsp; n++) { ydot[2+n] += m_inlet[i]->massFlowRate(n); } ydot[0] += mdot_in * m_inlet[i]->enthalpy_mass(); } } } } <commit_msg>added support for surface chemistry.<commit_after>/** * @file Reactor.cpp * * A zero-dimensional reactor */ // Copyright 2001 California Institute of Technology #ifdef WIN32 #pragma warning(disable:4786) #pragma warning(disable:4503) #endif #include "Reactor.h" #include "../CVode.h" #include "FlowDevice.h" #include "Wall.h" #include "../InterfaceKinetics.h" #include "../SurfPhase.h" namespace Cantera { doublereal quadInterp(doublereal x0, doublereal* x, doublereal* y); Reactor::Reactor() : ReactorBase(), FuncEval(), m_kin(0), m_integ(0), m_temp_atol(1.e-11), m_maxstep(0.0), m_vdot(0.0), m_Q(0.0), m_emis(0.0), m_h(0.0), m_area(1.0), m_ext_temp(0.0), m_ext_temp4(0.0), m_kv(0.0), m_p0(OneAtm), m_rtol(1.e-9), m_trad_set(false), m_chem(true), m_energy(true) { m_integ = new CVodeInt; // use backward differencing, with a full Jacobian computed // numerically, and use a Newton linear iterator m_integ->setMethod(BDF_Method); m_integ->setProblemType(DENSE + NOJAC); m_integ->setIterator(Newton_Iter); } // overloaded method of FuncEval. Called by the integrator to // get the initial conditions. void Reactor::getInitialConditions(double t0, size_t leny, double* y) { m_init = true; if (m_mix == 0) { cout << "Error: reactor is empty." << endl; return; } m_time = t0; // total mass doublereal mass = m_mix->density() * m_vol; // set components y + 2 ... y + K + 1 to the // mass M_k of each species m_mix->getMassFractions(leny-2, y+2); scale(y + 2, y + m_nsp + 2, y + 2, mass); // set the first component to the total internal // energy y[0] = m_thermo->intEnergy_mass() * mass; // set the second component to the total volume y[1] = m_vol; // set the remaining components to the surface species // coverages on the walls int loc = m_nsp + 2; SurfPhase* surf; for (int m = 0; m < m_nwalls; m++) { surf = m_wall[m]->surface(m_lr[m]); if (surf) { surf->getCoverages(y+loc); loc += surf->nSpecies(); } } } /** * Must be called before calling method 'advance' */ void Reactor::initialize(doublereal t0) { m_mix->restoreState(m_state); m_sdot.resize(m_nsp, 0.0); m_nv = m_nsp + 2; for (int w = 0; w < m_nwalls; w++) if (m_wall[w]->surface(m_lr[w])) m_nv += m_wall[w]->surface(m_lr[w])->nSpecies(); m_atol.resize(neq()); fill(m_atol.begin(), m_atol.end(), 1.e-15); m_integ->setTolerances(m_rtol, neq(), m_atol.begin()); m_integ->setMaxStep(m_maxstep); m_integ->initialize(t0, *this); m_enthalpy = m_thermo->enthalpy_mass(); m_pressure = m_thermo->pressure(); m_intEnergy = m_thermo->intEnergy_mass(); int nt, maxnt; for (int m = 0; m < m_nwalls; m++) { if (m_wall[m]->kinetics(m_lr[m])) { nt = m_wall[m]->kinetics(m_lr[m])->nTotalSpecies(); if (nt > maxnt) maxnt = nt; if (m_wall[m]->kinetics(m_lr[m])) { if (&m_kin->thermo(0) != &m_wall[m]->kinetics(m_lr[m])->thermo(0)) { throw CanteraError("Reactor::initialize", "First phase of all kinetics managers must be" " the gas."); } } } } m_work.resize(maxnt); m_init = true; } void Reactor::updateState(doublereal* y) { phase_t& mix = *m_mix; // define for readability // The components of y are the total internal energy, // the total volume, and the mass of each species. // Set the mass fractions and density of the mixture. doublereal u = y[0]; m_vol = y[1]; doublereal* mss = y + 2; doublereal mass = accumulate(y+2, y+2+m_nsp, 0.0); m_mix->setMassFractions(mss); m_mix->setDensity(mass/m_vol); doublereal temp = temperature(); mix.setTemperature(temp); if (m_energy) { doublereal u_mass = u/mass; // specific int. energy doublereal delta; do { delta = -(m_thermo->intEnergy_mass() - u_mass)/m_thermo->cv_mass(); temp += delta; mix.setTemperature(temp); } while (fabs(delta) > m_temp_atol); } mix.setTemperature(temp); m_state[0] = temp; int loc = m_nsp + 2; SurfPhase* surf; for (int m = 0; m < m_nwalls; m++) { surf = m_wall[m]->surface(m_lr[m]); if (surf) { surf->setTemperature(temp); surf->setCoverages(y+loc); loc += surf->nSpecies(); } } // save parameters needed by other connected reactors m_enthalpy = m_thermo->enthalpy_mass(); m_pressure = m_thermo->pressure(); m_intEnergy = m_thermo->intEnergy_mass(); } /** * Called by the integrator to evaluate ydot given y at time 'time'. */ void Reactor::eval(doublereal time, doublereal* y, doublereal* ydot) { int i, k, nk; m_time = time; updateState(y); // synchronize the reactor state with y m_vdot = 0.0; m_Q = 0.0; // compute wall terms doublereal vdot, rs0, sum, wallarea; Kinetics* kin; SurfPhase* surf; int lr, ns, loc = m_nsp+2, surfloc; fill(m_sdot.begin(), m_sdot.end(), 0.0); for (i = 0; i < m_nwalls; i++) { lr = 1 - 2*m_lr[i]; vdot = lr*m_wall[i]->vdot(time); m_vdot += vdot; m_Q += lr*m_wall[i]->Q(time); kin = m_wall[i]->kinetics(m_lr[i]); surf = m_wall[i]->surface(m_lr[i]); if (surf && kin) { rs0 = 1.0/surf->siteDensity(); nk = surf->nSpecies(); sum = 0.0; kin->getNetProductionRates(m_work.begin()); ns = kin->surfacePhaseIndex(); surfloc = kin->kineticsSpeciesIndex(0,ns); for (k = 1; k < nk; k++) { ydot[loc + k] = m_work[surfloc+k]*rs0*surf->size(k); sum -= ydot[loc + k]; } ydot[loc] = sum; loc += nk; wallarea = m_wall[i]->area(); for (k = 0; k < m_nsp; k++) { m_sdot[k] += m_work[k]*wallarea; } } } // volume equation ydot[1] = m_vdot; /* species equations * Equation is: * \dot M_k = \hat W_k \dot\omega_k + \dot m_{in} Y_{k,in} * - \dot m_{out} Y_{k} + A \dot s_k. */ const doublereal* mw = m_mix->molecularWeights().begin(); int n; m_kin->getNetProductionRates(ydot+2); // "omega dot" for (n = 0; n < m_nsp; n++) { ydot[n+2] *= m_vol; // moles/s/m^3 -> moles/s ydot[n+2] += m_sdot[n]; ydot[n+2] *= mw[n]; } /** * Energy equation. * \dot U = -P\dot V + A \dot q + \dot m_{in} h_{in} * - \dot m_{out} h. */ if (m_energy) { ydot[0] = - m_thermo->pressure() * m_vdot - m_Q; } else { ydot[0] = 0.0; } // add terms for open system if (m_open) { const doublereal* mf = m_mix->massFractions(); doublereal enthalpy = m_thermo->enthalpy_mass(); // outlets int n; doublereal mdot_out; for (i = 0; i < m_nOutlets; i++) { mdot_out = m_outlet[i]->massFlowRate(); for (n = 0; n < m_nsp; n++) { ydot[2+n] -= mdot_out * mf[n]; } ydot[0] -= mdot_out * enthalpy; } // inlets doublereal mdot_in; for (i = 0; i < m_nInlets; i++) { mdot_in = m_inlet[i]->massFlowRate(); for (n = 0; n < m_nsp; n++) { ydot[2+n] += m_inlet[i]->massFlowRate(n); } ydot[0] += mdot_in * m_inlet[i]->enthalpy_mass(); } } } } <|endoftext|>
<commit_before><commit_msg>runtime/profiling: more fixes for threading<commit_after><|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDataObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.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 notices for more information. =========================================================================*/ #include "itkDataObject.h" #include "itkProcessObject.h" #include "itkObjectFactory.h" #include "itkSmartPointerForwardReference.txx" // Manual instantiation is necessary to prevent link errors template class itk::SmartPointerForwardReference<itk::ProcessObject>; namespace itk { // after use by filter bool DataObject::m_GlobalReleaseDataFlag = false; DataObjectError ::DataObjectError() : ExceptionObject(), m_DataObject(0) { } DataObjectError ::DataObjectError(const char *file, unsigned int lineNumber) : ExceptionObject(file, lineNumber), m_DataObject(0) { } DataObjectError ::DataObjectError(const std::string& file, unsigned int lineNumber) : ExceptionObject(file, lineNumber), m_DataObject(0) { } DataObjectError ::DataObjectError(const DataObjectError &orig) : ExceptionObject( orig ) { m_DataObject = orig.m_DataObject; } DataObjectError& DataObjectError ::operator=( const DataObjectError& orig) { ExceptionObject::operator= (orig); m_DataObject = orig.m_DataObject; return *this; } void DataObjectError ::SetDataObject(DataObject *dobj) { m_DataObject = dobj; } DataObject* DataObjectError ::GetDataObject() { return m_DataObject; } void DataObjectError ::PrintSelf(std::ostream& os, Indent indent) const { ExceptionObject::Print( os); os << indent << "Data object: "; if (m_DataObject) { os << std::endl; m_DataObject->PrintSelf(os, indent.GetNextIndent()); } else { os << "(None)" << std::endl; } } InvalidRequestedRegionError ::InvalidRequestedRegionError() : DataObjectError() { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const char *file, unsigned int lineNumber) : DataObjectError(file, lineNumber) { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const std::string& file, unsigned int lineNumber) : DataObjectError(file, lineNumber) { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const InvalidRequestedRegionError &orig) : DataObjectError( orig ) { } InvalidRequestedRegionError& InvalidRequestedRegionError ::operator=( const InvalidRequestedRegionError& orig) { DataObjectError::operator= (orig); return *this; } void InvalidRequestedRegionError ::PrintSelf(std::ostream& os, Indent indent) const { DataObjectError::PrintSelf( os, indent ); } //---------------------------------------------------------------------------- DataObject:: DataObject() : m_UpdateMTime() { m_Source = 0; m_SourceOutputIndex = 0; m_ReleaseDataFlag = false; // We have to assume that if a user is creating the data on their own, // then they will fill it with valid data. m_DataReleased = false; m_PipelineMTime = 0; } //---------------------------------------------------------------------------- DataObject ::~DataObject() { } //---------------------------------------------------------------------------- void DataObject ::Initialize() { // We don't modify ourselves because the "ReleaseData" methods depend upon // no modification when initialized. // } //---------------------------------------------------------------------------- void DataObject ::SetGlobalReleaseDataFlag(bool val) { if (val == m_GlobalReleaseDataFlag) { return; } m_GlobalReleaseDataFlag = val; } //---------------------------------------------------------------------------- bool DataObject ::GetGlobalReleaseDataFlag() { return m_GlobalReleaseDataFlag; } //---------------------------------------------------------------------------- void DataObject ::ReleaseData() { this->Initialize(); m_DataReleased = true; } //---------------------------------------------------------------------------- bool DataObject ::ShouldIReleaseData() const { return ( m_GlobalReleaseDataFlag || m_ReleaseDataFlag ); } //---------------------------------------------------------------------------- // Set the process object that generates this data object. // void DataObject ::DisconnectPipeline() { itkDebugMacro( "disconnecting from the pipeline." ); // disconnect ourselves from the current process object if (m_Source) { m_Source->SetNthOutput(m_SourceOutputIndex, 0); } // set our release data flag to off by default (purposely done after // we have disconnected from the pipeline so the new output of the // source can copy our original ReleaseDataFlag) this->ReleaseDataFlagOff(); // reset our PipelineMTime (there is now nothing upstream from us) m_PipelineMTime = 0; this->Modified(); } bool DataObject ::DisconnectSource(ProcessObject *arg, unsigned int idx) const { if ( m_Source == arg && m_SourceOutputIndex == idx) { itkDebugMacro( "disconnecting source " << arg << ", source output index " << idx); m_Source = 0; m_SourceOutputIndex = 0; this->Modified(); return true; } else { itkDebugMacro( "could not disconnect source " << arg << ", source output index " << idx); return false; } } bool DataObject ::ConnectSource(ProcessObject *arg, unsigned int idx) const { if ( m_Source != arg || m_SourceOutputIndex != idx) { itkDebugMacro( "connecting source " << arg << ", source output index " << idx); m_Source = arg; m_SourceOutputIndex = idx; this->Modified(); return true; } else { itkDebugMacro( "could not connect source " << arg << ", source output index " << idx); return false; } } //---------------------------------------------------------------------------- SmartPointerForwardReference<ProcessObject> DataObject ::GetSource() const { itkDebugMacro("returning Source address " << m_Source.GetPointer() ); return m_Source.GetPointer(); } unsigned int DataObject ::GetSourceOutputIndex() const { itkDebugMacro("returning Source index " << m_SourceOutputIndex ); return m_SourceOutputIndex; } //---------------------------------------------------------------------------- void DataObject ::PrintSelf(std::ostream& os, Indent indent) const { Object::PrintSelf(os,indent); if ( m_Source ) { os << indent << "Source: (" << m_Source.GetPointer() << ") \n"; os << indent << "Source output index: " << m_SourceOutputIndex << "\n"; } else { os << indent << "Source: (none)\n"; os << indent << "Source output index: 0\n"; } os << indent << "Release Data: " << (m_ReleaseDataFlag ? "On\n" : "Off\n"); os << indent << "Data Released: " << (m_DataReleased ? "True\n" : "False\n"); os << indent << "Global Release Data: " << (m_GlobalReleaseDataFlag ? "On\n" : "Off\n"); os << indent << "PipelineMTime: " << m_PipelineMTime << std::endl; os << indent << "UpdateMTime: " << m_UpdateMTime << std::endl; } // The following methods are used for updating the data processing pipeline. // //---------------------------------------------------------------------------- void DataObject ::Update() { this->UpdateOutputInformation(); this->PropagateRequestedRegion(); this->UpdateOutputData(); } void DataObject ::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } } void DataObject ::ResetPipeline() { this->PropagateResetPipeline(); } void DataObject ::PropagateResetPipeline() { if (m_Source) { m_Source->PropagateResetPipeline(); } } //---------------------------------------------------------------------------- void DataObject ::PropagateRequestedRegion() throw (InvalidRequestedRegionError) { // If we need to update due to PipelineMTime, or the fact that our // data was released, then propagate the update region to the source // if there is one. if ( m_UpdateMTime < m_PipelineMTime || m_DataReleased || this->RequestedRegionIsOutsideOfTheBufferedRegion() ) { if ( m_Source ) { m_Source->PropagateRequestedRegion(this); } } // Check that the requested region lies within the largest possible region if ( ! this->VerifyRequestedRegion() ) { // invalid requested region, throw an exception InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(this); throw e; // return; } } //---------------------------------------------------------------------------- void DataObject ::UpdateOutputData() { // If we need to update due to PipelineMTime, or the fact that our // data was released, then propagate the UpdateOutputData to the source // if there is one. if ( m_UpdateMTime < m_PipelineMTime || m_DataReleased || this->RequestedRegionIsOutsideOfTheBufferedRegion() ) { if ( m_Source ) { m_Source->UpdateOutputData(this); } } } //---------------------------------------------------------------------------- void DataObject ::DataHasBeenGenerated() { m_DataReleased = 0; this->Modified(); m_UpdateMTime.Modified(); } //---------------------------------------------------------------------------- unsigned long DataObject ::GetUpdateMTime() const { return m_UpdateMTime.GetMTime(); } } // end namespace itk <commit_msg>BUG: 5647. Attempting to solve link issue in MinGW when using Shared libraries.<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDataObject.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. Portions of this code are covered under the VTK copyright. See VTKCopyright.txt or http://www.kitware.com/VTKCopyright.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 notices for more information. =========================================================================*/ #include "itkDataObject.h" #include "itkProcessObject.h" #include "itkObjectFactory.h" #include "itkSmartPointerForwardReference.txx" // Manual instantiation is necessary to prevent link errors ITKCommon_EXPORT template class itk::SmartPointerForwardReference<itk::ProcessObject>; namespace itk { // after use by filter bool DataObject::m_GlobalReleaseDataFlag = false; DataObjectError ::DataObjectError() : ExceptionObject(), m_DataObject(0) { } DataObjectError ::DataObjectError(const char *file, unsigned int lineNumber) : ExceptionObject(file, lineNumber), m_DataObject(0) { } DataObjectError ::DataObjectError(const std::string& file, unsigned int lineNumber) : ExceptionObject(file, lineNumber), m_DataObject(0) { } DataObjectError ::DataObjectError(const DataObjectError &orig) : ExceptionObject( orig ) { m_DataObject = orig.m_DataObject; } DataObjectError& DataObjectError ::operator=( const DataObjectError& orig) { ExceptionObject::operator= (orig); m_DataObject = orig.m_DataObject; return *this; } void DataObjectError ::SetDataObject(DataObject *dobj) { m_DataObject = dobj; } DataObject* DataObjectError ::GetDataObject() { return m_DataObject; } void DataObjectError ::PrintSelf(std::ostream& os, Indent indent) const { ExceptionObject::Print( os); os << indent << "Data object: "; if (m_DataObject) { os << std::endl; m_DataObject->PrintSelf(os, indent.GetNextIndent()); } else { os << "(None)" << std::endl; } } InvalidRequestedRegionError ::InvalidRequestedRegionError() : DataObjectError() { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const char *file, unsigned int lineNumber) : DataObjectError(file, lineNumber) { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const std::string& file, unsigned int lineNumber) : DataObjectError(file, lineNumber) { } InvalidRequestedRegionError ::InvalidRequestedRegionError(const InvalidRequestedRegionError &orig) : DataObjectError( orig ) { } InvalidRequestedRegionError& InvalidRequestedRegionError ::operator=( const InvalidRequestedRegionError& orig) { DataObjectError::operator= (orig); return *this; } void InvalidRequestedRegionError ::PrintSelf(std::ostream& os, Indent indent) const { DataObjectError::PrintSelf( os, indent ); } //---------------------------------------------------------------------------- DataObject:: DataObject() : m_UpdateMTime() { m_Source = 0; m_SourceOutputIndex = 0; m_ReleaseDataFlag = false; // We have to assume that if a user is creating the data on their own, // then they will fill it with valid data. m_DataReleased = false; m_PipelineMTime = 0; } //---------------------------------------------------------------------------- DataObject ::~DataObject() { } //---------------------------------------------------------------------------- void DataObject ::Initialize() { // We don't modify ourselves because the "ReleaseData" methods depend upon // no modification when initialized. // } //---------------------------------------------------------------------------- void DataObject ::SetGlobalReleaseDataFlag(bool val) { if (val == m_GlobalReleaseDataFlag) { return; } m_GlobalReleaseDataFlag = val; } //---------------------------------------------------------------------------- bool DataObject ::GetGlobalReleaseDataFlag() { return m_GlobalReleaseDataFlag; } //---------------------------------------------------------------------------- void DataObject ::ReleaseData() { this->Initialize(); m_DataReleased = true; } //---------------------------------------------------------------------------- bool DataObject ::ShouldIReleaseData() const { return ( m_GlobalReleaseDataFlag || m_ReleaseDataFlag ); } //---------------------------------------------------------------------------- // Set the process object that generates this data object. // void DataObject ::DisconnectPipeline() { itkDebugMacro( "disconnecting from the pipeline." ); // disconnect ourselves from the current process object if (m_Source) { m_Source->SetNthOutput(m_SourceOutputIndex, 0); } // set our release data flag to off by default (purposely done after // we have disconnected from the pipeline so the new output of the // source can copy our original ReleaseDataFlag) this->ReleaseDataFlagOff(); // reset our PipelineMTime (there is now nothing upstream from us) m_PipelineMTime = 0; this->Modified(); } bool DataObject ::DisconnectSource(ProcessObject *arg, unsigned int idx) const { if ( m_Source == arg && m_SourceOutputIndex == idx) { itkDebugMacro( "disconnecting source " << arg << ", source output index " << idx); m_Source = 0; m_SourceOutputIndex = 0; this->Modified(); return true; } else { itkDebugMacro( "could not disconnect source " << arg << ", source output index " << idx); return false; } } bool DataObject ::ConnectSource(ProcessObject *arg, unsigned int idx) const { if ( m_Source != arg || m_SourceOutputIndex != idx) { itkDebugMacro( "connecting source " << arg << ", source output index " << idx); m_Source = arg; m_SourceOutputIndex = idx; this->Modified(); return true; } else { itkDebugMacro( "could not connect source " << arg << ", source output index " << idx); return false; } } //---------------------------------------------------------------------------- SmartPointerForwardReference<ProcessObject> DataObject ::GetSource() const { itkDebugMacro("returning Source address " << m_Source.GetPointer() ); return m_Source.GetPointer(); } unsigned int DataObject ::GetSourceOutputIndex() const { itkDebugMacro("returning Source index " << m_SourceOutputIndex ); return m_SourceOutputIndex; } //---------------------------------------------------------------------------- void DataObject ::PrintSelf(std::ostream& os, Indent indent) const { Object::PrintSelf(os,indent); if ( m_Source ) { os << indent << "Source: (" << m_Source.GetPointer() << ") \n"; os << indent << "Source output index: " << m_SourceOutputIndex << "\n"; } else { os << indent << "Source: (none)\n"; os << indent << "Source output index: 0\n"; } os << indent << "Release Data: " << (m_ReleaseDataFlag ? "On\n" : "Off\n"); os << indent << "Data Released: " << (m_DataReleased ? "True\n" : "False\n"); os << indent << "Global Release Data: " << (m_GlobalReleaseDataFlag ? "On\n" : "Off\n"); os << indent << "PipelineMTime: " << m_PipelineMTime << std::endl; os << indent << "UpdateMTime: " << m_UpdateMTime << std::endl; } // The following methods are used for updating the data processing pipeline. // //---------------------------------------------------------------------------- void DataObject ::Update() { this->UpdateOutputInformation(); this->PropagateRequestedRegion(); this->UpdateOutputData(); } void DataObject ::UpdateOutputInformation() { if (this->GetSource()) { this->GetSource()->UpdateOutputInformation(); } } void DataObject ::ResetPipeline() { this->PropagateResetPipeline(); } void DataObject ::PropagateResetPipeline() { if (m_Source) { m_Source->PropagateResetPipeline(); } } //---------------------------------------------------------------------------- void DataObject ::PropagateRequestedRegion() throw (InvalidRequestedRegionError) { // If we need to update due to PipelineMTime, or the fact that our // data was released, then propagate the update region to the source // if there is one. if ( m_UpdateMTime < m_PipelineMTime || m_DataReleased || this->RequestedRegionIsOutsideOfTheBufferedRegion() ) { if ( m_Source ) { m_Source->PropagateRequestedRegion(this); } } // Check that the requested region lies within the largest possible region if ( ! this->VerifyRequestedRegion() ) { // invalid requested region, throw an exception InvalidRequestedRegionError e(__FILE__, __LINE__); e.SetLocation(ITK_LOCATION); e.SetDescription("Requested region is (at least partially) outside the largest possible region."); e.SetDataObject(this); throw e; // return; } } //---------------------------------------------------------------------------- void DataObject ::UpdateOutputData() { // If we need to update due to PipelineMTime, or the fact that our // data was released, then propagate the UpdateOutputData to the source // if there is one. if ( m_UpdateMTime < m_PipelineMTime || m_DataReleased || this->RequestedRegionIsOutsideOfTheBufferedRegion() ) { if ( m_Source ) { m_Source->UpdateOutputData(this); } } } //---------------------------------------------------------------------------- void DataObject ::DataHasBeenGenerated() { m_DataReleased = 0; this->Modified(); m_UpdateMTime.Modified(); } //---------------------------------------------------------------------------- unsigned long DataObject ::GetUpdateMTime() const { return m_UpdateMTime.GetMTime(); } } // end namespace itk <|endoftext|>
<commit_before>#include <handy/handy.h> using namespace std; using namespace handy; struct Report { long connected; long retry; long sended; long recved; Report() { memset(this, 0, sizeof(*this)); } }; int main(int argc, const char* argv[]) { if (argc < 9) { printf("usage %s <host> <begin port> <end port> <conn count> <create seconds> <subprocesses> <hearbeat interval> <send size> <management port>\n", argv[0]); return 1; } int c = 1; string host = argv[c++]; int begin_port = atoi(argv[c++]); int end_port = atoi(argv[c++]); int conn_count = atoi(argv[c++]); int create_seconds = atoi(argv[c++]); int processes = atoi(argv[c++]); conn_count = conn_count / processes; int heartbeat_interval = atoi(argv[c++]); int bsz = atoi(argv[c++]); int man_port = atoi(argv[c++]); int pid = 1; for (int i = 0; i < processes; i ++) { pid = fork(); if (pid == 0) { // a child process, break sleep(1); break; } } EventBase base; if (pid == 0) { //child process char *buf = new char[bsz]; ExitCaller ec1([=] {delete[] buf; }); Slice msg(buf, bsz); char heartbeat[] = "heartbeat"; int send = 0; int connected = 0; int retry = 0; int recved = 0; vector<TcpConnPtr> allConns; info("creating %d connections", conn_count); for (int k = 0; k < create_seconds; k ++) { base.runAfter(1000*k, [&]{ int c = conn_count / create_seconds; for (int i = 0; i < c; i++) { short port = begin_port + (i % (end_port - begin_port)); auto con = TcpConn::createConnection(&base, host, port, 20*1000); allConns.push_back(con); con->setReconnectInterval(20*1000); con->onMsg(new LengthCodec, [&](const TcpConnPtr& con, const Slice& msg) { if (heartbeat_interval == 0) { // echo the msg if no interval con->sendMsg(msg); send++; } recved ++; }); con->onState([&, i](const TcpConnPtr &con) { TcpConn::State st = con->getState(); if (st == TcpConn::Connected) { connected++; // send ++; // con->sendMsg(msg); } else if (st == TcpConn::Failed || st == TcpConn::Closed) { //连接出错 if (st == TcpConn::Closed) { connected--; } retry++; } }); } }); } if (heartbeat_interval) { base.runAfter(heartbeat_interval * 1000, [&] { for (int i = 0; i < heartbeat_interval; i ++) { base.runAfter(i*1000, [&,i]{ size_t block = allConns.size() / heartbeat_interval; for (size_t j=i*block; j<(i+1)*block && j<allConns.size(); j++) { if (allConns[i]->getState() == TcpConn::Connected) { allConns[i]->sendMsg(msg); send++; } } }); } }, heartbeat_interval * 1000); } TcpConnPtr report = TcpConn::createConnection(&base, "127.0.0.1", man_port, 3000); report->onMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) { if (msg == "exit") { info("recv exit msg from master, so exit"); base.exit(); } }); report->onState([&](const TcpConnPtr& con) { if (con->getState() == TcpConn::Closed) { base.exit(); } }); base.runAfter(2000, [&]() { report->sendMsg(util::format("%d connected: %ld retry: %ld send: %ld recved: %ld", getpid(), connected, retry, send, recved)); }, 100); base.loop(); } else { // master process map<int, Report> subs; TcpServerPtr master = TcpServer::startServer(&base, "127.0.0.1", man_port); master->onConnMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) { auto fs = msg.split(' '); if (fs.size() != 9) { error("number of fields is %lu expected 7", fs.size()); return; } Report& c = subs[atoi(fs[0].data())]; c.connected = atoi(fs[2].data()); c.retry= atoi(fs[4].data()); c.sended = atoi(fs[6].data()); c.recved = atoi(fs[8].data()); }); base.runAfter(3000, [&](){ for(auto& s: subs) { Report& r = s.second; printf("pid: %6ld connected %6ld retry %6ld sended %6ld recved %6ld\n", (long)s.first, r.connected, r.retry, r.sended, r.recved); } printf("\n"); }, 3000); base.loop(); } info("program exited"); } <commit_msg>add signal handling<commit_after>#include <handy/handy.h> using namespace std; using namespace handy; struct Report { long connected; long retry; long sended; long recved; Report() { memset(this, 0, sizeof(*this)); } }; int main(int argc, const char* argv[]) { if (argc < 9) { printf("usage %s <host> <begin port> <end port> <conn count> <create seconds> <subprocesses> <hearbeat interval> <send size> <management port>\n", argv[0]); return 1; } int c = 1; string host = argv[c++]; int begin_port = atoi(argv[c++]); int end_port = atoi(argv[c++]); int conn_count = atoi(argv[c++]); int create_seconds = atoi(argv[c++]); int processes = atoi(argv[c++]); conn_count = conn_count / processes; int heartbeat_interval = atoi(argv[c++]); int bsz = atoi(argv[c++]); int man_port = atoi(argv[c++]); int pid = 1; for (int i = 0; i < processes; i ++) { pid = fork(); if (pid == 0) { // a child process, break sleep(1); break; } } EventBase base; if (pid == 0) { //child process char *buf = new char[bsz]; ExitCaller ec1([=] {delete[] buf; }); Slice msg(buf, bsz); char heartbeat[] = "heartbeat"; int send = 0; int connected = 0; int retry = 0; int recved = 0; vector<TcpConnPtr> allConns; info("creating %d connections", conn_count); for (int k = 0; k < create_seconds; k ++) { base.runAfter(1000*k, [&]{ int c = conn_count / create_seconds; for (int i = 0; i < c; i++) { short port = begin_port + (i % (end_port - begin_port)); auto con = TcpConn::createConnection(&base, host, port, 20*1000); allConns.push_back(con); con->setReconnectInterval(20*1000); con->onMsg(new LengthCodec, [&](const TcpConnPtr& con, const Slice& msg) { if (heartbeat_interval == 0) { // echo the msg if no interval con->sendMsg(msg); send++; } recved ++; }); con->onState([&, i](const TcpConnPtr &con) { TcpConn::State st = con->getState(); if (st == TcpConn::Connected) { connected++; // send ++; // con->sendMsg(msg); } else if (st == TcpConn::Failed || st == TcpConn::Closed) { //连接出错 if (st == TcpConn::Closed) { connected--; } retry++; } }); } }); } if (heartbeat_interval) { base.runAfter(heartbeat_interval * 1000, [&] { for (int i = 0; i < heartbeat_interval; i ++) { base.runAfter(i*1000, [&,i]{ size_t block = allConns.size() / heartbeat_interval; for (size_t j=i*block; j<(i+1)*block && j<allConns.size(); j++) { if (allConns[i]->getState() == TcpConn::Connected) { allConns[i]->sendMsg(msg); send++; } } }); } }, heartbeat_interval * 1000); } TcpConnPtr report = TcpConn::createConnection(&base, "127.0.0.1", man_port, 3000); report->onMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) { if (msg == "exit") { info("recv exit msg from master, so exit"); base.exit(); } }); report->onState([&](const TcpConnPtr& con) { if (con->getState() == TcpConn::Closed) { base.exit(); } }); base.runAfter(2000, [&]() { report->sendMsg(util::format("%d connected: %ld retry: %ld send: %ld recved: %ld", getpid(), connected, retry, send, recved)); }, 100); base.loop(); } else { // master process map<int, Report> subs; TcpServerPtr master = TcpServer::startServer(&base, "127.0.0.1", man_port); master->onConnMsg(new LineCodec, [&](const TcpConnPtr& con, Slice msg) { auto fs = msg.split(' '); if (fs.size() != 9) { error("number of fields is %lu expected 7", fs.size()); return; } Report& c = subs[atoi(fs[0].data())]; c.connected = atoi(fs[2].data()); c.retry= atoi(fs[4].data()); c.sended = atoi(fs[6].data()); c.recved = atoi(fs[8].data()); }); base.runAfter(3000, [&](){ for(auto& s: subs) { Report& r = s.second; printf("pid: %6ld connected %6ld retry %6ld sended %6ld recved %6ld\n", (long)s.first, r.connected, r.retry, r.sended, r.recved); } printf("\n"); }, 3000); Signal::signal(SIGCHLD, []{ int status = 0; wait(&status); error("wait result: status: %d is signaled: %d signal: %d", status, WIFSIGNALED(status), WTERMSIG(status)); }); base.loop(); } info("program exited"); } <|endoftext|>
<commit_before>#include "routing/index_graph_starter.hpp" #include "geometry/distance.hpp" namespace { using namespace routing; m2::PointD CalcProjectionToSegment(Segment const & segment, m2::PointD const & point, WorldGraph & graph) { m2::ProjectionToSection<m2::PointD> projection; projection.SetBounds(graph.GetPoint(segment, false), graph.GetPoint(segment, true)); return projection(point); } } namespace routing { // static Segment constexpr IndexGraphStarter::kStartFakeSegment; Segment constexpr IndexGraphStarter::kFinishFakeSegment; IndexGraphStarter::IndexGraphStarter(FakeVertex const & start, FakeVertex const & finish, WorldGraph & graph) : m_graph(graph) , m_start(start.GetSegment(), CalcProjectionToSegment(start.GetSegment(), start.GetPoint(), graph)) , m_finish(finish.GetSegment(), CalcProjectionToSegment(finish.GetSegment(), finish.GetPoint(), graph)) { } m2::PointD const & IndexGraphStarter::GetPoint(Segment const & segment, bool front) { if (segment == kStartFakeSegment || (!front && m_start.Fits(segment))) return m_start.GetPoint(); if (segment == kFinishFakeSegment || (front && m_finish.Fits(segment))) return m_finish.GetPoint(); return m_graph.GetPoint(segment, front); } // static size_t IndexGraphStarter::GetRouteNumPoints(vector<Segment> const & segments) { // Valid route contains at least 3 segments: // start fake, finish fake and at least one normal nearest segment. CHECK_GREATER_OR_EQUAL(segments.size(), 3, ()); // -2 for fake start and finish. // +1 for front point of first segment. return segments.size() - 1; } m2::PointD const & IndexGraphStarter::GetRoutePoint(vector<Segment> const & segments, size_t pointIndex) { if (pointIndex == 0) return m_start.GetPoint(); CHECK_LESS(pointIndex, segments.size(), ()); return GetPoint(segments[pointIndex], true /* front */); } void IndexGraphStarter::GetEdgesList(Segment const & segment, bool isOutgoing, vector<SegmentEdge> & edges) { edges.clear(); if (segment == kStartFakeSegment) { GetFakeToNormalEdges(m_start, isOutgoing, edges); return; } if (segment == kFinishFakeSegment) { GetFakeToNormalEdges(m_finish, isOutgoing, edges); return; } m_graph.GetEdgeList(segment, isOutgoing, IsLeap(segment.GetMwmId()), edges); GetNormalToFakeEdge(segment, m_start, kStartFakeSegment, isOutgoing, edges); GetNormalToFakeEdge(segment, m_finish, kFinishFakeSegment, isOutgoing, edges); } void IndexGraphStarter::GetFakeToNormalEdges(FakeVertex const & fakeVertex, bool isOutgoing, vector<SegmentEdge> & edges) { if (m_graph.GetMode() == WorldGraph::Mode::LeapsOnly) { ConnectLeapToTransitions(fakeVertex, isOutgoing, edges); return; } GetFakeToNormalEdge(fakeVertex, true /* forward */, edges); if (!m_graph.GetRoadGeometry(fakeVertex.GetMwmId(), fakeVertex.GetFeatureId()).IsOneWay()) GetFakeToNormalEdge(fakeVertex, false /* forward */, edges); } void IndexGraphStarter::GetFakeToNormalEdge(FakeVertex const & fakeVertex, bool forward, vector<SegmentEdge> & edges) { auto const segment = fakeVertex.GetSegmentWithDirection(forward); m2::PointD const & pointTo = GetPoint(segment, true /* front */); double const weight = m_graph.GetEstimator().CalcLeapWeight(fakeVertex.GetPoint(), pointTo); edges.emplace_back(segment, weight); } void IndexGraphStarter::GetNormalToFakeEdge(Segment const & segment, FakeVertex const & fakeVertex, Segment const & fakeSegment, bool isOutgoing, vector<SegmentEdge> & edges) { m2::PointD const & pointFrom = GetPoint(segment, isOutgoing); if (segment.GetMwmId() == fakeVertex.GetMwmId() && m_graph.GetMode() == WorldGraph::Mode::LeapsOnly) { if (m_graph.IsTransition(segment, isOutgoing)) { edges.emplace_back(fakeSegment, m_graph.GetEstimator().CalcLeapWeight(pointFrom, fakeVertex.GetPoint())); } return; } if (!fakeVertex.Fits(segment)) return; edges.emplace_back(fakeSegment, m_graph.GetEstimator().CalcLeapWeight(pointFrom, fakeVertex.GetPoint())); } void IndexGraphStarter::ConnectLeapToTransitions(FakeVertex const & fakeVertex, bool isOutgoing, vector<SegmentEdge> & edges) { edges.clear(); m2::PointD const & segmentPoint = fakeVertex.GetPoint(); // Note. If |isOutgoing| == true it's necessary to add edges which connect the start with all // exits of its mwm. So |isEnter| below should be set to false. // If |isOutgoing| == false all enters of the finish mwm should be connected with the finish point. // So |isEnter| below should be set to true. m_graph.ForEachTransition( fakeVertex.GetMwmId(), !isOutgoing /* isEnter */, [&](Segment const & transition) { edges.emplace_back(transition, m_graph.GetEstimator().CalcLeapWeight( segmentPoint, GetPoint(transition, isOutgoing))); }); } } // namespace routing <commit_msg>[routing] Pull request #6054 review fixes<commit_after>#include "routing/index_graph_starter.hpp" #include "geometry/distance.hpp" namespace { using namespace routing; m2::PointD CalcProjectionToSegment(Segment const & segment, m2::PointD const & point, WorldGraph & graph) { m2::ProjectionToSection<m2::PointD> projection; projection.SetBounds(graph.GetPoint(segment, false /* front */), graph.GetPoint(segment, true /* front */)); return projection(point); } } // namespace namespace routing { // static Segment constexpr IndexGraphStarter::kStartFakeSegment; Segment constexpr IndexGraphStarter::kFinishFakeSegment; IndexGraphStarter::IndexGraphStarter(FakeVertex const & start, FakeVertex const & finish, WorldGraph & graph) : m_graph(graph) , m_start(start.GetSegment(), CalcProjectionToSegment(start.GetSegment(), start.GetPoint(), graph)) , m_finish(finish.GetSegment(), CalcProjectionToSegment(finish.GetSegment(), finish.GetPoint(), graph)) { } m2::PointD const & IndexGraphStarter::GetPoint(Segment const & segment, bool front) { if (segment == kStartFakeSegment || (!front && m_start.Fits(segment))) return m_start.GetPoint(); if (segment == kFinishFakeSegment || (front && m_finish.Fits(segment))) return m_finish.GetPoint(); return m_graph.GetPoint(segment, front); } // static size_t IndexGraphStarter::GetRouteNumPoints(vector<Segment> const & segments) { // Valid route contains at least 3 segments: // start fake, finish fake and at least one normal nearest segment. CHECK_GREATER_OR_EQUAL(segments.size(), 3, ()); // -2 for fake start and finish. // +1 for front point of first segment. return segments.size() - 1; } m2::PointD const & IndexGraphStarter::GetRoutePoint(vector<Segment> const & segments, size_t pointIndex) { if (pointIndex == 0) return m_start.GetPoint(); CHECK_LESS(pointIndex, segments.size(), ()); return GetPoint(segments[pointIndex], true /* front */); } void IndexGraphStarter::GetEdgesList(Segment const & segment, bool isOutgoing, vector<SegmentEdge> & edges) { edges.clear(); if (segment == kStartFakeSegment) { GetFakeToNormalEdges(m_start, isOutgoing, edges); return; } if (segment == kFinishFakeSegment) { GetFakeToNormalEdges(m_finish, isOutgoing, edges); return; } m_graph.GetEdgeList(segment, isOutgoing, IsLeap(segment.GetMwmId()), edges); GetNormalToFakeEdge(segment, m_start, kStartFakeSegment, isOutgoing, edges); GetNormalToFakeEdge(segment, m_finish, kFinishFakeSegment, isOutgoing, edges); } void IndexGraphStarter::GetFakeToNormalEdges(FakeVertex const & fakeVertex, bool isOutgoing, vector<SegmentEdge> & edges) { if (m_graph.GetMode() == WorldGraph::Mode::LeapsOnly) { ConnectLeapToTransitions(fakeVertex, isOutgoing, edges); return; } GetFakeToNormalEdge(fakeVertex, true /* forward */, edges); if (!m_graph.GetRoadGeometry(fakeVertex.GetMwmId(), fakeVertex.GetFeatureId()).IsOneWay()) GetFakeToNormalEdge(fakeVertex, false /* forward */, edges); } void IndexGraphStarter::GetFakeToNormalEdge(FakeVertex const & fakeVertex, bool forward, vector<SegmentEdge> & edges) { auto const segment = fakeVertex.GetSegmentWithDirection(forward); m2::PointD const & pointTo = GetPoint(segment, true /* front */); double const weight = m_graph.GetEstimator().CalcLeapWeight(fakeVertex.GetPoint(), pointTo); edges.emplace_back(segment, weight); } void IndexGraphStarter::GetNormalToFakeEdge(Segment const & segment, FakeVertex const & fakeVertex, Segment const & fakeSegment, bool isOutgoing, vector<SegmentEdge> & edges) { m2::PointD const & pointFrom = GetPoint(segment, isOutgoing); if (segment.GetMwmId() == fakeVertex.GetMwmId() && m_graph.GetMode() == WorldGraph::Mode::LeapsOnly) { if (m_graph.IsTransition(segment, isOutgoing)) { edges.emplace_back(fakeSegment, m_graph.GetEstimator().CalcLeapWeight(pointFrom, fakeVertex.GetPoint())); } return; } if (!fakeVertex.Fits(segment)) return; edges.emplace_back(fakeSegment, m_graph.GetEstimator().CalcLeapWeight(pointFrom, fakeVertex.GetPoint())); } void IndexGraphStarter::ConnectLeapToTransitions(FakeVertex const & fakeVertex, bool isOutgoing, vector<SegmentEdge> & edges) { edges.clear(); m2::PointD const & segmentPoint = fakeVertex.GetPoint(); // Note. If |isOutgoing| == true it's necessary to add edges which connect the start with all // exits of its mwm. So |isEnter| below should be set to false. // If |isOutgoing| == false all enters of the finish mwm should be connected with the finish point. // So |isEnter| below should be set to true. m_graph.ForEachTransition( fakeVertex.GetMwmId(), !isOutgoing /* isEnter */, [&](Segment const & transition) { edges.emplace_back(transition, m_graph.GetEstimator().CalcLeapWeight( segmentPoint, GetPoint(transition, isOutgoing))); }); } } // namespace routing <|endoftext|>
<commit_before>#include "Terrain.hpp" namespace Chimera { Terrain::Terrain() { SetDefaults(); } Terrain::~Terrain() {} void Terrain::SetDefaults() { terrain.setDefaults(); VertexBufferObject = 0; IndexBufferObject = 0; } bool Terrain::LoadTexture2D(char* FileName, float Scale, float Offset) { return terrain.loadTexture2D(FileName, Scale, Offset); } bool Terrain::LoadBinary(char* FileName) { bool okLoad = terrain.loadBinary(FileName); unsigned int sizeBufferVertex = terrain.vertices.size() * sizeof(VertexData); unsigned int sizeBufferIndex = terrain.indices.size() * sizeof(unsigned int); glGenBuffers(1, &VertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, VertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeBufferVertex, &terrain.vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); glGenBuffers(1, &IndexBufferObject); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferObject); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeBufferIndex, &terrain.indices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // TODO: TESTAR SE VALORES PASSAM!!!!! bspTree.Init(&terrain.vertices[0], &terrain.indices[0], terrain.indices.size(), terrain.getMin(), terrain.getMax()); return true; } int Terrain::CheckVisibility(Frustum& _frustum, bool SortVisibleGeometryNodes) { return bspTree.CheckVisibility(_frustum, SortVisibleGeometryNodes); } void Terrain::Render(bool VisualizeRenderingOrder) { glBindBuffer(GL_ARRAY_BUFFER, VertexBufferObject); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(VertexData), (void*)(sizeof(glm::vec3) * 0)); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(VertexData), (void*)(sizeof(glm::vec3) * 1)); bspTree.Render(VisualizeRenderingOrder); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Terrain::RenderSlow() { glBindBuffer(GL_ARRAY_BUFFER, VertexBufferObject); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(VertexData), (void*)(sizeof(glm::vec3) * 0)); glEnableClientState(GL_NORMAL_ARRAY); glNormalPointer(GL_FLOAT, sizeof(VertexData), (void*)(sizeof(glm::vec3) * 1)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferObject); glDrawElements(GL_TRIANGLES, terrain.indices.size(), GL_UNSIGNED_INT, NULL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_NORMAL_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Terrain::RenderSlowToShadowMap() { glBindBuffer(GL_ARRAY_BUFFER, VertexBufferObject); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, sizeof(VertexData), (void*)(sizeof(glm::vec3) * 0)); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndexBufferObject); glDrawElements(GL_TRIANGLES, terrain.indices.size(), GL_UNSIGNED_INT, NULL); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Terrain::RenderAABB(int Depth) { bspTree.RenderAABB(Depth); } void Terrain::Destroy() { terrain.destroy(); if (VertexBufferObject != 0) { glDeleteBuffers(1, &VertexBufferObject); } if (IndexBufferObject != 0) { glDeleteBuffers(1, &IndexBufferObject); } bspTree.Destroy(); } } // namespace Chimera<commit_msg>removido antigo terrain<commit_after><|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xeview.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2007-02-27 12:36:55 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_XEVIEW_HXX #define SC_XEVIEW_HXX #ifndef SC_XLVIEW_HXX #include "xlview.hxx" #endif #ifndef SC_XEROOT_HXX #include "xeroot.hxx" #endif #ifndef SC_XERECORD_HXX #include "xerecord.hxx" #endif // Workbook view settings records ============================================= /** Represents the WINDOW1 record containing global workbook view settings. */ class XclExpWindow1 : public XclExpRecord { public: explicit XclExpWindow1( const XclExpRoot& rRoot ); private: /** Writes the contents of the WINDOW1 record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnFlags; /// Option flags. sal_uInt16 mnTabBarSize; /// Size of tabbar relative to window width (per mill). }; // Sheet view settings records ================================================ /** Represents a WINDOW2 record with general view settings for a sheet. */ class XclExpWindow2 : public XclExpRecord { public: explicit XclExpWindow2( const XclExpRoot& rRoot, const XclTabViewData& rData, sal_uInt32 nGridColorId ); private: /** Writes the contents of the WINDOW2 record. */ virtual void WriteBody( XclExpStream& rStrm ); private: Color maGridColor; /// Grid color (<=BIFF5). sal_uInt32 mnGridColorId; /// Color ID of grid color (>=BIFF8). sal_uInt16 mnFlags; /// Option flags. XclAddress maFirstXclPos; /// First visible cell. sal_uInt16 mnNormalZoom; /// Zoom factor for normal view. sal_uInt16 mnPageZoom; /// Zoom factor for pagebreak preview. }; // ---------------------------------------------------------------------------- /** Represents an SCL record for the zoom factor of the current view of a sheet. */ class XclExpScl : public XclExpRecord { public: explicit XclExpScl( sal_uInt16 nZoom ); private: /** Tries to shorten numerator and denominator by the passed value. */ void Shorten( sal_uInt16 nFactor ); /** Writes the contents of the SCL record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnNum; /// Numerator of the zoom factor. sal_uInt16 mnDenom; /// Denominator of the zoom factor. }; // ---------------------------------------------------------------------------- /** Represents a PANE record containing settings for split/frozen windows. */ class XclExpPane : public XclExpRecord { public: explicit XclExpPane( const XclTabViewData& rData ); private: /** Writes the contents of the PANE record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnSplitX; /// Split X position, or frozen column. sal_uInt16 mnSplitY; /// Split Y position, or frozen row. XclAddress maSecondXclPos; /// First visible cell in additional panes. sal_uInt8 mnActivePane; /// Active pane (with cell cursor). }; // ---------------------------------------------------------------------------- /** Represents a SELECTION record with selection data for a pane. */ class XclExpSelection : public XclExpRecord { public: explicit XclExpSelection( const XclTabViewData& rData, sal_uInt8 nPane ); private: /** Writes the contents of the SELECTION record. */ virtual void WriteBody( XclExpStream& rStrm ); private: XclSelectionData maSelData; /// Selection data. sal_uInt8 mnPane; /// Pane identifier of this selection. }; // View settings ============================================================== /** Contains all view settings records for a single sheet. */ class XclExpTabViewSettings : public XclExpRecordBase, protected XclExpRoot { public: /** Creates all records containing the view settings of the specified sheet. */ explicit XclExpTabViewSettings( const XclExpRoot& rRoot, SCTAB nScTab ); /** Writes all view settings records to the stream. */ virtual void Save( XclExpStream& rStrm ); private: /** Creates selection data for the specified pane. */ void CreateSelectionData( sal_uInt8 nPane, const ScAddress& rCursor, const ScRangeList& rSelection ); void WriteWindow2( XclExpStream& rStrm ) const; void WriteScl( XclExpStream& rStrm ) const; void WritePane( XclExpStream& rStrm ) const; void WriteSelection( XclExpStream& rStrm, sal_uInt8 nPane ) const; private: XclTabViewData maData; /// All view settings for a sheet. sal_uInt32 mnGridColorId; /// Color identifier for grid color. }; // ============================================================================ #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.330); FILE MERGED 2008/04/01 12:36:22 thb 1.4.330.2: #i85898# Stripping all external header guards 2008/03/31 17:14:46 rt 1.4.330.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xeview.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef SC_XEVIEW_HXX #define SC_XEVIEW_HXX #include "xlview.hxx" #include "xeroot.hxx" #include "xerecord.hxx" // Workbook view settings records ============================================= /** Represents the WINDOW1 record containing global workbook view settings. */ class XclExpWindow1 : public XclExpRecord { public: explicit XclExpWindow1( const XclExpRoot& rRoot ); private: /** Writes the contents of the WINDOW1 record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnFlags; /// Option flags. sal_uInt16 mnTabBarSize; /// Size of tabbar relative to window width (per mill). }; // Sheet view settings records ================================================ /** Represents a WINDOW2 record with general view settings for a sheet. */ class XclExpWindow2 : public XclExpRecord { public: explicit XclExpWindow2( const XclExpRoot& rRoot, const XclTabViewData& rData, sal_uInt32 nGridColorId ); private: /** Writes the contents of the WINDOW2 record. */ virtual void WriteBody( XclExpStream& rStrm ); private: Color maGridColor; /// Grid color (<=BIFF5). sal_uInt32 mnGridColorId; /// Color ID of grid color (>=BIFF8). sal_uInt16 mnFlags; /// Option flags. XclAddress maFirstXclPos; /// First visible cell. sal_uInt16 mnNormalZoom; /// Zoom factor for normal view. sal_uInt16 mnPageZoom; /// Zoom factor for pagebreak preview. }; // ---------------------------------------------------------------------------- /** Represents an SCL record for the zoom factor of the current view of a sheet. */ class XclExpScl : public XclExpRecord { public: explicit XclExpScl( sal_uInt16 nZoom ); private: /** Tries to shorten numerator and denominator by the passed value. */ void Shorten( sal_uInt16 nFactor ); /** Writes the contents of the SCL record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnNum; /// Numerator of the zoom factor. sal_uInt16 mnDenom; /// Denominator of the zoom factor. }; // ---------------------------------------------------------------------------- /** Represents a PANE record containing settings for split/frozen windows. */ class XclExpPane : public XclExpRecord { public: explicit XclExpPane( const XclTabViewData& rData ); private: /** Writes the contents of the PANE record. */ virtual void WriteBody( XclExpStream& rStrm ); private: sal_uInt16 mnSplitX; /// Split X position, or frozen column. sal_uInt16 mnSplitY; /// Split Y position, or frozen row. XclAddress maSecondXclPos; /// First visible cell in additional panes. sal_uInt8 mnActivePane; /// Active pane (with cell cursor). }; // ---------------------------------------------------------------------------- /** Represents a SELECTION record with selection data for a pane. */ class XclExpSelection : public XclExpRecord { public: explicit XclExpSelection( const XclTabViewData& rData, sal_uInt8 nPane ); private: /** Writes the contents of the SELECTION record. */ virtual void WriteBody( XclExpStream& rStrm ); private: XclSelectionData maSelData; /// Selection data. sal_uInt8 mnPane; /// Pane identifier of this selection. }; // View settings ============================================================== /** Contains all view settings records for a single sheet. */ class XclExpTabViewSettings : public XclExpRecordBase, protected XclExpRoot { public: /** Creates all records containing the view settings of the specified sheet. */ explicit XclExpTabViewSettings( const XclExpRoot& rRoot, SCTAB nScTab ); /** Writes all view settings records to the stream. */ virtual void Save( XclExpStream& rStrm ); private: /** Creates selection data for the specified pane. */ void CreateSelectionData( sal_uInt8 nPane, const ScAddress& rCursor, const ScRangeList& rSelection ); void WriteWindow2( XclExpStream& rStrm ) const; void WriteScl( XclExpStream& rStrm ) const; void WritePane( XclExpStream& rStrm ) const; void WriteSelection( XclExpStream& rStrm, sal_uInt8 nPane ) const; private: XclTabViewData maData; /// All view settings for a sheet. sal_uInt32 mnGridColorId; /// Color identifier for grid color. }; // ============================================================================ #endif <|endoftext|>
<commit_before>/*************************************************************** * * Copyright (C) 2009-2011 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_daemon_core.h" #include "condor_debug.h" #include "condor_attributes.h" #include "get_daemon_name.h" #include "subsystem_info.h" #include "condor_config.h" #include "stat_info.h" #include "broker_utils.h" #include "stringSpace.h" #include "JobLogMirror.h" #include "JobServerJobLogConsumer.h" #include "JobServerObject.h" #include "HistoryProcessingUtils.h" #include "Globals.h" /* Using daemoncore, you get the benefits of a logging system with dprintf and you can read config files automatically. To start testing your daemon, run it with "-f -t" until you start specifying a config file to use(the daemon will automatically look in /etc/condor_config, /usr/local/etc/condor_config, ~condor/condor_config, or the env CONDOR_CONFIG if -t is not specifed). -f means run in the foreground, -t means print the debugging output to the terminal. */ //------------------------------------------------------------- using namespace qpid::management; using namespace qpid::types; using namespace qmf::com::redhat; using namespace qmf::com::redhat::grid; using namespace com::redhat::grid; // about self DECL_SUBSYSTEM("JOB_SERVER", SUBSYSTEM_TYPE_DAEMON ); // used by Daemon Core JobLogMirror *mirror; JobServerJobLogConsumer *consumer; JobServerObject *job_server; ClassAd *ad = NULL; ObjectId* schedd_oid = NULL; ManagementAgent::Singleton *singleton; extern MyString m_path; void construct_schedd_ref(ObjectId*& _oid); void init_classad(); void Dump(); int HandleMgmtSocket(Service *, Stream *); int HandleResetSignal(Service *, int); void ProcessHistoryTimer(Service*); //------------------------------------------------------------- int main_init(int /* argc */, char * /* argv */ []) { dprintf(D_ALWAYS, "main_init() called\n"); consumer = new JobServerJobLogConsumer(); mirror = new JobLogMirror(consumer); mirror->init(); char *host; char *username; char *password; char *mechanism; int port; char *tmp; string storefile,historyfile; singleton = new ManagementAgent::Singleton(); ManagementAgent *agent = singleton->getInstance(); JobServer::registerSelf(agent); Submission::registerSelf(agent); port = param_integer("QMF_BROKER_PORT", 5672); if (NULL == (host = param("QMF_BROKER_HOST"))) { host = strdup("localhost"); } tmp = param("QMF_STOREFILE"); if (NULL == tmp) { storefile = ".job_server_storefile"; } else { storefile = tmp; free(tmp); tmp = NULL; } if (NULL == (username = param("QMF_BROKER_USERNAME"))) { username = strdup(""); } if (NULL == (mechanism = param("QMF_BROKER_AUTH_MECH"))) { mechanism = strdup("ANONYMOUS"); } password = getBrokerPassword(); string jsName = build_valid_daemon_name("jobs@"); jsName += default_daemon_name(); agent->setName("com.redhat.grid","jobserver", jsName.c_str()); agent->init(string(host), port, param_integer("QMF_UPDATE_INTERVAL", 10), true, storefile, username, password, mechanism); free(host); free(username); free(password); free(mechanism); construct_schedd_ref(schedd_oid); job_server = new JobServerObject(agent, jsName.c_str(), *schedd_oid); init_classad(); ReliSock *sock = new ReliSock; if (!sock) { EXCEPT("Failed to allocate Mgmt socket"); } if (!sock->assign(agent->getSignalFd())) { EXCEPT("Failed to bind Mgmt socket"); } int index; if (-1 == (index = daemonCore->Register_Socket((Stream *) sock, "Mgmt Method Socket", (SocketHandler) HandleMgmtSocket, "Handler for Mgmt Methods."))) { EXCEPT("Failed to register Mgmt socket"); } // before doing any job history processing, set the location of the files // TODO: need to test mal-HISTORY values: HISTORY=/tmp/somewhere const char* tmp2 = param ( "HISTORY" ); StatInfo si( tmp2 ); tmp2 = si.DirPath (); if ( !tmp2 ) { dprintf ( D_ALWAYS, "warning: No HISTORY defined - Job Server will not process history jobs\n" ); } else { m_path = tmp2; dprintf ( D_FULLDEBUG, "HISTORY path is %s\n",tmp2 ); // register a timer for processing of historical job files if (-1 == (index = daemonCore->Register_Timer( 0, param_integer("HISTORY_INTERVAL",120), (TimerHandler)ProcessHistoryTimer, "Timer for processing job history files" ))) { EXCEPT("Failed to register history timer"); } } // useful for testing job coalescing // and potentially just useful if (-1 == (index = daemonCore->Register_Signal(SIGUSR1, "Forced Reset Signal", (SignalHandler) HandleResetSignal, "Handler for Reset signals"))) { EXCEPT("Failed to register Reset signal"); } return TRUE; } // synthetically create a QMF ObjectId that should point to the // correct SchedulerObject - all depends on the SCHEDD_NAME // assigned to this JOB_SERVER void construct_schedd_ref(ObjectId*& _oid) { std::string schedd_agent = "com.redhat.grid:scheduler:"; std::string schedd_name; char* tmp = param("SCHEDD_NAME"); if (tmp) { dprintf ( D_ALWAYS, "SCHEDD_NAME going into ObjectId is %s\n", tmp); schedd_name = build_valid_daemon_name( tmp ); free(tmp); tmp = NULL; } else { //go through the expected schedd defaults for this host schedd_name = default_daemon_name(); } schedd_agent += schedd_name; _oid = new ObjectId(schedd_agent,schedd_name); } void init_classad() { if ( ad ) { delete ad; } ad = new ClassAd(); ad->SetMyTypeName("JobServer"); ad->SetTargetTypeName("Daemon"); char* default_name = default_daemon_name(); if( ! default_name ) { EXCEPT( "default_daemon_name() returned NULL" ); } ad->Assign(ATTR_NAME, default_name); delete [] default_name; ad->Assign(ATTR_MY_ADDRESS, my_ip_string()); // Initialize all the DaemonCore-provided attributes daemonCore->publish( ad ); if (!job_server) { EXCEPT( "JobServerObject is NULL" ); } job_server->update(*ad); } //------------------------------------------------------------- int main_config() { dprintf(D_ALWAYS, "main_config() called\n"); mirror->config(); return TRUE; } //------------------------------------------------------------- void Stop() { if (param_boolean("DUMP_STATE", false)) { Dump(); } if (param_boolean("CLEANUP_ON_EXIT", false)) { consumer->Reset(); } mirror->stop(); delete schedd_oid; schedd_oid = NULL; delete job_server; job_server = NULL; delete singleton; singleton = NULL; delete mirror; mirror = NULL; DC_Exit(0); } //------------------------------------------------------------- int main_shutdown_fast() { dprintf(D_ALWAYS, "main_shutdown_fast() called\n"); Stop(); DC_Exit(0); return TRUE; // to satisfy c++ } //------------------------------------------------------------- int main_shutdown_graceful() { dprintf(D_ALWAYS, "main_shutdown_graceful() called\n"); Stop(); DC_Exit(0); return TRUE; // to satisfy c++ } //------------------------------------------------------------- void main_pre_dc_init( int /* argc */, char* /* argv */ [] ) { // dprintf isn't safe yet... } void main_pre_command_sock_init( ) { } int HandleMgmtSocket(Service *, Stream *) { singleton->getInstance()->pollCallbacks(); return KEEP_STREAM; } int HandleResetSignal(Service *, int) { consumer->Reset(); return TRUE; } void ProcessHistoryTimer(Service*) { dprintf(D_FULLDEBUG, "ProcessHistoryTimer() called\n"); ProcessHistoryDirectory(); ProcessOrphanedIndices(); ProcessCurrentHistory(); } void Dump() { dprintf(D_ALWAYS|D_NOHEADER, "***BEGIN DUMP***\n"); dprintf(D_ALWAYS|D_NOHEADER, "Total number of jobs: %u\n", g_jobs.size()); dprintf(D_ALWAYS|D_NOHEADER, "Total number of submission: %u\n", g_submissions.size()); for (SubmissionCollectionType::const_iterator i = g_submissions.begin(); g_submissions.end() != i; i++) { dprintf(D_ALWAYS|D_NOHEADER, "Submission: %s\n", (*i).first); dprintf(D_ALWAYS|D_NOHEADER, " Idle: %u\n", (*i).second->GetIdle().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetIdle().begin(); (*i).second->GetIdle().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Running: %u\n", (*i).second->GetRunning().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetRunning().begin(); (*i).second->GetRunning().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Removed: %u\n", (*i).second->GetRemoved().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetRemoved().begin(); (*i).second->GetRemoved().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Completed: %u\n", (*i).second->GetCompleted().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetCompleted().begin(); (*i).second->GetCompleted().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Held: %u\n", (*i).second->GetHeld().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetHeld().begin(); (*i).second->GetHeld().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); } dprintf(D_ALWAYS|D_NOHEADER, "***END DUMP***\n"); } <commit_msg>Introduced undocumented SCHEDULER_AGENT_ID to facilitate connection of JobServer to Scheduler when the Scheduler is published from the Collector.<commit_after>/*************************************************************** * * Copyright (C) 2009-2011 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_daemon_core.h" #include "condor_debug.h" #include "condor_attributes.h" #include "get_daemon_name.h" #include "subsystem_info.h" #include "condor_config.h" #include "stat_info.h" #include "broker_utils.h" #include "stringSpace.h" #include "JobLogMirror.h" #include "JobServerJobLogConsumer.h" #include "JobServerObject.h" #include "HistoryProcessingUtils.h" #include "Globals.h" /* Using daemoncore, you get the benefits of a logging system with dprintf and you can read config files automatically. To start testing your daemon, run it with "-f -t" until you start specifying a config file to use(the daemon will automatically look in /etc/condor_config, /usr/local/etc/condor_config, ~condor/condor_config, or the env CONDOR_CONFIG if -t is not specifed). -f means run in the foreground, -t means print the debugging output to the terminal. */ //------------------------------------------------------------- using namespace qpid::management; using namespace qpid::types; using namespace qmf::com::redhat; using namespace qmf::com::redhat::grid; using namespace com::redhat::grid; // about self DECL_SUBSYSTEM("JOB_SERVER", SUBSYSTEM_TYPE_DAEMON ); // used by Daemon Core JobLogMirror *mirror; JobServerJobLogConsumer *consumer; JobServerObject *job_server; ClassAd *ad = NULL; ObjectId* schedd_oid = NULL; ManagementAgent::Singleton *singleton; extern MyString m_path; void construct_schedd_ref(ObjectId*& _oid); void init_classad(); void Dump(); int HandleMgmtSocket(Service *, Stream *); int HandleResetSignal(Service *, int); void ProcessHistoryTimer(Service*); //------------------------------------------------------------- int main_init(int /* argc */, char * /* argv */ []) { dprintf(D_ALWAYS, "main_init() called\n"); consumer = new JobServerJobLogConsumer(); mirror = new JobLogMirror(consumer); mirror->init(); char *host; char *username; char *password; char *mechanism; int port; char *tmp; string storefile,historyfile; singleton = new ManagementAgent::Singleton(); ManagementAgent *agent = singleton->getInstance(); JobServer::registerSelf(agent); Submission::registerSelf(agent); port = param_integer("QMF_BROKER_PORT", 5672); if (NULL == (host = param("QMF_BROKER_HOST"))) { host = strdup("localhost"); } tmp = param("QMF_STOREFILE"); if (NULL == tmp) { storefile = ".job_server_storefile"; } else { storefile = tmp; free(tmp); tmp = NULL; } if (NULL == (username = param("QMF_BROKER_USERNAME"))) { username = strdup(""); } if (NULL == (mechanism = param("QMF_BROKER_AUTH_MECH"))) { mechanism = strdup("ANONYMOUS"); } password = getBrokerPassword(); string jsName = build_valid_daemon_name("jobs@"); jsName += default_daemon_name(); agent->setName("com.redhat.grid","jobserver", jsName.c_str()); agent->init(string(host), port, param_integer("QMF_UPDATE_INTERVAL", 10), true, storefile, username, password, mechanism); free(host); free(username); free(password); free(mechanism); construct_schedd_ref(schedd_oid); job_server = new JobServerObject(agent, jsName.c_str(), *schedd_oid); init_classad(); ReliSock *sock = new ReliSock; if (!sock) { EXCEPT("Failed to allocate Mgmt socket"); } if (!sock->assign(agent->getSignalFd())) { EXCEPT("Failed to bind Mgmt socket"); } int index; if (-1 == (index = daemonCore->Register_Socket((Stream *) sock, "Mgmt Method Socket", (SocketHandler) HandleMgmtSocket, "Handler for Mgmt Methods."))) { EXCEPT("Failed to register Mgmt socket"); } // before doing any job history processing, set the location of the files // TODO: need to test mal-HISTORY values: HISTORY=/tmp/somewhere const char* tmp2 = param ( "HISTORY" ); StatInfo si( tmp2 ); tmp2 = si.DirPath (); if ( !tmp2 ) { dprintf ( D_ALWAYS, "warning: No HISTORY defined - Job Server will not process history jobs\n" ); } else { m_path = tmp2; dprintf ( D_FULLDEBUG, "HISTORY path is %s\n",tmp2 ); // register a timer for processing of historical job files if (-1 == (index = daemonCore->Register_Timer( 0, param_integer("HISTORY_INTERVAL",120), (TimerHandler)ProcessHistoryTimer, "Timer for processing job history files" ))) { EXCEPT("Failed to register history timer"); } } // useful for testing job coalescing // and potentially just useful if (-1 == (index = daemonCore->Register_Signal(SIGUSR1, "Forced Reset Signal", (SignalHandler) HandleResetSignal, "Handler for Reset signals"))) { EXCEPT("Failed to register Reset signal"); } return TRUE; } // synthetically create a QMF ObjectId that should point to the // correct SchedulerObject - all depends on the SCHEDD_NAME // assigned to this JOB_SERVER void construct_schedd_ref(ObjectId*& _oid) { std::string schedd_agent = "com.redhat.grid:scheduler:"; std::string schedd_name; char* tmp = param("SCHEDD_NAME"); if (tmp) { dprintf ( D_ALWAYS, "SCHEDD_NAME going into ObjectId is %s\n", tmp); schedd_name = build_valid_daemon_name( tmp ); free(tmp); tmp = NULL; } else { //go through the expected schedd defaults for this host schedd_name = default_daemon_name(); } tmp = param("SCHEDULER_AGENT_ID"); if (tmp) { schedd_agent = tmp; free(tmp); tmp = NULL; } else { schedd_agent += schedd_name; } _oid = new ObjectId(schedd_agent,schedd_name); } void init_classad() { if ( ad ) { delete ad; } ad = new ClassAd(); ad->SetMyTypeName("JobServer"); ad->SetTargetTypeName("Daemon"); char* default_name = default_daemon_name(); if( ! default_name ) { EXCEPT( "default_daemon_name() returned NULL" ); } ad->Assign(ATTR_NAME, default_name); delete [] default_name; ad->Assign(ATTR_MY_ADDRESS, my_ip_string()); // Initialize all the DaemonCore-provided attributes daemonCore->publish( ad ); if (!job_server) { EXCEPT( "JobServerObject is NULL" ); } job_server->update(*ad); } //------------------------------------------------------------- int main_config() { dprintf(D_ALWAYS, "main_config() called\n"); mirror->config(); return TRUE; } //------------------------------------------------------------- void Stop() { if (param_boolean("DUMP_STATE", false)) { Dump(); } if (param_boolean("CLEANUP_ON_EXIT", false)) { consumer->Reset(); } mirror->stop(); delete schedd_oid; schedd_oid = NULL; delete job_server; job_server = NULL; delete singleton; singleton = NULL; delete mirror; mirror = NULL; DC_Exit(0); } //------------------------------------------------------------- int main_shutdown_fast() { dprintf(D_ALWAYS, "main_shutdown_fast() called\n"); Stop(); DC_Exit(0); return TRUE; // to satisfy c++ } //------------------------------------------------------------- int main_shutdown_graceful() { dprintf(D_ALWAYS, "main_shutdown_graceful() called\n"); Stop(); DC_Exit(0); return TRUE; // to satisfy c++ } //------------------------------------------------------------- void main_pre_dc_init( int /* argc */, char* /* argv */ [] ) { // dprintf isn't safe yet... } void main_pre_command_sock_init( ) { } int HandleMgmtSocket(Service *, Stream *) { singleton->getInstance()->pollCallbacks(); return KEEP_STREAM; } int HandleResetSignal(Service *, int) { consumer->Reset(); return TRUE; } void ProcessHistoryTimer(Service*) { dprintf(D_FULLDEBUG, "ProcessHistoryTimer() called\n"); ProcessHistoryDirectory(); ProcessOrphanedIndices(); ProcessCurrentHistory(); } void Dump() { dprintf(D_ALWAYS|D_NOHEADER, "***BEGIN DUMP***\n"); dprintf(D_ALWAYS|D_NOHEADER, "Total number of jobs: %u\n", g_jobs.size()); dprintf(D_ALWAYS|D_NOHEADER, "Total number of submission: %u\n", g_submissions.size()); for (SubmissionCollectionType::const_iterator i = g_submissions.begin(); g_submissions.end() != i; i++) { dprintf(D_ALWAYS|D_NOHEADER, "Submission: %s\n", (*i).first); dprintf(D_ALWAYS|D_NOHEADER, " Idle: %u\n", (*i).second->GetIdle().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetIdle().begin(); (*i).second->GetIdle().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Running: %u\n", (*i).second->GetRunning().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetRunning().begin(); (*i).second->GetRunning().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Removed: %u\n", (*i).second->GetRemoved().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetRemoved().begin(); (*i).second->GetRemoved().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Completed: %u\n", (*i).second->GetCompleted().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetCompleted().begin(); (*i).second->GetCompleted().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); dprintf(D_ALWAYS|D_NOHEADER, " Held: %u\n", (*i).second->GetHeld().size()); dprintf(D_ALWAYS|D_NOHEADER, " "); for (SubmissionObject::JobSet::const_iterator j = (*i).second->GetHeld().begin(); (*i).second->GetHeld().end() != j; j++) { dprintf(D_ALWAYS|D_NOHEADER, " %s", (*j)->GetKey()); } dprintf(D_ALWAYS|D_NOHEADER, "\n"); } dprintf(D_ALWAYS|D_NOHEADER, "***END DUMP***\n"); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: typeselectionpage.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hr $ $Date: 2003-03-25 16:00:54 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX #define EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif #ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #include "addresssettings.hxx" #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= TypeSelectionPage //===================================================================== class TypeSelectionPage : public AddressBookSourcePage { protected: FixedText m_aHint; FixedLine m_aTypeSep; RadioButton m_aMORK; RadioButton m_aLDAP; RadioButton m_aOutlook; RadioButton m_aOE; RadioButton m_aOther; public: TypeSelectionPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); // OImportPage overridables virtual sal_Bool determineNextButtonState(); private: DECL_LINK( OnTypeSelected, void* ); void selectType( AddressSourceType _eType ); AddressSourceType getSelectedType( ); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX <commit_msg>INTEGRATION: CWS evoab (1.2.30.1.10); FILE MERGED 2003/04/04 16:15:02 fs 1.2.30.1.10.1: #108648# (checkin on behalf of [email protected]): added support for evolution address book<commit_after>/************************************************************************* * * $RCSfile: typeselectionpage.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: vg $ $Date: 2003-06-02 08:04:29 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc.. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX #define EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX #ifndef EXTENSIONS_ABP_ABSPAGE_HXX #include "abspage.hxx" #endif #ifndef EXTENSIONS_ABP_ADDRESSSETTINGS_HXX #include "addresssettings.hxx" #endif #ifndef _SV_EDIT_HXX #include <vcl/edit.hxx> #endif //......................................................................... namespace abp { //......................................................................... //===================================================================== //= TypeSelectionPage //===================================================================== class TypeSelectionPage : public AddressBookSourcePage { protected: FixedText m_aHint; FixedLine m_aTypeSep; RadioButton m_aMORK; RadioButton m_aEvolution; RadioButton m_aLDAP; RadioButton m_aOutlook; RadioButton m_aOE; RadioButton m_aOther; public: TypeSelectionPage( OAddessBookSourcePilot* _pParent ); protected: // OWizardPage overridables virtual void initializePage(); virtual sal_Bool commitPage(COMMIT_REASON _eReason); // TabDialog overridables virtual void ActivatePage(); virtual void DeactivatePage(); // OImportPage overridables virtual sal_Bool determineNextButtonState(); private: DECL_LINK( OnTypeSelected, void* ); void selectType( AddressSourceType _eType ); AddressSourceType getSelectedType( ); }; //......................................................................... } // namespace abp //......................................................................... #endif // EXTENSIONS_ABP_TYPESELECTIONPAGE_HXX <|endoftext|>
<commit_before>#pragma once #include "search/search_query.hpp" #include "search/suggest.hpp" #if defined(USE_SEARCH_QUERY_V2) #include "search/v2/search_query_v2.hpp" #endif // defined(USE_SEARCH_QUERY_V2) #include "std/unique_ptr.hpp" namespace storage { class CountryInfoGetter; } namespace search { class SearchQueryFactory { public: virtual ~SearchQueryFactory() = default; virtual unique_ptr<Query> BuildSearchQuery(Index & index, CategoriesHolder const & categories, vector<Suggest> const & suggests, storage::CountryInfoGetter const & infoGetter) { #if defined(USE_SEARCH_QUERY_V2) return make_unique<v2::SearchQueryV2>(index, categories, suggests, infoGetter); #else return make_unique<Query>(index, categories, suggests, infoGetter); #endif // defined(USE_SEARCH_QUERY_V2) } }; } // namespace search <commit_msg>[search] Enable SearchQueryV2 by default.<commit_after>#pragma once #include "search/suggest.hpp" #include "search/v2/search_query_v2.hpp" #include "std/unique_ptr.hpp" namespace storage { class CountryInfoGetter; } namespace search { class SearchQueryFactory { public: virtual ~SearchQueryFactory() = default; virtual unique_ptr<Query> BuildSearchQuery(Index & index, CategoriesHolder const & categories, vector<Suggest> const & suggests, storage::CountryInfoGetter const & infoGetter) { return make_unique<v2::SearchQueryV2>(index, categories, suggests, infoGetter); } }; } // namespace search <|endoftext|>
<commit_before>/* * fontcolour.cpp - font and colour chooser widget * Program: kalarm * Copyright © 2001-2003,2005,2008 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <qobjectlist.h> #include <qwidget.h> #include <qgroupbox.h> #include <qpushbutton.h> #include <qhbox.h> #include <qlabel.h> #include <qlayout.h> #include <qwhatsthis.h> #include <kglobal.h> #include <klocale.h> #include <kcolordialog.h> #include "kalarmapp.h" #include "preferences.h" #include "colourcombo.h" #include "checkbox.h" #include "fontcolour.moc" FontColourChooser::FontColourChooser(QWidget *parent, const char *name, bool onlyFixed, const QStringList &fontList, const QString& frameLabel, bool editColours, bool fg, bool defaultFont, int visibleListSize) : QWidget(parent, name), mFgColourButton(0), mRemoveColourButton(0), mColourList(Preferences::messageColours()), mReadOnly(false) { QVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint()); QWidget* page = this; if (!frameLabel.isNull()) { page = new QGroupBox(frameLabel, this); topLayout->addWidget(page); topLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint()); topLayout->addSpacing(fontMetrics().height() - KDialog::marginHint() + KDialog::spacingHint()); } if (fg) { QBoxLayout* layout = new QHBoxLayout(topLayout); QHBox* box = new QHBox(page); // to group widgets for QWhatsThis text box->setSpacing(KDialog::spacingHint()); layout->addWidget(box); QLabel* label = new QLabel(i18n("&Foreground color:"), box); label->setMinimumSize(label->sizeHint()); mFgColourButton = new ColourCombo(box); mFgColourButton->setMinimumSize(mFgColourButton->sizeHint()); connect(mFgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour())); label->setBuddy(mFgColourButton); QWhatsThis::add(box, i18n("Select the alarm message foreground color")); layout->addStretch(); } QBoxLayout* layout = new QHBoxLayout(topLayout); QHBox* box = new QHBox(page); // to group widgets for QWhatsThis text box->setSpacing(KDialog::spacingHint()); layout->addWidget(box); QLabel* label = new QLabel(i18n("&Background color:"), box); label->setMinimumSize(label->sizeHint()); mBgColourButton = new ColourCombo(box); mBgColourButton->setMinimumSize(mBgColourButton->sizeHint()); connect(mBgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour())); label->setBuddy(mBgColourButton); QWhatsThis::add(box, i18n("Select the alarm message background color")); layout->addStretch(); if (editColours) { layout = new QHBoxLayout(topLayout); QPushButton* button = new QPushButton(i18n("Add Co&lor..."), page); button->setFixedSize(button->sizeHint()); connect(button, SIGNAL(clicked()), SLOT(slotAddColour())); QWhatsThis::add(button, i18n("Choose a new color to add to the color selection list.")); layout->addWidget(button); mRemoveColourButton = new QPushButton(i18n("&Remove Color"), page); mRemoveColourButton->setFixedSize(mRemoveColourButton->sizeHint()); connect(mRemoveColourButton, SIGNAL(clicked()), SLOT(slotRemoveColour())); QWhatsThis::add(mRemoveColourButton, i18n("Remove the color currently shown in the background color chooser, from the color selection list.")); layout->addWidget(mRemoveColourButton); } if (defaultFont) { layout = new QHBoxLayout(topLayout); mDefaultFont = new CheckBox(i18n("Use &default font"), page); mDefaultFont->setMinimumSize(mDefaultFont->sizeHint()); connect(mDefaultFont, SIGNAL(toggled(bool)), SLOT(slotDefaultFontToggled(bool))); QWhatsThis::add(mDefaultFont, i18n("Check to use the default font current at the time the alarm is displayed.")); layout->addWidget(mDefaultFont); layout->addWidget(new QWidget(page)); // left adjust the widget } else mDefaultFont = 0; mFontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize); mFontChooser->installEventFilter(this); // for read-only mode const QObjectList* kids = mFontChooser->queryList(); for (QObjectList::ConstIterator it = kids->constBegin(); it != kids->constEnd(); ++it) (*it)->installEventFilter(this); topLayout->addWidget(mFontChooser); slotDefaultFontToggled(false); } void FontColourChooser::setDefaultFont() { if (mDefaultFont) mDefaultFont->setChecked(true); } void FontColourChooser::setFont(const QFont& font, bool onlyFixed) { if (mDefaultFont) mDefaultFont->setChecked(false); mFontChooser->setFont(font, onlyFixed); } bool FontColourChooser::defaultFont() const { return mDefaultFont ? mDefaultFont->isChecked() : false; } QFont FontColourChooser::font() const { return (mDefaultFont && mDefaultFont->isChecked()) ? QFont() : mFontChooser->font(); } void FontColourChooser::setBgColour(const QColor& colour) { mBgColourButton->setColor(colour); mFontChooser->setBackgroundColor(colour); } void FontColourChooser::setSampleColour() { QColor bg = mBgColourButton->color(); mFontChooser->setBackgroundColor(bg); QColor fg = fgColour(); mFontChooser->setColor(fg); if (mRemoveColourButton) mRemoveColourButton->setEnabled(!mBgColourButton->isCustomColour()); // no deletion of custom colour } QColor FontColourChooser::bgColour() const { return mBgColourButton->color(); } QColor FontColourChooser::fgColour() const { if (mFgColourButton) return mFgColourButton->color(); else { QColor bg = mBgColourButton->color(); QPalette pal(bg, bg); return pal.color(QPalette::Active, QColorGroup::Text); } } QString FontColourChooser::sampleText() const { return mFontChooser->sampleText(); } void FontColourChooser::setSampleText(const QString& text) { mFontChooser->setSampleText(text); } void FontColourChooser::setFgColour(const QColor& colour) { if (mFgColourButton) { mFgColourButton->setColor(colour); mFontChooser->setColor(colour); } } void FontColourChooser::setReadOnly(bool ro) { if (ro != mReadOnly) { mReadOnly = ro; if (mFgColourButton) mFgColourButton->setReadOnly(ro); mBgColourButton->setReadOnly(ro); mDefaultFont->setReadOnly(ro); } } bool FontColourChooser::eventFilter(QObject*, QEvent* e) { if (mReadOnly) { switch (e->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::KeyPress: case QEvent::KeyRelease: return true; // prevent the event being handled default: break; } } return false; } void FontColourChooser::slotDefaultFontToggled(bool on) { mFontChooser->setEnabled(!on); } void FontColourChooser::setColours(const ColourList& colours) { mColourList = colours; mBgColourButton->setColours(mColourList); mFontChooser->setBackgroundColor(mBgColourButton->color()); } void FontColourChooser::slotAddColour() { QColor colour; if (KColorDialog::getColor(colour, this) == QDialog::Accepted) { mColourList.insert(colour); mBgColourButton->setColours(mColourList); } } void FontColourChooser::slotRemoveColour() { if (!mBgColourButton->isCustomColour()) { mColourList.remove(mBgColourButton->color()); mBgColourButton->setColours(mColourList); } } <commit_msg>Fix alignment of colour combos<commit_after>/* * fontcolour.cpp - font and colour chooser widget * Program: kalarm * Copyright © 2001-2003,2005,2008 by David Jarvie <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <qobjectlist.h> #include <qwidget.h> #include <qgroupbox.h> #include <qpushbutton.h> #include <qhbox.h> #include <qlabel.h> #include <qlayout.h> #include <qwhatsthis.h> #include <kglobal.h> #include <klocale.h> #include <kcolordialog.h> #include "kalarmapp.h" #include "preferences.h" #include "colourcombo.h" #include "checkbox.h" #include "fontcolour.moc" FontColourChooser::FontColourChooser(QWidget *parent, const char *name, bool onlyFixed, const QStringList &fontList, const QString& frameLabel, bool editColours, bool fg, bool defaultFont, int visibleListSize) : QWidget(parent, name), mFgColourButton(0), mRemoveColourButton(0), mColourList(Preferences::messageColours()), mReadOnly(false) { QVBoxLayout* topLayout = new QVBoxLayout(this, 0, KDialog::spacingHint()); QWidget* page = this; if (!frameLabel.isNull()) { page = new QGroupBox(frameLabel, this); topLayout->addWidget(page); topLayout = new QVBoxLayout(page, KDialog::marginHint(), KDialog::spacingHint()); topLayout->addSpacing(fontMetrics().height() - KDialog::marginHint() + KDialog::spacingHint()); } QHBoxLayout* hlayout = new QHBoxLayout(topLayout); QVBoxLayout* colourLayout = new QVBoxLayout(hlayout); if (fg) { QHBox* box = new QHBox(page); // to group widgets for QWhatsThis text box->setSpacing(KDialog::spacingHint()/2); colourLayout->addWidget(box); QLabel* label = new QLabel(i18n("&Foreground color:"), box); box->setStretchFactor(new QWidget(box), 0); mFgColourButton = new ColourCombo(box); connect(mFgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour())); label->setBuddy(mFgColourButton); QWhatsThis::add(box, i18n("Select the alarm message foreground color")); } QHBox* box = new QHBox(page); // to group widgets for QWhatsThis text box->setSpacing(KDialog::spacingHint()/2); colourLayout->addWidget(box); QLabel* label = new QLabel(i18n("&Background color:"), box); box->setStretchFactor(new QWidget(box), 0); mBgColourButton = new ColourCombo(box); connect(mBgColourButton, SIGNAL(activated(const QString&)), SLOT(setSampleColour())); label->setBuddy(mBgColourButton); QWhatsThis::add(box, i18n("Select the alarm message background color")); hlayout->addStretch(); if (editColours) { QHBoxLayout* layout = new QHBoxLayout(topLayout); QPushButton* button = new QPushButton(i18n("Add Co&lor..."), page); button->setFixedSize(button->sizeHint()); connect(button, SIGNAL(clicked()), SLOT(slotAddColour())); QWhatsThis::add(button, i18n("Choose a new color to add to the color selection list.")); layout->addWidget(button); mRemoveColourButton = new QPushButton(i18n("&Remove Color"), page); mRemoveColourButton->setFixedSize(mRemoveColourButton->sizeHint()); connect(mRemoveColourButton, SIGNAL(clicked()), SLOT(slotRemoveColour())); QWhatsThis::add(mRemoveColourButton, i18n("Remove the color currently shown in the background color chooser, from the color selection list.")); layout->addWidget(mRemoveColourButton); } if (defaultFont) { QHBoxLayout* layout = new QHBoxLayout(topLayout); mDefaultFont = new CheckBox(i18n("Use &default font"), page); mDefaultFont->setMinimumSize(mDefaultFont->sizeHint()); connect(mDefaultFont, SIGNAL(toggled(bool)), SLOT(slotDefaultFontToggled(bool))); QWhatsThis::add(mDefaultFont, i18n("Check to use the default font current at the time the alarm is displayed.")); layout->addWidget(mDefaultFont); layout->addWidget(new QWidget(page)); // left adjust the widget } else mDefaultFont = 0; mFontChooser = new KFontChooser(page, name, onlyFixed, fontList, false, visibleListSize); mFontChooser->installEventFilter(this); // for read-only mode const QObjectList* kids = mFontChooser->queryList(); for (QObjectList::ConstIterator it = kids->constBegin(); it != kids->constEnd(); ++it) (*it)->installEventFilter(this); topLayout->addWidget(mFontChooser); slotDefaultFontToggled(false); } void FontColourChooser::setDefaultFont() { if (mDefaultFont) mDefaultFont->setChecked(true); } void FontColourChooser::setFont(const QFont& font, bool onlyFixed) { if (mDefaultFont) mDefaultFont->setChecked(false); mFontChooser->setFont(font, onlyFixed); } bool FontColourChooser::defaultFont() const { return mDefaultFont ? mDefaultFont->isChecked() : false; } QFont FontColourChooser::font() const { return (mDefaultFont && mDefaultFont->isChecked()) ? QFont() : mFontChooser->font(); } void FontColourChooser::setBgColour(const QColor& colour) { mBgColourButton->setColor(colour); mFontChooser->setBackgroundColor(colour); } void FontColourChooser::setSampleColour() { QColor bg = mBgColourButton->color(); mFontChooser->setBackgroundColor(bg); QColor fg = fgColour(); mFontChooser->setColor(fg); if (mRemoveColourButton) mRemoveColourButton->setEnabled(!mBgColourButton->isCustomColour()); // no deletion of custom colour } QColor FontColourChooser::bgColour() const { return mBgColourButton->color(); } QColor FontColourChooser::fgColour() const { if (mFgColourButton) return mFgColourButton->color(); else { QColor bg = mBgColourButton->color(); QPalette pal(bg, bg); return pal.color(QPalette::Active, QColorGroup::Text); } } QString FontColourChooser::sampleText() const { return mFontChooser->sampleText(); } void FontColourChooser::setSampleText(const QString& text) { mFontChooser->setSampleText(text); } void FontColourChooser::setFgColour(const QColor& colour) { if (mFgColourButton) { mFgColourButton->setColor(colour); mFontChooser->setColor(colour); } } void FontColourChooser::setReadOnly(bool ro) { if (ro != mReadOnly) { mReadOnly = ro; if (mFgColourButton) mFgColourButton->setReadOnly(ro); mBgColourButton->setReadOnly(ro); mDefaultFont->setReadOnly(ro); } } bool FontColourChooser::eventFilter(QObject*, QEvent* e) { if (mReadOnly) { switch (e->type()) { case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: case QEvent::KeyPress: case QEvent::KeyRelease: return true; // prevent the event being handled default: break; } } return false; } void FontColourChooser::slotDefaultFontToggled(bool on) { mFontChooser->setEnabled(!on); } void FontColourChooser::setColours(const ColourList& colours) { mColourList = colours; mBgColourButton->setColours(mColourList); mFontChooser->setBackgroundColor(mBgColourButton->color()); } void FontColourChooser::slotAddColour() { QColor colour; if (KColorDialog::getColor(colour, this) == QDialog::Accepted) { mColourList.insert(colour); mBgColourButton->setColours(mColourList); } } void FontColourChooser::slotRemoveColour() { if (!mBgColourButton->isCustomColour()) { mColourList.remove(mBgColourButton->color()); mBgColourButton->setColours(mColourList); } } <|endoftext|>
<commit_before>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string> #include "paddle/fluid/framework/generator.h" #include "paddle/fluid/operators/fill_constant_op.h" namespace paddle { namespace operators { using framework::DataLayout; template <typename T> class GaussianMKLDNNKernel : public paddle::framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { float mean = context.Attr<float>("mean"); float std = context.Attr<float>("std"); auto* tensor = context.Output<framework::Tensor>("Out"); auto shape = GetShape(context); tensor->Resize(shape); T* data = tensor->mutable_data<T>(context.GetPlace()); int64_t size = tensor->numel(); std::normal_distribution<T> dist(mean, std); unsigned int seed = static_cast<unsigned int>(context.Attr<int>("seed")); auto engine = framework::GetCPURandomEngine(seed); for (int64_t i = 0; i < size; ++i) { data[i] = dist(*engine); } tensor->set_layout(DataLayout::kMKLDNN); tensor->set_format(dnnl::memory::format_tag::oihw); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(gaussian_random, MKLDNN, ::paddle::platform::CPUPlace, ops::GaussianMKLDNNKernel<float>); <commit_msg>fix for gaussian random (#41572)<commit_after>/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <string> #include "paddle/fluid/framework/generator.h" #include "paddle/fluid/operators/fill_constant_op.h" #include "paddle/fluid/platform/mkldnn_helper.h" namespace paddle { namespace operators { using framework::DataLayout; template <typename T> class GaussianMKLDNNKernel : public paddle::framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { float mean = context.Attr<float>("mean"); float std = context.Attr<float>("std"); auto* tensor = context.Output<framework::Tensor>("Out"); auto shape = GetShape(context); tensor->Resize(shape); T* data = tensor->mutable_data<T>(context.GetPlace()); int64_t size = tensor->numel(); std::normal_distribution<T> dist(mean, std); unsigned int seed = static_cast<unsigned int>(context.Attr<int>("seed")); auto engine = framework::GetCPURandomEngine(seed); for (int64_t i = 0; i < size; ++i) { data[i] = dist(*engine); } tensor->set_layout(DataLayout::kMKLDNN); tensor->set_format(platform::GetPlainMKLDNNFormat(tensor->dims().size())); } }; } // namespace operators } // namespace paddle namespace ops = paddle::operators; REGISTER_OP_KERNEL(gaussian_random, MKLDNN, ::paddle::platform::CPUPlace, ops::GaussianMKLDNNKernel<float>); <|endoftext|>
<commit_before>#pragma once //#define Boost_FOUND 1 #include <tudocomp/config.h> #include <vector> #include <tudocomp/ds/IntVector.hpp> #include <tudocomp/Algorithm.hpp> #include <tudocomp/ds/TextDS.hpp> #include <tudocomp/compressors/lzss/LZSSFactors.hpp> #include <tudocomp/ds/ArrayMaxHeap.hpp> #ifdef Boost_FOUND #include <boost/heap/pairing_heap.hpp> #endif namespace tdc { namespace lcpcomp { /// A very naive selection strategy for LCPComp. /// /// TODO: Describe class PLCPStrategy : public Algorithm { private: typedef TextDS<> text_t; public: using Algorithm::Algorithm; inline static Meta meta() { Meta m("lcpcomp_comp", "plcp"); return m; } #ifdef Boost_FOUND inline void factorize(text_t& text, size_t threshold, lzss::FactorBuffer& factors) { // Construct SA, ISA and LCP env().begin_stat_phase("Construct text ds"); text.require(text_t::SA | text_t::ISA | text_t::PLCP); env().end_stat_phase(); env().begin_stat_phase("Search Peaks"); const auto& sa = text.require_sa(); const auto& isa = text.require_isa(); auto lcpp = text.release_plcp(); auto lcp_datap = lcpp->relinquish(); auto& plcp = *lcp_datap; const len_t n = sa.size(); struct Poi { len_t pos; len_t lcp; len_t no; Poi(len_t _pos, len_t _lcp, len_t _no) : pos(_pos), lcp(_lcp), no(_no) {} bool operator<(const Poi& o) const { DCHECK_NE(o.pos, this->pos); if(o.lcp == this->lcp) return this->pos > o.pos; return this->lcp < o.lcp; } }; boost::heap::pairing_heap<Poi> heap; std::vector<boost::heap::pairing_heap<Poi>::handle_type> handles; IF_STATS(len_t max_heap_size = 0); // std::stack<poi> pois; // text positions of interest, i.e., starting positions of factors we want to replace len_t lastpos = 0; len_t lastpos_lcp = 0; for(len_t i = 0; i+1 < n; ++i) { const len_t plcp_i = plcp[i]; if(heap.empty()) { if(plcp_i >= threshold) { handles.emplace_back(heap.emplace(i, plcp_i, handles.size())); lastpos = i; lastpos_lcp = plcp[lastpos]; } continue; } if(i - lastpos >= lastpos_lcp || i+1 == n) { IF_DEBUG(bool first = true); IF_STATS(max_heap_size = std::max<len_t>(max_heap_size, heap.size())); DCHECK_EQ(heap.size(), handles.size()); while(!heap.empty()) { const Poi& top = heap.top(); const len_t source_position = sa[isa[top.pos]-1]; factors.emplace_back(top.pos, source_position, top.lcp); const len_t next_pos = top.pos; // store top, this is the current position that gets factorized IF_DEBUG(if(first) DCHECK_EQ(top.pos, lastpos); first = false;) { len_t newlcp_peak = 0; // a new peak can emerge at top.pos+top.lcp bool peak_exists = false; if(top.pos+top.lcp < i) for(len_t j = top.no+1; j < handles.size(); ++j) { // erase all right peaks that got substituted if( handles[j].node_ == nullptr) continue; const Poi poi = *(handles[j]); DCHECK_LT(next_pos, poi.pos); if(poi.pos < next_pos+top.lcp) { heap.erase(handles[j]); handles[j].node_ = nullptr; if(poi.lcp + poi.pos > next_pos+top.lcp) { const len_t remaining_lcp = poi.lcp+poi.pos - (next_pos+top.lcp); newlcp_peak = std::max(remaining_lcp, newlcp_peak); // bool has_overlapping = false; // number of peaks that cover the area of peak we are going to delete, but go on to the right -> we do not have to create a new peak if there is one // for(len_t j = i+1; j < handles.size(); ++j) { // if( handles[j].node_ == nullptr) continue; // const Poi poi_cand = *(handles[j]); // if(poi_cand.pos > poi.lcp + poi.pos) break; // if(poi_cand.pos+poi_cand.lcp <= next_pos+top.lcp) continue; // has_overlapping = true; // break; // } // if(!has_overlapping) { // a new, but small peak emerged that was not covered by the peak poi // const len_t remaining_lcp = poi.lcp+poi.pos - (next_pos+top.lcp); // if(remaining_lcp >= threshold) { // handles[i] = heap.emplace(next_pos+top.lcp, remaining_lcp, i); // } // } // break! } } else if( poi.pos == next_pos+top.lcp) { peak_exists=true; } //else { break; } // !TODO } if(peak_exists) { //TODO: DEBUG for(len_t j = top.no+1; j < handles.size(); ++j) { if( handles[j].node_ == nullptr) continue; const Poi& poi = *(handles[j]); if(poi.pos == next_pos+top.lcp) { DCHECK_LE(newlcp_peak, poi.lcp); break; } } // DCHECK_LE(newlcp_peak, [&] () -> len_t { // for(len_t j = top.no+1; j < handles.size(); ++j) { // const Poi& poi = *(handles[j]); // if(poi.pos == next_pos+top.lcp) { return poi.lcp; } // } // return (len_t)0; // }()); } if(!peak_exists && newlcp_peak >= threshold) { len_t j = top.no+1; DCHECK(handles[j].node_ == nullptr); handles[j] = heap.emplace(next_pos+top.lcp, newlcp_peak, j); } } handles[top.no].node_ = nullptr; heap.pop(); // top now gets erased for(auto it = handles.rbegin(); it != handles.rend(); ++it) { if( (*it).node_ == nullptr) continue; Poi& poi = (*(*it)); if(poi.pos > next_pos) continue; const len_t newlcp = next_pos - poi.pos; if(newlcp < poi.lcp) { if(newlcp < threshold) { heap.erase(*it); it->node_ = nullptr; } else { poi.lcp = newlcp; heap.decrease(*it); } // continue; //!TODO } //break; // !TODO } } handles.clear(); --i; continue; } DCHECK_EQ(plcp_i, plcp[i]); if(plcp_i <= lastpos_lcp) continue; DCHECK_LE(threshold, plcp[i]); handles.emplace_back(heap.emplace(i,plcp[i], handles.size())); lastpos = i; lastpos_lcp = plcp[lastpos]; } IF_STATS(env().log_stat("max heap size", max_heap_size)); env().end_stat_phase(); } #else//Boost_FOUND inline void factorize(text_t&, size_t, lzss::FactorBuffer& ) { #warning "plcpcomp is a dummy without boost" } #endif//Boost_FOUND }; }}//ns <commit_msg>optimized plcp<commit_after>#pragma once //#define Boost_FOUND 1 #include <tudocomp/config.h> #include <vector> #include <tudocomp/ds/IntVector.hpp> #include <tudocomp/Algorithm.hpp> #include <tudocomp/ds/TextDS.hpp> #include <tudocomp/compressors/lzss/LZSSFactors.hpp> #include <tudocomp/ds/ArrayMaxHeap.hpp> #ifdef Boost_FOUND #include <boost/heap/pairing_heap.hpp> #endif namespace tdc { namespace lcpcomp { /// A very naive selection strategy for LCPComp. /// /// TODO: Describe class PLCPStrategy : public Algorithm { private: typedef TextDS<> text_t; public: using Algorithm::Algorithm; inline static Meta meta() { Meta m("lcpcomp_comp", "plcp"); return m; } #ifdef Boost_FOUND inline void factorize(text_t& text, size_t threshold, lzss::FactorBuffer& factors) { // Construct SA, ISA and LCP env().begin_stat_phase("Construct text ds"); text.require(text_t::SA | text_t::ISA | text_t::PLCP); env().end_stat_phase(); env().begin_stat_phase("Search Peaks"); const auto& sa = text.require_sa(); const auto& isa = text.require_isa(); auto lcpp = text.release_plcp(); auto lcp_datap = lcpp->relinquish(); auto& plcp = *lcp_datap; const len_t n = sa.size(); struct Poi { len_t pos; len_t lcp; len_t no; Poi(len_t _pos, len_t _lcp, len_t _no) : pos(_pos), lcp(_lcp), no(_no) {} bool operator<(const Poi& o) const { DCHECK_NE(o.pos, this->pos); if(o.lcp == this->lcp) return this->pos > o.pos; return this->lcp < o.lcp; } }; boost::heap::pairing_heap<Poi> heap; std::vector<boost::heap::pairing_heap<Poi>::handle_type> handles; IF_STATS(len_t max_heap_size = 0); // std::stack<poi> pois; // text positions of interest, i.e., starting positions of factors we want to replace len_t lastpos = 0; len_t lastpos_lcp = 0; for(len_t i = 0; i+1 < n; ++i) { const len_t plcp_i = plcp[i]; if(heap.empty()) { if(plcp_i >= threshold) { handles.emplace_back(heap.emplace(i, plcp_i, handles.size())); lastpos = i; lastpos_lcp = plcp[lastpos]; } continue; } if(i - lastpos >= lastpos_lcp || tdc_unlikely(i+1 == n)) { IF_DEBUG(bool first = true); IF_STATS(max_heap_size = std::max<len_t>(max_heap_size, heap.size())); DCHECK_EQ(heap.size(), handles.size()); while(!heap.empty()) { const Poi& top = heap.top(); const len_t source_position = sa[isa[top.pos]-1]; factors.emplace_back(top.pos, source_position, top.lcp); const len_t next_pos = top.pos; // store top, this is the current position that gets factorized IF_DEBUG(if(first) DCHECK_EQ(top.pos, lastpos); first = false;) { len_t newlcp_peak = 0; // a new peak can emerge at top.pos+top.lcp bool peak_exists = false; if(top.pos+top.lcp < i) for(len_t j = top.no+1; j < handles.size(); ++j) { // erase all right peaks that got substituted if( handles[j].node_ == nullptr) continue; const Poi poi = *(handles[j]); DCHECK_LT(next_pos, poi.pos); if(poi.pos < next_pos+top.lcp) { heap.erase(handles[j]); handles[j].node_ = nullptr; if(poi.lcp + poi.pos > next_pos+top.lcp) { const len_t remaining_lcp = poi.lcp+poi.pos - (next_pos+top.lcp); DCHECK_NE(remaining_lcp,0); if(newlcp_peak != 0) DCHECK_LE(remaining_lcp, newlcp_peak); newlcp_peak = std::max(remaining_lcp, newlcp_peak); } } else if( poi.pos == next_pos+top.lcp) { peak_exists=true; } else { break; } // only for performance } #ifdef DEBUG if(peak_exists) { //TODO: DEBUG for(len_t j = top.no+1; j < handles.size(); ++j) { if( handles[j].node_ == nullptr) continue; const Poi& poi = *(handles[j]); if(poi.pos == next_pos+top.lcp) { DCHECK_LE(newlcp_peak, poi.lcp); break; } } } #endif if(!peak_exists && newlcp_peak >= threshold) { len_t j = top.no+1; DCHECK(handles[j].node_ == nullptr); handles[j] = heap.emplace(next_pos+top.lcp, newlcp_peak, j); } } handles[top.no].node_ = nullptr; heap.pop(); // top now gets erased for(auto it = handles.rbegin(); it != handles.rend(); ++it) { if( (*it).node_ == nullptr) continue; Poi& poi = (*(*it)); if(poi.pos > next_pos) continue; const len_t newlcp = next_pos - poi.pos; if(newlcp < poi.lcp) { if(newlcp < threshold) { heap.erase(*it); it->node_ = nullptr; } else { poi.lcp = newlcp; heap.decrease(*it); } } else { break; } } } handles.clear(); --i; continue; } DCHECK_EQ(plcp_i, plcp[i]); if(plcp_i <= lastpos_lcp) continue; DCHECK_LE(threshold, plcp[i]); handles.emplace_back(heap.emplace(i,plcp[i], handles.size())); lastpos = i; lastpos_lcp = plcp[lastpos]; } IF_STATS(env().log_stat("max heap size", max_heap_size)); env().end_stat_phase(); } #else//Boost_FOUND inline void factorize(text_t&, size_t, lzss::FactorBuffer& ) { #warning "plcpcomp is a dummy without boost" } #endif//Boost_FOUND }; }}//ns <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2019 JlnWntr ([email protected]) * * 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. */ #ifndef LUA_ADAPTER_H #define LUA_ADAPTER_H #ifdef LUA_ADAPTER_DEBUG #include <iostream> #define LUA_ADAPTER_PREFIX "Lua > " #warning Debug-information will be displayed during execution! #endif #include <string> #include <memory> #include <lua.hpp> class LuaTable; class LuaState { private: lua_State *const lua; public: LuaState(lua_State *const l):lua{l}{} LuaState() :lua{luaL_newstate()} { luaL_openlibs(this->lua); } ~LuaState(){ lua_close(this->lua); } LuaState & operator=(const LuaState&) = delete; LuaState(const LuaState&) = delete; lua_State *const Lua() const { return this->lua; }; }; class LuaAdapter { public: /** * Default-Constructor */ LuaAdapter() :Lua{std::make_shared<LuaState>()}{} /** * Constructor * @param lua uses an pre-existing lua_state. * (See for example testCFunction() in test.cpp) */ LuaAdapter(lua_State *const lua) :Lua{std::make_shared<LuaState>(lua)}{} LuaAdapter(LuaAdapter &lua) :Lua{lua.GetLuaState()}{} LuaAdapter(const LuaAdapter& lua) :Lua{lua.GetLuaState()}{} /** * This constructor inits Lua and loads a .Lua-file. * @param filename .Lua-file to load */ LuaAdapter(const std::string &filename) : Lua{std::make_shared<LuaState>()}{ this->Load(filename); } /** * Destructor */ ~LuaAdapter() {} /** * Loads a *.Lua-sourcefile * * @param filename lua file to load * @return true on success, false on error */ bool Load(const std::string &filename){return Load(filename.c_str());} bool Load(const char *filename) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || (luaL_loadfile(this->Lua.get()->Lua(), filename) != 0) ){ #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error. Could not load '"; std::cerr << filename << "'" << std::endl; #endif return false; } if(lua_pcall(this->Lua.get()->Lua(), 0, 0, 0) == 0) return true; #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error in Lua-file "; std::cerr << lua_tostring(this->Lua.get()->Lua(), -1); std::cerr << std::endl; #endif return false; } /** * Loads 'precompiled' Lua-Code * * @param bytecode Lua-Code * @param amounts of bytes * @return true on success, false on error */ bool Load(const char *bytecode, const size_t length) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || (luaL_loadbuffer(this->Lua.get()->Lua(), bytecode, length, nullptr) != 0) ){ #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error. Could not load Lua-bytecode'"; std::cerr << std::endl; #endif return false; } if(lua_pcall(this->Lua.get()->Lua(), 0, 0, 0) == 0) return true; #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error in Lua-file "; std::cerr << lua_tostring(this->Lua.get()->Lua(), -1); std::cerr << std::endl; #endif return false; } /** * Gets the value of a global variable. * @param name of the variable inside loaded Lua-state * @param r value is saved in this variable * @return true on success, false on error */ template <typename R> bool Get(const char *name, R &r) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || !name ) return false; switch (lua_getglobal(this->Lua.get()->Lua(), name)) { case LUA_TNUMBER: if (lua_isinteger(this->Lua.get()->Lua(), -1)) { if constexpr(std::is_same_v<R, int>) r = lua_tointeger(this->Lua.get()->Lua(), -1); } else if constexpr(std::is_same_v<double, R> || std::is_same_v<R, float>) r = lua_tonumber(this->Lua.get()->Lua(), -1); break; case LUA_TBOOLEAN: if constexpr(std::is_same_v<R, bool>) r = lua_toboolean(this->Lua.get()->Lua(), -1); break; case LUA_TSTRING: if constexpr(std::is_same_v<R, std::string>) r = lua_tostring(this->Lua.get()->Lua(), -1); break; default: return false; break; } #ifdef LUA_ADAPTER_DEBUG std::cout << LUA_ADAPTER_PREFIX << "got '" << name << "' = '" << r << "'" << std::endl; #endif lua_pop(this->Lua.get()->Lua(), 1); return true; } /** * Sets the value of a global Lua-variable. * @param name of the variable * @param a the var's value * @return true on success, false on error */ template <typename A> bool Set(const char *name, const A a) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || !name ) return false; if (this->Push(a) == true) { lua_setglobal(this->Lua.get()->Lua(), name); #ifdef LUA_ADAPTER_DEBUG std::cout << LUA_ADAPTER_PREFIX << "set '" << name << "' = '" << a << "'" << std::endl; #endif return true; } return false; } /** * Execute any string * @param string to execute, for example "test = io.read()" * @return true on success, false on error */ bool DoString(const char *string) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return luaL_dostring(this->Lua.get()->Lua(), string); } /** * Push data on the lua stack. * @param a variable to push * @return true on success, false on error */ template <typename A> bool Push(A a) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; if constexpr(std::is_same_v<A, int>) lua_pushinteger(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, float> || std::is_same_v<A, double>) lua_pushnumber(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, bool>) lua_pushboolean(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, std::string>) lua_pushlstring(this->Lua.get()->Lua(), a.c_str(), a.length()); else return false; return true; } /** * Resets Lua's internal stack * @return true on success, false on error */ bool Flush() { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; lua_settop(this->Lua.get()->Lua(), 0); return true; } /** * Pops i entries from Lua's internal stack * @param i number of entries */ void Pop(int i = 1) { if( (this->Lua.get()) && (this->Lua.get()->Lua()) ) lua_pop(this->Lua.get()->Lua(), i); } /** * Gets the stack position * @return the stack position */ int GetTop() const { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return lua_gettop(this->Lua.get()->Lua()); } /** * Gets the value type of the current stack position * (LUA_TNIL (0), LUA_TNUMBER, LUA_TBOOLEAN, LUA_TSTRING, LUA_TTABLE, * LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD, and LUA_TLIGHTUSERDATA.) * [https://www.lua.org/manual/5.3/manual.html#lua_type] * @return the type */ int GetType() const { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return lua_type(this->Lua.get()->Lua(), 0); } /** * Returns the current LuaState which is used * This is necessary, * because you need this state for LuaFunctions or LuaTables. * @return the current LuaState */ std::shared_ptr<LuaState> GetLuaState() const { return this->Lua; } private: std::shared_ptr<LuaState> Lua; }; #endif <commit_msg>Code duplication.<commit_after>/* * Copyright (c) 2015-2019 JlnWntr ([email protected]) * * 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. */ #ifndef LUA_ADAPTER_H #define LUA_ADAPTER_H #ifdef LUA_ADAPTER_DEBUG #include <iostream> #define LUA_ADAPTER_PREFIX "Lua > " #warning Debug-information will be displayed during execution! #endif #include <string> #include <memory> #include <lua.hpp> class LuaTable; class LuaState { private: lua_State *const lua; public: LuaState(lua_State *const l):lua{l}{} LuaState() :lua{luaL_newstate()} { luaL_openlibs(this->lua); } ~LuaState(){ lua_close(this->lua); } LuaState & operator=(const LuaState&) = delete; LuaState(const LuaState&) = delete; lua_State *const Lua() const { return this->lua; }; }; class LuaAdapter { public: /** * Default-Constructor */ LuaAdapter() :Lua{std::make_shared<LuaState>()}{} /** * Constructor * @param lua uses an pre-existing lua_state. * (See for example testCFunction() in test.cpp) */ LuaAdapter(lua_State *const lua) :Lua{std::make_shared<LuaState>(lua)}{} LuaAdapter(LuaAdapter &lua) :Lua{lua.GetLuaState()}{} LuaAdapter(const LuaAdapter& lua) :Lua{lua.GetLuaState()}{} /** * This constructor inits Lua and loads a .Lua-file. * @param filename .Lua-file to load */ LuaAdapter(const std::string &filename) : Lua{std::make_shared<LuaState>()}{ this->Load(filename); } /** * Destructor */ ~LuaAdapter() {} /** * Loads and interprets Lua-code. * If length is given, then LuaAdapter will regard the given bytestring (code) as 'precompiled' Lua-code.* * @param code Lua-Code * @param length amounts of bytes * @return true on success, false on error */ bool Load(const std::string &filename){return Load(filename.c_str());} bool Load(const char *code, const size_t length=0) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || (!code) || ((length==0) && (luaL_loadfile(this->Lua.get()->Lua(), code) != 0)) || ((length!=0) && (luaL_loadbuffer(this->Lua.get()->Lua(), code, length, nullptr) != 0)) ){ #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error. Could not load '"; std::cerr << filename << "'" << std::endl; #endif return false; } if(lua_pcall(this->Lua.get()->Lua(), 0, 0, 0) == 0) return true; #ifdef LUA_ADAPTER_DEBUG std::cerr << LUA_ADAPTER_PREFIX << "Error in Lua-file "; std::cerr << lua_tostring(this->Lua.get()->Lua(), -1); std::cerr << std::endl; #endif return false; } /** * Gets the value of a global variable. * @param name of the variable inside loaded Lua-state * @param r value is saved in this variable * @return true on success, false on error */ template <typename R> bool Get(const char *name, R &r) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || !name ) return false; switch (lua_getglobal(this->Lua.get()->Lua(), name)) { case LUA_TNUMBER: if (lua_isinteger(this->Lua.get()->Lua(), -1)) { if constexpr(std::is_same_v<R, int>) r = lua_tointeger(this->Lua.get()->Lua(), -1); } else if constexpr(std::is_same_v<double, R> || std::is_same_v<R, float>) r = lua_tonumber(this->Lua.get()->Lua(), -1); break; case LUA_TBOOLEAN: if constexpr(std::is_same_v<R, bool>) r = lua_toboolean(this->Lua.get()->Lua(), -1); break; case LUA_TSTRING: if constexpr(std::is_same_v<R, std::string>) r = lua_tostring(this->Lua.get()->Lua(), -1); break; default: return false; break; } #ifdef LUA_ADAPTER_DEBUG std::cout << LUA_ADAPTER_PREFIX << "got '" << name << "' = '" << r << "'" << std::endl; #endif lua_pop(this->Lua.get()->Lua(), 1); return true; } /** * Sets the value of a global Lua-variable. * @param name of the variable * @param a the var's value * @return true on success, false on error */ template <typename A> bool Set(const char *name, const A a) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) || !name ) return false; if (this->Push(a) == true) { lua_setglobal(this->Lua.get()->Lua(), name); #ifdef LUA_ADAPTER_DEBUG std::cout << LUA_ADAPTER_PREFIX << "set '" << name << "' = '" << a << "'" << std::endl; #endif return true; } return false; } /** * Execute any string * @param string to execute, for example "test = io.read()" * @return true on success, false on error */ bool DoString(const char *string) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return luaL_dostring(this->Lua.get()->Lua(), string); } /** * Push data on the lua stack. * @param a variable to push * @return true on success, false on error */ template <typename A> bool Push(A a) { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; if constexpr(std::is_same_v<A, int>) lua_pushinteger(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, float> || std::is_same_v<A, double>) lua_pushnumber(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, bool>) lua_pushboolean(this->Lua.get()->Lua(), a); else if constexpr(std::is_same_v<A, std::string>) lua_pushlstring(this->Lua.get()->Lua(), a.c_str(), a.length()); else return false; return true; } /** * Resets Lua's internal stack * @return true on success, false on error */ bool Flush() { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; lua_settop(this->Lua.get()->Lua(), 0); return true; } /** * Pops i entries from Lua's internal stack * @param i number of entries */ void Pop(int i = 1) { if( (this->Lua.get()) && (this->Lua.get()->Lua()) ) lua_pop(this->Lua.get()->Lua(), i); } /** * Gets the stack position * @return the stack position */ int GetTop() const { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return lua_gettop(this->Lua.get()->Lua()); } /** * Gets the value type of the current stack position * (LUA_TNIL (0), LUA_TNUMBER, LUA_TBOOLEAN, LUA_TSTRING, LUA_TTABLE, * LUA_TFUNCTION, LUA_TUSERDATA, LUA_TTHREAD, and LUA_TLIGHTUSERDATA.) * [https://www.lua.org/manual/5.3/manual.html#lua_type] * @return the type */ int GetType() const { if( (!this->Lua.get()) || (!this->Lua.get()->Lua()) ) return false; return lua_type(this->Lua.get()->Lua(), 0); } /** * Returns the current LuaState which is used * This is necessary, * because you need this state for LuaFunctions or LuaTables. * @return the current LuaState */ std::shared_ptr<LuaState> GetLuaState() const { return this->Lua; } private: std::shared_ptr<LuaState> Lua; }; #endif <|endoftext|>
<commit_before>// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // 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. #ifndef FAINT_WINDOW_APP_CONTEXT_HH #define FAINT_WINDOW_APP_CONTEXT_HH #include "app/app-context.hh" #include "app/faint-common-cursors.hh" #include "app/faint-slider-cursors.hh" #include "gui/canvas-panel.hh" // Fixme #include "gui/command-window.hh" #include "gui/dialogs/resize-dialog-options.hh" // Fixme: impl #include "gui/faint-window.hh" // Fixme: Consider forward declaration #include "gui/transparency-style.hh" // Fixme: impl #include "tools/tool.hh" #include "util/bound-setting.hh" // Fixme: For BoundSetting #include "util/dumb-ptr.hh" // Fixme: impl #include "util/grid.hh" // Fixme: impl class wxStatusBar; namespace faint{ class Art; class Canvas; class FilePath; class FaintWindow; class HelpFrame; class InterpreterFrame; class TabCtrl; class SBInterface final : public StatusInterface { public: SBInterface(wxStatusBar&); void SetMainText(const utf8_string& text) override; void SetText(const utf8_string& text, int field=0) override; void Clear() override; SBInterface& operator=(const SBInterface&) = delete; private: wxStatusBar& m_statusbar; }; using from_control = LessDistinct<bool, 0>; class FaintDialogContext final : public DialogContext{ public: FaintDialogContext(AppContext&, const Art&, FaintWindow&); SliderCursors& GetSliderCursors() override; CommonCursors& GetCommonCursors() override; void Show(std::unique_ptr<CommandWindow>&& w) override; void UpdateSettings(const Settings&); void Reinitialize(); Optional<CommandWindow&> ShownWindow(); void Close(); private: void BeginModalDialog() override; void EndModalDialog() override; void OnClosed(BitmapCommand*); AppContext& m_app; std::unique_ptr<CommandWindow> m_commandWindow; FaintCommonCursors m_commonCursors; FaintWindow& m_faintWindow; FaintSliderCursors m_sliderCursors; std::unique_ptr<WindowFeedback> m_windowFeedback; }; class FaintWindowExtraOverlay final : public ExtraOverlay{ public: // Fixme: Weird class. Use the WindowFeedback instead? FaintWindowExtraOverlay(FaintDialogContext&); void Draw(FaintDC& dc, Overlays& overlays, const PosInfo& info) override; FaintWindowExtraOverlay& operator=(FaintWindowExtraOverlay&) = delete; private: FaintDialogContext& m_dialogContext; }; class FaintWindowInteraction final : public Interaction{ public: FaintWindowInteraction(FaintDialogContext&); bool MouseMove(const PosInfo&) override; FaintWindowInteraction& operator=(const FaintWindowInteraction&) = delete; private: FaintDialogContext& m_ctx; }; class FaintWindowContext final : public AppContext { public: FaintWindowContext(FaintWindow&, const Art&, wxStatusBar&, HelpFrame&, InterpreterFrame&); void AddFormat(Format*) override; void AddToPalette(const Paint&) override; void BeginModalDialog() override; void BeginTextEntry() override; void Close(Canvas& canvas) override; void DialogOpenFile() override; void DialogSaveAs(Canvas& canvas, bool backup) override; void EndModalDialog() override; void EndTextEntry() override; bool Exists(const CanvasId&) override; bool FaintWindowFocused() const override; BoolSetting::ValueType Get(const BoolSetting&) override; StringSetting::ValueType Get(const StringSetting&) override; IntSetting::ValueType Get(const IntSetting&) override; PaintSetting::ValueType Get(const PaintSetting&) override; FloatSetting::ValueType Get(const FloatSetting&) override; Interaction& GetInteraction() override; ExtraOverlay& GetExtraOverlay() override; Canvas& GetActiveCanvas() override; Tool* GetActiveTool() override; Canvas& GetCanvas(const Index&) override; Canvas& GetCanvas(const CanvasId&) override; Index GetCanvasCount() const override; Grid GetDefaultGrid() const override; ImageInfo GetDefaultImageInfo() override; FaintDialogContext& GetDialogContext() override; std::vector<Format*> GetFormats() override; ResizeDialogOptions GetDefaultResizeDialogOptions() const override; Layer GetLayerType() const override; IntPoint GetMousePos() override; StatusInterface& GetStatusInfo(); // Non virtual ToolId GetToolId() const override; Settings GetToolSettings() const override; const TransparencyStyle& GetTransparencyStyle() const override; bool IsFullScreen() const override; Canvas* Load(const FilePath&, const change_tab&) override; void Load(const FileList&) override; Canvas* LoadAsFrames(const FileList& paths, const change_tab& changeTab) override; void Maximize() override; void MaximizeInterpreter() override; bool ModalDialogShown() const override; Canvas& NewDocument(const ImageInfo& info) override; Canvas& NewDocument(ImageProps&& props) override; void NextTab() override; void PreviousTab() override; void QueueLoad(const FileList& filenames) override; void Quit() override; void RaiseWindow() override; bool Save(Canvas& canvas) override; void SelectTool(ToolId id) override; void Set(const BoolSetting&, BoolSetting::ValueType) override; void Set(const StringSetting&, const StringSetting::ValueType&) override; void Set(const IntSetting&, IntSetting::ValueType) override; void Set(const PaintSetting&, PaintSetting::ValueType) override; void Set(const FloatSetting&, FloatSetting::ValueType) override; void SetActiveCanvas(const CanvasId&) override; void SetDefaultGrid(const Grid&) override; void SetDefaultResizeDialogOptions(const ResizeDialogOptions& opts) override; void SetInterpreterBackground(const ColRGB& c) override; void SetInterpreterTextColor(const ColRGB& c) override; void SetPalette(const PaintMap& paintMap) override; void SetTransparencyStyle(const TransparencyStyle& style) override; void SetLayer(Layer layer) override; void ModalFull(const dialog_func& show_dialog) override; void Modal(const bmp_dialog_func& show_dialog) override; void ToggleHelpFrame() override; void TogglePythonConsole() override; void ShowColorPanel(bool show) override; void ShowPythonConsole() override; void ShowStatusbar(bool show) override; void ShowToolPanel(bool show) override; int TabletGetCursor() override; // Note: Not an override, used directly by FaintWindow void TabletSetCursor(int tabletCursor); void ToggleFullScreen(bool) override; void ToggleMaximize() override; void UpdateShownSettings() override; void UpdateToolSettings(const Settings&) override; void SetTabCtrl(TabCtrl*); // Non virtual private: FaintDialogContext m_dialogContext; FaintWindowExtraOverlay m_extraOverlay; FaintWindow& m_faintWindow; HelpFrame& m_helpFrame; FaintWindowInteraction m_interaction; InterpreterFrame& m_interpreterFrame; int m_modalDialog; SBInterface m_statusbar; Grid m_defaultGrid; ResizeDialogOptions m_defaultResizeSettings; TransparencyStyle m_transparencyStyle; int m_tabletCursor; dumb_ptr<TabCtrl> m_tabControl; }; template<typename T> void change_setting(FaintWindow& window, const T& setting, typename T::ValueType value, const from_control& fromControl, FaintDialogContext& dialogContext) { dialogContext.ShownWindow().Visit( [&](CommandWindow& w){ const auto& windowSettings(w.GetSettings()); if (windowSettings.Has(setting)){ // Fixme: Silly dialogContext.UpdateSettings(with(windowSettings, setting, value)); // w.UpdateSettings(with(windowSettings, setting, value)); } }, [](){}); Tool* tool = window.GetActiveTool(); if (tool->GetSettings().Has(setting)){ bool toolModified = tool->Set({setting, value}); if (toolModified) { window.GetActiveCanvas().Refresh(); } if (tool->EatsSettings()){ if (!fromControl.Get()){ window.UpdateShownSettings(); } return; } } window.GetToolSettings().Set(setting, value); if (!fromControl.Get()){ window.UpdateShownSettings(); } } } // namespace #endif <commit_msg>Removed unnecessary include.<commit_after>// -*- coding: us-ascii-unix -*- // Copyright 2014 Lukas Kemmer // // 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. #ifndef FAINT_WINDOW_APP_CONTEXT_HH #define FAINT_WINDOW_APP_CONTEXT_HH #include "app/app-context.hh" #include "app/faint-common-cursors.hh" #include "app/faint-slider-cursors.hh" #include "gui/canvas-panel.hh" // Fixme #include "gui/command-window.hh" #include "gui/dialogs/resize-dialog-options.hh" // Fixme: impl #include "gui/transparency-style.hh" // Fixme: impl #include "tools/tool.hh" #include "util/bound-setting.hh" // Fixme: For BoundSetting #include "util/dumb-ptr.hh" // Fixme: impl #include "util/grid.hh" // Fixme: impl class wxStatusBar; namespace faint{ class Art; class Canvas; class FilePath; class FaintWindow; class HelpFrame; class InterpreterFrame; class TabCtrl; class SBInterface final : public StatusInterface { public: SBInterface(wxStatusBar&); void SetMainText(const utf8_string& text) override; void SetText(const utf8_string& text, int field=0) override; void Clear() override; SBInterface& operator=(const SBInterface&) = delete; private: wxStatusBar& m_statusbar; }; using from_control = LessDistinct<bool, 0>; class FaintDialogContext final : public DialogContext{ public: FaintDialogContext(AppContext&, const Art&, FaintWindow&); SliderCursors& GetSliderCursors() override; CommonCursors& GetCommonCursors() override; void Show(std::unique_ptr<CommandWindow>&& w) override; void UpdateSettings(const Settings&); void Reinitialize(); Optional<CommandWindow&> ShownWindow(); void Close(); private: void BeginModalDialog() override; void EndModalDialog() override; void OnClosed(BitmapCommand*); AppContext& m_app; std::unique_ptr<CommandWindow> m_commandWindow; FaintCommonCursors m_commonCursors; FaintWindow& m_faintWindow; FaintSliderCursors m_sliderCursors; std::unique_ptr<WindowFeedback> m_windowFeedback; }; class FaintWindowExtraOverlay final : public ExtraOverlay{ public: // Fixme: Weird class. Use the WindowFeedback instead? FaintWindowExtraOverlay(FaintDialogContext&); void Draw(FaintDC& dc, Overlays& overlays, const PosInfo& info) override; FaintWindowExtraOverlay& operator=(FaintWindowExtraOverlay&) = delete; private: FaintDialogContext& m_dialogContext; }; class FaintWindowInteraction final : public Interaction{ public: FaintWindowInteraction(FaintDialogContext&); bool MouseMove(const PosInfo&) override; FaintWindowInteraction& operator=(const FaintWindowInteraction&) = delete; private: FaintDialogContext& m_ctx; }; class FaintWindowContext final : public AppContext { public: FaintWindowContext(FaintWindow&, const Art&, wxStatusBar&, HelpFrame&, InterpreterFrame&); void AddFormat(Format*) override; void AddToPalette(const Paint&) override; void BeginModalDialog() override; void BeginTextEntry() override; void Close(Canvas& canvas) override; void DialogOpenFile() override; void DialogSaveAs(Canvas& canvas, bool backup) override; void EndModalDialog() override; void EndTextEntry() override; bool Exists(const CanvasId&) override; bool FaintWindowFocused() const override; BoolSetting::ValueType Get(const BoolSetting&) override; StringSetting::ValueType Get(const StringSetting&) override; IntSetting::ValueType Get(const IntSetting&) override; PaintSetting::ValueType Get(const PaintSetting&) override; FloatSetting::ValueType Get(const FloatSetting&) override; Interaction& GetInteraction() override; ExtraOverlay& GetExtraOverlay() override; Canvas& GetActiveCanvas() override; Tool* GetActiveTool() override; Canvas& GetCanvas(const Index&) override; Canvas& GetCanvas(const CanvasId&) override; Index GetCanvasCount() const override; Grid GetDefaultGrid() const override; ImageInfo GetDefaultImageInfo() override; FaintDialogContext& GetDialogContext() override; std::vector<Format*> GetFormats() override; ResizeDialogOptions GetDefaultResizeDialogOptions() const override; Layer GetLayerType() const override; IntPoint GetMousePos() override; StatusInterface& GetStatusInfo(); // Non virtual ToolId GetToolId() const override; Settings GetToolSettings() const override; const TransparencyStyle& GetTransparencyStyle() const override; bool IsFullScreen() const override; Canvas* Load(const FilePath&, const change_tab&) override; void Load(const FileList&) override; Canvas* LoadAsFrames(const FileList& paths, const change_tab& changeTab) override; void Maximize() override; void MaximizeInterpreter() override; bool ModalDialogShown() const override; Canvas& NewDocument(const ImageInfo& info) override; Canvas& NewDocument(ImageProps&& props) override; void NextTab() override; void PreviousTab() override; void QueueLoad(const FileList& filenames) override; void Quit() override; void RaiseWindow() override; bool Save(Canvas& canvas) override; void SelectTool(ToolId id) override; void Set(const BoolSetting&, BoolSetting::ValueType) override; void Set(const StringSetting&, const StringSetting::ValueType&) override; void Set(const IntSetting&, IntSetting::ValueType) override; void Set(const PaintSetting&, PaintSetting::ValueType) override; void Set(const FloatSetting&, FloatSetting::ValueType) override; void SetActiveCanvas(const CanvasId&) override; void SetDefaultGrid(const Grid&) override; void SetDefaultResizeDialogOptions(const ResizeDialogOptions& opts) override; void SetInterpreterBackground(const ColRGB& c) override; void SetInterpreterTextColor(const ColRGB& c) override; void SetPalette(const PaintMap& paintMap) override; void SetTransparencyStyle(const TransparencyStyle& style) override; void SetLayer(Layer layer) override; void ModalFull(const dialog_func& show_dialog) override; void Modal(const bmp_dialog_func& show_dialog) override; void ToggleHelpFrame() override; void TogglePythonConsole() override; void ShowColorPanel(bool show) override; void ShowPythonConsole() override; void ShowStatusbar(bool show) override; void ShowToolPanel(bool show) override; int TabletGetCursor() override; // Note: Not an override, used directly by FaintWindow void TabletSetCursor(int tabletCursor); void ToggleFullScreen(bool) override; void ToggleMaximize() override; void UpdateShownSettings() override; void UpdateToolSettings(const Settings&) override; void SetTabCtrl(TabCtrl*); // Non virtual private: FaintDialogContext m_dialogContext; FaintWindowExtraOverlay m_extraOverlay; FaintWindow& m_faintWindow; HelpFrame& m_helpFrame; FaintWindowInteraction m_interaction; InterpreterFrame& m_interpreterFrame; int m_modalDialog; SBInterface m_statusbar; Grid m_defaultGrid; ResizeDialogOptions m_defaultResizeSettings; TransparencyStyle m_transparencyStyle; int m_tabletCursor; dumb_ptr<TabCtrl> m_tabControl; }; template<typename T> void change_setting(FaintWindow& window, const T& setting, typename T::ValueType value, const from_control& fromControl, FaintDialogContext& dialogContext) { dialogContext.ShownWindow().Visit( [&](CommandWindow& w){ const auto& windowSettings(w.GetSettings()); if (windowSettings.Has(setting)){ // Fixme: Silly dialogContext.UpdateSettings(with(windowSettings, setting, value)); // w.UpdateSettings(with(windowSettings, setting, value)); } }, [](){}); Tool* tool = window.GetActiveTool(); if (tool->GetSettings().Has(setting)){ bool toolModified = tool->Set({setting, value}); if (toolModified) { window.GetActiveCanvas().Refresh(); } if (tool->EatsSettings()){ if (!fromControl.Get()){ window.UpdateShownSettings(); } return; } } window.GetToolSettings().Set(setting, value); if (!fromControl.Get()){ window.UpdateShownSettings(); } } } // namespace #endif <|endoftext|>
<commit_before>/* This file is part of Fabula. Copyright (C) 2010 Mike McQuaid <[email protected]> Fabula 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. Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>. */ #include "MainWindow.h" #include "ui_MainWindow.h" #include "Database.h" #include "TableTreeModel.h" #include "TwoRowDelegate.h" #include "PreferencesDialog.h" #include "EventDialog.h" #include <QFileDialog> #include <QSqlRelationalTableModel> #include <QTableView> #include <QFile> #include <QDebug> #include <QSortFilterProxyModel> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), database(0), eventsModel(0), conversationsModel(0) { ui->setupUi(this); QString fileName = settings.value("database").toString(); if (fileName.isEmpty()) { newFile(); } else { openFile(fileName); } ui->statusBar->hide(); ui->splitter->setStretchFactor(1, 3); PreferencesDialog *preferences = new PreferencesDialog(this); EventDialog *eventDialog = new EventDialog(this); eventDialog->setModal(false); eventDialog->show(); connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile())); connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile())); connect(ui->actionAdd_Event, SIGNAL(triggered()), this, SLOT(addEvent())); connect(ui->actionDelete_Event, SIGNAL(triggered()), this, SLOT(deleteEvent())); connect(ui->actionAdd_Conversation, SIGNAL(triggered()), this, SLOT(addToConversationTree())); connect(ui->actionDelete_Conversation, SIGNAL(triggered()), this, SLOT(removeFromConversationTree())); connect(ui->actionPreferences, SIGNAL(triggered()), preferences, SLOT(open())); connect(ui->conversationsView, SIGNAL(clicked(QModelIndex)), this, SLOT(filterOnConversation(QModelIndex))); eventsModel = new QSqlRelationalTableModel(); eventsModel->setTable("events"); eventsModel->setEditStrategy(QSqlTableModel::OnFieldChange); eventsModel->setHeaderData(0, Qt::Horizontal, tr("ID")); eventsModel->setHeaderData(1, Qt::Horizontal, tr("Type")); eventsModel->setRelation(1, QSqlRelation("event_types", "id", "name")); eventsModel->setHeaderData(2, Qt::Horizontal, tr("Conversation")); eventsModel->setRelation(2, QSqlRelation("conversations", "id", "name")); eventsModel->setHeaderData(3, Qt::Horizontal, tr("Character")); eventsModel->setRelation(3, QSqlRelation("characters", "id", "name")); eventsModel->setHeaderData(4, Qt::Horizontal, tr("Audio File")); eventsModel->setRelation(4, QSqlRelation("audiofiles", "id", "url")); eventsModel->setHeaderData(5, Qt::Horizontal, tr("Text")); eventsModel->select(); ui->eventsView->setModel(eventsModel); ui->eventsView->hideColumn(0); ui->eventsView->horizontalHeader()->setStretchLastSection(true); ui->eventsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); ui->eventsView->setWordWrap(true); ui->eventsView->setShowGrid(true); ui->eventsView->setAlternatingRowColors(true); QSqlRelationalDelegate *eventsDelegate = new QSqlRelationalDelegate(this); ui->eventsView->setItemDelegate(eventsDelegate); conversationsModel = new SqlTreeModel(this); ui->conversationsView->setSelectionMode(QAbstractItemView::SingleSelection); ui->conversationsView->setUniformRowHeights(true); ui->conversationsView->header()->setStretchLastSection(false); ui->conversationsView->header()->setResizeMode(QHeaderView::ResizeToContents); ui->conversationsView->setModel(conversationsModel); connect(conversationsModel, SIGNAL(submitted()), this, SLOT(reloadEvents())); } void MainWindow::newFile() { QString fileName = QFileDialog::getSaveFileName( this, tr("New File"), desktopServices.storageLocation(QDesktopServices::DocumentsLocation), tr("Fabula Files (*.fabula)")); if (QFile::exists(fileName)) QFile::remove(fileName); openFile(fileName); } void MainWindow::openFile(QString fileName) { if (fileName.isEmpty()) { fileName = QFileDialog::getOpenFileName( this, tr("Open File"), desktopServices.storageLocation(QDesktopServices::DocumentsLocation), tr("Fabula Files (*.fabula)")); } if (!fileName.isEmpty()) { if (database) { delete database; database = 0; } database = new Database(fileName); settings.setValue("database", fileName); reloadEvents(); if (conversationsModel) conversationsModel->reset(); setWindowTitle(QString("%1 - Fabula").arg(fileName)); ui->centralWidget->setEnabled(true); } else { if (!database) { ui->centralWidget->setEnabled(false); } } } void MainWindow::filterOnConversation(const QModelIndex& index) { static const int conversationRow = 2; static const int characterRow = 3; if (!conversationsModel || !eventsModel) return; QString filter; int row = 0; if (index.parent().isValid()) row = conversationRow; else row = characterRow; const QString name = conversationsModel->data(index).toString(); // The "relTblAl_" is from the QSqlRelationalTableModel source. // This was needed as otherwise it's not obvious how to filter without breaking relations. filter = QString("relTblAl_%1.name='%2'").arg(row).arg(name); eventsModel->setFilter(filter); } void MainWindow::addEvent() { eventsModel->insertRow(ui->eventsView->currentIndex().row()+1); } void MainWindow::deleteEvent() { eventsModel->removeRow(ui->eventsView->currentIndex().row()); } void MainWindow::addToConversationTree() { conversationsModel->insertRow(ui->conversationsView->currentIndex().row(), ui->conversationsView->currentIndex().parent()); } void MainWindow::removeFromConversationTree() { conversationsModel->removeRow(ui->conversationsView->currentIndex().row(), ui->conversationsView->currentIndex().parent()); } void MainWindow::reloadEvents() { if (eventsModel) eventsModel->select(); if (ui->conversationsView) filterOnConversation(ui->conversationsView->currentIndex()); } MainWindow::~MainWindow() { delete ui; // Delete here rather than using this object as parent so we can ensure the // database is deleted last. delete eventsModel; delete database; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } <commit_msg>Fix missing include compilation error.<commit_after>/* This file is part of Fabula. Copyright (C) 2010 Mike McQuaid <[email protected]> Fabula 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. Fabula 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 Fabula. If not, see <http://www.gnu.org/licenses/>. */ #include "MainWindow.h" #include "ui_MainWindow.h" #include "Database.h" #include "TableTreeModel.h" #include "PreferencesDialog.h" #include "EventDialog.h" #include <QFileDialog> #include <QSqlRelationalTableModel> #include <QTableView> #include <QFile> #include <QDebug> #include <QSortFilterProxyModel> #include <QSqlRelationalDelegate> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), database(0), eventsModel(0), conversationsModel(0) { ui->setupUi(this); QString fileName = settings.value("database").toString(); if (fileName.isEmpty()) { newFile(); } else { openFile(fileName); } ui->statusBar->hide(); ui->splitter->setStretchFactor(1, 3); PreferencesDialog *preferences = new PreferencesDialog(this); EventDialog *eventDialog = new EventDialog(this); eventDialog->setModal(false); eventDialog->show(); connect(ui->actionNew, SIGNAL(triggered()), this, SLOT(newFile())); connect(ui->actionOpen, SIGNAL(triggered()), this, SLOT(openFile())); connect(ui->actionAdd_Event, SIGNAL(triggered()), this, SLOT(addEvent())); connect(ui->actionDelete_Event, SIGNAL(triggered()), this, SLOT(deleteEvent())); connect(ui->actionAdd_Conversation, SIGNAL(triggered()), this, SLOT(addToConversationTree())); connect(ui->actionDelete_Conversation, SIGNAL(triggered()), this, SLOT(removeFromConversationTree())); connect(ui->actionPreferences, SIGNAL(triggered()), preferences, SLOT(open())); connect(ui->conversationsView, SIGNAL(clicked(QModelIndex)), this, SLOT(filterOnConversation(QModelIndex))); eventsModel = new QSqlRelationalTableModel(); eventsModel->setTable("events"); eventsModel->setEditStrategy(QSqlTableModel::OnFieldChange); eventsModel->setHeaderData(0, Qt::Horizontal, tr("ID")); eventsModel->setHeaderData(1, Qt::Horizontal, tr("Type")); eventsModel->setRelation(1, QSqlRelation("event_types", "id", "name")); eventsModel->setHeaderData(2, Qt::Horizontal, tr("Conversation")); eventsModel->setRelation(2, QSqlRelation("conversations", "id", "name")); eventsModel->setHeaderData(3, Qt::Horizontal, tr("Character")); eventsModel->setRelation(3, QSqlRelation("characters", "id", "name")); eventsModel->setHeaderData(4, Qt::Horizontal, tr("Audio File")); eventsModel->setRelation(4, QSqlRelation("audiofiles", "id", "url")); eventsModel->setHeaderData(5, Qt::Horizontal, tr("Text")); eventsModel->select(); ui->eventsView->setModel(eventsModel); ui->eventsView->hideColumn(0); ui->eventsView->horizontalHeader()->setStretchLastSection(true); ui->eventsView->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); ui->eventsView->setWordWrap(true); ui->eventsView->setShowGrid(true); ui->eventsView->setAlternatingRowColors(true); QSqlRelationalDelegate *eventsDelegate = new QSqlRelationalDelegate(this); ui->eventsView->setItemDelegate(eventsDelegate); conversationsModel = new SqlTreeModel(this); ui->conversationsView->setSelectionMode(QAbstractItemView::SingleSelection); ui->conversationsView->setUniformRowHeights(true); ui->conversationsView->header()->setStretchLastSection(false); ui->conversationsView->header()->setResizeMode(QHeaderView::ResizeToContents); ui->conversationsView->setModel(conversationsModel); connect(conversationsModel, SIGNAL(submitted()), this, SLOT(reloadEvents())); } void MainWindow::newFile() { QString fileName = QFileDialog::getSaveFileName( this, tr("New File"), desktopServices.storageLocation(QDesktopServices::DocumentsLocation), tr("Fabula Files (*.fabula)")); if (QFile::exists(fileName)) QFile::remove(fileName); openFile(fileName); } void MainWindow::openFile(QString fileName) { if (fileName.isEmpty()) { fileName = QFileDialog::getOpenFileName( this, tr("Open File"), desktopServices.storageLocation(QDesktopServices::DocumentsLocation), tr("Fabula Files (*.fabula)")); } if (!fileName.isEmpty()) { if (database) { delete database; database = 0; } database = new Database(fileName); settings.setValue("database", fileName); reloadEvents(); if (conversationsModel) conversationsModel->reset(); setWindowTitle(QString("%1 - Fabula").arg(fileName)); ui->centralWidget->setEnabled(true); } else { if (!database) { ui->centralWidget->setEnabled(false); } } } void MainWindow::filterOnConversation(const QModelIndex& index) { static const int conversationRow = 2; static const int characterRow = 3; if (!conversationsModel || !eventsModel) return; QString filter; int row = 0; if (index.parent().isValid()) row = conversationRow; else row = characterRow; const QString name = conversationsModel->data(index).toString(); // The "relTblAl_" is from the QSqlRelationalTableModel source. // This was needed as otherwise it's not obvious how to filter without breaking relations. filter = QString("relTblAl_%1.name='%2'").arg(row).arg(name); eventsModel->setFilter(filter); } void MainWindow::addEvent() { eventsModel->insertRow(ui->eventsView->currentIndex().row()+1); } void MainWindow::deleteEvent() { eventsModel->removeRow(ui->eventsView->currentIndex().row()); } void MainWindow::addToConversationTree() { conversationsModel->insertRow(ui->conversationsView->currentIndex().row(), ui->conversationsView->currentIndex().parent()); } void MainWindow::removeFromConversationTree() { conversationsModel->removeRow(ui->conversationsView->currentIndex().row(), ui->conversationsView->currentIndex().parent()); } void MainWindow::reloadEvents() { if (eventsModel) eventsModel->select(); if (ui->conversationsView) filterOnConversation(ui->conversationsView->currentIndex()); } MainWindow::~MainWindow() { delete ui; // Delete here rather than using this object as parent so we can ensure the // database is deleted last. delete eventsModel; delete database; } void MainWindow::changeEvent(QEvent *e) { QMainWindow::changeEvent(e); switch (e->type()) { case QEvent::LanguageChange: ui->retranslateUi(this); break; default: break; } } <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Float.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h" #include "../../../Foundation/Streams/BinaryInputStream.h" #include "../CommonMeasurementTypes.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::BinaryFileInputStream; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 namespace { template <typename T> void ReadMemInfoLine_ (Optional<T>* result, const String& n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<T> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } } template <typename T> void ReadVMStatLine_ (Optional<T>* result, const String& n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<T> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } } Instruments::Memory::Info capture_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture_"); #endif constexpr bool kManuallyComputePagesPerSecond_ { true }; Instruments::Memory::Info result; #if qPlatform_POSIX { DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&result.fFreePhysicalMemory, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&result.fTotalVirtualMemory, String_Constant (L"VmallocTotal"), line); ReadMemInfoLine_ (&result.fUsedVirtualMemory, String_Constant (L"VmallocUsed"), line); ReadMemInfoLine_ (&result.fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line); } } { DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcVMStatFileName_, BinaryFileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); ReadVMStatLine_ (&result.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } if (pgfault.IsPresent () and result.fMajorPageFaultsSinceBoot.IsPresent ()) { result.fMinorPageFaultsSinceBoot = *pgfault - *result.fMajorPageFaultsSinceBoot; } } #elif qPlatform_Windows #endif if (kManuallyComputePagesPerSecond_) { static mutex s_Mutex_; static uint64_t s_Saved_MajorPageFaultsSinceBoot {}; static Time::DurationSecondsType s_Saved_MajorPageFaultsSinceBoot_At {}; if (result.fMajorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); auto critSec { Execution::make_unique_lock (s_Mutex_) }; if (s_Saved_MajorPageFaultsSinceBoot_At != 0) { result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - s_Saved_MajorPageFaultsSinceBoot) / (now - s_Saved_MajorPageFaultsSinceBoot_At); } s_Saved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot; s_Saved_MajorPageFaultsSinceBoot_At = now; } } return result; } } const MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L"System-Memory")); /* ******************************************************************************** ******************** Instruments::Memory::GetObjectVariantMapper *************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L"Total-Virtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L"UsedV-irtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second") }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument () { static Instrument kInstrument_ = Instrument ( InstrumentNameType (String_Constant (L"Memory")), [] () -> MeasurementSet { MeasurementSet results; DateTime before = DateTime::Now (); Instruments::Memory::Info rawMeasurement = capture_ (); results.fMeasuredAt = DateTimeRange (before, DateTime::Now ()); Measurement m; m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement); m.fType = kSystemMemoryMeasurement; results.fMeasurements.Add (m); return results; }, {kMemoryUsage}, GetObjectVariantMapper () ); return kInstrument_; } <commit_msg>Refactor systemperofrmacne instrumewnt to use capture pattern, and got windows memory capture stats working (at least well enuf for frictionscanner)<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2015. All rights reserved */ #include "../../StroikaPreComp.h" #include "../../../Foundation/Characters/String_Constant.h" #include "../../../Foundation/Characters/String2Float.h" #include "../../../Foundation/Characters/String2Int.h" #include "../../../Foundation/Containers/Mapping.h" #include "../../../Foundation/Containers/Sequence.h" #include "../../../Foundation/Containers/Set.h" #include "../../../Foundation/Debug/Assertions.h" #include "../../../Foundation/Debug/Trace.h" #include "../../../Foundation/DataExchange/CharacterDelimitedLines/Reader.h" #include "../../../Foundation/Execution/Sleep.h" #include "../../../Foundation/IO/FileSystem/BinaryFileInputStream.h" #include "../../../Foundation/Streams/BinaryInputStream.h" #include "../CommonMeasurementTypes.h" #include "Memory.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Containers; using namespace Stroika::Foundation::DataExchange; using namespace Stroika::Foundation::Memory; using namespace Stroika::Frameworks; using namespace Stroika::Frameworks::SystemPerformance; using Characters::Character; using Characters::String_Constant; using Containers::Mapping; using Containers::Sequence; using Containers::Set; using IO::FileSystem::BinaryFileInputStream; // Comment this in to turn on aggressive noisy DbgTrace in this module //#define USE_NOISY_TRACE_IN_THIS_MODULE_ 1 #ifndef qUseWMICollectionSupport_ #define qUseWMICollectionSupport_ qPlatform_Windows #endif #if qUseWMICollectionSupport_ #include "../Support/WMICollector.h" using SystemPerformance::Support::WMICollector; #endif namespace { #if qUseWMICollectionSupport_ const String_Constant kCommittedBytes_ { L"Committed Bytes" }; const String_Constant kCommitLimit_ { L"Commit Limit" }; const String_Constant kPagesPerSec_ { L"Pages/sec" }; // hard page faults/sec #endif } namespace { template <typename T> void ReadMemInfoLine_ (Optional<T>* result, const String& n, const Sequence<String>& line) { if (line.size () >= 3 and line[0] == n) { String unit = line[2]; double factor = (unit == L"kB") ? 1024 : 1; *result = static_cast<T> (round (Characters::String2Float<double> (line[1]) * factor)); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } } template <typename T> void ReadVMStatLine_ (Optional<T>* result, const String& n, const Sequence<String>& line) { if (line.size () >= 2 and line[0] == n) { *result = Characters::String2Int<T> (line[1]); #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"Set %s = %ld", n.c_str (), static_cast<long> (**result)); #endif } } } namespace { struct CapturerWithContext_ { #if qUseWMICollectionSupport_ WMICollector fMemoryWMICollector_ { L"Memory", {L"_Total"}, {kCommittedBytes_, kCommitLimit_, kPagesPerSec_ } }; #endif CapturerWithContext_ () { #if qUseWMICollectionSupport_ fMemoryWMICollector_.Collect (); { const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 }; Execution::Sleep (kUseIntervalIfNoBaseline_); } #endif } CapturerWithContext_ (const CapturerWithContext_& from) #if qUseWMICollectionSupport_ : fMemoryWMICollector_ (from.fMemoryWMICollector_) #endif { #if qUseWMICollectionSupport_ fMemoryWMICollector_.Collect (); { const Time::DurationSecondsType kUseIntervalIfNoBaseline_ { 1.0 }; Execution::Sleep (kUseIntervalIfNoBaseline_); } #endif } Instruments::Memory::Info capture_ () { #if USE_NOISY_TRACE_IN_THIS_MODULE_ Debug::TraceContextBumper ctx ("Instruments::Memory::Info capture_"); #endif constexpr bool kManuallyComputePagesPerSecond_ { true }; Instruments::Memory::Info result; #if qPlatform_POSIX { DataExchange::CharacterDelimitedLines::Reader reader {{ ':', ' ', '\t' }}; const String_Constant kProcMemInfoFileName_ { L"/proc/meminfo" }; //const String_Constant kProcMemInfoFileName_ { L"c:\\Sandbox\\VMSharedFolder\\meminfo" }; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcMemInfoFileName_, BinaryFileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadMemInfoLine_ (&result.fFreePhysicalMemory, String_Constant (L"MemFree"), line); ReadMemInfoLine_ (&result.fTotalVirtualMemory, String_Constant (L"VmallocTotal"), line); ReadMemInfoLine_ (&result.fUsedVirtualMemory, String_Constant (L"VmallocUsed"), line); ReadMemInfoLine_ (&result.fLargestAvailableVirtualChunk, String_Constant (L"VmallocChunk"), line); } } { DataExchange::CharacterDelimitedLines::Reader reader {{ ' ', '\t' }}; const String_Constant kProcVMStatFileName_ { L"/proc/vmstat" }; Optional<uint64_t> pgfault; // Note - /procfs files always unseekable for (Sequence<String> line : reader.ReadMatrix (BinaryFileInputStream::mk (kProcVMStatFileName_, BinaryFileInputStream::eNotSeekable))) { #if USE_NOISY_TRACE_IN_THIS_MODULE_ DbgTrace (L"***in Instruments::Memory::Info capture_ linesize=%d, line[0]=%s", line.size(), line.empty () ? L"" : line[0].c_str ()); #endif ReadVMStatLine_ (&pgfault, String_Constant (L"pgfault"), line); ReadVMStatLine_ (&result.fMajorPageFaultsSinceBoot, String_Constant (L"pgmajfault"), line); } if (pgfault.IsPresent () and result.fMajorPageFaultsSinceBoot.IsPresent ()) { result.fMinorPageFaultsSinceBoot = *pgfault - *result.fMajorPageFaultsSinceBoot; } } #elif qPlatform_Windows #if qUseWMICollectionSupport_ fMemoryWMICollector_.Collect (); { if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kCommittedBytes_)) { result.fUsedVirtualMemory = *o ; } if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kCommitLimit_)) { // bad names - RETHINK result.fTotalVirtualMemory = *o ; } if (auto o = fMemoryWMICollector_.PeekCurrentValue (L"_Total", kPagesPerSec_)) { result.fMajorPageFaultsPerSecond = *o ; } } #endif { MEMORYSTATUSEX statex; statex.dwLength = sizeof (statex); Verify (::GlobalMemoryStatusEx (&statex) != 0); result.fFreePhysicalMemory = statex.ullAvailPhys; } #endif if (kManuallyComputePagesPerSecond_) { static mutex s_Mutex_; static uint64_t s_Saved_MajorPageFaultsSinceBoot {}; static Time::DurationSecondsType s_Saved_MajorPageFaultsSinceBoot_At {}; if (result.fMajorPageFaultsSinceBoot.IsPresent ()) { Time::DurationSecondsType now = Time::GetTickCount (); auto critSec { Execution::make_unique_lock (s_Mutex_) }; if (s_Saved_MajorPageFaultsSinceBoot_At != 0) { result.fMajorPageFaultsPerSecond = (*result.fMajorPageFaultsSinceBoot - s_Saved_MajorPageFaultsSinceBoot) / (now - s_Saved_MajorPageFaultsSinceBoot_At); } s_Saved_MajorPageFaultsSinceBoot = *result.fMajorPageFaultsSinceBoot; s_Saved_MajorPageFaultsSinceBoot_At = now; } } return result; } }; } const MeasurementType Instruments::Memory::kSystemMemoryMeasurement = MeasurementType (String_Constant (L"System-Memory")); /* ******************************************************************************** ******************** Instruments::Memory::GetObjectVariantMapper *************** ******************************************************************************** */ ObjectVariantMapper Instruments::Memory::GetObjectVariantMapper () { using StructureFieldInfo = ObjectVariantMapper::StructureFieldInfo; ObjectVariantMapper sMapper_ = [] () -> ObjectVariantMapper { ObjectVariantMapper mapper; mapper.AddCommonType<Optional<uint64_t>> (); mapper.AddCommonType<Optional<double>> (); DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Winvalid-offsetof\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 mapper.AddClass<Info> (initializer_list<StructureFieldInfo> { { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fFreePhysicalMemory), String_Constant (L"Free-Physical-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fTotalVirtualMemory), String_Constant (L"Total-Virtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fUsedVirtualMemory), String_Constant (L"UsedV-irtual-Memory") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fLargestAvailableVirtualChunk), String_Constant (L"Largest-Available-Virtual-Chunk") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsSinceBoot), String_Constant (L"Major-Page-Faults-Since-Boot") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsSinceBoot), String_Constant (L"Minor-Page-Faults-Since-Boot") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMajorPageFaultsPerSecond), String_Constant (L"Major-Page-Faults-Per-Second") }, { Stroika_Foundation_DataExchange_ObjectVariantMapper_FieldInfoKey (Info, fMinorPageFaultsPerSecond), String_Constant (L"Minor-Page-Faults-Per-Second") }, }); DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Winvalid-offsetof\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-offsetof\""); return mapper; } (); return sMapper_; } /* ******************************************************************************** ******************* Instruments::Memory::GetInstrument ************************* ******************************************************************************** */ Instrument SystemPerformance::Instruments::Memory::GetInstrument () { CapturerWithContext_ useCaptureContext; // capture context so copyable in mutable lambda static Instrument kInstrument_ = Instrument ( InstrumentNameType (String_Constant (L"Memory")), [useCaptureContext] () mutable -> MeasurementSet { MeasurementSet results; DateTime before = DateTime::Now (); Instruments::Memory::Info rawMeasurement = useCaptureContext.capture_ (); results.fMeasuredAt = DateTimeRange (before, DateTime::Now ()); Measurement m; m.fValue = GetObjectVariantMapper ().FromObject (rawMeasurement); m.fType = kSystemMemoryMeasurement; results.fMeasurements.Add (m); return results; }, {kMemoryUsage}, GetObjectVariantMapper () ); return kInstrument_; } <|endoftext|>
<commit_before>//Author: Stefan Toman #include <stdio.h> #include <string.h> #include <algorithm> #include <map> #include <math.h> using namespace std; int main() { int t; scanf("%d", &t); for (int i = 0; i < t; ++i) { long n, p; scanf("%ld %ld", &n, &p); long b[n]; for (long j = 0; j < n; j++) { scanf("%ld", &b[j]); } long long r = 0; long right = -1, sum = 0; for (long left = 0; left < n && right < n; left++) { while(right+1 < n && sum + b[right+1] <= p) { sum += b[right+1]; right++; } r += right - left + 1; sum -= b[left]; } printf("Case #%d: %I64d\n", i+1, r); } return 0; } <commit_msg>fix problem thepriceiscorrect<commit_after>//Author: Stefan Toman #include <iostream> #include <string.h> #include <algorithm> #include <map> #include <math.h> using namespace std; int main() { int t; cin >> t; for (int i = 0; i < t; ++i) { long n, p; cin >> n >> p; long b[n]; for (long j = 0; j < n; j++) { cin >> b[j]; } long long r = 0; long right = -1, sum = 0; for (long left = 0; left < n && right < n; left++) { while(right+1 < n && sum + b[right+1] <= p) { sum += b[right+1]; right++; } r += right - left + 1; sum -= b[left]; } cout << "Case #" << i+1 << ": " << r << endl; } return 0; } <|endoftext|>
<commit_before>/* * Montgomery Exponentiation * (C) 1999-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/def_powm.h> #include <botan/numthry.h> #include <botan/internal/mp_core.h> namespace Botan { /* * Set the exponent */ void Montgomery_Exponentiator::set_exponent(const BigInt& exp) { this->exp = exp; exp_bits = exp.bits(); } /* * Set the base */ void Montgomery_Exponentiator::set_base(const BigInt& base) { window_bits = Power_Mod::window_bits(exp.bits(), base.bits(), hints); g.resize((1 << window_bits) - 1); SecureVector<word> z(2 * (mod_words + 1)); SecureVector<word> workspace(z.size()); g[0] = (base >= modulus) ? (base % modulus) : base; bigint_monty_mul(&z[0], z.size(), g[0].data(), g[0].size(), g[0].sig_words(), R2.data(), R2.size(), R2.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); g[0].assign(&z[0], mod_words + 1); const BigInt& x = g[0]; const size_t x_sig = x.sig_words(); for(size_t i = 1; i != g.size(); ++i) { const BigInt& y = g[i-1]; const size_t y_sig = y.sig_words(); zeroise(z); bigint_monty_mul(&z[0], z.size(), x.data(), x.size(), x_sig, y.data(), y.size(), y_sig, modulus.data(), mod_words, mod_prime, &workspace[0]); g[i].assign(&z[0], mod_words + 1); } } /* * Compute the result */ BigInt Montgomery_Exponentiator::execute() const { const size_t exp_nibbles = (exp_bits + window_bits - 1) / window_bits; BigInt x = R_mod; SecureVector<word> z(2 * (mod_words + 1)); SecureVector<word> workspace(2 * (mod_words + 1)); for(size_t i = exp_nibbles; i > 0; --i) { for(size_t k = 0; k != window_bits; ++k) { zeroise(z); bigint_monty_sqr(&z[0], z.size(), x.data(), x.size(), x.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.assign(&z[0], mod_words + 1); } if(u32bit nibble = exp.get_substring(window_bits*(i-1), window_bits)) { const BigInt& y = g[nibble-1]; zeroise(z); bigint_monty_mul(&z[0], z.size(), x.data(), x.size(), x.sig_words(), y.data(), y.size(), y.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.assign(&z[0], mod_words + 1); } } x.get_reg().resize(2*mod_words+1); bigint_monty_redc(&x[0], x.size(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.get_reg().resize(mod_words+1); return x; } /* * Montgomery_Exponentiator Constructor */ Montgomery_Exponentiator::Montgomery_Exponentiator(const BigInt& mod, Power_Mod::Usage_Hints hints) { // Montgomery reduction only works for positive odd moduli if(!mod.is_positive() || mod.is_even()) throw Invalid_Argument("Montgomery_Exponentiator: invalid modulus"); window_bits = 0; this->hints = hints; modulus = mod; mod_words = modulus.sig_words(); BigInt mod_prime_bn(BigInt::Power2, MP_WORD_BITS); mod_prime = (mod_prime_bn - inverse_mod(modulus, mod_prime_bn)).word_at(0); R_mod = BigInt(BigInt::Power2, MP_WORD_BITS * mod_words); R_mod %= modulus; R2 = BigInt(BigInt::Power2, 2 * MP_WORD_BITS * mod_words); R2 %= modulus; } } <commit_msg>Simplify Montgomery setup here a bit<commit_after>/* * Montgomery Exponentiation * (C) 1999-2010 Jack Lloyd * * Distributed under the terms of the Botan license */ #include <botan/internal/def_powm.h> #include <botan/numthry.h> #include <botan/internal/mp_core.h> namespace Botan { /* * Set the exponent */ void Montgomery_Exponentiator::set_exponent(const BigInt& exp) { this->exp = exp; exp_bits = exp.bits(); } /* * Set the base */ void Montgomery_Exponentiator::set_base(const BigInt& base) { window_bits = Power_Mod::window_bits(exp.bits(), base.bits(), hints); g.resize((1 << window_bits) - 1); SecureVector<word> z(2 * (mod_words + 1)); SecureVector<word> workspace(z.size()); g[0] = (base >= modulus) ? (base % modulus) : base; bigint_monty_mul(&z[0], z.size(), g[0].data(), g[0].size(), g[0].sig_words(), R2.data(), R2.size(), R2.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); g[0].assign(&z[0], mod_words + 1); const BigInt& x = g[0]; const size_t x_sig = x.sig_words(); for(size_t i = 1; i != g.size(); ++i) { const BigInt& y = g[i-1]; const size_t y_sig = y.sig_words(); zeroise(z); bigint_monty_mul(&z[0], z.size(), x.data(), x.size(), x_sig, y.data(), y.size(), y_sig, modulus.data(), mod_words, mod_prime, &workspace[0]); g[i].assign(&z[0], mod_words + 1); } } /* * Compute the result */ BigInt Montgomery_Exponentiator::execute() const { const size_t exp_nibbles = (exp_bits + window_bits - 1) / window_bits; BigInt x = R_mod; SecureVector<word> z(2 * (mod_words + 1)); SecureVector<word> workspace(2 * (mod_words + 1)); for(size_t i = exp_nibbles; i > 0; --i) { for(size_t k = 0; k != window_bits; ++k) { zeroise(z); bigint_monty_sqr(&z[0], z.size(), x.data(), x.size(), x.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.assign(&z[0], mod_words + 1); } if(u32bit nibble = exp.get_substring(window_bits*(i-1), window_bits)) { const BigInt& y = g[nibble-1]; zeroise(z); bigint_monty_mul(&z[0], z.size(), x.data(), x.size(), x.sig_words(), y.data(), y.size(), y.sig_words(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.assign(&z[0], mod_words + 1); } } x.get_reg().resize(2*mod_words+1); bigint_monty_redc(&x[0], x.size(), modulus.data(), mod_words, mod_prime, &workspace[0]); x.get_reg().resize(mod_words+1); return x; } /* * Montgomery_Exponentiator Constructor */ Montgomery_Exponentiator::Montgomery_Exponentiator(const BigInt& mod, Power_Mod::Usage_Hints hints) { // Montgomery reduction only works for positive odd moduli if(!mod.is_positive() || mod.is_even()) throw Invalid_Argument("Montgomery_Exponentiator: invalid modulus"); window_bits = 0; this->hints = hints; modulus = mod; mod_words = modulus.sig_words(); BigInt r(BigInt::Power2, mod_words * BOTAN_MP_WORD_BITS); mod_prime = (((r * inverse_mod(r, mod)) - 1) / mod).word_at(0); R_mod = r % modulus; R2 = (R_mod * R_mod) % modulus; } } <|endoftext|>
<commit_before>/* Copyright (c) 2010-2015, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 121123 D. Dirkx File created. * 130124 K. Kumar Added missing file header; updated layout; migrated force * free function to separate file; added acceleration free * function. * * References * * Notes * */ #include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h" #include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureAcceleration.h" #include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureForce.h" #include <cmath> #include <vector> #include <Eigen/Core> namespace tudat { namespace electro_magnetism { //! Compute radiation pressure acceleration using an ideal sail model. Eigen::Vector3d computeIdealRadiationPressureAcceleration(const double radiationPressure, const Eigen::Vector3d& normalFromSource, const Eigen::Vector3d& normalToSail, const double area, const double radiationPressureCoefficient, const double mass ) { return computeIdealRadiationPressureForce( radiationPressure, normalToSail, normalFromSource, area, radiationPressureCoefficient - 1.0 ) / mass;; } } // namespace electro_magnetism } // namespace tudat <commit_msg>minor corrections<commit_after>/* Copyright (c) 2010-2015, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 121123 D. Dirkx File created. * 130124 K. Kumar Added missing file header; updated layout; migrated force * free function to separate file; added acceleration free * function. * * References * * Notes * */ #include "Tudat/Mathematics/BasicMathematics/mathematicalConstants.h" #include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureAcceleration.h" #include "Tudat/Astrodynamics/ElectroMagnetism/idealRadiationPressureForce.h" #include <cmath> #include <vector> #include <Eigen/Core> namespace tudat { namespace electro_magnetism { //! Compute radiation pressure acceleration using an ideal sail model. Eigen::Vector3d computeIdealRadiationPressureAcceleration( const double radiationPressure, const Eigen::Vector3d& vectorFromSource, const Eigen::Vector3d& normalToSail, const double area, const double radiationPressureCoefficient, const double mass ) { return computeIdealRadiationPressureForce( radiationPressure, normalToSail, vectorFromSource, area, radiationPressureCoefficient - 1.0 ) / mass;; } } // namespace electro_magnetism } // namespace tudat <|endoftext|>
<commit_before>/** * @file backtrace.cpp * @author Grzegorz Krajewski * * Implementation of the Backtrace class. * * This file is part of mlpack 2.0.1. * * mlpack is free software; you may redstribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <sstream> #ifdef HAS_BFD_DL #include <execinfo.h> #include <signal.h> #include <unistd.h> #include <cxxabi.h> #ifndef PACKAGE #define PACKAGE #ifndef PACKAGE_VERSION #define PACKAGE_VERSION #include <bfd.h> #undef PACKAGE_VERSION #else #include <bfd.h> #endif #undef PACKAGE #else #ifndef PACKAGE_VERSION #define PACKAGE_VERSION #include <bfd.h> #undef PACKAGE_VERSION #else #include <bfd.h> #endif #endif #include <dlfcn.h> #endif #include "prefixedoutstream.hpp" #include "backtrace.hpp" #include "log.hpp" // Easier to read Backtrace::DecodeAddress(). #ifdef HAS_BFD_DL #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler)) #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file) #endif using namespace mlpack; // Initialize Backtrace static inctances. Backtrace::Frames Backtrace::frame; std::vector<Backtrace::Frames> Backtrace::stack; #ifdef HAS_BFD_DL // Binary File Descriptor objects. bfd* abfd = 0; // Descriptor datastructure. asymbol **syms = 0; // Symbols datastructure. asection *text = 0; // Strings datastructure. #endif #ifdef HAS_BFD_DL Backtrace::Backtrace(int maxDepth) { frame.address = NULL; frame.function = "0"; frame.file = "0"; frame.line = 0; stack.clear(); GetAddress(maxDepth); } #else Backtrace::Backtrace() { // Dummy constructor } #endif #ifdef HAS_BFD_DL void Backtrace::GetAddress(int maxDepth) { void* trace[maxDepth]; int stackDepth = backtrace(trace, maxDepth); // Skip first stack frame (points to Backtrace::Backtrace). for (int i = 1; i < stackDepth; i++) { Dl_info addressHandler; //No backtrace will be printed if no compile flags: -g -rdynamic if(TRACE_CONDITION_1) { return ; } frame.address = addressHandler.dli_saddr; DecodeAddress((long)frame.address); } } void Backtrace::DecodeAddress(long addr) { // Check to see if there is anything to descript. If it doesn't, we'll // dump running program. if (!abfd) { char ename[1024]; int l = readlink("/proc/self/exe",ename,sizeof(ename)); if (l == -1) { perror("Failed to open executable!\n"); return; } ename[l] = 0; bfd_init(); abfd = bfd_openr(ename, 0); if (!abfd) { perror("bfd_openr failed: "); return; } bfd_check_format(abfd,bfd_object); unsigned storage_needed = bfd_get_symtab_upper_bound(abfd); syms = (asymbol **) malloc(storage_needed); text = bfd_get_section_by_name(abfd, ".text"); } long offset = addr - text->vma; if (offset > 0) { if(FIND_LINE) { DemangleFunction(); // Save retrieved informations. stack.push_back(frame); } } } void Backtrace::DemangleFunction() { int status; char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status); // If demangling is successful, reallocate 'frame.function' pointer to // demangled name. Else if 'status != 0', leave 'frame.function as it is. if (status == 0) { frame.function = tmp; } } #else void Backtrace::GetAddress(int /* maxDepth */) { } void Backtrace::DecodeAddress(long /* address */) { } void Backtrace::DemangleFunction() { } #endif std::string Backtrace::ToString() { std::string stackStr; #ifdef HAS_BFD_DL std::ostringstream lineOss; std::ostringstream it; if(stack.size() <= 0) { stackStr = "Cannot give backtrace because program was compiled"; stackStr += " without: -g -rdynamic\nFor a backtrace,"; stackStr += " recompile with: -g -rdynamic.\n"; return stackStr; } for(unsigned int i = 0; i < stack.size(); i++) { frame = stack[i]; lineOss << frame.line; it << i + 1; stackStr += "[bt]: (" + it.str() + ") " + frame.file + ":" + lineOss.str() + " " + frame.function + ":\n"; lineOss.str(""); it.str(""); } #else stackStr = "[bt]: No backtrace for this OS. Work in progress."; #endif return stackStr; } <commit_msg>Add comment describing the need for setting PACKAGE and PACKAGE_VERSION.<commit_after>/** * @file backtrace.cpp * @author Grzegorz Krajewski * * Implementation of the Backtrace class. * * This file is part of mlpack 2.0.1. * * mlpack is free software; you may redstribute it and/or modify it under the * terms of the 3-clause BSD license. You should have received a copy of the * 3-clause BSD license along with mlpack. If not, see * http://www.opensource.org/licenses/BSD-3-Clause for more information. */ #include <sstream> #ifdef HAS_BFD_DL #include <execinfo.h> #include <signal.h> #include <unistd.h> #include <cxxabi.h> // Some versions of libbfd require PACKAGE and PACKAGE_VERSION to be set in // order for the include to not fail. For more information: // https://github.com/mlpack/mlpack/issues/574 #ifndef PACKAGE #define PACKAGE #ifndef PACKAGE_VERSION #define PACKAGE_VERSION #include <bfd.h> #undef PACKAGE_VERSION #else #include <bfd.h> #endif #undef PACKAGE #else #ifndef PACKAGE_VERSION #define PACKAGE_VERSION #include <bfd.h> #undef PACKAGE_VERSION #else #include <bfd.h> #endif #endif #include <dlfcn.h> #endif #include "prefixedoutstream.hpp" #include "backtrace.hpp" #include "log.hpp" // Easier to read Backtrace::DecodeAddress(). #ifdef HAS_BFD_DL #define TRACE_CONDITION_1 (!dladdr(trace[i], &addressHandler)) #define FIND_LINE (bfd_find_nearest_line(abfd, text, syms, offset, &frame.file, &frame.function, &frame.line) && frame.file) #endif using namespace mlpack; // Initialize Backtrace static inctances. Backtrace::Frames Backtrace::frame; std::vector<Backtrace::Frames> Backtrace::stack; #ifdef HAS_BFD_DL // Binary File Descriptor objects. bfd* abfd = 0; // Descriptor datastructure. asymbol **syms = 0; // Symbols datastructure. asection *text = 0; // Strings datastructure. #endif #ifdef HAS_BFD_DL Backtrace::Backtrace(int maxDepth) { frame.address = NULL; frame.function = "0"; frame.file = "0"; frame.line = 0; stack.clear(); GetAddress(maxDepth); } #else Backtrace::Backtrace() { // Dummy constructor } #endif #ifdef HAS_BFD_DL void Backtrace::GetAddress(int maxDepth) { void* trace[maxDepth]; int stackDepth = backtrace(trace, maxDepth); // Skip first stack frame (points to Backtrace::Backtrace). for (int i = 1; i < stackDepth; i++) { Dl_info addressHandler; //No backtrace will be printed if no compile flags: -g -rdynamic if(TRACE_CONDITION_1) { return ; } frame.address = addressHandler.dli_saddr; DecodeAddress((long)frame.address); } } void Backtrace::DecodeAddress(long addr) { // Check to see if there is anything to descript. If it doesn't, we'll // dump running program. if (!abfd) { char ename[1024]; int l = readlink("/proc/self/exe",ename,sizeof(ename)); if (l == -1) { perror("Failed to open executable!\n"); return; } ename[l] = 0; bfd_init(); abfd = bfd_openr(ename, 0); if (!abfd) { perror("bfd_openr failed: "); return; } bfd_check_format(abfd,bfd_object); unsigned storage_needed = bfd_get_symtab_upper_bound(abfd); syms = (asymbol **) malloc(storage_needed); text = bfd_get_section_by_name(abfd, ".text"); } long offset = addr - text->vma; if (offset > 0) { if(FIND_LINE) { DemangleFunction(); // Save retrieved informations. stack.push_back(frame); } } } void Backtrace::DemangleFunction() { int status; char* tmp = abi::__cxa_demangle(frame.function, 0, 0, &status); // If demangling is successful, reallocate 'frame.function' pointer to // demangled name. Else if 'status != 0', leave 'frame.function as it is. if (status == 0) { frame.function = tmp; } } #else void Backtrace::GetAddress(int /* maxDepth */) { } void Backtrace::DecodeAddress(long /* address */) { } void Backtrace::DemangleFunction() { } #endif std::string Backtrace::ToString() { std::string stackStr; #ifdef HAS_BFD_DL std::ostringstream lineOss; std::ostringstream it; if(stack.size() <= 0) { stackStr = "Cannot give backtrace because program was compiled"; stackStr += " without: -g -rdynamic\nFor a backtrace,"; stackStr += " recompile with: -g -rdynamic.\n"; return stackStr; } for(unsigned int i = 0; i < stack.size(); i++) { frame = stack[i]; lineOss << frame.line; it << i + 1; stackStr += "[bt]: (" + it.str() + ") " + frame.file + ":" + lineOss.str() + " " + frame.function + ":\n"; lineOss.str(""); it.str(""); } #else stackStr = "[bt]: No backtrace for this OS. Work in progress."; #endif return stackStr; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: LayerTabBar.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-01-20 11:35:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_LAYER_TAB_BAR_HXX #define SD_LAYER_TAB_BAR_HXX #ifndef _TABBAR_HXX #include <svtools/tabbar.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif namespace sd { /************************************************************************* |* |* TabBar fuer die Layerverwaltung |* \************************************************************************/ class DrawViewShell; class LayerTabBar : public TabBar, public DropTargetHelper { public: LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent); virtual ~LayerTabBar (void); /** Inform all listeners of this control that the current layer has been activated. Call this method after switching the current layer and is not done elsewhere (like when using ctrl + page up/down keys). */ void SendActivatePageEvent (void); /** Inform all listeners of this control that the current layer has been deactivated. Call this method before switching the current layer and is not done elsewhere (like when using ctrl page up/down keys). */ void SendDeactivatePageEvent (void); protected: DrawViewShell* pDrViewSh; // TabBar virtual void Select(); virtual void DoubleClick(); virtual void MouseButtonDown(const MouseEvent& rMEvt); virtual void Command(const CommandEvent& rCEvt); virtual long StartRenaming(); virtual long AllowRenaming(); virtual void EndRenaming(); virtual void ActivatePage(); // DropTargetHelper virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); }; } // end of namespace sd #endif <commit_msg>INTEGRATION: CWS impress2 (1.2.26); FILE MERGED 2004/04/22 15:08:25 af 1.2.26.1: #i22705# Added a constructor that takes a resource id as additional parameter.<commit_after>/************************************************************************* * * $RCSfile: LayerTabBar.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: rt $ $Date: 2004-07-13 13:56:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_LAYER_TAB_BAR_HXX #define SD_LAYER_TAB_BAR_HXX #ifndef _TABBAR_HXX #include <svtools/tabbar.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif namespace sd { /************************************************************************* |* |* TabBar fuer die Layerverwaltung |* \************************************************************************/ class DrawViewShell; class LayerTabBar : public TabBar, public DropTargetHelper { public: LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent); LayerTabBar ( DrawViewShell* pDrViewSh, ::Window* pParent, const ResId& rResId); virtual ~LayerTabBar (void); /** Inform all listeners of this control that the current layer has been activated. Call this method after switching the current layer and is not done elsewhere (like when using ctrl + page up/down keys). */ void SendActivatePageEvent (void); /** Inform all listeners of this control that the current layer has been deactivated. Call this method before switching the current layer and is not done elsewhere (like when using ctrl page up/down keys). */ void SendDeactivatePageEvent (void); protected: DrawViewShell* pDrViewSh; // TabBar virtual void Select(); virtual void DoubleClick(); virtual void MouseButtonDown(const MouseEvent& rMEvt); virtual void Command(const CommandEvent& rCEvt); virtual long StartRenaming(); virtual long AllowRenaming(); virtual void EndRenaming(); virtual void ActivatePage(); // DropTargetHelper virtual sal_Int8 AcceptDrop( const AcceptDropEvent& rEvt ); virtual sal_Int8 ExecuteDrop( const ExecuteDropEvent& rEvt ); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unovwcrs.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: kz $ $Date: 2001-09-13 12:58:12 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_ #include <com/sun/star/text/XTextViewCursor.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_ #include <com/sun/star/view/XScreenCursor.hpp> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #include "sdview.hxx" #ifndef SVX_LIGHT #include "docshell.hxx" #endif #include "viewshel.hxx" #include "fuslshow.hxx" #include <cppuhelper/implbase2.hxx> using namespace ::vos; using namespace ::rtl; using namespace ::com::sun::star; class SdXTextViewCursor : public ::cppu::WeakImplHelper2< text::XTextViewCursor, view::XScreenCursor > { SdView* mpView; public: SdXTextViewCursor(SdView* pVw) throw(); virtual ~SdXTextViewCursor() throw(); //XTextViewCursor virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException ); virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException ); virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException ); //XTextCursor virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException ); virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException); //XTextRange virtual uno::Reference< text::XText > SAL_CALL getText(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getStart(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getEnd(void) throw( uno::RuntimeException ); virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException ); virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException ); //XScreenCursor virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException ); void Invalidate() { mpView = 0; } }; text::XTextViewCursor* CreateSdXTextViewCursor( SdView* mpView ) { return new SdXTextViewCursor( mpView ); } SdXTextViewCursor::SdXTextViewCursor(SdView* pSdView ) throw() : mpView(pSdView) { } SdXTextViewCursor::~SdXTextViewCursor() throw() { } sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return awt::Point(); } void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { SdViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) ); return sal_True; } } } return sal_False; } sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { SdViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) ); return sal_True; } } } return sal_False; } uno::Reference< text::XText > SdXTextViewCursor::getText(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XText > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return OUString(); } void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } <commit_msg>INTEGRATION: CWS impress1 (1.3.240); FILE MERGED 2003/09/17 09:44:57 af 1.3.240.1: #111996# Transition to stacked sub-shells. Introduction of namespace sd.<commit_after>/************************************************************************* * * $RCSfile: unovwcrs.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-01-20 12:36:52 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_TEXT_XTEXTVIEWCURSOR_HPP_ #include <com/sun/star/text/XTextViewCursor.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XSCREENCURSOR_HPP_ #include <com/sun/star/view/XScreenCursor.hpp> #endif #ifndef _SFXREQUEST_HXX #include <sfx2/request.hxx> #endif #ifndef _VOS_MUTEX_HXX_ //autogen #include <vos/mutex.hxx> #endif #ifndef SD_VIEW_HXX #include "View.hxx" #endif #ifndef SVX_LIGHT #ifndef SD_DRAW_DOC_SHELL_HXX #include "DrawDocShell.hxx" #endif #endif #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #ifndef SD_FU_SLIDE_SHOW_HXX #include "fuslshow.hxx" #endif #include <cppuhelper/implbase2.hxx> using namespace ::vos; using namespace ::rtl; using namespace ::com::sun::star; class SdXTextViewCursor : public ::cppu::WeakImplHelper2< text::XTextViewCursor, view::XScreenCursor > { public: SdXTextViewCursor(::sd::View* pVw) throw(); virtual ~SdXTextViewCursor() throw(); //XTextViewCursor virtual sal_Bool SAL_CALL isVisible(void) throw( uno::RuntimeException ); virtual void SAL_CALL setVisible(sal_Bool bVisible) throw( uno::RuntimeException ); virtual awt::Point SAL_CALL getPosition(void) throw( uno::RuntimeException ); //XTextCursor virtual void SAL_CALL collapseToStart(void) throw( uno::RuntimeException ); virtual void SAL_CALL collapseToEnd(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL isCollapsed(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goLeft(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL goRight(sal_Int16 nCount, sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoStart(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoEnd(sal_Bool Expand) throw( uno::RuntimeException ); virtual void SAL_CALL gotoRange(const uno::Reference< text::XTextRange > & rRange, sal_Bool bExpand ) throw (::com::sun::star::uno::RuntimeException); //XTextRange virtual uno::Reference< text::XText > SAL_CALL getText(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getStart(void) throw( uno::RuntimeException ); virtual uno::Reference< text::XTextRange > SAL_CALL getEnd(void) throw( uno::RuntimeException ); virtual OUString SAL_CALL getString(void) throw( uno::RuntimeException ); virtual void SAL_CALL setString(const OUString& aString) throw( uno::RuntimeException ); //XScreenCursor virtual sal_Bool SAL_CALL screenDown(void) throw( uno::RuntimeException ); virtual sal_Bool SAL_CALL screenUp(void) throw( uno::RuntimeException ); void Invalidate() { mpView = 0; } private: ::sd::View* mpView; }; text::XTextViewCursor* CreateSdXTextViewCursor(::sd::View* mpView ) { return new SdXTextViewCursor( mpView ); } SdXTextViewCursor::SdXTextViewCursor(::sd::View* pSdView ) throw() : mpView(pSdView) { } SdXTextViewCursor::~SdXTextViewCursor() throw() { } sal_Bool SdXTextViewCursor::isVisible(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } void SdXTextViewCursor::setVisible(sal_Bool bVisible) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } awt::Point SdXTextViewCursor::getPosition(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return awt::Point(); } void SdXTextViewCursor::collapseToStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::collapseToEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::isCollapsed(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_True; } sal_Bool SdXTextViewCursor::goLeft(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } sal_Bool SdXTextViewCursor::goRight(sal_Int16 nCount, sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return sal_False; } void SdXTextViewCursor::gotoRange(const uno::Reference< text::XTextRange > & xRange, sal_Bool bExpand) throw (::com::sun::star::uno::RuntimeException) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoStart(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } void SdXTextViewCursor::gotoEnd(sal_Bool bExpand) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } sal_Bool SdXTextViewCursor::screenDown(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_SPACE ) ) ); return sal_True; } } } return sal_False; } sal_Bool SdXTextViewCursor::screenUp(void) throw( uno::RuntimeException ) { OGuard aGuard(Application::GetSolarMutex()); sal_Bool bRet = sal_False; if( mpView && mpView->GetDocSh() ) { ::sd::ViewShell* pViewSh = mpView->GetDocSh()->GetViewShell(); if( pViewSh ) { ::sd::FuSlideShow* pShow = pViewSh->GetSlideShow(); if( pShow ) { pShow->KeyInput( KeyEvent( 32, KeyCode( KEY_BACKSPACE ) ) ); return sal_True; } } } return sal_False; } uno::Reference< text::XText > SdXTextViewCursor::getText(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XText > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getStart(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } uno::Reference< text::XTextRange > SdXTextViewCursor::getEnd(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return uno::Reference< text::XTextRange > (); } OUString SdXTextViewCursor::getString(void) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") return OUString(); } void SdXTextViewCursor::setString(const OUString& aString) throw( uno::RuntimeException ) { DBG_WARNING("not implemented") } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: styledlg.cxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:52:31 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #ifndef _SFX_WHITER_HXX //autogen #include <svtools/whiter.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #pragma hdrstop #include "styledlg.hxx" #include "mgetempl.hxx" #include "sfxresid.hxx" #include "sfxuno.hxx" #include "dialog.hrc" // class SfxStyleDialog -------------------------------------------------- #if SUP <= 372 SfxStyleDialog::SfxStyleDialog ( Window* pParent, // Parent const ResId& rResId, // ResId SfxStyleSheetBase& rStyle, // zu bearbeitendes StyleSheet BOOL bFreeRes // Flag Resourcen freigeben ) : /* [Beschreibung] Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen. */ SfxTabDialog( pParent, rResId, rStyle.GetItemSet().Clone(), // auch ohne ParentSupport TRUE "ubergeben, aber erweitert // um den StandardButton zu unterdr"ucken rStyle.HasParentSupport() ? TRUE : 2 ), pStyle( &rStyle ) { AddTabPage( ID_TABPAGE_MANAGESTYLES, String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ), SfxManageStyleSheetPage::Create, 0, FALSE, 0 ); // bei neuer Vorlage immer die Verwaltungsseite als aktuelle // Seite setzen if( !rStyle.GetName().Len() ) SetCurPageId( ID_TABPAGE_MANAGESTYLES ); else { String sTxt( GetText() ); sTxt += DEFINE_CONST_UNICODE(": "); sTxt += rStyle.GetName(); SetText( sTxt ); } delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt pExampleSet = &pStyle->GetItemSet(); if ( bFreeRes ) FreeResource(); GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) ); } #endif SfxStyleDialog::SfxStyleDialog ( Window* pParent, // Parent const ResId& rResId, // ResId SfxStyleSheetBase& rStyle, // zu bearbeitendes StyleSheet BOOL bFreeRes, // Flag Resourcen freigeben const String* pUserBtnTxt ) : /* [Beschreibung] Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen. */ SfxTabDialog( pParent, rResId, rStyle.GetItemSet().Clone(), // auch ohne ParentSupport TRUE "ubergeben, aber erweitert // um den StandardButton zu unterdr"ucken rStyle.HasParentSupport() ? TRUE : 2, pUserBtnTxt ), pStyle( &rStyle ) { AddTabPage( ID_TABPAGE_MANAGESTYLES, String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ), SfxManageStyleSheetPage::Create, 0, FALSE, 0 ); // bei neuer Vorlage immer die Verwaltungsseite als aktuelle // Seite setzen if( !rStyle.GetName().Len() ) SetCurPageId( ID_TABPAGE_MANAGESTYLES ); else { String sTxt( GetText() ); sTxt += DEFINE_CONST_UNICODE(": ") ; sTxt += rStyle.GetName(); SetText( sTxt ); } delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt pExampleSet = &pStyle->GetItemSet(); if ( bFreeRes ) FreeResource(); GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) ); } // ----------------------------------------------------------------------- SfxStyleDialog::~SfxStyleDialog() /* [Beschreibung] Destruktor: ExampleSet auf NULL setzen, damit der SfxTabDialog nicht den Set vom Style l"oscht. */ { pExampleSet = 0; pStyle = 0; delete GetInputSetImpl(); } // ----------------------------------------------------------------------- const SfxItemSet* SfxStyleDialog::GetRefreshedSet() /* [Beschreibung] Diese wird gerufen, wenn <SfxTabPage::DeactivatePage(SfxItemSet *)> <SfxTabPage::REFRESH_SET> liefert. */ { return GetInputSetImpl(); } // ----------------------------------------------------------------------- short SfxStyleDialog::Ok() /* [Beschreibung] "Uberladen, damit immer RET_OK zur"uckgegeben wird. */ { SfxTabDialog::Ok(); return RET_OK; } // ----------------------------------------------------------------------- IMPL_LINK( SfxStyleDialog, CancelHdl, Button *, pButton ) /* [Beschreibung] Wenn der Dialog abgebrochen wurde, m"ussen alle schon eingestellten Attribute wieder zur"uckgesetzt werden. */ { SfxTabPage* pPage = GetTabPage( ID_TABPAGE_MANAGESTYLES ); const SfxItemSet* pInSet = GetInputSetImpl(); SfxWhichIter aIter( *pInSet ); USHORT nWhich = aIter.FirstWhich(); while ( nWhich ) { SfxItemState eState = pInSet->GetItemState( nWhich, FALSE ); if ( SFX_ITEM_DEFAULT == eState ) pExampleSet->ClearItem( nWhich ); else pExampleSet->Put( pInSet->Get( nWhich ) ); nWhich = aIter.NextWhich(); } if ( pPage ) pPage->Reset( *GetInputSetImpl() ); EndDialog( RET_CANCEL ); return 0; } <commit_msg>INTEGRATION: CWS ooo20040329 (1.1.1.1.480); FILE MERGED 2004/03/18 10:39:06 waratah 1.1.1.1.480.1: :#i1858# exclude pragma hdrstop by bracketting for gcc<commit_after>/************************************************************************* * * $RCSfile: styledlg.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: svesik $ $Date: 2004-04-21 13:14:25 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #ifndef _SFX_WHITER_HXX //autogen #include <svtools/whiter.hxx> #endif #ifndef _SFXSTYLE_HXX //autogen #include <svtools/style.hxx> #endif #ifndef _MSGBOX_HXX //autogen #include <vcl/msgbox.hxx> #endif #ifndef GCC #pragma hdrstop #endif #include "styledlg.hxx" #include "mgetempl.hxx" #include "sfxresid.hxx" #include "sfxuno.hxx" #include "dialog.hrc" // class SfxStyleDialog -------------------------------------------------- #if SUP <= 372 SfxStyleDialog::SfxStyleDialog ( Window* pParent, // Parent const ResId& rResId, // ResId SfxStyleSheetBase& rStyle, // zu bearbeitendes StyleSheet BOOL bFreeRes // Flag Resourcen freigeben ) : /* [Beschreibung] Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen. */ SfxTabDialog( pParent, rResId, rStyle.GetItemSet().Clone(), // auch ohne ParentSupport TRUE "ubergeben, aber erweitert // um den StandardButton zu unterdr"ucken rStyle.HasParentSupport() ? TRUE : 2 ), pStyle( &rStyle ) { AddTabPage( ID_TABPAGE_MANAGESTYLES, String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ), SfxManageStyleSheetPage::Create, 0, FALSE, 0 ); // bei neuer Vorlage immer die Verwaltungsseite als aktuelle // Seite setzen if( !rStyle.GetName().Len() ) SetCurPageId( ID_TABPAGE_MANAGESTYLES ); else { String sTxt( GetText() ); sTxt += DEFINE_CONST_UNICODE(": "); sTxt += rStyle.GetName(); SetText( sTxt ); } delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt pExampleSet = &pStyle->GetItemSet(); if ( bFreeRes ) FreeResource(); GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) ); } #endif SfxStyleDialog::SfxStyleDialog ( Window* pParent, // Parent const ResId& rResId, // ResId SfxStyleSheetBase& rStyle, // zu bearbeitendes StyleSheet BOOL bFreeRes, // Flag Resourcen freigeben const String* pUserBtnTxt ) : /* [Beschreibung] Konstruktor: Verwalten-TabPage zuf"ugen, ExampleSet vom Style setzen. */ SfxTabDialog( pParent, rResId, rStyle.GetItemSet().Clone(), // auch ohne ParentSupport TRUE "ubergeben, aber erweitert // um den StandardButton zu unterdr"ucken rStyle.HasParentSupport() ? TRUE : 2, pUserBtnTxt ), pStyle( &rStyle ) { AddTabPage( ID_TABPAGE_MANAGESTYLES, String( SfxResId( STR_TABPAGE_MANAGESTYLES ) ), SfxManageStyleSheetPage::Create, 0, FALSE, 0 ); // bei neuer Vorlage immer die Verwaltungsseite als aktuelle // Seite setzen if( !rStyle.GetName().Len() ) SetCurPageId( ID_TABPAGE_MANAGESTYLES ); else { String sTxt( GetText() ); sTxt += DEFINE_CONST_UNICODE(": ") ; sTxt += rStyle.GetName(); SetText( sTxt ); } delete pExampleSet; // im SfxTabDialog::Ctor() schon angelegt pExampleSet = &pStyle->GetItemSet(); if ( bFreeRes ) FreeResource(); GetCancelButton().SetClickHdl( LINK(this, SfxStyleDialog, CancelHdl) ); } // ----------------------------------------------------------------------- SfxStyleDialog::~SfxStyleDialog() /* [Beschreibung] Destruktor: ExampleSet auf NULL setzen, damit der SfxTabDialog nicht den Set vom Style l"oscht. */ { pExampleSet = 0; pStyle = 0; delete GetInputSetImpl(); } // ----------------------------------------------------------------------- const SfxItemSet* SfxStyleDialog::GetRefreshedSet() /* [Beschreibung] Diese wird gerufen, wenn <SfxTabPage::DeactivatePage(SfxItemSet *)> <SfxTabPage::REFRESH_SET> liefert. */ { return GetInputSetImpl(); } // ----------------------------------------------------------------------- short SfxStyleDialog::Ok() /* [Beschreibung] "Uberladen, damit immer RET_OK zur"uckgegeben wird. */ { SfxTabDialog::Ok(); return RET_OK; } // ----------------------------------------------------------------------- IMPL_LINK( SfxStyleDialog, CancelHdl, Button *, pButton ) /* [Beschreibung] Wenn der Dialog abgebrochen wurde, m"ussen alle schon eingestellten Attribute wieder zur"uckgesetzt werden. */ { SfxTabPage* pPage = GetTabPage( ID_TABPAGE_MANAGESTYLES ); const SfxItemSet* pInSet = GetInputSetImpl(); SfxWhichIter aIter( *pInSet ); USHORT nWhich = aIter.FirstWhich(); while ( nWhich ) { SfxItemState eState = pInSet->GetItemState( nWhich, FALSE ); if ( SFX_ITEM_DEFAULT == eState ) pExampleSet->ClearItem( nWhich ); else pExampleSet->Put( pInSet->Get( nWhich ) ); nWhich = aIter.NextWhich(); } if ( pPage ) pPage->Reset( *GetInputSetImpl() ); EndDialog( RET_CANCEL ); return 0; } <|endoftext|>
<commit_before>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> #include "../src/PointSpreadFunc.cpp" #include "../src/RawImage.cpp" #include "../src/LayeredImage.cpp" #include "../src/ImageStack.cpp" #include "../src/KBMOSearch.cpp" namespace py = pybind11; using pf = kbmod::PointSpreadFunc; using ri = kbmod::RawImage; using li = kbmod::LayeredImage; using is = kbmod::ImageStack; using ks = kbmod::KBMOSearch; using tj = kbmod::trajectory; using td = kbmod::trajRegion; using std::to_string; PYBIND11_MODULE(kbmod, m) { py::class_<pf>(m, "psf", py::buffer_protocol()) .def_buffer([](pf &m) -> py::buffer_info { return py::buffer_info( m.kernelData(), sizeof(float), py::format_descriptor<float>::format(), 2, { m.getDim(), m.getDim() }, { sizeof(float) * m.getDim(), sizeof(float) } ); }) .def(py::init<float>()) .def(py::init<py::array_t<float>>()) .def("set_array", &pf::setArray) .def("get_stdev", &pf::getStdev) .def("get_sum", &pf::getSum) .def("get_dim", &pf::getDim) .def("get_radius", &pf::getRadius) .def("get_size", &pf::getSize) .def("square_psf", &pf::squarePSF) .def("print_psf", &pf::printPSF); py::class_<ri>(m, "raw_image", py::buffer_protocol()) .def_buffer([](ri &m) -> py::buffer_info { return py::buffer_info( m.getDataRef(), sizeof(float), py::format_descriptor<float>::format(), 2, { m.getHeight(), m.getWidth() }, { sizeof(float) * m.getHeight(), sizeof(float) } ); }) .def(py::init<int, int>()) .def(py::init<py::array_t<float>>()) .def("set_array", &ri::setArray) .def("pool", &ri::pool) .def("pool_min", &ri::poolMin) .def("pool_max", &ri::poolMax) .def("set_pixel", &ri::setPixel) .def("set_all", &ri::setAllPix) .def("get_pixel", &ri::getPixel) .def("get_pixel_interp", &ri::getPixelInterp) .def("get_ppi", &ri::getPPI) .def("convolve", &ri::convolve); py::class_<li>(m, "layered_image") .def(py::init<const std::string>()) .def(py::init<std::string, int, int, double, float, float>()) .def("apply_mask_flags", &li::applyMaskFlags) //.def("sci_numpy", &li::sciToNumpy) .def("save_layers", &li::saveLayers) .def("save_sci", &li::saveSci) .def("save_mask", &li::saveMask) .def("save_var", &li::saveVar) .def("get_science", &li::getScience) .def("get_mask", &li::getMask) .def("get_variance", &li::getVariance) .def("convolve", &li::convolve) .def("get_science_pooled", &li::poolScience) .def("get_variance_pooled", &li::poolVariance) .def("add_object", &li::addObject) .def("get_width", &li::getWidth) .def("get_height", &li::getHeight) .def("get_ppi", &li::getPPI) .def("get_time", &li::getTime); py::class_<is>(m, "image_stack") .def(py::init<std::vector<std::string>>()) .def(py::init<std::vector<li>>()) .def("get_images", &is::getImages) .def("get_times", &is::getTimes) .def("set_times", &is::setTimes) .def("img_count", &is::imgCount) .def("apply_mask_flags", &is::applyMaskFlags) .def("apply_master_mask", &is::applyMasterMask) .def("simple_difference", &is::simpleDifference) .def("save_master_mask", &is::saveMasterMask) .def("save_images", &is::saveImages) .def("get_master_mask", &is::getMasterMask) .def("get_sciences", &is::getSciences) .def("get_masks", &is::getMasks) .def("get_variances", &is::getVariances) .def("convolve", &is::convolve) .def("get_width", &is::getWidth) .def("get_height", &is::getHeight) .def("get_ppi", &is::getPPI); py::class_<ks>(m, "stack_search") .def(py::init<is, pf>()) .def("save_psi_phi", &ks::savePsiPhi) .def("gpu", &ks::gpu) .def("region_search", &ks::regionSearch) .def("set_debug", &ks::setDebug) .def("filter_min_obs", &ks::filterResults) // For testing .def("extreme_in_region", &ks::findExtremeInRegion) .def("biggest_fit", &ks::biggestFit) .def("read_pixel_depth", &ks::readPixelDepth) .def("subdivide", &ks::subdivide) .def("filter_bounds", &ks::filterBounds) .def("square_sdf", &ks::squareSDF) .def("filter_lh", &ks::filterLH) .def("pixel_extreme", &ks::pixelExtreme) .def("get_psi_images", &ks::getPsiImages) .def("get_phi_images", &ks::getPhiImages) .def("get_psi_pooled", &ks::getPsiPooled) .def("get_phi_pooled", &ks::getPhiPooled) .def("clear_psi_phi", &ks::clearPsiPhi) .def("get_results", &ks::getResults) .def("save_results", &ks::saveResults); py::class_<tj>(m, "trajectory") .def(py::init<>()) .def_readwrite("x_v", &tj::xVel) .def_readwrite("y_v", &tj::yVel) .def_readwrite("lh", &tj::lh) .def_readwrite("flux", &tj::flux) .def_readwrite("x", &tj::x) .def_readwrite("y", &tj::y) .def_readwrite("obs_count", &tj::obsCount) .def("__repr__", [](const tj &t) { return "lh: " + to_string(t.lh) + " flux: " + to_string(t.flux) + " x: " + to_string(t.x) + " y: " + to_string(t.y) + " x_v: " + to_string(t.xVel) + " y_v: " + to_string(t.yVel) + " obs_count: " + to_string(t.obsCount); } ); py::class_<td>(m, "traj_region") .def(py::init<>()) .def_readwrite("ix", &td::ix) .def_readwrite("iy", &td::iy) .def_readwrite("fx", &td::fx) .def_readwrite("fy", &td::fy) .def_readwrite("depth", &td::depth) .def_readwrite("obs_count", &td::obs_count) .def_readwrite("likelihood", &td::likelihood) .def_readwrite("flux", &td::flux) .def("__repr__", [](const td &t) { return "ix: " + to_string(t.ix) + " iy: " + to_string(t.iy) + " fx: " + to_string(t.fx) + " fy: " + to_string(t.fy) + " depth: " + to_string(static_cast<int>(t.depth)) + " obs_count: " + to_string(static_cast<int>(t.obs_count)) + " lh: " + to_string(t.likelihood) + " flux " + to_string(t.flux); } ); } <commit_msg>bindings for seting sci mask var + others<commit_after>#include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> #include "../src/PointSpreadFunc.cpp" #include "../src/RawImage.cpp" #include "../src/LayeredImage.cpp" #include "../src/ImageStack.cpp" #include "../src/KBMOSearch.cpp" namespace py = pybind11; using pf = kbmod::PointSpreadFunc; using ri = kbmod::RawImage; using li = kbmod::LayeredImage; using is = kbmod::ImageStack; using ks = kbmod::KBMOSearch; using tj = kbmod::trajectory; using td = kbmod::trajRegion; using std::to_string; PYBIND11_MODULE(kbmod, m) { py::class_<pf>(m, "psf", py::buffer_protocol()) .def_buffer([](pf &m) -> py::buffer_info { return py::buffer_info( m.kernelData(), sizeof(float), py::format_descriptor<float>::format(), 2, { m.getDim(), m.getDim() }, { sizeof(float) * m.getDim(), sizeof(float) } ); }) .def(py::init<float>()) .def(py::init<py::array_t<float>>()) .def("set_array", &pf::setArray) .def("get_stdev", &pf::getStdev) .def("get_sum", &pf::getSum) .def("get_dim", &pf::getDim) .def("get_radius", &pf::getRadius) .def("get_size", &pf::getSize) .def("square_psf", &pf::squarePSF) .def("print_psf", &pf::printPSF); py::class_<ri>(m, "raw_image", py::buffer_protocol()) .def_buffer([](ri &m) -> py::buffer_info { return py::buffer_info( m.getDataRef(), sizeof(float), py::format_descriptor<float>::format(), 2, { m.getHeight(), m.getWidth() }, { sizeof(float) * m.getHeight(), sizeof(float) } ); }) .def(py::init<int, int>()) .def(py::init<py::array_t<float>>()) .def("set_array", &ri::setArray) .def("pool", &ri::pool) .def("pool_min", &ri::poolMin) .def("pool_max", &ri::poolMax) .def("set_pixel", &ri::setPixel) .def("add_pixel", &ri::addToPixel) .def("mask_object", &ri::maskObject) .def("set_all", &ri::setAllPix) .def("get_pixel", &ri::getPixel) .def("get_pixel_interp", &ri::getPixelInterp) .def("get_ppi", &ri::getPPI) .def("convolve", &ri::convolve) .def("save_fits", &ri::saveToFile); py::class_<li>(m, "layered_image") .def(py::init<const std::string>()) .def(py::init<std::string, int, int, double, float, float>()) .def("apply_mask_flags", &li::applyMaskFlags) .def("sub_template", &li::subtractTemplate) .def("save_layers", &li::saveLayers) .def("save_sci", &li::saveSci) .def("save_mask", &li::saveMask) .def("save_var", &li::saveVar) .def("get_science", &li::getScience) .def("get_mask", &li::getMask) .def("get_variance", &li::getVariance) .def("set_science", &li::setScience) .def("set_mask", &li::setMask) .def("set_variance", &li::setVariance) .def("convolve", &li::convolve) .def("get_science_pooled", &li::poolScience) .def("get_variance_pooled", &li::poolVariance) .def("add_object", &li::addObject) .def("mask_object", &li::addObject) .def("get_name", &li::getName) .def("get_width", &li::getWidth) .def("get_height", &li::getHeight) .def("get_ppi", &li::getPPI) .def("get_time", &li::getTime); py::class_<is>(m, "image_stack") .def(py::init<std::vector<std::string>>()) .def(py::init<std::vector<li>>()) .def("get_images", &is::getImages) .def("get_times", &is::getTimes) .def("set_times", &is::setTimes) .def("img_count", &is::imgCount) .def("apply_mask_flags", &is::applyMaskFlags) .def("apply_master_mask", &is::applyMasterMask) .def("simple_difference", &is::simpleDifference) .def("save_master_mask", &is::saveMasterMask) .def("save_images", &is::saveImages) .def("get_master_mask", &is::getMasterMask) .def("get_sciences", &is::getSciences) .def("get_masks", &is::getMasks) .def("get_variances", &is::getVariances) .def("convolve", &is::convolve) .def("get_width", &is::getWidth) .def("get_height", &is::getHeight) .def("get_ppi", &is::getPPI); py::class_<ks>(m, "stack_search") .def(py::init<is, pf>()) .def("save_psi_phi", &ks::savePsiPhi) .def("gpu", &ks::gpu) .def("region_search", &ks::regionSearch) .def("set_debug", &ks::setDebug) .def("filter_min_obs", &ks::filterResults) // For testing .def("extreme_in_region", &ks::findExtremeInRegion) .def("biggest_fit", &ks::biggestFit) .def("read_pixel_depth", &ks::readPixelDepth) .def("subdivide", &ks::subdivide) .def("filter_bounds", &ks::filterBounds) .def("square_sdf", &ks::squareSDF) .def("filter_lh", &ks::filterLH) .def("pixel_extreme", &ks::pixelExtreme) .def("get_psi_images", &ks::getPsiImages) .def("get_phi_images", &ks::getPhiImages) .def("get_psi_pooled", &ks::getPsiPooled) .def("get_phi_pooled", &ks::getPhiPooled) .def("clear_psi_phi", &ks::clearPsiPhi) .def("get_results", &ks::getResults) .def("save_results", &ks::saveResults); py::class_<tj>(m, "trajectory") .def(py::init<>()) .def_readwrite("x_v", &tj::xVel) .def_readwrite("y_v", &tj::yVel) .def_readwrite("lh", &tj::lh) .def_readwrite("flux", &tj::flux) .def_readwrite("x", &tj::x) .def_readwrite("y", &tj::y) .def_readwrite("obs_count", &tj::obsCount) .def("__repr__", [](const tj &t) { return "lh: " + to_string(t.lh) + " flux: " + to_string(t.flux) + " x: " + to_string(t.x) + " y: " + to_string(t.y) + " x_v: " + to_string(t.xVel) + " y_v: " + to_string(t.yVel) + " obs_count: " + to_string(t.obsCount); } ); py::class_<td>(m, "traj_region") .def(py::init<>()) .def_readwrite("ix", &td::ix) .def_readwrite("iy", &td::iy) .def_readwrite("fx", &td::fx) .def_readwrite("fy", &td::fy) .def_readwrite("depth", &td::depth) .def_readwrite("obs_count", &td::obs_count) .def_readwrite("likelihood", &td::likelihood) .def_readwrite("flux", &td::flux) .def("__repr__", [](const td &t) { return "ix: " + to_string(t.ix) + " iy: " + to_string(t.iy) + " fx: " + to_string(t.fx) + " fy: " + to_string(t.fy) + " depth: " + to_string(static_cast<int>(t.depth)) + " obs_count: " + to_string(static_cast<int>(t.obs_count)) + " lh: " + to_string(t.likelihood) + " flux " + to_string(t.flux); } ); } <|endoftext|>
<commit_before>#include <geometry_msgs/Quaternion.h> #include <ros/ros.h> #include <serial/serial.h> #include <sensor_msgs/Imu.h> #include <std_msgs/String.h> #include <std_srvs/Empty.h> #include <string> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> bool zero_orientation_set = false; bool set_zero_orientation(std_srvs::Empty::Request&, std_srvs::Empty::Response&) { ROS_INFO("Zero Orientation Set."); zero_orientation_set = false; return true; } int main(int argc, char** argv) { serial::Serial ser; std::string port; std::string tf_parent_frame_id; std::string tf_frame_id; std::string imu_frame_id; double time_offset_in_seconds; tf::Quaternion orientation; tf::Quaternion zero_orientation; std::string partial_line = ""; ros::init(argc, argv, "mpu6050_serial_to_imu_node"); ros::NodeHandle private_node_handle("~"); private_node_handle.param<std::string>("port", port, "/dev/ttyACM0"); private_node_handle.param<std::string>("tf_parent_frame_id", tf_parent_frame_id, "imu_base"); private_node_handle.param<std::string>("tf_frame_id", tf_frame_id, "imu"); private_node_handle.param<std::string>("imu_frame_id", imu_frame_id, "imu_base"); private_node_handle.param<double>("time_offset_in_seconds", time_offset_in_seconds, 0.0); ros::NodeHandle nh; ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 50); ros::ServiceServer service = nh.advertiseService("set_zero_orientation", set_zero_orientation); ros::Rate r(1000); // 1000 hz while(ros::ok()) { try { if (ser.isOpen()) { // read string from serial device if(ser.available()) { std_msgs::String result; result.data = ser.readline(ser.available(), "\n"); std::string input = partial_line + result.data; if (input.at( input.length() - 1 ) == '\n') { // line complete, delete partial_line var partial_line = ""; // TODO check if line is long enough?? if (input.compare(0,53,"Send any character to begin DMP programming and demo:") == 0 ) { ROS_DEBUG("Sending 'A'"); ser.write("A"); } // parse line, get quaternion values if (input.compare(0,2,"$\x02") == 0 && (input.size() == 14)) { uint w = (((0xff &(char)input[2]) << 8) | 0xff &(char)input[3]); ROS_DEBUG("w = %04x", w ); uint x = (((0xff &(char)input[4]) << 8) | 0xff &(char)input[5]); ROS_DEBUG("x = %04x", x ); uint y = (((0xff &(char)input[6]) << 8) | 0xff &(char)input[7]); ROS_DEBUG("y = %04x", y ); uint z = (((0xff &(char)input[8]) << 8) | 0xff &(char)input[9]); ROS_DEBUG("z = %04x", z ); double wf = w/16384.0; double xf = x/16384.0; double yf = y/16384.0; double zf = z/16384.0; if (wf >= 2.0) { wf = -4.0 +wf; } if (xf >= 2.0) { xf = -4.0 +xf; } if (yf >= 2.0) { yf = -4.0 +yf; } if (zf >= 2.0) { zf = -4.0 +zf; } tf::Quaternion orientation(xf, yf, zf, wf); if (!zero_orientation_set) { zero_orientation = orientation; zero_orientation_set = true; } //http://answers.ros.org/question/10124/relative-rotation-between-two-quaternions/ tf::Quaternion differential_rotation; differential_rotation = zero_orientation.inverse() * orientation; // calculate measurement time ros::Time measurement_time = ros::Time::now() + ros::Duration(time_offset_in_seconds); // publish imu message sensor_msgs::Imu imu; imu.header.stamp = measurement_time; imu.header.frame_id = imu_frame_id; quaternionTFToMsg(differential_rotation, imu.orientation); // i do not know the orientation covariance imu.orientation_covariance[0] = 0; imu.orientation_covariance[1] = 0; imu.orientation_covariance[2] = 0; imu.orientation_covariance[3] = 0; imu.orientation_covariance[4] = 0; imu.orientation_covariance[5] = 0; imu.orientation_covariance[6] = 0; imu.orientation_covariance[7] = 0; imu.orientation_covariance[8] = 0; // angular velocity is not provided imu.angular_velocity_covariance[0] = -1; // linear acceleration is not provided imu.linear_acceleration_covariance[0] = -1; imu_pub.publish(imu); // publish tf transform static tf::TransformBroadcaster br; tf::Transform transform; transform.setRotation(differential_rotation); br.sendTransform(tf::StampedTransform(transform, measurement_time, tf_parent_frame_id, tf_frame_id)); } } else { // line incomplete, remember already received characters partial_line = input; } } else // ser not available { } } else { // try and open the serial port try { ser.setPort(port); ser.setBaudrate(115200); serial::Timeout to = serial::Timeout::simpleTimeout(1000); ser.setTimeout(to); ser.open(); } catch (serial::IOException& e) { ROS_ERROR_STREAM("Unable to open serial port " << ser.getPort() << ". Trying again in 5 seconds."); ros::Duration(5).sleep(); } if(ser.isOpen()) { ROS_DEBUG_STREAM("Serial port " << ser.getPort() << " initialized."); } else { //ROS_INFO_STREAM("Could not initialize serial port."); } } } catch (serial::IOException& e) { ROS_ERROR_STREAM("Error reading from the serial port " << ser.getPort() << ". Closing connection."); ser.close(); } ros::spinOnce(); r.sleep(); } } <commit_msg>changed comment and output<commit_after>#include <geometry_msgs/Quaternion.h> #include <ros/ros.h> #include <serial/serial.h> #include <sensor_msgs/Imu.h> #include <std_msgs/String.h> #include <std_srvs/Empty.h> #include <string> #include <tf/transform_broadcaster.h> #include <tf/transform_datatypes.h> bool zero_orientation_set = false; bool set_zero_orientation(std_srvs::Empty::Request&, std_srvs::Empty::Response&) { ROS_INFO("Zero Orientation Set."); zero_orientation_set = false; return true; } int main(int argc, char** argv) { serial::Serial ser; std::string port; std::string tf_parent_frame_id; std::string tf_frame_id; std::string imu_frame_id; double time_offset_in_seconds; tf::Quaternion orientation; tf::Quaternion zero_orientation; std::string partial_line = ""; ros::init(argc, argv, "mpu6050_serial_to_imu_node"); ros::NodeHandle private_node_handle("~"); private_node_handle.param<std::string>("port", port, "/dev/ttyACM0"); private_node_handle.param<std::string>("tf_parent_frame_id", tf_parent_frame_id, "imu_base"); private_node_handle.param<std::string>("tf_frame_id", tf_frame_id, "imu"); private_node_handle.param<std::string>("imu_frame_id", imu_frame_id, "imu_base"); private_node_handle.param<double>("time_offset_in_seconds", time_offset_in_seconds, 0.0); ros::NodeHandle nh; ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>("imu", 50); ros::ServiceServer service = nh.advertiseService("set_zero_orientation", set_zero_orientation); ros::Rate r(1000); // 1000 hz while(ros::ok()) { try { if (ser.isOpen()) { // read string from serial device if(ser.available()) { std_msgs::String result; result.data = ser.readline(ser.available(), "\n"); std::string input = partial_line + result.data; if (input.at( input.length() - 1 ) == '\n') { // line complete, delete partial_line var partial_line = ""; // TODO: check if line is long enough?? if (input.compare(0,53,"Send any character to begin DMP programming and demo:") == 0 ) { ROS_DEBUG("Sending 'A' to start sending of IMU data."); ser.write("A"); } // parse line, get quaternion values if (input.compare(0,2,"$\x02") == 0 && (input.size() == 14)) { uint w = (((0xff &(char)input[2]) << 8) | 0xff &(char)input[3]); ROS_DEBUG("w = %04x", w ); uint x = (((0xff &(char)input[4]) << 8) | 0xff &(char)input[5]); ROS_DEBUG("x = %04x", x ); uint y = (((0xff &(char)input[6]) << 8) | 0xff &(char)input[7]); ROS_DEBUG("y = %04x", y ); uint z = (((0xff &(char)input[8]) << 8) | 0xff &(char)input[9]); ROS_DEBUG("z = %04x", z ); double wf = w/16384.0; double xf = x/16384.0; double yf = y/16384.0; double zf = z/16384.0; if (wf >= 2.0) { wf = -4.0 +wf; } if (xf >= 2.0) { xf = -4.0 +xf; } if (yf >= 2.0) { yf = -4.0 +yf; } if (zf >= 2.0) { zf = -4.0 +zf; } tf::Quaternion orientation(xf, yf, zf, wf); if (!zero_orientation_set) { zero_orientation = orientation; zero_orientation_set = true; } //http://answers.ros.org/question/10124/relative-rotation-between-two-quaternions/ tf::Quaternion differential_rotation; differential_rotation = zero_orientation.inverse() * orientation; // calculate measurement time ros::Time measurement_time = ros::Time::now() + ros::Duration(time_offset_in_seconds); // publish imu message sensor_msgs::Imu imu; imu.header.stamp = measurement_time; imu.header.frame_id = imu_frame_id; quaternionTFToMsg(differential_rotation, imu.orientation); // i do not know the orientation covariance imu.orientation_covariance[0] = 0; imu.orientation_covariance[1] = 0; imu.orientation_covariance[2] = 0; imu.orientation_covariance[3] = 0; imu.orientation_covariance[4] = 0; imu.orientation_covariance[5] = 0; imu.orientation_covariance[6] = 0; imu.orientation_covariance[7] = 0; imu.orientation_covariance[8] = 0; // angular velocity is not provided imu.angular_velocity_covariance[0] = -1; // linear acceleration is not provided imu.linear_acceleration_covariance[0] = -1; imu_pub.publish(imu); // publish tf transform static tf::TransformBroadcaster br; tf::Transform transform; transform.setRotation(differential_rotation); br.sendTransform(tf::StampedTransform(transform, measurement_time, tf_parent_frame_id, tf_frame_id)); } } else { // line incomplete, remember already received characters partial_line = input; } } else // ser not available { } } else { // try and open the serial port try { ser.setPort(port); ser.setBaudrate(115200); serial::Timeout to = serial::Timeout::simpleTimeout(1000); ser.setTimeout(to); ser.open(); } catch (serial::IOException& e) { ROS_ERROR_STREAM("Unable to open serial port " << ser.getPort() << ". Trying again in 5 seconds."); ros::Duration(5).sleep(); } if(ser.isOpen()) { ROS_DEBUG_STREAM("Serial port " << ser.getPort() << " initialized."); } else { //ROS_INFO_STREAM("Could not initialize serial port."); } } } catch (serial::IOException& e) { ROS_ERROR_STREAM("Error reading from the serial port " << ser.getPort() << ". Closing connection."); ser.close(); } ros::spinOnce(); r.sleep(); } } <|endoftext|>
<commit_before>// sample.hxx -- Sound sample encapsulation class // // Written by Curtis Olson, started April 2004. // // Copyright (C) 2004 Curtis L. Olson - [email protected] // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ /** * \file sample.hxx * Provides a sound sample encapsulation */ #ifndef _SG_SAMPLE_HXX #define _SG_SAMPLE_HXX 1 #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include <AL/al.h> #include <simgear/debug/logstream.hxx> /** * manages everything we need to know for an individual sound sample */ class SGSoundSample { private: // Buffers hold sound data. ALuint buffer; // Sources are points emitting sound. ALuint source; // Position of the source sound. ALfloat source_pos[3]; // Velocity of the source sound. ALfloat source_vel[3]; // configuration values ALenum format; ALsizei size; ALvoid* data; ALsizei freq; double pitch; double volume; ALboolean loop; public: SGSoundSample( const char *path, const char *file ); SGSoundSample( unsigned char *_data, int len, int _freq ); ~SGSoundSample(); /** * Start playing this sample. * * @param looped Define wether the sound should be played in a loop. */ void play( bool _loop ); /** * Stop playing this sample. * * @param sched A pointer to the appropriate scheduler. */ void stop(); /** * Play this sample once. * @see #play */ inline void play_once() { play(false); } /** * Play this sample looped. * @see #play */ inline void play_looped() { play(true); } /** * Test if a sample is curretnly playing. * @return true if is is playing, false otherwise. */ inline bool is_playing( ) { ALint result; alGetSourcei( source, AL_SOURCE_STATE, &result ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample is_playing()!" ); } return (result == AL_PLAYING) ; } /** * Get the current pitch setting of this sample. */ inline double get_pitch() const { return pitch; } /** * Set the pitch of this sample. */ inline void set_pitch( double p ) { pitch = p; alSourcef( source, AL_PITCH, pitch ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample set_pitch()! " << p ); } } /** * Get the current volume setting of this sample. */ inline double get_volume() const { return volume; } /** * Set the volume of this sample. */ inline void set_volume( double v ) { volume = v; alSourcef( source, AL_GAIN, volume ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample set_volume()!" ); } } /** * Returns the size of the sounds sample */ inline int get_size() { return size; } /** * Return a pointer to the raw data */ inline char *get_data() { return (char *)data; } }; #endif // _SG_SAMPLE_HXX <commit_msg>Clamp pitch values rather than just dumping an error message.<commit_after>// sample.hxx -- Sound sample encapsulation class // // Written by Curtis Olson, started April 2004. // // Copyright (C) 2004 Curtis L. Olson - [email protected] // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation; either version 2 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. // // $Id$ /** * \file sample.hxx * Provides a sound sample encapsulation */ #ifndef _SG_SAMPLE_HXX #define _SG_SAMPLE_HXX 1 #ifndef __cplusplus # error This library requires C++ #endif #include <simgear/compiler.h> #include <AL/al.h> #include <simgear/debug/logstream.hxx> /** * manages everything we need to know for an individual sound sample */ class SGSoundSample { private: // Buffers hold sound data. ALuint buffer; // Sources are points emitting sound. ALuint source; // Position of the source sound. ALfloat source_pos[3]; // Velocity of the source sound. ALfloat source_vel[3]; // configuration values ALenum format; ALsizei size; ALvoid* data; ALsizei freq; double pitch; double volume; ALboolean loop; public: SGSoundSample( const char *path, const char *file ); SGSoundSample( unsigned char *_data, int len, int _freq ); ~SGSoundSample(); /** * Start playing this sample. * * @param looped Define wether the sound should be played in a loop. */ void play( bool _loop ); /** * Stop playing this sample. * * @param sched A pointer to the appropriate scheduler. */ void stop(); /** * Play this sample once. * @see #play */ inline void play_once() { play(false); } /** * Play this sample looped. * @see #play */ inline void play_looped() { play(true); } /** * Test if a sample is curretnly playing. * @return true if is is playing, false otherwise. */ inline bool is_playing( ) { ALint result; alGetSourcei( source, AL_SOURCE_STATE, &result ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample is_playing()!" ); } return (result == AL_PLAYING) ; } /** * Get the current pitch setting of this sample. */ inline double get_pitch() const { return pitch; } /** * Set the pitch of this sample. */ inline void set_pitch( double p ) { // clamp in the range of 0.01 to 2.0 if ( p < 0.01 ) { p = 0.01; } if ( p > 2.0 ) { p = 2.0; } pitch = p; alSourcef( source, AL_PITCH, pitch ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample set_pitch()! " << p ); } } /** * Get the current volume setting of this sample. */ inline double get_volume() const { return volume; } /** * Set the volume of this sample. */ inline void set_volume( double v ) { volume = v; alSourcef( source, AL_GAIN, volume ); if ( alGetError() != AL_NO_ERROR) { SG_LOG( SG_GENERAL, SG_ALERT, "Oops AL error in sample set_volume()!" ); } } /** * Returns the size of the sounds sample */ inline int get_size() { return size; } /** * Return a pointer to the raw data */ inline char *get_data() { return (char *)data; } }; #endif // _SG_SAMPLE_HXX <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; if (parse_tree.get() == nullptr) return plan_tree; // std::unique_ptr<planner::AbstractPlan> child_plan; // // // TODO: Transform the parse tree // // // One to one Mapping // auto parse_item_node_type = parse_tree->GetParseNodeType(); // // switch(parse_item_node_type){ // case PARSE_NODE_TYPE_DROP: // child_plan = std::make_unique(new planner::DropPlan("department-table")); // break; // // case PARSE_NODE_TYPE_SCAN: // child_plan = std::make_unique(new planner::SeqScanPlan()); // break; // // default: // LOG_INFO("Unsupported Parse Node Type"); // } // //// Need to recurse and give base case. for every child in parse tree. // // if (child_plan != nullptr) { // if (plan_tree != nullptr) // plan_tree->AddChild(std::move(child_plan)); // else // plan_tree = child_plan; // } return plan_tree; } } // namespace optimizer } // namespace peloton <commit_msg>uncommented simple optimizer .. checking for more bugs<commit_after>//===----------------------------------------------------------------------===// // // PelotonDB // // simple_optimizer.cpp // // Identification: /peloton/src/optimizer/simple_optimizer.cpp // // Copyright (c) 2016, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include "optimizer/simple_optimizer.h" #include "parser/peloton/abstract_parse.h" #include "planner/abstract_plan.h" #include "common/logger.h" #include <memory> namespace peloton { namespace optimizer { SimpleOptimizer::SimpleOptimizer() { } ; SimpleOptimizer::~SimpleOptimizer() { } ; std::shared_ptr<planner::AbstractPlan> SimpleOptimizer::BuildPlanTree( const std::unique_ptr<parser::AbstractParse>& parse_tree) { std::shared_ptr<planner::AbstractPlan> plan_tree; if (parse_tree.get() == nullptr) return plan_tree; std::unique_ptr<planner::AbstractPlan> child_plan; // TODO: Transform the parse tree // One to one Mapping auto parse_item_node_type = parse_tree->GetParseNodeType(); switch(parse_item_node_type){ case PARSE_NODE_TYPE_DROP: child_plan = std::make_unique(new planner::DropPlan("department-table")); break; case PARSE_NODE_TYPE_SCAN: child_plan = std::make_unique(new planner::SeqScanPlan()); break; default: LOG_INFO("Unsupported Parse Node Type"); } // Need to recurse and give base case. for every child in parse tree. if (child_plan != nullptr) { if (plan_tree != nullptr) plan_tree->AddChild(std::move(child_plan)); else plan_tree = child_plan; } return plan_tree; } } // namespace optimizer } // namespace peloton <|endoftext|>
<commit_before>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <osvr/Server/RouteContainer.h> // Library/third-party includes #include <json/value.h> #include <json/reader.h> #include <json/writer.h> // Standard includes #include <stdexcept> #include <functional> #include <algorithm> namespace osvr { namespace server { static inline Json::Value parseRoutingDirective(std::string const &routingDirective) { Json::Reader reader; Json::Value val; if (!reader.parse(routingDirective, val)) { throw std::runtime_error("Invalid JSON routing directive: " + routingDirective); } return val; } static const char DESTINATION_KEY[] = "destination"; static inline std::string getDestination(Json::Value const &routingDirective) { return routingDirective.get(DESTINATION_KEY, "").asString(); } static inline std::string toFastString(Json::Value const &val) { Json::FastWriter writer; return writer.write(val); } RouteContainer::RouteContainer() {} RouteContainer::RouteContainer(std::string const &routes) { Json::Reader reader; Json::Value routesVal; if (!reader.parse(routes, routesVal)) { throw std::runtime_error("Invalid JSON routing directive array: " + routes); } for (Json::ArrayIndex i = 0, e = routesVal.size(); i < e; ++i) { const Json::Value thisRoute = routesVal[i]; m_addRoute(getDestination(thisRoute), toFastString(thisRoute)); } } bool RouteContainer::addRoute(std::string const &routingDirective) { auto route = parseRoutingDirective(routingDirective); return m_addRoute(getDestination(route), routingDirective); } std::string RouteContainer::getRoutes(bool styled) const { Json::Value routes(Json::arrayValue); for (auto const &r : m_routingDirectives) { routes.append(parseRoutingDirective(r)); } if (styled) { return routes.toStyledString(); } else { return toFastString(routes); } } std::string RouteContainer::getSource(std::string const &destination) const { auto it = std::find_if(begin(m_routingDirectives), end(m_routingDirectives), [&](std::string const &directive) { return (getDestination(parseRoutingDirective(directive)) == destination); }); if (it != end(m_routingDirectives)) { return *it; } else { return std::string(); } } bool RouteContainer::m_addRoute(std::string const &destination, std::string const &routingDirective) { bool replaced = false; /// If a route already exists with the same destination, replace it /// with this new one. std::replace_if( begin(m_routingDirectives), end(m_routingDirectives), [&](std::string const &directive) { Json::Value candidate = parseRoutingDirective(directive); bool match = (getDestination(candidate) == destination); if (match) { replaced = true; } return match; }, routingDirective); /// If we didn't replace an existing route, just add this one. if (!replaced) { m_routingDirectives.push_back(routingDirective); } return !replaced; } } // namespace server } // namespace osvr<commit_msg>Fix getSource to do what it says it will.<commit_after>/** @file @brief Implementation @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, Inc. // // All rights reserved. // // (Final version intended to be licensed under // the Apache License, Version 2.0) // Internal Includes #include <osvr/Server/RouteContainer.h> // Library/third-party includes #include <json/value.h> #include <json/reader.h> #include <json/writer.h> // Standard includes #include <stdexcept> #include <functional> #include <algorithm> namespace osvr { namespace server { static inline Json::Value parseRoutingDirective(std::string const &routingDirective) { Json::Reader reader; Json::Value val; if (!reader.parse(routingDirective, val)) { throw std::runtime_error("Invalid JSON routing directive: " + routingDirective); } return val; } static const char DESTINATION_KEY[] = "destination"; static inline std::string getDestination(Json::Value const &routingDirective) { return routingDirective.get(DESTINATION_KEY, "").asString(); } static inline std::string toFastString(Json::Value const &val) { Json::FastWriter writer; return writer.write(val); } RouteContainer::RouteContainer() {} RouteContainer::RouteContainer(std::string const &routes) { Json::Reader reader; Json::Value routesVal; if (!reader.parse(routes, routesVal)) { throw std::runtime_error("Invalid JSON routing directive array: " + routes); } for (Json::ArrayIndex i = 0, e = routesVal.size(); i < e; ++i) { const Json::Value thisRoute = routesVal[i]; m_addRoute(getDestination(thisRoute), toFastString(thisRoute)); } } bool RouteContainer::addRoute(std::string const &routingDirective) { auto route = parseRoutingDirective(routingDirective); return m_addRoute(getDestination(route), routingDirective); } std::string RouteContainer::getRoutes(bool styled) const { Json::Value routes(Json::arrayValue); for (auto const &r : m_routingDirectives) { routes.append(parseRoutingDirective(r)); } if (styled) { return routes.toStyledString(); } else { return toFastString(routes); } } static const char SOURCE_KEY[] = "source"; std::string RouteContainer::getSource(std::string const &destination) const { auto it = std::find_if(begin(m_routingDirectives), end(m_routingDirectives), [&](std::string const &directive) { return (getDestination(parseRoutingDirective(directive)) == destination); }); if (it != end(m_routingDirectives)) { Json::Value directive = parseRoutingDirective(*it); if (directive.isMember(SOURCE_KEY)) { return directive[SOURCE_KEY].toStyledString(); } } return std::string(); } bool RouteContainer::m_addRoute(std::string const &destination, std::string const &routingDirective) { bool replaced = false; /// If a route already exists with the same destination, replace it /// with this new one. std::replace_if( begin(m_routingDirectives), end(m_routingDirectives), [&](std::string const &directive) { Json::Value candidate = parseRoutingDirective(directive); bool match = (getDestination(candidate) == destination); if (match) { replaced = true; } return match; }, routingDirective); /// If we didn't replace an existing route, just add this one. if (!replaced) { m_routingDirectives.push_back(routingDirective); } return !replaced; } } // namespace server } // namespace osvr<|endoftext|>
<commit_before>#include "DartResource.h" #include "private/AbstractResource_p.h" #include <QtCore/QDebug> #include <QtCore/QProcess> namespace web { namespace page { namespace resource { class DartResourcePrivate : public AbstractResourcePrivate { public: QString dartFileName; }; const QString DART2JS_SCRIPT = QStringLiteral("../../../../dart/dart-sdk/bin/dart2js"); DartResource::DartResource(const QString &dartFile, const QString &jsFile) : AbstractResource(new DartResourcePrivate) { Q_D(DartResource); d->fileName = jsFile; d->dartFileName = dartFile; compileDartFile(); } void DartResource::compileDartFile() { Q_D(DartResource); QStringList arguments; #ifdef QT_WEBFRAMEWORK_DEBUG arguments << QStringLiteral("--checked") << QStringLiteral("--out=") + d->fileName << d->dartFileName; #else #endif QProcess::startDetached(DART2JS_SCRIPT, arguments); } } } } <commit_msg>Different arguments for the dart2js executable<commit_after>#include "DartResource.h" #include "private/AbstractResource_p.h" #include <QtCore/QDebug> #include <QtCore/QProcess> namespace web { namespace page { namespace resource { class DartResourcePrivate : public AbstractResourcePrivate { public: QString dartFileName; }; const QString DART2JS_SCRIPT = QStringLiteral("../../../../dart/dart-sdk/bin/dart2js"); DartResource::DartResource(const QString &dartFile, const QString &jsFile) : AbstractResource(new DartResourcePrivate) { Q_D(DartResource); d->fileName = jsFile; d->dartFileName = dartFile; compileDartFile(); } void DartResource::compileDartFile() { Q_D(DartResource); QStringList arguments; #ifdef QT_WEBFRAMEWORK_DEBUG arguments << QStringLiteral("--checked") << QStringLiteral("--out=") + d->fileName << d->dartFileName; #else arguments << QStringLiteral("--minify") << QStringLiteral("--out=") + d->fileName << d->dartFileName; #endif QProcess::startDetached(DART2JS_SCRIPT, arguments); } } } } <|endoftext|>
<commit_before>#include "MotionControl.hpp" #include <Geometry2d/Util.hpp> #include <Robot.hpp> #include <RobotConfig.hpp> #include <SystemState.hpp> #include <Utils.hpp> #include <planning/MotionInstant.hpp> #include "TrapezoidalMotion.hpp" #include <stdio.h> #include <algorithm> using namespace std; using namespace Geometry2d; using namespace Planning; #pragma mark Config Variables REGISTER_CONFIGURABLE(MotionControl); ConfigDouble* MotionControl::_max_acceleration; ConfigDouble* MotionControl::_max_velocity; void MotionControl::createConfiguration(Configuration* cfg) { _max_acceleration = new ConfigDouble(cfg, "MotionControl/Max Acceleration", 1.5); _max_velocity = new ConfigDouble(cfg, "MotionControl/Max Velocity", 2.0); } #pragma mark MotionControl MotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 50) { _robot = robot; _robot->robotPacket.set_uid(_robot->shell()); } void MotionControl::run() { if (!_robot) return; const MotionConstraints& constraints = _robot->motionConstraints(); // update PID parameters _positionXController.kp = *_robot->config->translation.p; _positionXController.ki = *_robot->config->translation.i; _positionXController.setWindup(*_robot->config->translation.i_windup); _positionXController.kd = *_robot->config->translation.d; _positionYController.kp = *_robot->config->translation.p; _positionYController.ki = *_robot->config->translation.i; _positionYController.setWindup(*_robot->config->translation.i_windup); _positionYController.kd = *_robot->config->translation.d; _angleController.kp = *_robot->config->rotation.p; _angleController.ki = *_robot->config->rotation.i; _angleController.kd = *_robot->config->rotation.d; RJ::Seconds timeIntoPath = (RJ::now() - _robot->path().startTime()) + RJ::Seconds(1.0 / 60); // evaluate path - where should we be right now? boost::optional<RobotInstant> optTarget = _robot->path().evaluate(timeIntoPath); if (!optTarget) { optTarget = _robot->path().end(); _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::red, "Planning"); } else { Point start = _robot->pos; _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::green, "Planning"); } // Angle control ////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// float targetW = 0; auto& rotationCommand = _robot->rotationCommand(); const auto& rotationConstraints = _robot->rotationConstraints(); boost::optional<Geometry2d::Point> targetPt; const auto& motionCommand = _robot->motionCommand(); boost::optional<float> targetAngleFinal; // if (motionCommand->getCommandType() == MotionCommand::Pivot) { // PivotCommand command = // *static_cast<PivotCommand*>(motionCommand.get()); // targetPt = command.pivotTarget; //} else { if (optTarget) { if (optTarget->angle) { if (optTarget->angle->angle) { targetAngleFinal = *optTarget->angle->angle; } } } //} if (targetPt) { // fixing the angle ensures that we don't go the long way around to get // to our final angle targetAngleFinal = (*targetPt - _robot->pos).angle(); } if (!targetAngleFinal) { _targetAngleVel(0); } else { float angleError = fixAngleRadians(*targetAngleFinal - _robot->angle); targetW = _angleController.run(angleError); // limit W if (abs(targetW) > (rotationConstraints.maxSpeed)) { if (targetW > 0) { targetW = (rotationConstraints.maxSpeed); } else { targetW = -(rotationConstraints.maxSpeed); } } /* _robot->addText(QString("targetW: %1").arg(targetW)); _robot->addText(QString("angleError: %1").arg(angleError)); _robot->addText(QString("targetGlobalAngle: %1").arg(targetAngleFinal)); _robot->addText(QString("angle: %1").arg(_robot->angle)); */ _targetAngleVel(targetW); } // handle body velocity for pivot command /* if (motionCommand->getCommandType() == MotionCommand::Pivot) { float r = Robot_Radius; const float FudgeFactor = *_robot->config->pivotVelMultiplier; float speed = RadiansToDegrees(r * targetW * FudgeFactor); Point vel(speed, 0); // the robot body coordinate system is wierd... vel.rotate(-M_PI_2); _targetBodyVel(vel); return; // pivot handles both angle and position } */ // Position control /////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// MotionInstant target = optTarget->motion; // tracking error Point posError = target.pos - _robot->pos; // acceleration factor Point acceleration; boost::optional<RobotInstant> nextTarget = _robot->path().evaluate(timeIntoPath + RJ::Seconds(1) / 60.0); if (nextTarget) { acceleration = (nextTarget->motion.vel - target.vel) / 60.0f; } else { acceleration = {0, 0}; } Point accelFactor = acceleration * 60.0f * (*_robot->config->accelerationMultiplier); target.vel += accelFactor; // PID on position target.vel.x() += _positionXController.run(posError.x()); target.vel.y() += _positionYController.run(posError.y()); // draw target pt _robot->state()->drawCircle(target.pos, .04, Qt::red, "MotionControl"); _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue, "MotionControl"); // Clamp World Acceleration auto dt = RJ::Seconds(RJ::now() - _lastCmdTime); Point targetAccel = (target.vel - _lastWorldVelCmd) / dt.count(); targetAccel.clamp(*_max_acceleration); target.vel = _lastWorldVelCmd + targetAccel * dt.count(); _lastWorldVelCmd = target.vel; _lastCmdTime = RJ::now(); // convert from world to body coordinates // the +y axis of the robot points forwards target.vel = target.vel.rotated(M_PI_2 - _robot->angle); this->_targetBodyVel(target.vel); } void MotionControl::stopped() { _targetBodyVel(Point(0, 0)); _targetAngleVel(0); } void MotionControl::_targetAngleVel(float angleVel) { // velocity multiplier angleVel *= *_robot->config->angleVelMultiplier; // If the angular speed is very low, it won't make the robot move at all, so // we make sure it's above a threshold value float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed; if (std::abs(angleVel) < minEffectiveAngularSpeed && std::abs(angleVel) > .05) { angleVel = angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed; } // the robot firmware still speaks degrees, so that's how we send it over _robot->control->set_avelocity(angleVel); } void MotionControl::_targetBodyVel(Point targetVel) { // Limit Velocity targetVel.clamp(*_max_velocity); // Limit Acceleration // make sure we don't send any bad values if (std::isnan(targetVel.x()) || std::isnan(targetVel.y())) { targetVel = Point(0, 0); debugThrow("A bad value was calculated."); } // track these values so we can limit acceleration // velocity multiplier targetVel *= *_robot->config->velMultiplier; // if the velocity is nonzero, make sure it's not so small that the robot // doesn't even move float minEffectiveVelocity = *_robot->config->minEffectiveVelocity; if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.02) { targetVel = targetVel.normalized() * minEffectiveVelocity; } // set control values _robot->control->set_xvelocity(targetVel.x()); _robot->control->set_yvelocity(targetVel.y()); } <commit_msg>Change AngleController constructor to match<commit_after>#include "MotionControl.hpp" #include <Geometry2d/Util.hpp> #include <Robot.hpp> #include <RobotConfig.hpp> #include <SystemState.hpp> #include <Utils.hpp> #include <planning/MotionInstant.hpp> #include "TrapezoidalMotion.hpp" #include <stdio.h> #include <algorithm> using namespace std; using namespace Geometry2d; using namespace Planning; #pragma mark Config Variables REGISTER_CONFIGURABLE(MotionControl); ConfigDouble* MotionControl::_max_acceleration; ConfigDouble* MotionControl::_max_velocity; void MotionControl::createConfiguration(Configuration* cfg) { _max_acceleration = new ConfigDouble(cfg, "MotionControl/Max Acceleration", 1.5); _max_velocity = new ConfigDouble(cfg, "MotionControl/Max Velocity", 2.0); } #pragma mark MotionControl MotionControl::MotionControl(OurRobot* robot) : _angleController(0, 0, 0, 0, 50) { _robot = robot; _robot->robotPacket.set_uid(_robot->shell()); } void MotionControl::run() { if (!_robot) return; const MotionConstraints& constraints = _robot->motionConstraints(); // update PID parameters _positionXController.kp = *_robot->config->translation.p; _positionXController.ki = *_robot->config->translation.i; _positionXController.setWindup(*_robot->config->translation.i_windup); _positionXController.kd = *_robot->config->translation.d; _positionYController.kp = *_robot->config->translation.p; _positionYController.ki = *_robot->config->translation.i; _positionYController.setWindup(*_robot->config->translation.i_windup); _positionYController.kd = *_robot->config->translation.d; _angleController.kp = *_robot->config->rotation.p; _angleController.ki = *_robot->config->rotation.i; _angleController.kd = *_robot->config->rotation.d; RJ::Seconds timeIntoPath = (RJ::now() - _robot->path().startTime()) + RJ::Seconds(1.0 / 60); // evaluate path - where should we be right now? boost::optional<RobotInstant> optTarget = _robot->path().evaluate(timeIntoPath); if (!optTarget) { optTarget = _robot->path().end(); _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::red, "Planning"); } else { Point start = _robot->pos; _robot->state()->drawCircle(optTarget->motion.pos, .15, Qt::green, "Planning"); } // Angle control ////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// float targetW = 0; auto& rotationCommand = _robot->rotationCommand(); const auto& rotationConstraints = _robot->rotationConstraints(); boost::optional<Geometry2d::Point> targetPt; const auto& motionCommand = _robot->motionCommand(); boost::optional<float> targetAngleFinal; // if (motionCommand->getCommandType() == MotionCommand::Pivot) { // PivotCommand command = // *static_cast<PivotCommand*>(motionCommand.get()); // targetPt = command.pivotTarget; //} else { if (optTarget) { if (optTarget->angle) { if (optTarget->angle->angle) { targetAngleFinal = *optTarget->angle->angle; } } } //} if (targetPt) { // fixing the angle ensures that we don't go the long way around to get // to our final angle targetAngleFinal = (*targetPt - _robot->pos).angle(); } if (!targetAngleFinal) { _targetAngleVel(0); } else { float angleError = fixAngleRadians(*targetAngleFinal - _robot->angle); targetW = _angleController.run(angleError); // limit W if (abs(targetW) > (rotationConstraints.maxSpeed)) { if (targetW > 0) { targetW = (rotationConstraints.maxSpeed); } else { targetW = -(rotationConstraints.maxSpeed); } } /* _robot->addText(QString("targetW: %1").arg(targetW)); _robot->addText(QString("angleError: %1").arg(angleError)); _robot->addText(QString("targetGlobalAngle: %1").arg(targetAngleFinal)); _robot->addText(QString("angle: %1").arg(_robot->angle)); */ _targetAngleVel(targetW); } // handle body velocity for pivot command /* if (motionCommand->getCommandType() == MotionCommand::Pivot) { float r = Robot_Radius; const float FudgeFactor = *_robot->config->pivotVelMultiplier; float speed = RadiansToDegrees(r * targetW * FudgeFactor); Point vel(speed, 0); // the robot body coordinate system is wierd... vel.rotate(-M_PI_2); _targetBodyVel(vel); return; // pivot handles both angle and position } */ // Position control /////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// MotionInstant target = optTarget->motion; // tracking error Point posError = target.pos - _robot->pos; // acceleration factor Point acceleration; boost::optional<RobotInstant> nextTarget = _robot->path().evaluate(timeIntoPath + RJ::Seconds(1) / 60.0); if (nextTarget) { acceleration = (nextTarget->motion.vel - target.vel) / 60.0f; } else { acceleration = {0, 0}; } Point accelFactor = acceleration * 60.0f * (*_robot->config->accelerationMultiplier); target.vel += accelFactor; // PID on position target.vel.x() += _positionXController.run(posError.x()); target.vel.y() += _positionYController.run(posError.y()); // draw target pt _robot->state()->drawCircle(target.pos, .04, Qt::red, "MotionControl"); _robot->state()->drawLine(target.pos, target.pos + target.vel, Qt::blue, "MotionControl"); // Clamp World Acceleration auto dt = RJ::Seconds(RJ::now() - _lastCmdTime); Point targetAccel = (target.vel - _lastWorldVelCmd) / dt.count(); targetAccel.clamp(*_max_acceleration); target.vel = _lastWorldVelCmd + targetAccel * dt.count(); _lastWorldVelCmd = target.vel; _lastCmdTime = RJ::now(); // convert from world to body coordinates // the +y axis of the robot points forwards target.vel = target.vel.rotated(M_PI_2 - _robot->angle); this->_targetBodyVel(target.vel); } void MotionControl::stopped() { _targetBodyVel(Point(0, 0)); _targetAngleVel(0); } void MotionControl::_targetAngleVel(float angleVel) { // velocity multiplier angleVel *= *_robot->config->angleVelMultiplier; // If the angular speed is very low, it won't make the robot move at all, so // we make sure it's above a threshold value float minEffectiveAngularSpeed = *_robot->config->minEffectiveAngularSpeed; if (std::abs(angleVel) < minEffectiveAngularSpeed && std::abs(angleVel) > .05) { angleVel = angleVel > 0 ? minEffectiveAngularSpeed : -minEffectiveAngularSpeed; } // the robot firmware still speaks degrees, so that's how we send it over _robot->control->set_avelocity(angleVel); } void MotionControl::_targetBodyVel(Point targetVel) { // Limit Velocity targetVel.clamp(*_max_velocity); // Limit Acceleration // make sure we don't send any bad values if (std::isnan(targetVel.x()) || std::isnan(targetVel.y())) { targetVel = Point(0, 0); debugThrow("A bad value was calculated."); } // track these values so we can limit acceleration // velocity multiplier targetVel *= *_robot->config->velMultiplier; // if the velocity is nonzero, make sure it's not so small that the robot // doesn't even move float minEffectiveVelocity = *_robot->config->minEffectiveVelocity; if (targetVel.mag() < minEffectiveVelocity && targetVel.mag() > 0.02) { targetVel = targetVel.normalized() * minEffectiveVelocity; } // set control values _robot->control->set_xvelocity(targetVel.x()); _robot->control->set_yvelocity(targetVel.y()); } <|endoftext|>
<commit_before>//Jonathan's class #include "FreeLookCamera.h" FreeLookCamera::FreeLookCamera(GLint viewWidth, GLint viewHeight, GLfloat viewNearPlane, GLfloat viewFarPlane) { Camera::initialize(viewWidth, viewHeight, viewNearPlane, viewFarPlane); //camera rotation yaw = 0.0f; pitch = 0.0f; roll = 0.0f; //camera location locX = 25.0f; locY = 10.0f; locZ = 25.0f; fovy = DEFAULT_FOVY; mouseSensitivity = DEFAULT_MOUSE_SENSITIVITY; movementSensitivity = DEFAULT_MOVEMENT_SENSITIVITY; for (int i = 0; i < 3; i++) directionVector[i] = 0.0; upVector[0] = 0.0f; upVector[1] = 1.0f; upVector[2] = 0.0f; } void FreeLookCamera::view() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, viewWidth / viewHeight, viewNearPlane, viewFarPlane); gluLookAt(locX, locY, locZ, locX + directionVector[0], locY + directionVector[1], locZ + directionVector[2], upVector[0], upVector[1], upVector[2]); } void FreeLookCamera::moveCameraForwards(bool negateTheValue) { GLfloat multiplier = 1.0f; if (negateTheValue) multiplier *= -1.0f; locX += directionVector[0] * multiplier * movementSensitivity; locY += directionVector[1] * multiplier * movementSensitivity; locZ += directionVector[2] * multiplier * movementSensitivity; } void FreeLookCamera::moveCameraStrafe(bool negateTheValue) { GLfloat multiplier = 1.0; if (negateTheValue) multiplier *= -1.0; locX -= directionVector[2] * multiplier * movementSensitivity; locZ += directionVector[0] * multiplier * movementSensitivity; glutPostRedisplay(); } void FreeLookCamera::modifyYaw(bool negateTheValue, int x, int y) { int diffX, diffY; diffX = x - centerX; diffY = y - centerY; if (diffX != 0 || diffY != 0) { glutWarpPointer(centerX, centerY); yaw += diffX * mouseSensitivity; pitch += diffY * mouseSensitivity; if (pitch > MAX_PITCH) pitch = MAX_PITCH; else if (pitch < MIN_PITCH) pitch = MIN_PITCH; directionVector[0] = cos(yaw); directionVector[1] = -sin(pitch); directionVector[2] = sin(yaw); } } void FreeLookCamera::incrementRoll(bool negateTheValue) { if (negateTheValue) roll -= 0.4f; else roll += 0.4f; //http://www.gamedev.net/topic/546975-calculating-the-up-vector/ upVector[0] = cos(yaw) * sin(pitch) * sin(roll) - sin(yaw) * cos(roll); upVector[1] = sin(yaw) * sin(pitch) * sin(roll) + cos(yaw) * cos(roll); upVector[2] = cos(pitch) * sin(roll); } void FreeLookCamera::resetPitchAndRoll() { pitch = 0.0f; roll = 0.0f; directionVector[0] = cos(yaw); directionVector[1] = pitch; directionVector[2] = sin(yaw); upVector[0] = 0.0f; upVector[1] = 1.0f; upVector[2] = 0.0f; }<commit_msg>Rolling is a bit smoother<commit_after>//Jonathan's class #include "FreeLookCamera.h" FreeLookCamera::FreeLookCamera(GLint viewWidth, GLint viewHeight, GLfloat viewNearPlane, GLfloat viewFarPlane) { Camera::initialize(viewWidth, viewHeight, viewNearPlane, viewFarPlane); //camera rotation yaw = 0.0f; pitch = 0.0f; roll = 0.0f; //camera location locX = 25.0f; locY = 10.0f; locZ = 25.0f; fovy = DEFAULT_FOVY; mouseSensitivity = DEFAULT_MOUSE_SENSITIVITY; movementSensitivity = DEFAULT_MOVEMENT_SENSITIVITY; for (int i = 0; i < 3; i++) directionVector[i] = 0.0; upVector[0] = 0.0f; upVector[1] = 1.0f; upVector[2] = 0.0f; } void FreeLookCamera::view() { glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fovy, viewWidth / viewHeight, viewNearPlane, viewFarPlane); gluLookAt(locX, locY, locZ, locX + directionVector[0], locY + directionVector[1], locZ + directionVector[2], upVector[0], upVector[1], upVector[2]); } void FreeLookCamera::moveCameraForwards(bool negateTheValue) { GLfloat multiplier = 1.0f; if (negateTheValue) multiplier *= -1.0f; locX += directionVector[0] * multiplier * movementSensitivity; locY += directionVector[1] * multiplier * movementSensitivity; locZ += directionVector[2] * multiplier * movementSensitivity; } void FreeLookCamera::moveCameraStrafe(bool negateTheValue) { GLfloat multiplier = 1.0; if (negateTheValue) multiplier *= -1.0; locX -= directionVector[2] * multiplier * movementSensitivity; locZ += directionVector[0] * multiplier * movementSensitivity; glutPostRedisplay(); } void FreeLookCamera::modifyYaw(bool negateTheValue, int x, int y) { int diffX, diffY; diffX = x - centerX; diffY = y - centerY; if (diffX != 0 || diffY != 0) { glutWarpPointer(centerX, centerY); yaw += diffX * mouseSensitivity; pitch += diffY * mouseSensitivity; if (pitch > MAX_PITCH) pitch = MAX_PITCH; else if (pitch < MIN_PITCH) pitch = MIN_PITCH; directionVector[0] = cos(yaw); directionVector[1] = -sin(pitch); directionVector[2] = sin(yaw); } } void FreeLookCamera::incrementRoll(bool negateTheValue) { if (negateTheValue) roll -= 0.4f; else roll += 0.4f; //http://www.gamedev.net/topic/546975-calculating-the-up-vector/ upVector[0] = cos(yaw) * sin(pitch) * sin(roll) - sin(yaw) * cos(roll); upVector[1] = sin(yaw) * sin(pitch) * sin(roll) + cos(yaw) * cos(roll); upVector[2] = /*cos(pitch) */ sin(roll); } void FreeLookCamera::resetPitchAndRoll() { pitch = 0.0f; roll = 0.0f; directionVector[0] = cos(yaw); directionVector[1] = pitch; directionVector[2] = sin(yaw); upVector[0] = 0.0f; upVector[1] = 1.0f; upVector[2] = 0.0f; }<|endoftext|>
<commit_before>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } int main (int argc, char** argv) { /***** begin camera setup *****/ CvCapture* capture = 0; int width, height; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream config_file (".config"); if (config_file.is_open()) { // does not support corrupted .config string line; getline(config_file, line); istringstream(line)>>width; getline(config_file, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); config_file.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream config_file_out(".config"); config_file_out << width; config_file_out << "\n"; config_file_out << height; config_file_out << "\n"; config_file_out.close(); } for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } /***** end camera setup *****/ /***** filter setup *****/ Mat acbg(256, 256, CV_8UC3, Scalar(0,0,0)); // accumulated background Mat acbg_m(256, 256, CV_8UC1, Scalar(0)); // accumulated background mask int haar_scale = width/300; if (haar_scale < 1) haar_scale = 1; // can't use 256x256 since haar isn't stretch invariant Mat acfg(height, width, CV_8UC1, Scalar(0)); // accumulated foreground Mat img_256_p(256, 256, CV_8UC3, Scalar(0,0,0)); // previous image Mat delta_flows[4]; delta_flows[0] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[1] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[2] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[3] = Mat(256, 256, CV_8UC1, Scalar(1)); // delta of past 3 frames Mat haar_t_p(256, 256, CV_8UC1, Scalar(1)); // previous possible locations for mouth /***** end filter setup *****/ /***** misc *****/ unsigned long long times[100]; for (int i=0; i<100; i++) times[i] = 0; int tracker1, tracker2, tracker3, tracker4; namedWindow("settings",1); createTrackbar("1","settings",&tracker1,100); createTrackbar("2","settings",&tracker2,100); createTrackbar("3","settings",&tracker3,100); createTrackbar("4","settings",&tracker4,100); unsigned long long timenow = getMilliseconds(); bool keep_going = true; CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); /***** begin filter loop *****/ while (keep_going) { Mat image(cvQueryFrame(capture)); // imshow("webcam", image); // at some point preprocess by rotating according to OVR roll // right now really annoying because of state variables Mat gray, img_256, gray_256; resize(image, img_256, Size(256, 256)); cvtColor(image, gray, CV_RGB2GRAY); cvtColor(img_256, gray_256, CV_RGB2GRAY); // this mask gets anything kind of dark (DK2) and dilates // should work *great* Mat gr_m; // gray mask equalizeHist(gray_256, gr_m); threshold(gr_m, gr_m, 215, 1, THRESH_BINARY); dilate(gr_m, gr_m, ellipticKernel(23)); erode(gr_m, gr_m, ellipticKernel(45)); // imshow("gray mask", gray_256.mul(1-gr_m)); bitwise_or(acbg_m, gr_m, acbg_m); // imshow("accumulated bg mask", gray_256.mul(1-acbg_m)); // this mask watches for flow against accumulated bg Mat fl_m; // flow mask absdiff(img_256, acbg, fl_m); cvtColor(fl_m, fl_m, CV_BGR2GRAY); fl_m = acbg_m.mul(fl_m); threshold(fl_m, fl_m, 45, 1, THRESH_BINARY_INV); erode(fl_m, fl_m, ellipticKernel(51)); // imshow("flow mask", fl_m*255); Mat bg_m; bitwise_and(acbg_m, fl_m, bg_m); bitwise_or(gr_m, bg_m, bg_m); // imshow("bgm", bg_m*255); // maybe do some morphological operations on bg_m? // previously combined bg_m with its opening // ugly way to compute: // acbg = [acbg'.(1-bg_m)]+[((acbg'+img_256)/2).bg_m] // find a nicer way later // problem is masks are 1 channel while images are 3 channel Mat bg_m3; Mat tmp0[3]; tmp0[0] = tmp0[1] = tmp0[2] = bg_m; merge(tmp0, 3, bg_m3); // imshow("bg_m3", bg_m3*255); acbg = acbg.mul(Scalar(1,1,1)-bg_m3) + (acbg/2+img_256/2).mul(bg_m3); // imshow("acbg", acbg); // imshow("bg mask", gray_256.mul(1-bg_m)); Mat df_m; // delta flow mask absdiff(img_256, img_256_p, df_m); cvtColor(df_m, df_m, CV_BGR2GRAY); blur(df_m, df_m, Size(10, 10)); threshold(df_m, df_m, 5, 1, THRESH_BINARY); dilate(df_m, df_m, ellipticKernel(25, 25)); erode(df_m, df_m, ellipticKernel(25, 25)); img_256_p = img_256.clone(); delta_flows[3] = delta_flows[2]; delta_flows[2] = delta_flows[1]; delta_flows[1] = delta_flows[0]; delta_flows[0] = df_m.clone(); bitwise_or(df_m, delta_flows[3], df_m); bitwise_or(df_m, delta_flows[2], df_m); bitwise_or(df_m, delta_flows[1], df_m); Mat fg_m; bitwise_or(haar_t_p, df_m, fg_m); Mat haar_m; bitwise_and(1 - bg_m, fg_m, haar_m); // run haar classifier Mat gray_haar; resize(gray, gray_haar, Size(width/haar_scale, height/haar_scale)); equalizeHist(gray_haar, gray_haar); vector<Rect> mouth_rects; resize(haar_m, haar_m, Size(width/haar_scale, height/haar_scale)); gray_haar = gray_haar.mul(haar_m); mouth_cascade.detectMultiScale(gray_haar, mouth_rects, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat fg(height, width, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouth_rects.size(); i++) { Rect scaled(mouth_rects[i].x*haar_scale, mouth_rects[i].y*haar_scale, mouth_rects[i].width*haar_scale,mouth_rects[i].height*haar_scale); Mat new_rect(height, width, CV_8UC1, Scalar(0)); rectangle(new_rect, scaled, Scalar(1), CV_FILLED); fg += new_rect; } // or maybe equalize? this whole thing needs to be rewritten // with the new fg and temporal coherence ideas // very interesting idea: // if nothing moved in some place over the past frame, // and nothing was detected last frame, whatever is // detected now is more likely to be bogus acfg = acfg*0.2 + fg; double min_val, max_val; minMaxLoc(fg, &min_val, &max_val); Mat rect_thresh; threshold(acfg, rect_thresh, max_val*0.9, 1, THRESH_BINARY); imshow("mouth", rect_thresh.mul(gray)); resize(acfg, haar_t_p, Size(256, 256)); if (max_val < 10) max_val = 10; threshold(haar_t_p, haar_t_p, max_val*0.1, 1, THRESH_BINARY); /* Moments m = moments(rect_thresh, 1); circle(image, Point(m.m10/m.m00,m.m01/m.m00),20,Scalar(128),30); imshow("centroid", image); */ keep_going = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" #include <chrono> using namespace cv; using namespace std; Mat ellipticKernel(int width, int height = -1) { if (height==-1) { return getStructuringElement(MORPH_ELLIPSE,Size(width,width), Point(width/2, width/2)); } else { return getStructuringElement(MORPH_ELLIPSE,Size(width,height), Point(width/2, height/2)); } } unsigned long long getMilliseconds() { return chrono::system_clock::now().time_since_epoch()/chrono::milliseconds(1); } int main (int argc, char** argv) { /***** begin camera setup *****/ CvCapture* capture = 0; int width, height; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream config_file (".config"); if (config_file.is_open()) { // does not support corrupted .config string line; getline(config_file, line); istringstream(line)>>width; getline(config_file, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); config_file.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream config_file_out(".config"); config_file_out << width; config_file_out << "\n"; config_file_out << height; config_file_out << "\n"; config_file_out.close(); } for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } /***** end camera setup *****/ /***** filter setup *****/ Mat acbg(256, 256, CV_8UC3, Scalar(0,0,0)); // accumulated background Mat acbg_m(256, 256, CV_8UC1, Scalar(0)); // accumulated background mask int haar_scale = width/300; if (haar_scale < 1) haar_scale = 1; // can't use 256x256 since haar isn't stretch invariant Mat acfg(height, width, CV_8UC1, Scalar(0)); // accumulated foreground Mat img_256_p(256, 256, CV_8UC3, Scalar(0,0,0)); // previous image Mat delta_flows[4]; delta_flows[0] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[1] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[2] = Mat(256, 256, CV_8UC1, Scalar(1)); delta_flows[3] = Mat(256, 256, CV_8UC1, Scalar(1)); // delta of past 3 frames Mat haar_t_p(256, 256, CV_8UC1, Scalar(1)); // previous possible locations for mouth /***** end filter setup *****/ /***** misc *****/ unsigned long long times[100]; for (int i=0; i<100; i++) times[i] = 0; int tracker1, tracker2, tracker3, tracker4; namedWindow("settings",1); createTrackbar("1","settings",&tracker1,100); createTrackbar("2","settings",&tracker2,100); createTrackbar("3","settings",&tracker3,100); createTrackbar("4","settings",&tracker4,100); unsigned long long timenow = getMilliseconds(); bool keep_going = true; CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); /***** begin filter loop *****/ while (keep_going) { Mat image(cvQueryFrame(capture)); // imshow("webcam", image); // at some point preprocess by rotating according to OVR roll // right now really annoying because of state variables Mat gray, img_256, gray_256; resize(image, img_256, Size(256, 256)); cvtColor(image, gray, CV_RGB2GRAY); cvtColor(img_256, gray_256, CV_RGB2GRAY); // this mask gets anything kind of dark (DK2) and dilates // should work *great* Mat gr_m; // gray mask equalizeHist(gray_256, gr_m); threshold(gr_m, gr_m, 215, 1, THRESH_BINARY); dilate(gr_m, gr_m, ellipticKernel(23)); erode(gr_m, gr_m, ellipticKernel(45)); // imshow("gray mask", gray_256.mul(1-gr_m)); bitwise_or(acbg_m, gr_m, acbg_m); // imshow("accumulated bg mask", gray_256.mul(1-acbg_m)); // this mask watches for flow against accumulated bg Mat fl_m; // flow mask absdiff(img_256, acbg, fl_m); cvtColor(fl_m, fl_m, CV_BGR2GRAY); fl_m = acbg_m.mul(fl_m); threshold(fl_m, fl_m, 45, 1, THRESH_BINARY_INV); erode(fl_m, fl_m, ellipticKernel(51)); // imshow("flow mask", fl_m*255); Mat bg_m; bitwise_and(acbg_m, fl_m, bg_m); bitwise_or(gr_m, bg_m, bg_m); // imshow("bgm", bg_m*255); // maybe do some morphological operations on bg_m? // previously combined bg_m with its opening // ugly way to compute: // acbg = [acbg'.(1-bg_m)]+[((acbg'+img_256)/2).bg_m] // find a nicer way later // problem is masks are 1 channel while images are 3 channel Mat bg_m3; Mat tmp0[3]; tmp0[0] = tmp0[1] = tmp0[2] = bg_m; merge(tmp0, 3, bg_m3); // imshow("bg_m3", bg_m3*255); acbg = acbg.mul(Scalar(1,1,1)-bg_m3) + (acbg/2+img_256/2).mul(bg_m3); // imshow("acbg", acbg); // imshow("bg mask", gray_256.mul(1-bg_m)); Mat df_m; // delta flow mask absdiff(img_256, img_256_p, df_m); cvtColor(df_m, df_m, CV_BGR2GRAY); blur(df_m, df_m, Size(10, 10)); threshold(df_m, df_m, 5, 1, THRESH_BINARY); dilate(df_m, df_m, ellipticKernel(25, 25)); erode(df_m, df_m, ellipticKernel(25, 25)); img_256_p = img_256.clone(); delta_flows[3] = delta_flows[2]; delta_flows[2] = delta_flows[1]; delta_flows[1] = delta_flows[0]; delta_flows[0] = df_m.clone(); bitwise_or(df_m, delta_flows[3], df_m); bitwise_or(df_m, delta_flows[2], df_m); bitwise_or(df_m, delta_flows[1], df_m); Mat fg_m; bitwise_or(haar_t_p, df_m, fg_m); Mat haar_m; bitwise_and(1 - bg_m, fg_m, haar_m); // run haar classifier Mat gray_haar; resize(gray, gray_haar, Size(width/haar_scale, height/haar_scale)); equalizeHist(gray_haar, gray_haar); vector<Rect> mouth_rects; resize(haar_m, haar_m, Size(width/haar_scale, height/haar_scale)); gray_haar = gray_haar.mul(haar_m); mouth_cascade.detectMultiScale(gray_haar, mouth_rects, 1.1, 0, CV_HAAR_SCALE_IMAGE); Mat fg(height, width, CV_8UC1, Scalar(0)); for (size_t i=0; i<mouth_rects.size(); i++) { Rect scaled(mouth_rects[i].x*haar_scale, mouth_rects[i].y*haar_scale, mouth_rects[i].width*haar_scale,mouth_rects[i].height*haar_scale); Mat new_rect(height, width, CV_8UC1, Scalar(0)); rectangle(new_rect, scaled, Scalar(1), CV_FILLED); fg += new_rect; } // or maybe equalize? this whole thing needs to be rewritten // with the new fg and temporal coherence ideas // very interesting idea: // if nothing moved in some place over the past frame, // and nothing was detected last frame, whatever is // detected now is more likely to be bogus acfg = acfg*0.2 + fg; double min_val, max_val; minMaxLoc(fg, &min_val, &max_val); Mat rect_thresh; threshold(acfg, rect_thresh, max_val*0.9, 1, THRESH_BINARY); // imshow("mouth", rect_thresh.mul(gray)); resize(acfg, haar_t_p, Size(256, 256)); if (max_val < 10) max_val = 10; threshold(haar_t_p, haar_t_p, max_val*0.1, 1, THRESH_BINARY); Moments m = moments(rect_thresh, 1); circle(image, Point(m.m10/m.m00,m.m01/m.m00),20,Scalar(128),30); imshow("centroid", image); keep_going = (waitKey(1)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before>#include "StdAfx.h" #include "settings_page.h" #include "settings.h" namespace App { bool SettingsPage::PerformOnInitDialog() { App::Settings* pSet = dynamic_cast<App::Settings*>(Parent()); COND_STRICT(pSet, Err::CriticalError, TX("Settings page had an invalid parent.")); Move(pSet->GetPagePosition()); if (!PerformOnInitPage()) return false; return true; } } <commit_msg>Removed cond_strict garbage<commit_after>#include "StdAfx.h" #include "settings_page.h" #include "settings.h" namespace App { bool SettingsPage::PerformOnInitDialog() { auto* pSet = dynamic_cast<App::Settings*>(Parent()); if (pSet == nullptr) { DO_THROW(Err::CriticalError, TX("Settings page had an invalid parent.")); } Move(pSet->GetPagePosition()); if (!PerformOnInitPage()) return false; return true; } } <|endoftext|>
<commit_before>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); imshow("background", background); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray; cvtColor(image, gray, CV_RGB2GRAY); // this mask filters out areas with too many edges Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; blur(image, flow, Size(50,50)); absdiff(flow, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); // blur(flow, flow, Size(tracker1+1,tracker1+1)); // equalizeHist(flow, flow); int factor = ((tracker1)+1)/5; Mat flowKernel = getStructuringElement(MORPH_ELLIPSE, Size( width/factor+(1-(width/factor)%2), height/factor+(1-(height/factor)%2) ) ); imshow("FLOW1", flow); waitKey(1); dilate(flow, flow, flowKernel); imshow("FLOW1.5", flow); waitKey(1); threshold(flow, flow, tracker2*3, 1, THRESH_BINARY); imshow("FLOW2", gray.mul(flow)); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); /* CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis; bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <commit_msg>hacking<commit_after>#include "webcam.hpp" using namespace cv; using namespace std; int main (int argc, char** argv) { int tracker1, tracker2, tracker3; namedWindow("s",1); createTrackbar("1","s",&tracker1,100); createTrackbar("2","s",&tracker2,100); createTrackbar("3","s",&tracker3,100); CvCapture* capture = 0; int width, height, fps; capture = cvCaptureFromCAM(0); if (!capture) { printf("No camera detected!"); return -1; } ifstream configFile (".config"); if (configFile.is_open()) { //probably want to support corrupted .config string line; getline(configFile, line); istringstream(line)>>width; getline(configFile, line); istringstream(line)>>height; cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, height); configFile.close(); } else { initResolutions(); for (int i=36; i<150; i++) { cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, resolutions[i].width); cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, resolutions[i].height); } width = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH); height = cvGetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT); ofstream configFileOut(".config"); configFileOut << width; configFileOut << "\n"; configFileOut << height; configFileOut << "\n"; configFileOut.close(); } bool keepGoing = true; // srand(890);//not interested in good randomness for (int i = 0; i < 30; i++) { // capture some frames so exposure correction takes place cvQueryFrame(capture); } Mat background = cvQueryFrame(capture); background = background.clone(); blur(background, background, Size(50,50)); imshow("background", background); Mat image; Mat channel[3]; while (keepGoing) { image = cvQueryFrame(capture); // preprocess by rotating according to OVR roll imshow("webcam", image); // let's make multiple masks where 0=not mouth, 1=uncertain // then multiply them together and multiply that with image // and run haar classifier on image Mat gray; cvtColor(image, gray, CV_RGB2GRAY); // this mask filters out areas with too many edges Mat canny; Canny(gray, canny, 50, 50, 3); blur(canny, canny, Size(width/20,height/20)); bitwise_not(canny, canny); threshold(canny, canny, 200, 1, THRESH_BINARY); blur(canny*255, canny, Size(width/10, height/10)); threshold(canny, canny, 220, 1, THRESH_BINARY); // this mask filters out areas which have not changed much // background needs to be updated when person is not in frame // use OVR SDK to do this later Mat flow; blur(image, flow, Size(50,50)); absdiff(flow, background, flow); cvtColor(flow, flow, CV_RGB2GRAY); // blur(flow, flow, Size(tracker1+1,tracker1+1)); // equalizeHist(flow, flow); int factor = (tracker1/5) + 1; Mat flowKernel = getStructuringElement(MORPH_ELLIPSE, Size( width/factor+(1-(width/factor)%2), height/factor+(1-(height/factor)%2) ) ); imshow("FLOW1", flow); waitKey(1); dilate(flow, flow, flowKernel); imshow("FLOW1.5", flow); waitKey(1); threshold(flow, flow, tracker2*3, 1, THRESH_BINARY); imshow("FLOW2", gray.mul(flow)); // Moments lol = moments(mask, 1); // circle(image, Point(lol.m10/lol.m00,lol.m01/lol.m00),20,Scalar(128),30); // imshow("leimage", image); /* CascadeClassifier mouth_cascade; mouth_cascade.load("Mouth.xml"); vector<Rect> mouths; Mat classifyThis; bilateralFilter(gray, classifyThis, 15, 10, 1); equalizeHist(classifyThis, classifyThis); classifyThis = classifyThis.mul(mask); mouth_cascade.detectMultiScale(classifyThis, mouths, 1.1, 2, CV_HAAR_SCALE_IMAGE); for (size_t i=0; i<mouths.size(); i++) { Point center( mouths[i].x + mouths[i].width*0.5, mouths[i].y + mouths[i].height*0.5 ); ellipse( image, center, Size( mouths[i].width*0.5, mouths[i].height*0.5), 0, 0, 360, Scalar( 255, 0, 255 ), 4, 8, 0 ); } imshow("MOUTH", image); */ keepGoing = (waitKey(25)<0); } cvReleaseCapture(&capture); return 0; } <|endoftext|>
<commit_before> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkBitmapFactory.h" #include "SkImage.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkMovie.h" class SkColorTable; class SkStream; class SkStreamRewindable; // Empty implementations for SkImageDecoder. SkImageDecoder::SkImageDecoder() {} SkImageDecoder::~SkImageDecoder() {} SkImageDecoder* SkImageDecoder::Factory(SkStreamRewindable*) { return NULL; } void SkImageDecoder::copyFieldsToOther(SkImageDecoder* ) {} bool SkImageDecoder::DecodeFile(const char[], SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::decode(SkStream*, SkBitmap*, SkBitmap::Config, Mode) { return false; } bool SkImageDecoder::DecodeStream(SkStreamRewindable*, SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::DecodeMemory(const void*, size_t, SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::buildTileIndex(SkStreamRewindable*, int *width, int *height) { return false; } bool SkImageDecoder::decodeSubset(SkBitmap*, const SkIRect&, SkBitmap::Config) { return false; } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } SkImageDecoder::Format SkImageDecoder::GetStreamFormat(SkStreamRewindable*) { return kUnknown_Format; } const char* SkImageDecoder::GetFormatName(Format) { return NULL; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker*) { return NULL; } SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser*) { return NULL; } SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator*) { return NULL; } void SkImageDecoder::setSampleSize(int) {} bool SkImageDecoder::DecodeMemoryToTarget(const void*, size_t, SkImageInfo*, const SkBitmapFactory::Target*) { return false; } SkBitmap::Config SkImageDecoder::GetDeviceConfig() { return SkBitmap::kNo_Config; } void SkImageDecoder::SetDeviceConfig(SkBitmap::Config) {} bool SkImageDecoder::cropBitmap(SkBitmap*, SkBitmap*, int, int, int, int, int, int, int) { return false; } bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config, int, int) const { return false; } bool SkImageDecoder::allocPixelRef(SkBitmap*, SkColorTable*) const { return false; } SkBitmap::Config SkImageDecoder::getPrefConfig(SrcDepth, bool) const { return SkBitmap::kNo_Config; } ///////////////////////////////////////////////////////////////////////// // Empty implementation for SkMovie. SkMovie* SkMovie::DecodeStream(SkStreamRewindable* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// // Empty implementations for SkImageEncoder. SkImageEncoder* SkImageEncoder::Create(Type t) { return NULL; } bool SkImageEncoder::EncodeFile(const char file[], const SkBitmap&, Type, int quality) { return false; } bool SkImageEncoder::EncodeStream(SkWStream*, const SkBitmap&, SkImageEncoder::Type, int) { return false; } SkData* SkImageEncoder::EncodeData(const SkBitmap&, Type, int quality) { return NULL; } bool SkImageEncoder::encodeStream(SkWStream*, const SkBitmap&, int) { return false; } SkData* SkImageEncoder::encodeData(const SkBitmap&, int) { return NULL; } bool SkImageEncoder::encodeFile(const char file[], const SkBitmap& bm, int quality) { return false; } ///////////////////////////////////////////////////////////////////////// // Empty implementation for SkImages. #include "SkImages.h" void SkImages::InitializeFlattenables() {} <commit_msg>Fix change src/ports/SkImageDecoder_empty.cpp missed in 103033002<commit_after> /* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBitmap.h" #include "SkImage.h" #include "SkImageDecoder.h" #include "SkImageEncoder.h" #include "SkMovie.h" class SkColorTable; class SkStream; class SkStreamRewindable; // Empty implementations for SkImageDecoder. SkImageDecoder::SkImageDecoder() {} SkImageDecoder::~SkImageDecoder() {} SkImageDecoder* SkImageDecoder::Factory(SkStreamRewindable*) { return NULL; } void SkImageDecoder::copyFieldsToOther(SkImageDecoder* ) {} bool SkImageDecoder::DecodeFile(const char[], SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::decode(SkStream*, SkBitmap*, SkBitmap::Config, Mode) { return false; } bool SkImageDecoder::DecodeStream(SkStreamRewindable*, SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::DecodeMemory(const void*, size_t, SkBitmap*, SkBitmap::Config, SkImageDecoder::Mode, SkImageDecoder::Format*) { return false; } bool SkImageDecoder::buildTileIndex(SkStreamRewindable*, int *width, int *height) { return false; } bool SkImageDecoder::decodeSubset(SkBitmap*, const SkIRect&, SkBitmap::Config) { return false; } SkImageDecoder::Format SkImageDecoder::getFormat() const { return kUnknown_Format; } SkImageDecoder::Format SkImageDecoder::GetStreamFormat(SkStreamRewindable*) { return kUnknown_Format; } const char* SkImageDecoder::GetFormatName(Format) { return NULL; } SkImageDecoder::Peeker* SkImageDecoder::setPeeker(Peeker*) { return NULL; } SkImageDecoder::Chooser* SkImageDecoder::setChooser(Chooser*) { return NULL; } SkBitmap::Allocator* SkImageDecoder::setAllocator(SkBitmap::Allocator*) { return NULL; } void SkImageDecoder::setSampleSize(int) {} bool SkImageDecoder::DecodeMemoryToTarget(const void*, size_t, SkImageInfo*, const SkImageDecoder::Target*) { return false; } SkBitmap::Config SkImageDecoder::GetDeviceConfig() { return SkBitmap::kNo_Config; } void SkImageDecoder::SetDeviceConfig(SkBitmap::Config) {} bool SkImageDecoder::cropBitmap(SkBitmap*, SkBitmap*, int, int, int, int, int, int, int) { return false; } bool SkImageDecoder::chooseFromOneChoice(SkBitmap::Config, int, int) const { return false; } bool SkImageDecoder::allocPixelRef(SkBitmap*, SkColorTable*) const { return false; } SkBitmap::Config SkImageDecoder::getPrefConfig(SrcDepth, bool) const { return SkBitmap::kNo_Config; } ///////////////////////////////////////////////////////////////////////// // Empty implementation for SkMovie. SkMovie* SkMovie::DecodeStream(SkStreamRewindable* stream) { return NULL; } ///////////////////////////////////////////////////////////////////////// // Empty implementations for SkImageEncoder. SkImageEncoder* SkImageEncoder::Create(Type t) { return NULL; } bool SkImageEncoder::EncodeFile(const char file[], const SkBitmap&, Type, int quality) { return false; } bool SkImageEncoder::EncodeStream(SkWStream*, const SkBitmap&, SkImageEncoder::Type, int) { return false; } SkData* SkImageEncoder::EncodeData(const SkBitmap&, Type, int quality) { return NULL; } bool SkImageEncoder::encodeStream(SkWStream*, const SkBitmap&, int) { return false; } SkData* SkImageEncoder::encodeData(const SkBitmap&, int) { return NULL; } bool SkImageEncoder::encodeFile(const char file[], const SkBitmap& bm, int quality) { return false; } ///////////////////////////////////////////////////////////////////////// // Empty implementation for SkImages. #include "SkImages.h" void SkImages::InitializeFlattenables() {} <|endoftext|>
<commit_before>#include "GPU.H" #include "CAMERA.H" #include "LOAD_LEV.H" #include "PROFILE.H" #include "SHADOWS.H" #include "SPECIFIC.H" #include <assert.h> #include <LIBGPU.H> #include <LIBETC.H> unsigned long GnFrameCounter = 19; unsigned long GnLastFrameCount = 19; struct PSXTEXTSTRUCT* psxtextinfo; struct PSXSPRITESTRUCT* psxspriteinfo; int rgbscaleme = 256; int gfx_debugging_mode; struct DB_STRUCT db; struct MMTEXTURE* RoomTextInfo; unsigned long GadwOrderingTables_V2[512]; static int LnFlipFrame; unsigned long GadwOrderingTables[5128]; unsigned long GadwPolygonBuffers[52260]; void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) { #if 0 db.order_table[0] = &pBuffers[0]; db.order_table[1] = &pBuffers[nOTSize]; db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)&db.disp[1]; db.pickup_order_table[1] = &GadwOrderingTables_V2[256]; #else //Should be safe to use 32-bit ptrs tho db.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF); db.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF); db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF); db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF); #endif return; } void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<), { #if 0 db.nPBSize = nPBSize; db.poly_buffer[0] = &pBuffers[0]; db.poly_buffer[1] = &pBuffers[nPBSize]; #else db.nPBSize = nPBSize; db.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF); db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF); #endif return; } void GPU_EndScene()//5DFDC(<), 5F23C(<) (F) { #if DEBUG_VERSION int nPolys; static int nWorstPolys; nPolys = ((int) &db.polyptr[0] - (int) &db.curpolybuf[0]) * 0x4EC4EC4F / 16 - (((long) &db.polyptr[0] - (long) &db.curpolybuf[0]) >> 31); if (psxtextinfo->u2v2pad < nPolys) { psxtextinfo->u2v2pad = nPolys; } //loc_5E020 #endif OptimiseOTagR(&db.ot[0], db.nOTSize); #if DEBUG_VERSION ProfileRGB(255, 255, 255); do_gfx_debug_mode(&db.ot[db.nOTSize - 1]); ProfileRGB(0, 255, 255); #endif return; } int GPU_FlipNoIdle()//5E078(<), 5F264(<) (F) { #if DEBUG_VERSION if (ProfileDraw) { ProfileRGB(255, 255, 255); ProfileAddOT(&db.ot[0]); } #endif //loc_5E0B0 DrawSync(0); #if DEBUG_VERSION if (ProfileDraw) { ProfileAddDrawOT(&db.ot[0]); } #endif LnFlipFrame = GnLastFrameCount; //loc_5E0D8 if (LnFlipFrame < 2) { do { VSync(0); LnFlipFrame++; } while (LnFlipFrame < 2); } else { //loc_5E120 VSync(0); LnFlipFrame++; } GnLastFrameCount = 0; PutDispEnv(&db.disp[db.current_buffer]); DrawOTagEnv(&db.ot[db.nOTSize-1], &db.draw[db.current_buffer]); #if DEBUG_VERSION ProfileStartCount(); #endif db.current_buffer ^= 1; return LnFlipFrame; } void do_gfx_debug_mode(unsigned long* otstart) { S_Warn("[do_gfx_debug_mode] - Unimplemented!\n"); } void GPU_FlipStory(unsigned long* gfx)//5E448(<), * (F) { RECT r; RECT* fuckmyanalpassage; DrawSync(0); VSync(0); PutDispEnv(&db.disp[db.current_buffer]); fuckmyanalpassage = (RECT*) &db.disp[db.current_buffer ^ 1].disp; r.x = fuckmyanalpassage->x; r.y = fuckmyanalpassage->y; r.w = fuckmyanalpassage->w; r.h = fuckmyanalpassage->h; LoadImage(&r, gfx); DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]); db.current_buffer ^= 1; }<commit_msg>Add do_gfx_debug_mode()<commit_after>#include "GPU.H" #include "CAMERA.H" #include "FXTRIG.H" #include "LOAD_LEV.H" #include "PROFILE.H" #include "PSXINPUT.H" #include "SHADOWS.H" #include "SPECIFIC.H" #include <assert.h> #include <LIBGPU.H> #include <LIBETC.H> #include <STDIO.H> unsigned long GnFrameCounter = 19; unsigned long GnLastFrameCount = 19; struct PSXTEXTSTRUCT* psxtextinfo; struct PSXSPRITESTRUCT* psxspriteinfo; int rgbscaleme = 256; int gfx_debugging_mode; struct DB_STRUCT db; struct MMTEXTURE* RoomTextInfo; unsigned long GadwOrderingTables_V2[512]; static int LnFlipFrame; unsigned long GadwOrderingTables[5128]; unsigned long GadwPolygonBuffers[52260]; void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) { #if 0 db.order_table[0] = &pBuffers[0]; db.order_table[1] = &pBuffers[nOTSize]; db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)&db.disp[1]; db.pickup_order_table[1] = &GadwOrderingTables_V2[256]; #else //Should be safe to use 32-bit ptrs tho db.order_table[0] = (unsigned long*)((unsigned long) pBuffers & 0xFFFFFF); db.order_table[1] = (unsigned long*)((unsigned long) &pBuffers[nOTSize] & 0xFFFFFF); db.nOTSize = nOTSize; db.pickup_order_table[0] = (unsigned long*)((unsigned long)&db.disp[1] & 0xFFFFFF); db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256] & 0xFFFFFF); #endif return; } void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<), { #if 0 db.nPBSize = nPBSize; db.poly_buffer[0] = &pBuffers[0]; db.poly_buffer[1] = &pBuffers[nPBSize]; #else db.nPBSize = nPBSize; db.poly_buffer[0] = (unsigned long*)((unsigned long)pBuffers & 0xFFFFFF); db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize] & 0xFFFFFF); #endif return; } void GPU_EndScene()//5DFDC(<), 5F23C(<) (F) { #if DEBUG_VERSION int nPolys; static int nWorstPolys; nPolys = ((int) &db.polyptr[0] - (int) &db.curpolybuf[0]) * 0x4EC4EC4F / 16 - (((long) &db.polyptr[0] - (long) &db.curpolybuf[0]) >> 31); if (psxtextinfo->u2v2pad < nPolys) { psxtextinfo->u2v2pad = nPolys; } //loc_5E020 #endif OptimiseOTagR(&db.ot[0], db.nOTSize); #if DEBUG_VERSION ProfileRGB(255, 255, 255); do_gfx_debug_mode(&db.ot[db.nOTSize - 1]); ProfileRGB(0, 255, 255); #endif return; } int GPU_FlipNoIdle()//5E078(<), 5F264(<) (F) { #if DEBUG_VERSION if (ProfileDraw) { ProfileRGB(255, 255, 255); ProfileAddOT(&db.ot[0]); } #endif //loc_5E0B0 DrawSync(0); #if DEBUG_VERSION if (ProfileDraw) { ProfileAddDrawOT(&db.ot[0]); } #endif LnFlipFrame = GnLastFrameCount; //loc_5E0D8 if (LnFlipFrame < 2) { do { VSync(0); LnFlipFrame++; } while (LnFlipFrame < 2); } else { //loc_5E120 VSync(0); LnFlipFrame++; } GnLastFrameCount = 0; PutDispEnv(&db.disp[db.current_buffer]); DrawOTagEnv(&db.ot[db.nOTSize-1], &db.draw[db.current_buffer]); #if DEBUG_VERSION ProfileStartCount(); #endif db.current_buffer ^= 1; return LnFlipFrame; } void do_gfx_debug_mode(unsigned long* otstart)//5E1B4(<) ? (F) { unsigned long* data; unsigned char code; int ntri; int nquad; unsigned short x0; unsigned short y0; unsigned short x1; unsigned short y1; unsigned short x2; unsigned short y2; LINE_F2* line2; char txbuf[64]; if (RawEdge & 8) { gfx_debugging_mode++; } //loc_5E1E0 nquad = 0; if (gfx_debugging_mode > 2) { gfx_debugging_mode = 0; } //loc_5E1F8 data = (unsigned long*)otstart[0]; ntri = 0; if (((unsigned long)data & 0xFFFFFF) != 0xFFFFFF) { do { if (data[0] & 0xFF000000 != 0) { code = ((char*)data)[7]; if (gfx_debugging_mode < 2) { if ((code & 0xFC) == 0x7C) { if (gfx_debugging_mode != 0) { ((short*)data)[13] &= 0xFF9F; } else { //loc_5E27C ((char*)data)[7] = (code & 2) | 0x3C; } nquad = 1; } else if ((code & 0xFC) == 0x74) { //loc_5E290 if (gfx_debugging_mode != 0) { ((char*)data)[7] = 0x36; ((short*)data)[13] &= 0xFF9F; } else { //loc_5E2B4 ((char*)data)[7] = (code & 2) | 0x34; } ntri = 1; }//loc_5E3C4 } else if (gfx_debugging_mode == 2) { //loc_5E2C8 if ((code & 0xFC) == 0x7C) { x0 = ((unsigned short*)data)[4]; y0 = ((unsigned short*)data)[5]; x1 = ((unsigned short*)data)[10]; y1 = ((unsigned short*)data)[11]; x2 = ((unsigned short*)data)[16]; y2 = ((unsigned short*)data)[17]; nquad++; ((char*)data)[7] = 0x4C; ((char*)data)[4] = 0x0; ((char*)data)[5] = 0x50; ((char*)data)[6] = 0x0; ((long*)data)[6] = 0x55555555; ((short*)data)[8] = ((unsigned short*)data)[22]; line2 = (struct LINE_F2*)&data[6]; ((short*)data)[9] = ((unsigned short*)data)[23]; ((short*)data)[4] = x0; ((short*)data)[5] = y0; ((short*)data)[6] = x1; ((short*)data)[7] = y1; ((short*)data)[10] = x2; ((short*)data)[11] = y2; line2->code = 0x40; line2->x0 = x0; line2->y0 = y0; line2->x1 = x2; line2->y1 = y2; line2->r0 = 0; line2->g0 = 80; line2->b0 = 0; ((char*)data)[3] = 9; } else if ((code & 0xFC) == 0x74) { //loc_5E368 ntri++; x0 = ((unsigned short*)data)[4]; y0 = ((unsigned short*)data)[5]; x1 = ((unsigned short*)data)[10]; y1 = ((unsigned short*)data)[11]; x2 = ((unsigned short*)data)[16]; y2 = ((unsigned short*)data)[17]; ((char*)data)[7] = 76; ((char*)data)[4] = 0; ((char*)data)[5] = 80; ((char*)data)[6] = 0; ((long*)data)[6] = 0x55555555; ((char*)data)[3] = 6; ((short*)data)[4] = x0; ((short*)data)[5] = y0; ((short*)data)[6] = x1; ((short*)data)[7] = y1; ((short*)data)[8] = x2; ((short*)data)[9] = y2; ((short*)data)[10] = x0; ((short*)data)[11] = y0; } }//loc_5E3C4 } }while (data[0] != 0xFFFFFF); //loc_5E3C4 } //loc_5E3D8 if (gfx_debugging_mode == 0) { return; } sprintf(&txbuf[0], "TRI %d", ntri); PrintString(34, 220, 3, &txbuf[0], 0); sprintf(&txbuf[0], "QUAD %d", nquad); PrintString(34, 232, 3, &txbuf[0], 0); } void GPU_FlipStory(unsigned long* gfx)//5E448(<), * (F) { RECT r; RECT* fuckmyanalpassage; DrawSync(0); VSync(0); PutDispEnv(&db.disp[db.current_buffer]); fuckmyanalpassage = (RECT*) &db.disp[db.current_buffer ^ 1].disp; r.x = fuckmyanalpassage->x; r.y = fuckmyanalpassage->y; r.w = fuckmyanalpassage->w; r.h = fuckmyanalpassage->h; LoadImage(&r, gfx); DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]); db.current_buffer ^= 1; }<|endoftext|>
<commit_before>/* *The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * 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. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE http_connection_tests #include <boost/test/unit_test.hpp> #include <errno.h> #include "buffered_socket.h" #include "eventloop.h" #include "http_connection.h" #include "socket.h" #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)) #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif static bool close_called = false; static bool create_called = false; static const char *readbuffer; static const char *readbuffer_ptr; static size_t readbuffer_length; static char write_buffer[5000]; size_t write_buffer_written; static char *write_buffer_ptr; static const int FD_WOULDBLOCK = 1; static const int FD_COMPLETE_STARTLINE = 2; static const int FD_CLOSE = 3; static const int FD_ERROR = 4; extern "C" { ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count) { (void)io_vec; (void)count; switch (sock) { case FD_COMPLETE_STARTLINE: { size_t complete_length = 0; for (unsigned int i = 0; i < count; i++) { memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len); complete_length += io_vec[i].iov_len; write_buffer_ptr += io_vec[i].iov_len; } write_buffer_written = complete_length; return complete_length; } case FD_WOULDBLOCK: default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_read(socket_type sock, void *buf, size_t count) { (void)buf; (void)count; switch (sock) { case FD_COMPLETE_STARTLINE: if (readbuffer_length > 0) { size_t len = MIN(readbuffer_length, count); memcpy(buf, readbuffer_ptr, len); readbuffer_length -= len; readbuffer_ptr += len; return len; } else { errno = EWOULDBLOCK; return -1; } break; case FD_CLOSE: return 0; case FD_ERROR: errno = EINVAL; return -1; case FD_WOULDBLOCK: default: errno = EWOULDBLOCK; return -1; } } int socket_close(socket_type sock) { (void)sock; close_called = true; return 0; } } static enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; return EL_CONTINUE_LOOP; } static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; } int on_create(struct http_connection *connection) { (void)connection; create_called = true; return 0; } struct F { F() { close_called = false; create_called = false; loop.this_ptr = NULL; loop.init = NULL; loop.destroy = NULL; loop.run = NULL; loop.add = eventloop_fake_add; loop.remove = eventloop_fake_remove; readbuffer_ptr = readbuffer; write_buffer_ptr = write_buffer; write_buffer_written = 0; http_parser_settings_init(&parser_settings); http_parser_init(&parser, HTTP_RESPONSE); handler[0].request_target = "/"; handler[0].create = NULL; handler[0].on_header_field = NULL; handler[0].on_header_value = NULL; handler[0].on_headers_complete = NULL; handler[0].on_body = NULL; handler[0].on_message_complete = NULL; http_server.handler = handler; http_server.num_handlers = ARRAY_SIZE(handler); } ~F() { } struct eventloop loop; http_parser parser; http_parser_settings parser_settings; struct url_handler handler[1]; struct http_server http_server; }; BOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F) { struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false); BOOST_CHECK_MESSAGE(connection != NULL, "Connection allocation failed!"); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F) { struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false); BOOST_CHECK(connection != NULL); struct buffered_socket *bs = connection->bs; connection->bs = NULL; free_connection(connection); BOOST_CHECK_MESSAGE(!close_called, "Close was called after buffered_socket migration!"); buffered_socket_close(bs); free(bs); BOOST_CHECK_MESSAGE(close_called, "Close was not called after buffered_socket_close!"); } BOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_close, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_error, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F) { readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection != NULL); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F) { handler[0].create = on_create; readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection != NULL); BOOST_CHECK_MESSAGE(create_called, "Create callback was not called!"); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F) { handler[0].request_target = "/foobar/"; readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 404); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F) { handler[0].request_target = "/foobar/"; readbuffer = "GET http://ww%.google.de/ HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 400); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F) { readbuffer = "CONNECT www.example.com:443 HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 400); } <commit_msg>Initialize the event structure in http_server completely.<commit_after>/* *The MIT License (MIT) * * Copyright (c) <2016> <Stephan Gatzka> * * 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. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MAIN #define BOOST_TEST_MODULE http_connection_tests #include <boost/test/unit_test.hpp> #include <errno.h> #include "buffered_socket.h" #include "eventloop.h" #include "http_connection.h" #include "socket.h" #define MIN(X, Y) (((X) < (Y)) ? (X) : (Y)) #ifndef ARRAY_SIZE #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #endif static bool close_called = false; static bool create_called = false; static const char *readbuffer; static const char *readbuffer_ptr; static size_t readbuffer_length; static char write_buffer[5000]; size_t write_buffer_written; static char *write_buffer_ptr; static const int FD_WOULDBLOCK = 1; static const int FD_COMPLETE_STARTLINE = 2; static const int FD_CLOSE = 3; static const int FD_ERROR = 4; extern "C" { ssize_t socket_writev(socket_type sock, struct buffered_socket_io_vector *io_vec, unsigned int count) { (void)io_vec; (void)count; switch (sock) { case FD_COMPLETE_STARTLINE: { size_t complete_length = 0; for (unsigned int i = 0; i < count; i++) { memcpy(write_buffer_ptr, io_vec[i].iov_base, io_vec[i].iov_len); complete_length += io_vec[i].iov_len; write_buffer_ptr += io_vec[i].iov_len; } write_buffer_written = complete_length; return complete_length; } case FD_WOULDBLOCK: default: errno = EWOULDBLOCK; return -1; } } ssize_t socket_read(socket_type sock, void *buf, size_t count) { (void)buf; (void)count; switch (sock) { case FD_COMPLETE_STARTLINE: if (readbuffer_length > 0) { size_t len = MIN(readbuffer_length, count); memcpy(buf, readbuffer_ptr, len); readbuffer_length -= len; readbuffer_ptr += len; return len; } else { errno = EWOULDBLOCK; return -1; } break; case FD_CLOSE: return 0; case FD_ERROR: errno = EINVAL; return -1; case FD_WOULDBLOCK: default: errno = EWOULDBLOCK; return -1; } } int socket_close(socket_type sock) { (void)sock; close_called = true; return 0; } } static enum eventloop_return eventloop_fake_add(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; return EL_CONTINUE_LOOP; } static void eventloop_fake_remove(const void *this_ptr, const struct io_event *ev) { (void)this_ptr; (void)ev; } int on_create(struct http_connection *connection) { (void)connection; create_called = true; return 0; } struct F { F() { close_called = false; create_called = false; loop.this_ptr = NULL; loop.init = NULL; loop.destroy = NULL; loop.run = NULL; loop.add = eventloop_fake_add; loop.remove = eventloop_fake_remove; readbuffer_ptr = readbuffer; write_buffer_ptr = write_buffer; write_buffer_written = 0; http_parser_settings_init(&parser_settings); http_parser_init(&parser, HTTP_RESPONSE); handler[0].request_target = "/"; handler[0].create = NULL; handler[0].on_header_field = NULL; handler[0].on_header_value = NULL; handler[0].on_headers_complete = NULL; handler[0].on_body = NULL; handler[0].on_message_complete = NULL; http_server.handler = handler; http_server.num_handlers = ARRAY_SIZE(handler); http_server.ev.read_function = NULL; http_server.ev.write_function = NULL; http_server.ev.error_function = NULL; http_server.ev.loop = NULL; http_server.ev.sock = 0; } ~F() { } struct eventloop loop; http_parser parser; http_parser_settings parser_settings; struct url_handler handler[1]; struct http_server http_server; }; BOOST_FIXTURE_TEST_CASE(test_websocket_alloc, F) { struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false); BOOST_CHECK_MESSAGE(connection != NULL, "Connection allocation failed!"); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_buffered_socket_migration, F) { struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_WOULDBLOCK, false); BOOST_CHECK(connection != NULL); struct buffered_socket *bs = connection->bs; connection->bs = NULL; free_connection(connection); BOOST_CHECK_MESSAGE(!close_called, "Close was called after buffered_socket migration!"); buffered_socket_close(bs); free(bs); BOOST_CHECK_MESSAGE(close_called, "Close was not called after buffered_socket_close!"); } BOOST_FIXTURE_TEST_CASE(test_read_invalid_startline, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_close, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_CLOSE, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_error, F) { readbuffer = "aaaa\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(NULL, &loop, FD_ERROR, false); BOOST_CHECK(connection == NULL); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match, F) { readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection != NULL); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_match_create_called, F) { handler[0].create = on_create; readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection != NULL); BOOST_CHECK_MESSAGE(create_called, "Create callback was not called!"); free_connection(connection); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_url_no_match, F) { handler[0].request_target = "/foobar/"; readbuffer = "GET /infotext.html HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 404); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_invalid_url, F) { handler[0].request_target = "/foobar/"; readbuffer = "GET http://ww%.google.de/ HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 400); } BOOST_FIXTURE_TEST_CASE(test_read_valid_startline_connect_request_url_match, F) { readbuffer = "CONNECT www.example.com:443 HTTP/1.1\r\n"; readbuffer_ptr = readbuffer; readbuffer_length = ::strlen(readbuffer); struct http_connection *connection = alloc_http_connection(&http_server, &loop, FD_COMPLETE_STARTLINE, false); BOOST_CHECK(connection == NULL); size_t nparsed = http_parser_execute(&parser, &parser_settings, write_buffer, write_buffer_written); BOOST_CHECK(nparsed == write_buffer_written); BOOST_CHECK(parser.status_code == 400); } <|endoftext|>
<commit_before>/** * @file /tip-server/src/tip/http/server/connection.cpp * @brief * @date Jul 8, 2015 * @author: zmij */ #include <tip/http/server/connection.hpp> #include <tip/http/server/request_handler.hpp> #include <tip/http/server/remote_address.hpp> #include <tip/http/server/reply_context.hpp> #include <tip/http/common/request.hpp> #include <tip/http/common/response.hpp> #include <tip/http/common/grammar/response_generate.hpp> #include <tip/http/version.hpp> #include <tip/log.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <functional> namespace tip { namespace http { namespace server { LOCAL_LOGGING_FACILITY(HTTPCONN, TRACE); connection::connection(io_service_ptr io_service, request_handler_ptr handler) : io_service_(io_service), strand_(*io_service), socket_(*io_service), request_handler_(handler), default_headers_{ { Server, "tip-http-server/" + tip::VERSION } } { } connection::~connection() { } boost::asio::ip::tcp::socket& connection::socket() { return socket_; } void connection::start(endpoint_ptr peer) { local_log() << "Start new connection with " << peer->address(); peer_ = peer; read_request_headers(); } void connection::read_request_headers() { boost::asio::async_read_until(socket_, incoming_, "\r\n\r\n", strand_.wrap(std::bind(&connection::handle_read_headers, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void connection::handle_read_headers(const boost::system::error_code& e, std::size_t bytes_transferred) { if (!e) { typedef boost::spirit::istream_iterator buffer_iterator; std::istream is(&incoming_); request_ptr req = std::make_shared< request >(); if (req->read_headers(is)) { read_request_body(req, req->read_body(is)); } else { // Bad request send_error(req, response_status::bad_request); local_log(logger::ERROR) << "Error parsing headers"; } } else { local_log(logger::DEBUG) << "Error reading request headers: " << e.message(); } } void connection::read_request_body(request_ptr req, read_result_type res) { using std::placeholders::_1; using std::placeholders::_2; if (res.result) { // success read io_service_ptr io = io_service_.lock(); if (io) { reply rep{ io, req, strand_.wrap(std::bind(&connection::send_response, shared_from_this(), req, std::placeholders::_1)), strand_.wrap(std::bind(&connection::send_error, shared_from_this(), req, std::placeholders::_1)) }; add_context(rep, new remote_address(rep, peer_)); try { request_handler_->handle_request(rep); } catch (::std::exception const& e) { local_log(logger::ERROR) << "Exception when dispatching request " << req->path << ": " << e.what(); } catch (...) { local_log(logger::ERROR) << "Unknown exception when dispatching request " << req->path; } } else { local_log(logger::WARNING) << "IO service weak pointer is bad"; } } else if (!res.result) { // fail read local_log(logger::WARNING) << "Failed to read request body"; send_error(req, response_status::bad_request); } else if (res.callback) { boost::asio::async_read(socket_, incoming_, boost::asio::transfer_at_least(1), strand_.wrap( std::bind( &connection::handle_read_body, shared_from_this(), _1, _2, req, res.callback) )); } else { // need more data but no callback local_log(logger::WARNING) << "Request read body returned " "indeterminate, but provided no callback"; } } void connection::handle_read_body(const boost::system::error_code& e, std::size_t bytes_transferred, request_ptr req, read_callback cb) { if (!e) { std::istream is(&incoming_); read_request_body(req, cb(is)); } else { local_log(logger::DEBUG) << "Error reading request body: " << e.message(); } // If an error occurs then no new asynchronous operations are started. This // means that all shared_ptr references to the connection object will // disappear and the object will be destroyed automatically after this // handler returns. The connection class's destructor closes the socket. } void connection::send_response(request_ptr req, response_const_ptr resp) { typedef std::vector< boost::asio::const_buffer > output_buffers_type; using std::placeholders::_1; using std::placeholders::_2; local_log() << req->method << " " << req->path << " " << resp->status << " '" << resp->status_line << "'"; if (is_error(resp->status) && (HTTPCONN_DEFAULT_SEVERITY != logger::OFF)) { local_log() << "Request headers:\n" << req->headers_; } std::ostream os(&outgoing_); os << *resp; if (!resp->headers_.count(ContentLength)) { header content_length{ ContentLength, boost::lexical_cast<std::string>( resp->body_.size() ) }; os << content_length; } if (!default_headers_.empty()) { os << default_headers_; } os << "\r\n"; output_buffers_type buffers; buffers.push_back(boost::asio::buffer(outgoing_.data())); buffers.push_back(boost::asio::buffer(resp->body_)); boost::asio::async_write(socket_, buffers, strand_.wrap(std::bind(&connection::handle_write_response, shared_from_this(), _1, _2, resp))); } void connection::send_error(request_ptr req, response_status status) { response_const_ptr resp = response::stock_response(status); send_response(req, resp); } void connection::handle_write(const boost::system::error_code& e) { if (!e) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } // TODO Keep-Alive and timer // No new asynchronous operations are started. This means that all shared_ptr // references to the connection object will disappear and the object will be // destroyed automatically after this handler returns. The connection class's // destructor closes the socket. } void connection::handle_write_response(boost::system::error_code const& e, size_t bytes_transferred, response_const_ptr resp) { if (!e) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } // TODO Keep-Alive and timer // No new asynchronous operations are started. This means that all shared_ptr // references to the connection object will disappear and the object will be // destroyed automatically after this handler returns. The connection class's // destructor closes the socket. } } // namespace server } // namespace http } // namespace tip <commit_msg>Output first 100 bytes of erroneous request to trace log<commit_after>/** * @file /tip-server/src/tip/http/server/connection.cpp * @brief * @date Jul 8, 2015 * @author: zmij */ #include <tip/http/server/connection.hpp> #include <tip/http/server/request_handler.hpp> #include <tip/http/server/remote_address.hpp> #include <tip/http/server/reply_context.hpp> #include <tip/http/common/request.hpp> #include <tip/http/common/response.hpp> #include <tip/http/common/grammar/response_generate.hpp> #include <tip/http/version.hpp> #include <tip/log.hpp> #include <boost/spirit/include/support_istream_iterator.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <functional> namespace tip { namespace http { namespace server { LOCAL_LOGGING_FACILITY(HTTPCONN, TRACE); connection::connection(io_service_ptr io_service, request_handler_ptr handler) : io_service_(io_service), strand_(*io_service), socket_(*io_service), request_handler_(handler), default_headers_{ { Server, "tip-http-server/" + tip::VERSION } } { } connection::~connection() { } boost::asio::ip::tcp::socket& connection::socket() { return socket_; } void connection::start(endpoint_ptr peer) { local_log() << "Start new connection with " << peer->address(); peer_ = peer; read_request_headers(); } void connection::read_request_headers() { boost::asio::async_read_until(socket_, incoming_, "\r\n\r\n", strand_.wrap(std::bind(&connection::handle_read_headers, shared_from_this(), std::placeholders::_1, std::placeholders::_2))); } void connection::handle_read_headers(const boost::system::error_code& e, std::size_t bytes_transferred) { if (!e) { typedef boost::spirit::istream_iterator buffer_iterator; std::istream is(&incoming_); request_ptr req = std::make_shared< request >(); if (req->read_headers(is)) { read_request_body(req, req->read_body(is)); } else { // Bad request send_error(req, response_status::bad_request); local_log(logger::ERROR) << "Error parsing headers"; } } else { local_log(logger::DEBUG) << "Error reading request headers: " << e.message(); } } void connection::read_request_body(request_ptr req, read_result_type res) { using std::placeholders::_1; using std::placeholders::_2; if (res.result) { // success read io_service_ptr io = io_service_.lock(); if (io) { reply rep{ io, req, strand_.wrap(std::bind(&connection::send_response, shared_from_this(), req, std::placeholders::_1)), strand_.wrap(std::bind(&connection::send_error, shared_from_this(), req, std::placeholders::_1)) }; add_context(rep, new remote_address(rep, peer_)); try { request_handler_->handle_request(rep); } catch (::std::exception const& e) { local_log(logger::ERROR) << "Exception when dispatching request " << req->path << ": " << e.what(); } catch (...) { local_log(logger::ERROR) << "Unknown exception when dispatching request " << req->path; } } else { local_log(logger::WARNING) << "IO service weak pointer is bad"; } } else if (!res.result) { // fail read local_log(logger::WARNING) << "Failed to read request body"; send_error(req, response_status::bad_request); } else if (res.callback) { boost::asio::async_read(socket_, incoming_, boost::asio::transfer_at_least(1), strand_.wrap( std::bind( &connection::handle_read_body, shared_from_this(), _1, _2, req, res.callback) )); } else { // need more data but no callback local_log(logger::WARNING) << "Request read body returned " "indeterminate, but provided no callback"; } } void connection::handle_read_body(const boost::system::error_code& e, std::size_t bytes_transferred, request_ptr req, read_callback cb) { if (!e) { std::istream is(&incoming_); read_request_body(req, cb(is)); } else { local_log(logger::DEBUG) << "Error reading request body: " << e.message(); } // If an error occurs then no new asynchronous operations are started. This // means that all shared_ptr references to the connection object will // disappear and the object will be destroyed automatically after this // handler returns. The connection class's destructor closes the socket. } void connection::send_response(request_ptr req, response_const_ptr resp) { typedef std::vector< boost::asio::const_buffer > output_buffers_type; using std::placeholders::_1; using std::placeholders::_2; local_log() << req->method << " " << req->path << " " << resp->status << " '" << resp->status_line << "'"; if (is_error(resp->status) && (HTTPCONN_DEFAULT_SEVERITY != logger::OFF)) { local_log() << "Request headers:\n" << req->headers_; if (!req->body_.empty()) { ::std::size_t bs = req->body_.size() < 100 ? req->body_.size() : 100; ::std::string body(req->body_.begin(), req->body_.begin() + 100); local_log() << "Request body (max 100 bytes):\n" << body; } } std::ostream os(&outgoing_); os << *resp; if (!resp->headers_.count(ContentLength)) { header content_length{ ContentLength, boost::lexical_cast<std::string>( resp->body_.size() ) }; os << content_length; } if (!default_headers_.empty()) { os << default_headers_; } os << "\r\n"; output_buffers_type buffers; buffers.push_back(boost::asio::buffer(outgoing_.data())); buffers.push_back(boost::asio::buffer(resp->body_)); boost::asio::async_write(socket_, buffers, strand_.wrap(std::bind(&connection::handle_write_response, shared_from_this(), _1, _2, resp))); } void connection::send_error(request_ptr req, response_status status) { response_const_ptr resp = response::stock_response(status); send_response(req, resp); } void connection::handle_write(const boost::system::error_code& e) { if (!e) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } // TODO Keep-Alive and timer // No new asynchronous operations are started. This means that all shared_ptr // references to the connection object will disappear and the object will be // destroyed automatically after this handler returns. The connection class's // destructor closes the socket. } void connection::handle_write_response(boost::system::error_code const& e, size_t bytes_transferred, response_const_ptr resp) { if (!e) { // Initiate graceful connection closure. boost::system::error_code ignored_ec; socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec); } // TODO Keep-Alive and timer // No new asynchronous operations are started. This means that all shared_ptr // references to the connection object will disappear and the object will be // destroyed automatically after this handler returns. The connection class's // destructor closes the socket. } } // namespace server } // namespace http } // namespace tip <|endoftext|>
<commit_before>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <emscripten/emscripten.h> #include <map> #include <string> #include "perfetto/base/logging.h" #include "perfetto/trace_processor/trace_processor.h" #include "perfetto/trace_processor/raw_query.pb.h" #include "perfetto/trace_processor/sched.pb.h" namespace perfetto { namespace trace_processor { using RequestID = uint32_t; // Reply(): replies to a RPC method invocation. // Called asynchronously (i.e. in a separate task) by the C++ code inside the // trace processor to return data for a RPC method call. // The function is generic and thankfully we need just one for all methods // because the output is always a protobuf buffer. // Args: // RequestID: the ID passed by the embedder when invoking the RPC method (e.g., // the first argument passed to sched_getSchedEvents()). using ReplyFunction = void (*)(RequestID, bool success, const char* /*proto_reply_data*/, uint32_t /*len*/); namespace { TraceProcessor* g_trace_processor; ReplyFunction g_reply; } // namespace // +---------------------------------------------------------------------------+ // | Exported functions called by the JS/TS running in the worker. | // +---------------------------------------------------------------------------+ extern "C" { void EMSCRIPTEN_KEEPALIVE Initialize(ReplyFunction); void Initialize(ReplyFunction reply_function) { PERFETTO_ILOG("Initializing WASM bridge"); Config config; g_trace_processor = TraceProcessor::CreateInstance(config).release(); g_reply = reply_function; } void EMSCRIPTEN_KEEPALIVE trace_processor_parse(RequestID, const uint8_t*, uint32_t); void trace_processor_parse(RequestID id, const uint8_t* data, size_t size) { // TODO(primiano): This copy is extremely unfortunate. Ideally there should be // a way to take the Blob coming from JS (either from FileReader or from th // fetch() stream) and move into WASM. // See https://github.com/WebAssembly/design/issues/1162. std::unique_ptr<uint8_t[]> buf(new uint8_t[size]); memcpy(buf.get(), data, size); g_trace_processor->Parse(std::move(buf), size); g_reply(id, true, "", 0); } // We keep the same signature as other methods even though we don't take input // arguments for simplicity. void EMSCRIPTEN_KEEPALIVE trace_processor_notifyEof(RequestID, const uint8_t*, uint32_t); void trace_processor_notifyEof(RequestID id, const uint8_t*, uint32_t size) { PERFETTO_DCHECK(!size); g_trace_processor->NotifyEndOfFile(); g_reply(id, true, "", 0); } void EMSCRIPTEN_KEEPALIVE trace_processor_rawQuery(RequestID, const uint8_t*, int); void trace_processor_rawQuery(RequestID id, const uint8_t* query_data, int len) { protos::RawQueryArgs query; bool parsed = query.ParseFromArray(query_data, len); if (!parsed) { std::string err = "Failed to parse input request"; g_reply(id, false, err.data(), err.size()); return; } // When the C++ class implementing the service replies, serialize the protobuf // result and post it back to the worker script (|g_reply|). auto callback = [id](const protos::RawQueryResult& res) { std::string encoded; res.SerializeToString(&encoded); g_reply(id, true, encoded.data(), static_cast<uint32_t>(encoded.size())); }; g_trace_processor->ExecuteQuery(query, callback); } } // extern "C" } // namespace trace_processor } // namespace perfetto <commit_msg>ui: make UI use the iterator API of trace processor<commit_after>/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <emscripten/emscripten.h> #include <map> #include <string> #include "perfetto/base/logging.h" #include "perfetto/trace_processor/trace_processor.h" #include "perfetto/trace_processor/raw_query.pb.h" #include "perfetto/trace_processor/sched.pb.h" namespace perfetto { namespace trace_processor { using RequestID = uint32_t; // Reply(): replies to a RPC method invocation. // Called asynchronously (i.e. in a separate task) by the C++ code inside the // trace processor to return data for a RPC method call. // The function is generic and thankfully we need just one for all methods // because the output is always a protobuf buffer. // Args: // RequestID: the ID passed by the embedder when invoking the RPC method (e.g., // the first argument passed to sched_getSchedEvents()). using ReplyFunction = void (*)(RequestID, bool success, const char* /*proto_reply_data*/, uint32_t /*len*/); namespace { TraceProcessor* g_trace_processor; ReplyFunction g_reply; } // namespace // +---------------------------------------------------------------------------+ // | Exported functions called by the JS/TS running in the worker. | // +---------------------------------------------------------------------------+ extern "C" { void EMSCRIPTEN_KEEPALIVE Initialize(ReplyFunction); void Initialize(ReplyFunction reply_function) { PERFETTO_ILOG("Initializing WASM bridge"); Config config; g_trace_processor = TraceProcessor::CreateInstance(config).release(); g_reply = reply_function; } void EMSCRIPTEN_KEEPALIVE trace_processor_parse(RequestID, const uint8_t*, uint32_t); void trace_processor_parse(RequestID id, const uint8_t* data, size_t size) { // TODO(primiano): This copy is extremely unfortunate. Ideally there should be // a way to take the Blob coming from JS (either from FileReader or from th // fetch() stream) and move into WASM. // See https://github.com/WebAssembly/design/issues/1162. std::unique_ptr<uint8_t[]> buf(new uint8_t[size]); memcpy(buf.get(), data, size); g_trace_processor->Parse(std::move(buf), size); g_reply(id, true, "", 0); } // We keep the same signature as other methods even though we don't take input // arguments for simplicity. void EMSCRIPTEN_KEEPALIVE trace_processor_notifyEof(RequestID, const uint8_t*, uint32_t); void trace_processor_notifyEof(RequestID id, const uint8_t*, uint32_t size) { PERFETTO_DCHECK(!size); g_trace_processor->NotifyEndOfFile(); g_reply(id, true, "", 0); } void EMSCRIPTEN_KEEPALIVE trace_processor_rawQuery(RequestID, const uint8_t*, int); void trace_processor_rawQuery(RequestID id, const uint8_t* query_data, int len) { protos::RawQueryArgs query; bool parsed = query.ParseFromArray(query_data, len); if (!parsed) { std::string err = "Failed to parse input request"; g_reply(id, false, err.data(), err.size()); return; } using ColumnDesc = protos::RawQueryResult::ColumnDesc; protos::RawQueryResult result; auto it = g_trace_processor->ExecuteQuery(query.sql_query().c_str()); for (uint32_t col = 0; col < it.ColumnCount(); ++col) { // Setup the descriptors. auto* descriptor = result.add_column_descriptors(); descriptor->set_name(it.GetColumName(col)); descriptor->set_type(ColumnDesc::UNKNOWN); // Add an empty column. result.add_columns(); } for (uint32_t rows = 0; it.Next(); ++rows) { for (uint32_t col = 0; col < it.ColumnCount(); ++col) { auto* column = result.mutable_columns(static_cast<int>(col)); auto* desc = result.mutable_column_descriptors(static_cast<int>(col)); using SqlValue = trace_processor::SqlValue; auto cell = it.Get(col); if (desc->type() == ColumnDesc::UNKNOWN) { switch (cell.type) { case SqlValue::Type::kLong: desc->set_type(ColumnDesc::LONG); break; case SqlValue::Type::kString: desc->set_type(ColumnDesc::STRING); break; case SqlValue::Type::kDouble: desc->set_type(ColumnDesc::DOUBLE); break; case SqlValue::Type::kNull: break; } } // If either the column type is null or we still don't know the type, // just add null values to all the columns. if (cell.type == SqlValue::Type::kNull || desc->type() == ColumnDesc::UNKNOWN) { column->add_long_values(0); column->add_string_values("[NULL]"); column->add_double_values(0); column->add_is_nulls(true); continue; } // Cast the sqlite value to the type of the column. switch (desc->type()) { case ColumnDesc::LONG: PERFETTO_CHECK(cell.type == SqlValue::Type::kLong || cell.type == SqlValue::Type::kDouble); if (cell.type == SqlValue::Type::kLong) { column->add_long_values(cell.long_value); } else /* if (cell.type == SqlValue::Type::kDouble) */ { column->add_long_values(static_cast<int64_t>(cell.double_value)); } column->add_is_nulls(false); break; case ColumnDesc::STRING: { PERFETTO_CHECK(cell.type == SqlValue::Type::kString); column->add_string_values(cell.string_value); column->add_is_nulls(false); break; } case ColumnDesc::DOUBLE: PERFETTO_CHECK(cell.type == SqlValue::Type::kLong || cell.type == SqlValue::Type::kDouble); if (cell.type == SqlValue::Type::kLong) { column->add_double_values(static_cast<double>(cell.long_value)); } else /* if (cell.type == SqlValue::Type::kDouble) */ { column->add_double_values(cell.double_value); } column->add_is_nulls(false); break; case ColumnDesc::UNKNOWN: PERFETTO_FATAL("Handled in if statement above."); } } result.set_num_records(rows + 1); } if (auto opt_error = it.GetLastError()) { result.set_error(*opt_error); } std::string encoded; result.SerializeToString(&encoded); g_reply(id, true, encoded.data(), static_cast<uint32_t>(encoded.size())); } } // extern "C" } // namespace trace_processor } // namespace perfetto <|endoftext|>
<commit_before>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_LOGGINGMACROS_HPP #define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_LOGGINGMACROS_HPP #include <QLoggingCategory> /** * @defgroup cutehmi-loggingMacros Logging macros * * Logging macros. Convenient macros to log messages with Qt logging categories. These macros can be used by other modules * providing that they implement loggingCategory() function in their own namespace. This function should return QLoggingCategory * object, which is declared and defined with Q_DECLARE_LOGGING_CATEGORY and Q_LOGGING_CATEGORY macros, as described in Qt * documentation. Macros are corresponding to Qt debug streams. * - CUTEHMI_DEBUG - debug message (qCDebug()). * - CUTEHMI_INFO - informative message (qCInfo()). * - CUTEHMI_WARNING - informative message (qCWarning()). * - CUTEHMI_CRITICAL - informative message (qCCritical()). * . * * There's no CUTEHMI_FATAL, because Qt (5.12) does not provide QDebug output stream for fatal errors. Instead CUTEHMI_DIE macro * can be used. Unlike the other logging macros CUTEHMI_DIE does not wrap QDebug output stream, so a formatted string should be * passed as macro argument (see QMessageLogger::fatal()). */ ///@{ /** @def CUTEHMI_DEBUG(EXPR) Print debug message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NDEBUG #define CUTEHMI_DEBUG(EXPR) qCDebug(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_DEBUG(EXPR) (void)0 #endif /** @def CUTEHMI_INFO(EXPR) Print informative message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NINFO #define CUTEHMI_INFO(EXPR) qCInfo(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_INFO(EXPR) (void)0 #endif /** @def CUTEHMI_WARNING(EXPR) Print warning. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NWARNING #define CUTEHMI_WARNING(EXPR) qCWarning(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_WARNING(EXPR) (void)0 #endif /** @def CUTEHMI_CRITICAL(EXPR) Print critical message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NCRITICAL #define CUTEHMI_CRITICAL(EXPR) qCCritical(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_CRITICAL(EXPR) (void)0 #endif /** @def CUTEHMI_DIE(...) Print fatal message and abort or exit program. @param ... fatal message and optional list of arguments interpreted by message format string. */ #define CUTEHMI_DIE(...) QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, loggingCategory().categoryName()).fatal(__VA_ARGS__) /** @def CUTEHMI_ASSERT(EXPR, MSG) Assert. @param EXPR assert expression @param MSG message printed in case of assertion failure. */ #ifndef CUTEHMI_NDEBUG #define CUTEHMI_ASSERT(EXPR, MSG) Q_ASSERT_X(EXPR, __FILE__, MSG) #else #define CUTEHMI_ASSERT(EXPR, MSG) (void)0 #endif ///@} #endif //(c)C: Copyright © 2018-2019, Michał Policht <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <commit_msg>Fix Doxygen brief.<commit_after>#ifndef H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_LOGGINGMACROS_HPP #define H_EXTENSIONS_CUTEHMI_2_INCLUDE_CUTEHMI_LOGGINGMACROS_HPP #include <QLoggingCategory> /** * @defgroup cutehmi-loggingMacros Logging macros * * Logging macros. * * Convenient macros to log messages with Qt logging categories. These macros can be used by other modules providing that they * implement loggingCategory() function in their own namespace. This function should return QLoggingCategory object, which is * declared and defined with Q_DECLARE_LOGGING_CATEGORY and Q_LOGGING_CATEGORY macros, as described in Qt documentation. Macros are * corresponding to Qt debug streams. * - CUTEHMI_DEBUG - debug message (qCDebug()). * - CUTEHMI_INFO - informative message (qCInfo()). * - CUTEHMI_WARNING - informative message (qCWarning()). * - CUTEHMI_CRITICAL - informative message (qCCritical()). * . * * There's no CUTEHMI_FATAL, because Qt (5.12) does not provide QDebug output stream for fatal errors. Instead CUTEHMI_DIE macro * can be used. Unlike the other logging macros CUTEHMI_DIE does not wrap QDebug output stream, so a formatted string should be * passed as macro argument (see QMessageLogger::fatal()). */ ///@{ /** @def CUTEHMI_DEBUG(EXPR) Print debug message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NDEBUG #define CUTEHMI_DEBUG(EXPR) qCDebug(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_DEBUG(EXPR) (void)0 #endif /** @def CUTEHMI_INFO(EXPR) Print informative message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NINFO #define CUTEHMI_INFO(EXPR) qCInfo(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_INFO(EXPR) (void)0 #endif /** @def CUTEHMI_WARNING(EXPR) Print warning. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NWARNING #define CUTEHMI_WARNING(EXPR) qCWarning(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_WARNING(EXPR) (void)0 #endif /** @def CUTEHMI_CRITICAL(EXPR) Print critical message. @param EXPR message (can be composed of stream expression). */ #ifndef CUTEHMI_NCRITICAL #define CUTEHMI_CRITICAL(EXPR) qCCritical(loggingCategory()).nospace().noquote() << EXPR #else #define CUTEHMI_CRITICAL(EXPR) (void)0 #endif /** @def CUTEHMI_DIE(...) Print fatal message and abort or exit program. @param ... fatal message and optional list of arguments interpreted by message format string. */ #define CUTEHMI_DIE(...) QMessageLogger(__FILE__, __LINE__, Q_FUNC_INFO, loggingCategory().categoryName()).fatal(__VA_ARGS__) /** @def CUTEHMI_ASSERT(EXPR, MSG) Assert. @param EXPR assert expression @param MSG message printed in case of assertion failure. */ #ifndef CUTEHMI_NDEBUG #define CUTEHMI_ASSERT(EXPR, MSG) Q_ASSERT_X(EXPR, __FILE__, MSG) #else #define CUTEHMI_ASSERT(EXPR, MSG) (void)0 #endif ///@} #endif //(c)C: Copyright © 2018-2019, Michał Policht <[email protected]>. All rights reserved. //(c)C: This file is a part of CuteHMI. //(c)C: CuteHMI 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 3 of the License, or (at your option) any later version. //(c)C: CuteHMI 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. //(c)C: You should have received a copy of the GNU Lesser General Public License along with CuteHMI. If not, see <https://www.gnu.org/licenses/>. <|endoftext|>
<commit_before>#include <catch.hpp> // ----------------------------------------------------------------------------- #include <time.h> #include <limits> #include "UniSetTypes.h" #include "MBTCPMultiMaster.h" // ----------------------------------------------------------------------------- using namespace std; using namespace UniSetTypes; // ----------------------------------------------------------------------------- #include <catch.hpp> // ----------------------------------------------------------------------------- #include <time.h> #include <memory> #include <limits> #include "UniSetTypes.h" #include "MBTCPTestServer.h" #include "MBTCPMultiMaster.h" // ----------------------------------------------------------------------------- using namespace std; using namespace UniSetTypes; // ----------------------------------------------------------------------------- static ModbusRTU::ModbusAddr slaveaddr = 0x01; // conf->getArgInt("--mbs-my-addr"); static int port = 20050; // conf->getArgInt("--mbs-inet-port"); static string addr("127.0.0.1"); // conf->getArgParam("--mbs-inet-addr"); static int port2 = 20052; static string addr2("127.0.0.1"); static ModbusRTU::ModbusAddr slaveADDR = 0x01; static shared_ptr<MBTCPTestServer> mbs1; static shared_ptr<MBTCPTestServer> mbs2; static shared_ptr<UInterface> ui; static ObjectId mbID = 6005; // MBTCPMultiMaster1 static int polltime=50; // conf->getArgInt("--mbtcp-polltime"); static ObjectId slaveNotRespond = 10; // Slave_Not_Respond_S static ObjectId slave1NotRespond = 12; // Slave1_Not_Respond_S static ObjectId slave2NotRespond = 13; // Slave2_Not_Respond_S static const ObjectId exchangeMode = 11; // MBTCPMaster_Mode_AS // ----------------------------------------------------------------------------- static void InitTest() { auto conf = uniset_conf(); CHECK( conf!=nullptr ); if( !ui ) { ui = make_shared<UInterface>(); // UI понадобиться для проверки записанных в SM значений. CHECK( ui->getObjectIndex() != nullptr ); CHECK( ui->getConf() == conf ); CHECK( ui->waitReady(slaveNotRespond,8000) ); } if( !mbs1 ) { mbs1 = make_shared<MBTCPTestServer>(slaveADDR,addr,port,false); CHECK( mbs1!= nullptr ); mbs1->setReply(0); mbs1->runThread(); for( int i=0; !mbs1->isRunning() && i<10; i++ ) msleep(200); CHECK( mbs1->isRunning() ); msleep(7000); CHECK( ui->getValue(slaveNotRespond) == 0 ); } if( !mbs2 ) { mbs2 = make_shared<MBTCPTestServer>(slaveADDR,addr2,port2,false); CHECK( mbs2!= nullptr ); mbs2->setReply(0); mbs2->runThread(); for( int i=0; !mbs2->isRunning() && i<10; i++ ) msleep(200); CHECK( mbs2->isRunning() ); } } // ----------------------------------------------------------------------------- TEST_CASE("MBTCPMultiMaster: rotate channel","[modbus][mbmaster][mbtcpmultimaster]") { InitTest(); CHECK( ui->isExist(mbID) ); REQUIRE( ui->getValue(1003) == 0 ); mbs1->setReply(100); mbs2->setReply(10); msleep(polltime+1000); REQUIRE( ui->getValue(1003) == 100 ); mbs1->disableExchange(true); msleep(3200); // --mbtcp-timeout 3000 (см. run_test_mbtcmultipmaster.sh) REQUIRE( ui->getValue(1003) == 10 ); mbs1->disableExchange(false); mbs2->disableExchange(true); msleep(3200); // --mbtcp-timeout 3000 (см. run_test_mbtcmultipmaster.sh) REQUIRE( ui->getValue(1003) == 100 ); mbs2->disableExchange(false); REQUIRE( ui->getValue(1003) == 100 ); } // ----------------------------------------------------------------------------- <commit_msg>(ModbusMaster): сделал test немного стабильнее.<commit_after>#include <catch.hpp> // ----------------------------------------------------------------------------- #include <time.h> #include <limits> #include "UniSetTypes.h" #include "MBTCPMultiMaster.h" // ----------------------------------------------------------------------------- using namespace std; using namespace UniSetTypes; // ----------------------------------------------------------------------------- #include <catch.hpp> // ----------------------------------------------------------------------------- #include <time.h> #include <memory> #include <limits> #include "UniSetTypes.h" #include "MBTCPTestServer.h" #include "MBTCPMultiMaster.h" // ----------------------------------------------------------------------------- using namespace std; using namespace UniSetTypes; // ----------------------------------------------------------------------------- static ModbusRTU::ModbusAddr slaveaddr = 0x01; // conf->getArgInt("--mbs-my-addr"); static int port = 20050; // conf->getArgInt("--mbs-inet-port"); static string addr("127.0.0.1"); // conf->getArgParam("--mbs-inet-addr"); static int port2 = 20052; static string addr2("127.0.0.1"); static ModbusRTU::ModbusAddr slaveADDR = 0x01; static shared_ptr<MBTCPTestServer> mbs1; static shared_ptr<MBTCPTestServer> mbs2; static shared_ptr<UInterface> ui; static ObjectId mbID = 6005; // MBTCPMultiMaster1 static int polltime=50; // conf->getArgInt("--mbtcp-polltime"); static ObjectId slaveNotRespond = 10; // Slave_Not_Respond_S static ObjectId slave1NotRespond = 12; // Slave1_Not_Respond_S static ObjectId slave2NotRespond = 13; // Slave2_Not_Respond_S static const ObjectId exchangeMode = 11; // MBTCPMaster_Mode_AS // ----------------------------------------------------------------------------- static void InitTest() { auto conf = uniset_conf(); CHECK( conf!=nullptr ); if( !ui ) { ui = make_shared<UInterface>(); // UI понадобиться для проверки записанных в SM значений. CHECK( ui->getObjectIndex() != nullptr ); CHECK( ui->getConf() == conf ); CHECK( ui->waitReady(slaveNotRespond,8000) ); } if( !mbs1 ) { mbs1 = make_shared<MBTCPTestServer>(slaveADDR,addr,port,false); CHECK( mbs1!= nullptr ); mbs1->setReply(0); mbs1->runThread(); for( int i=0; !mbs1->isRunning() && i<10; i++ ) msleep(200); CHECK( mbs1->isRunning() ); msleep(7000); CHECK( ui->getValue(slaveNotRespond) == 0 ); } if( !mbs2 ) { mbs2 = make_shared<MBTCPTestServer>(slaveADDR,addr2,port2,false); CHECK( mbs2!= nullptr ); mbs2->setReply(0); mbs2->runThread(); for( int i=0; !mbs2->isRunning() && i<10; i++ ) msleep(200); CHECK( mbs2->isRunning() ); } } // ----------------------------------------------------------------------------- TEST_CASE("MBTCPMultiMaster: rotate channel","[modbus][mbmaster][mbtcpmultimaster]") { InitTest(); CHECK( ui->isExist(mbID) ); REQUIRE( ui->getValue(1003) == 0 ); mbs1->setReply(100); mbs2->setReply(10); msleep(polltime+1000); REQUIRE( ui->getValue(1003) == 100 ); mbs1->disableExchange(true); msleep(4000); // --mbtcp-timeout 3000 (см. run_test_mbtcmultipmaster.sh) REQUIRE( ui->getValue(1003) == 10 ); mbs1->disableExchange(false); mbs2->disableExchange(true); msleep(4000); // --mbtcp-timeout 3000 (см. run_test_mbtcmultipmaster.sh) REQUIRE( ui->getValue(1003) == 100 ); mbs2->disableExchange(false); REQUIRE( ui->getValue(1003) == 100 ); } // ----------------------------------------------------------------------------- <|endoftext|>
<commit_before>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2009 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" initialiseSingleton( TaxiMgr ); /************************ * TaxiPath * ************************/ void TaxiPath::ComputeLen() { m_length1 = m_length1 = 0; m_map1 = m_map2 = 0; float * curptr = &m_length1; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float x = itr->second->x; float y = itr->second->y; float z = itr->second->z; uint32 curmap = itr->second->mapid; m_map1 = curmap; itr++; while (itr != m_pathNodes.end()) { if( itr->second->mapid != curmap ) { curptr = &m_length2; m_map2 = itr->second->mapid; curmap = itr->second->mapid; } *curptr += sqrt((itr->second->x - x)*(itr->second->x - x) + (itr->second->y - y)*(itr->second->y - y) + (itr->second->z - z)*(itr->second->z - z)); x = itr->second->x; y = itr->second->y; z = itr->second->z; itr++; } } void TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid) { if (!time) return; float length; if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; x = 0; y = 0; z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 0; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; *last_node = nodecounter; return; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; nodecounter++; } x = nx; y = ny; z = nz; } TaxiPathNode* TaxiPath::GetPathNode(uint32 i) { if (m_pathNodes.find(i) == m_pathNodes.end()) return NULL; else return m_pathNodes.find(i)->second; } void TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time) { if (!time) return; float length; uint32 mapid = riding->GetMapId(); if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx,ny,nz = 0.0f; bool set = false; uint32 nodecounter = 1; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); size_t pos; *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time)); *data << uint32( nodecounter ); pos = data->wpos(); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; if( pn->mapid != mapid ) break; *data << pn->x << pn->y << pn->z; ++itr; ++nodecounter; } *(uint32*)&(data->contents()[pos]) = nodecounter; to->delayedPackets.add(data); /* if (!time) return; float traveled_len = (time/(getLength() * TAXI_TRAVEL_SPEED))*getLength();; uint32 len = 0, count = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx = itr->second->x; float ny = itr->second->y; float nz = itr->second->z; itr++; while (itr != m_pathNodes.end()) { len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len > traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; count++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time)); *data << uint32( GetNodeCount() - count ); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; *data << pn->x << pn->y << pn->z; itr++; } //to->GetSession()->SendPacket(&data); to->delayedPackets.add(data);*/ } /*********************** * TaxiMgr * ***********************/ void TaxiMgr::_LoadTaxiNodes() { uint32 i; for(i = 0; i < dbcTaxiNode.GetNumRows(); i++) { DBCTaxiNode *node = dbcTaxiNode.LookupRow(i); if (node) { TaxiNode *n = new TaxiNode; n->id = node->id; n->mapid = node->mapid; n->alliance_mount = node->alliance_mount; n->horde_mount = node->horde_mount; n->x = node->x; n->y = node->y; n->z = node->z; this->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n)); } } //todo: load mounts } void TaxiMgr::_LoadTaxiPaths() { uint32 i, j; for(i = 0; i < dbcTaxiPath.GetNumRows(); i++) { DBCTaxiPath *path = dbcTaxiPath.LookupRow(i); if (path) { TaxiPath *p = new TaxiPath; p->from = path->from; p->to = path->to; p->id = path->id; p->price = path->price; //Load Nodes for(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++) { DBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j); if (pathnode) { if (pathnode->path == p->id) { TaxiPathNode *pn = new TaxiPathNode; pn->x = pathnode->x; pn->y = pathnode->y; pn->z = pathnode->z; pn->mapid = pathnode->mapid; p->AddPathNode(pathnode->seq, pn); } } } p->ComputeLen(); this->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p)); } } } TaxiPath* TaxiMgr::GetTaxiPath(uint32 path) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; itr = this->m_taxiPaths.find(path); if (itr == m_taxiPaths.end()) return NULL; else return itr->second; } TaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) if ((itr->second->to == to) && (itr->second->from == from)) return itr->second; return NULL; } TaxiNode* TaxiMgr::GetTaxiNode(uint32 node) { HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; itr = this->m_taxiNodes.find(node); if (itr == m_taxiNodes.end()) return NULL; else return itr->second; } uint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid ) { uint32 nearest = 0; float distance = -1; float nx, ny, nz, nd; HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; for (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++) { if (itr->second->mapid == mapid) { nx = itr->second->x - x; ny = itr->second->y - y; nz = itr->second->z - z; nd = nx * nx + ny * ny + nz * nz; if( nd < distance || distance < 0 ) { distance = nd; nearest = itr->second->id; } } } return nearest; } bool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask ) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; uint8 field; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) { /*if( itr->second->from == curloc ) {*/ field = (uint8)((itr->second->to - 1) / 32); Mask[field] |= 1 << ( (itr->second->to - 1 ) % 32 ); //} } return true; } <commit_msg>FIXED: Potentially uninitialized variables<commit_after>/* * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2009 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "StdAfx.h" initialiseSingleton( TaxiMgr ); /************************ * TaxiPath * ************************/ void TaxiPath::ComputeLen() { m_length1 = m_length1 = 0; m_map1 = m_map2 = 0; float * curptr = &m_length1; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float x = itr->second->x; float y = itr->second->y; float z = itr->second->z; uint32 curmap = itr->second->mapid; m_map1 = curmap; itr++; while (itr != m_pathNodes.end()) { if( itr->second->mapid != curmap ) { curptr = &m_length2; m_map2 = itr->second->mapid; curmap = itr->second->mapid; } *curptr += sqrt((itr->second->x - x)*(itr->second->x - x) + (itr->second->y - y)*(itr->second->y - y) + (itr->second->z - z)*(itr->second->z - z)); x = itr->second->x; y = itr->second->y; z = itr->second->z; itr++; } } void TaxiPath::SetPosForTime(float &x, float &y, float &z, uint32 time, uint32 *last_node, uint32 mapid) { if (!time) return; float length; if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; x = 0; y = 0; z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx, ny, nz; nx = ny = nz = 0.0f; bool set = false; uint32 nodecounter = 0; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; *last_node = nodecounter; return; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; nodecounter++; } x = nx; y = ny; z = nz; } TaxiPathNode* TaxiPath::GetPathNode(uint32 i) { if (m_pathNodes.find(i) == m_pathNodes.end()) return NULL; else return m_pathNodes.find(i)->second; } void TaxiPath::SendMoveForTime(Player *riding, Player *to, uint32 time) { if (!time) return; float length; uint32 mapid = riding->GetMapId(); if( mapid == m_map1 ) length = m_length1; else length = m_length2; float traveled_len = (time/(length * TAXI_TRAVEL_SPEED))*length; uint32 len = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx, ny, nz; nx = ny = nz = 0.0f; bool set = false; uint32 nodecounter = 1; while (itr != m_pathNodes.end()) { if( itr->second->mapid != mapid ) { itr++; nodecounter++; continue; } if(!set) { nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; set = true; continue; } len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len >= traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); size_t pos; *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((length * TAXI_TRAVEL_SPEED) - time)); *data << uint32( nodecounter ); pos = data->wpos(); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; if( pn->mapid != mapid ) break; *data << pn->x << pn->y << pn->z; ++itr; ++nodecounter; } *(uint32*)&(data->contents()[pos]) = nodecounter; to->delayedPackets.add(data); /* if (!time) return; float traveled_len = (time/(getLength() * TAXI_TRAVEL_SPEED))*getLength();; uint32 len = 0, count = 0; float x = 0,y = 0,z = 0; if (!m_pathNodes.size()) return; std::map<uint32, TaxiPathNode*>::iterator itr; itr = m_pathNodes.begin(); float nx = itr->second->x; float ny = itr->second->y; float nz = itr->second->z; itr++; while (itr != m_pathNodes.end()) { len = (uint32)sqrt((itr->second->x - nx)*(itr->second->x - nx) + (itr->second->y - ny)*(itr->second->y - ny) + (itr->second->z - nz)*(itr->second->z - nz)); if (len > traveled_len) { x = (itr->second->x - nx)*(traveled_len/len) + nx; y = (itr->second->y - ny)*(traveled_len/len) + ny; z = (itr->second->z - nz)*(traveled_len/len) + nz; break; } else { traveled_len -= len; } nx = itr->second->x; ny = itr->second->y; nz = itr->second->z; itr++; count++; } if (itr == m_pathNodes.end()) return; WorldPacket * data = new WorldPacket(SMSG_MONSTER_MOVE, 2000); *data << riding->GetNewGUID(); *data << riding->GetPositionX( ) << riding->GetPositionY( ) << riding->GetPositionZ( ); *data << getMSTime(); *data << uint8( 0 ); *data << uint32( 0x00000300 ); *data << uint32( uint32((getLength() * TAXI_TRAVEL_SPEED) - time)); *data << uint32( GetNodeCount() - count ); *data << nx << ny << nz; while (itr != m_pathNodes.end()) { TaxiPathNode *pn = itr->second; *data << pn->x << pn->y << pn->z; itr++; } //to->GetSession()->SendPacket(&data); to->delayedPackets.add(data);*/ } /*********************** * TaxiMgr * ***********************/ void TaxiMgr::_LoadTaxiNodes() { uint32 i; for(i = 0; i < dbcTaxiNode.GetNumRows(); i++) { DBCTaxiNode *node = dbcTaxiNode.LookupRow(i); if (node) { TaxiNode *n = new TaxiNode; n->id = node->id; n->mapid = node->mapid; n->alliance_mount = node->alliance_mount; n->horde_mount = node->horde_mount; n->x = node->x; n->y = node->y; n->z = node->z; this->m_taxiNodes.insert(std::map<uint32, TaxiNode*>::value_type(n->id, n)); } } //todo: load mounts } void TaxiMgr::_LoadTaxiPaths() { uint32 i, j; for(i = 0; i < dbcTaxiPath.GetNumRows(); i++) { DBCTaxiPath *path = dbcTaxiPath.LookupRow(i); if (path) { TaxiPath *p = new TaxiPath; p->from = path->from; p->to = path->to; p->id = path->id; p->price = path->price; //Load Nodes for(j = 0; j < dbcTaxiPathNode.GetNumRows(); j++) { DBCTaxiPathNode *pathnode = dbcTaxiPathNode.LookupRow(j); if (pathnode) { if (pathnode->path == p->id) { TaxiPathNode *pn = new TaxiPathNode; pn->x = pathnode->x; pn->y = pathnode->y; pn->z = pathnode->z; pn->mapid = pathnode->mapid; p->AddPathNode(pathnode->seq, pn); } } } p->ComputeLen(); this->m_taxiPaths.insert(std::map<uint32, TaxiPath*>::value_type(p->id, p)); } } } TaxiPath* TaxiMgr::GetTaxiPath(uint32 path) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; itr = this->m_taxiPaths.find(path); if (itr == m_taxiPaths.end()) return NULL; else return itr->second; } TaxiPath* TaxiMgr::GetTaxiPath(uint32 from, uint32 to) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) if ((itr->second->to == to) && (itr->second->from == from)) return itr->second; return NULL; } TaxiNode* TaxiMgr::GetTaxiNode(uint32 node) { HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; itr = this->m_taxiNodes.find(node); if (itr == m_taxiNodes.end()) return NULL; else return itr->second; } uint32 TaxiMgr::GetNearestTaxiNode( float x, float y, float z, uint32 mapid ) { uint32 nearest = 0; float distance = -1; float nx, ny, nz, nd; HM_NAMESPACE::hash_map<uint32, TaxiNode*>::iterator itr; for (itr = m_taxiNodes.begin(); itr != m_taxiNodes.end(); itr++) { if (itr->second->mapid == mapid) { nx = itr->second->x - x; ny = itr->second->y - y; nz = itr->second->z - z; nd = nx * nx + ny * ny + nz * nz; if( nd < distance || distance < 0 ) { distance = nd; nearest = itr->second->id; } } } return nearest; } bool TaxiMgr::GetGlobalTaxiNodeMask( uint32 curloc, uint32 *Mask ) { HM_NAMESPACE::hash_map<uint32, TaxiPath*>::iterator itr; uint8 field; for (itr = m_taxiPaths.begin(); itr != m_taxiPaths.end(); itr++) { /*if( itr->second->from == curloc ) {*/ field = (uint8)((itr->second->to - 1) / 32); Mask[field] |= 1 << ( (itr->second->to - 1 ) % 32 ); //} } return true; } <|endoftext|>
<commit_before>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_ISA_TRAITS_HH__ #define __ARCH_SPARC_ISA_TRAITS_HH__ #include "arch/sparc/types.hh" #include "base/misc.hh" #include "config/full_system.hh" #include "sim/host.hh" class ThreadContext; class FastCPU; //class FullCPU; class Checkpoint; class StaticInst; class StaticInstPtr; namespace BigEndianGuest {} #if FULL_SYSTEM #include "arch/sparc/isa_fullsys_traits.hh" #endif namespace SparcISA { class RegFile; //This makes sure the big endian versions of certain functions are used. using namespace BigEndianGuest; // Alpha Does NOT have a delay slot #define ISA_HAS_DELAY_SLOT 1 //TODO this needs to be a SPARC Noop // Alpha UNOP (ldq_u r31,0(r0)) const MachInst NoopMachInst = 0x2ffe0000; const int NumIntRegs = 32; const int NumFloatRegs = 64; const int NumMiscRegs = 40; // These enumerate all the registers for dependence tracking. enum DependenceTags { // 0..31 are the integer regs 0..31 // 32..95 are the FP regs 0..31, i.e. use (reg + FP_Base_DepTag) FP_Base_DepTag = NumIntRegs, Ctrl_Base_DepTag = NumIntRegs + NumFloatRegs, //XXX These are here solely to get compilation and won't work Fpcr_DepTag = 0, Uniq_DepTag = 0 }; // MAXTL - maximum trap level const int MaxPTL = 2; const int MaxTL = 6; const int MaxGL = 3; const int MaxPGL = 2; // NWINDOWS - number of register windows, can be 3 to 32 const int NWindows = 32; // semantically meaningful register indices const int ZeroReg = 0; // architecturally meaningful // the rest of these depend on the ABI const int StackPointerReg = 14; const int ReturnAddressReg = 31; // post call, precall is 15 const int ReturnValueReg = 8; // Post return, 24 is pre-return. const int FramePointerReg = 30; const int ArgumentReg0 = 8; const int ArgumentReg1 = 9; const int ArgumentReg2 = 10; const int ArgumentReg3 = 11; const int ArgumentReg4 = 12; const int ArgumentReg5 = 13; // Some OS syscall use a second register (o1) to return a second value const int SyscallPseudoReturnReg = ArgumentReg1; //XXX These numbers are bogus const int MaxInstSrcRegs = 8; const int MaxInstDestRegs = 9; //8K. This value is implmentation specific; and should probably //be somewhere else. const int LogVMPageSize = 13; const int VMPageSize = (1 << LogVMPageSize); //Why does both the previous set of constants and this one exist? const int PageShift = 13; const int PageBytes = ULL(1) << PageShift; const int BranchPredAddrShiftAmt = 2; const int MachineBytes = 8; const int WordBytes = 4; const int HalfwordBytes = 2; const int ByteBytes = 1; void serialize(std::ostream & os); void unserialize(Checkpoint *cp, const std::string &section); StaticInstPtr decodeInst(ExtMachInst); // return a no-op instruction... used for instruction fetch faults extern const MachInst NoopMachInst; } #endif // __ARCH_SPARC_ISA_TRAITS_HH__ <commit_msg>Replace the Alpha No op with a SPARC one.<commit_after>/* * Copyright (c) 2003-2005 The Regents of The University of Michigan * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Authors: Gabe Black */ #ifndef __ARCH_SPARC_ISA_TRAITS_HH__ #define __ARCH_SPARC_ISA_TRAITS_HH__ #include "arch/sparc/types.hh" #include "base/misc.hh" #include "config/full_system.hh" #include "sim/host.hh" class ThreadContext; class FastCPU; //class FullCPU; class Checkpoint; class StaticInst; class StaticInstPtr; namespace BigEndianGuest {} #if FULL_SYSTEM #include "arch/sparc/isa_fullsys_traits.hh" #endif namespace SparcISA { class RegFile; //This makes sure the big endian versions of certain functions are used. using namespace BigEndianGuest; // SPARC have a delay slot #define ISA_HAS_DELAY_SLOT 1 // SPARC NOP (sethi %(hi(0), g0) const MachInst NoopMachInst = 0x01000000; const int NumIntRegs = 32; const int NumFloatRegs = 64; const int NumMiscRegs = 40; // These enumerate all the registers for dependence tracking. enum DependenceTags { // 0..31 are the integer regs 0..31 // 32..95 are the FP regs 0..31, i.e. use (reg + FP_Base_DepTag) FP_Base_DepTag = NumIntRegs, Ctrl_Base_DepTag = NumIntRegs + NumFloatRegs, //XXX These are here solely to get compilation and won't work Fpcr_DepTag = 0, Uniq_DepTag = 0 }; // MAXTL - maximum trap level const int MaxPTL = 2; const int MaxTL = 6; const int MaxGL = 3; const int MaxPGL = 2; // NWINDOWS - number of register windows, can be 3 to 32 const int NWindows = 32; // semantically meaningful register indices const int ZeroReg = 0; // architecturally meaningful // the rest of these depend on the ABI const int StackPointerReg = 14; const int ReturnAddressReg = 31; // post call, precall is 15 const int ReturnValueReg = 8; // Post return, 24 is pre-return. const int FramePointerReg = 30; const int ArgumentReg0 = 8; const int ArgumentReg1 = 9; const int ArgumentReg2 = 10; const int ArgumentReg3 = 11; const int ArgumentReg4 = 12; const int ArgumentReg5 = 13; // Some OS syscall use a second register (o1) to return a second value const int SyscallPseudoReturnReg = ArgumentReg1; //XXX These numbers are bogus const int MaxInstSrcRegs = 8; const int MaxInstDestRegs = 9; //8K. This value is implmentation specific; and should probably //be somewhere else. const int LogVMPageSize = 13; const int VMPageSize = (1 << LogVMPageSize); //Why does both the previous set of constants and this one exist? const int PageShift = 13; const int PageBytes = ULL(1) << PageShift; const int BranchPredAddrShiftAmt = 2; const int MachineBytes = 8; const int WordBytes = 4; const int HalfwordBytes = 2; const int ByteBytes = 1; void serialize(std::ostream & os); void unserialize(Checkpoint *cp, const std::string &section); StaticInstPtr decodeInst(ExtMachInst); // return a no-op instruction... used for instruction fetch faults extern const MachInst NoopMachInst; } #endif // __ARCH_SPARC_ISA_TRAITS_HH__ <|endoftext|>
<commit_before>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include <boost/variant/variant.hpp> #include "ast/ContextAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/ASTVisitor.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "BlockContext.hpp" #include "VisitorUtils.hpp" using namespace eddic; class AnnotateVisitor : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> globalContext; std::shared_ptr<FunctionContext> functionContext; std::shared_ptr<Context> currentContext; public: AUTO_RECURSE_BINARY_CONDITION() AUTO_RECURSE_FUNCTION_CALLS() AUTO_RECURSE_BUILTIN_OPERATORS() void operator()(ast::SourceFile& program){ currentContext = program.Content->context = globalContext = std::make_shared<GlobalContext>(); visit_each(*this, program.Content->blocks); } void operator()(ast::GlobalVariableDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::GlobalArrayDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::FunctionDeclaration& function){ currentContext = function.Content->context = functionContext = std::make_shared<FunctionContext>(currentContext); visit_each(*this, function.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::While& while_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, while_.Content->condition); visit_each(*this, while_.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::DoWhile& while_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, while_.Content->condition); visit_each(*this, while_.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::For& for_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_optional(*this, for_.Content->start); visit_optional(*this, for_.Content->condition); visit_optional(*this, for_.Content->repeat); visit_each(*this, for_.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::Foreach& foreach){ foreach.Content->context = currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_each(*this, foreach.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::ForeachIn& foreach){ foreach.Content->context = currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_each(*this, foreach.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::If& if_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, if_.Content->condition); visit_each(*this, if_.Content->instructions); currentContext = currentContext->parent(); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, elseIf.condition); visit_each(*this, elseIf.instructions); currentContext = currentContext->parent(); } void operator()(ast::Else& else_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_each(*this, else_.instructions); currentContext = currentContext->parent(); } void operator()(ast::VariableDeclaration& declaration){ declaration.Content->context = currentContext; visit(*this, *declaration.Content->value); } void operator()(ast::ArrayDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::Assignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->value); } void operator()(ast::CompoundAssignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->value); } void operator()(ast::ArrayAssignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->indexValue); visit(*this, assignment.Content->value); } void operator()(ast::Swap& swap){ swap.Content->context = currentContext; } void operator()(ast::SuffixOperation& operation){ operation.Content->context = currentContext; } void operator()(ast::PrefixOperation& operation){ operation.Content->context = currentContext; } void operator()(ast::ComposedValue& value){ value.Content->context = currentContext; visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); } void operator()(ast::Plus& value){ visit(*this, value.Content->value); } void operator()(ast::Minus& value){ visit(*this, value.Content->value); } void operator()(ast::VariableValue& variable){ variable.Content->context = currentContext; } void operator()(ast::ArrayValue& array){ array.Content->context = currentContext; visit(*this, array.Content->indexValue); } void operator()(ast::Return& return_){ return_.Content->context = functionContext; visit(*this, return_.Content->value); } void operator()(ast::Import&){ //No context there } void operator()(ast::StandardImport&){ //No Context there } void operator()(ast::TerminalNode&){ //A terminal node has no context } }; void ast::ContextAnnotator::annotate(ast::SourceFile& program) const { AnnotateVisitor visitor; visitor(program); } <commit_msg>Improve the visitor with template functions<commit_after>//======================================================================= // Copyright Baptiste Wicht 2011. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) //======================================================================= #include <algorithm> #include <memory> #include <boost/variant/variant.hpp> #include "ast/ContextAnnotator.hpp" #include "ast/SourceFile.hpp" #include "ast/ASTVisitor.hpp" #include "Context.hpp" #include "GlobalContext.hpp" #include "FunctionContext.hpp" #include "BlockContext.hpp" #include "VisitorUtils.hpp" using namespace eddic; class AnnotateVisitor : public boost::static_visitor<> { private: std::shared_ptr<GlobalContext> globalContext; std::shared_ptr<FunctionContext> functionContext; std::shared_ptr<Context> currentContext; public: AUTO_RECURSE_BINARY_CONDITION() AUTO_RECURSE_FUNCTION_CALLS() AUTO_RECURSE_BUILTIN_OPERATORS() void operator()(ast::SourceFile& program){ currentContext = program.Content->context = globalContext = std::make_shared<GlobalContext>(); visit_each(*this, program.Content->blocks); } void operator()(ast::GlobalVariableDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::GlobalArrayDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::FunctionDeclaration& function){ currentContext = function.Content->context = functionContext = std::make_shared<FunctionContext>(currentContext); visit_each(*this, function.Content->instructions); currentContext = currentContext->parent(); } template<typename Loop> void annotateWhileLoop(Loop& loop){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, loop.Content->condition); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::While& while_){ annotateWhileLoop(while_); } void operator()(ast::DoWhile& while_){ annotateWhileLoop(while_); } void operator()(ast::For& for_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_optional(*this, for_.Content->start); visit_optional(*this, for_.Content->condition); visit_optional(*this, for_.Content->repeat); visit_each(*this, for_.Content->instructions); currentContext = currentContext->parent(); } template<typename Loop> void annotateSimpleLoop(Loop& loop){ loop.Content->context = currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_each(*this, loop.Content->instructions); currentContext = currentContext->parent(); } void operator()(ast::Foreach& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::ForeachIn& foreach){ annotateSimpleLoop(foreach); } void operator()(ast::If& if_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, if_.Content->condition); visit_each(*this, if_.Content->instructions); currentContext = currentContext->parent(); visit_each_non_variant(*this, if_.Content->elseIfs); visit_optional_non_variant(*this, if_.Content->else_); } void operator()(ast::ElseIf& elseIf){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit(*this, elseIf.condition); visit_each(*this, elseIf.instructions); currentContext = currentContext->parent(); } void operator()(ast::Else& else_){ currentContext = std::make_shared<BlockContext>(currentContext, functionContext); visit_each(*this, else_.instructions); currentContext = currentContext->parent(); } void operator()(ast::VariableDeclaration& declaration){ declaration.Content->context = currentContext; visit(*this, *declaration.Content->value); } void operator()(ast::ArrayDeclaration& declaration){ declaration.Content->context = currentContext; } void operator()(ast::Assignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->value); } void operator()(ast::CompoundAssignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->value); } void operator()(ast::ArrayAssignment& assignment){ assignment.Content->context = currentContext; visit(*this, assignment.Content->indexValue); visit(*this, assignment.Content->value); } void operator()(ast::Swap& swap){ swap.Content->context = currentContext; } void operator()(ast::SuffixOperation& operation){ operation.Content->context = currentContext; } void operator()(ast::PrefixOperation& operation){ operation.Content->context = currentContext; } void operator()(ast::ComposedValue& value){ value.Content->context = currentContext; visit(*this, value.Content->first); for_each(value.Content->operations.begin(), value.Content->operations.end(), [&](ast::Operation& operation){ visit(*this, operation.get<1>()); }); } void operator()(ast::Plus& value){ visit(*this, value.Content->value); } void operator()(ast::Minus& value){ visit(*this, value.Content->value); } void operator()(ast::VariableValue& variable){ variable.Content->context = currentContext; } void operator()(ast::ArrayValue& array){ array.Content->context = currentContext; visit(*this, array.Content->indexValue); } void operator()(ast::Return& return_){ return_.Content->context = functionContext; visit(*this, return_.Content->value); } void operator()(ast::Import&){ //No context there } void operator()(ast::StandardImport&){ //No Context there } void operator()(ast::TerminalNode&){ //A terminal node has no context } }; void ast::ContextAnnotator::annotate(ast::SourceFile& program) const { AnnotateVisitor visitor; visitor(program); } <|endoftext|>
<commit_before>// Copyright 2010-2015 RethinkDB, all rights reserved. #ifndef BTREE_BACKFILL_DEBUG_HPP_ #define BTREE_BACKFILL_DEBUG_HPP_ #include <string> #include "btree/keys.hpp" /* If the `ENABLE_BACKFILL_DEBUG` symbol is defined, then backfilling-related events will be recorded in a log and indexed by key. This can be useful for diagnosing bugs in the backfilling logic. Obviously, this should be disabled when not in use. */ #define ENABLE_BACKFILL_DEBUG #ifdef ENABLE_BACKFILL_DEBUG void backfill_debug_clear_log(); void backfill_debug_key(const store_key_t &key, const std::string &msg); void backfill_debug_range(const key_range_t &range, const std::string &msg); void backfill_debug_all(const std::string &msg); void backfill_debug_dump_log(const store_key_t &key); #else #define backfill_debug_clear_log() ((void)0) #define backfill_debug_key(key, msg) ((void)0) #define backfill_debug_range(range, msg) ((void)0) #define backfill_debug_all(msg) ((void)0) #define backfill_debug_dump_log(key) ((void)0) #endif /* ENABLE_BACKFILL_DEBUG */ #endif /* BTREE_BACKFILL_DEBUG_HPP_ */ <commit_msg>Disable backfill debugging, because it shouldn't be on when not in use.<commit_after>// Copyright 2010-2015 RethinkDB, all rights reserved. #ifndef BTREE_BACKFILL_DEBUG_HPP_ #define BTREE_BACKFILL_DEBUG_HPP_ #include <string> #include "btree/keys.hpp" /* If the `ENABLE_BACKFILL_DEBUG` symbol is defined, then backfilling-related events will be recorded in a log and indexed by key. This can be useful for diagnosing bugs in the backfilling logic. Obviously, this should be disabled when not in use. */ // #define ENABLE_BACKFILL_DEBUG #ifdef ENABLE_BACKFILL_DEBUG void backfill_debug_clear_log(); void backfill_debug_key(const store_key_t &key, const std::string &msg); void backfill_debug_range(const key_range_t &range, const std::string &msg); void backfill_debug_all(const std::string &msg); void backfill_debug_dump_log(const store_key_t &key); #else #define backfill_debug_clear_log() ((void)0) #define backfill_debug_key(key, msg) ((void)0) #define backfill_debug_range(range, msg) ((void)0) #define backfill_debug_all(msg) ((void)0) #define backfill_debug_dump_log(key) ((void)0) #endif /* ENABLE_BACKFILL_DEBUG */ #endif /* BTREE_BACKFILL_DEBUG_HPP_ */ <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * 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.1 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TRANSFORM_GRAMMAR_X3_DEF_HPP #define MAPNIK_TRANSFORM_GRAMMAR_X3_DEF_HPP #include <mapnik/transform_expression.hpp> #include <mapnik/transform_expression_grammar_x3.hpp> #include <mapnik/expression_grammar_x3.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/fusion/include/adapt_struct.hpp> #pragma GCC diagnostic pop // skewX BOOST_FUSION_ADAPT_STRUCT(mapnik::skewX_node, (mapnik::expr_node, angle_)) // skewY BOOST_FUSION_ADAPT_STRUCT(mapnik::skewY_node, (mapnik::expr_node, angle_)) // Following specializations are required to avoid trasferring mapnik::skewX/Y nodes as underlying expressions // // template <typename Source, typename Dest> // inline void // move_to_plain(Source&& src, Dest& dest, mpl::true_) // src is a single-element tuple // { // dest = std::move(fusion::front(src)); // } // which will fail to compile with latest (more strict) `mapbox::variant` (boost_1_61) namespace boost { namespace spirit { namespace x3 { namespace traits { template <> inline void move_to<mapnik::skewX_node, mapnik::detail::transform_node>(mapnik::skewX_node && src, mapnik::detail::transform_node& dst) { dst = std::move(src); } template <> inline void move_to<mapnik::skewY_node, mapnik::detail::transform_node>(mapnik::skewY_node && src, mapnik::detail::transform_node& dst) { dst = std::move(src); } }}}} namespace mapnik { namespace grammar { namespace x3 = boost::spirit::x3; namespace ascii = boost::spirit::x3::ascii; // [http://www.w3.org/TR/SVG/coords.html#TransformAttribute] // The value of the ‘transform’ attribute is a <transform-list>, which // is defined as a list of transform definitions, which are applied in // the order provided. The individual transform definitions are // separated by whitespace and/or a comma. using x3::double_; using x3::no_skip; using x3::no_case; using x3::lit; auto const create_expr_node = [](auto const& ctx) { _val(ctx) = _attr(ctx); }; auto const construct_matrix = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& a = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& b = boost::fusion::at<boost::mpl::int_<1>>(attr); auto const& c = boost::fusion::at<boost::mpl::int_<2>>(attr); auto const& d = boost::fusion::at<boost::mpl::int_<3>>(attr); auto const& e = boost::fusion::at<boost::mpl::int_<4>>(attr); auto const& f = boost::fusion::at<boost::mpl::int_<5>>(attr); _val(ctx) = mapnik::matrix_node(a, b, c, d, e, f); }; auto const construct_translate = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& dx = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& dy = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional _val(ctx) = mapnik::translate_node(dx, dy); }; auto const construct_scale = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& sx = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& sy = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional _val(ctx) = mapnik::scale_node(sx, sy); }; auto const construct_rotate = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& a = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& sx = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional auto const& sy = boost::fusion::at<boost::mpl::int_<2>>(attr); //optional _val(ctx) = mapnik::rotate_node(a, sx, sy); }; // starting rule transform_expression_grammar_type const transform("transform"); // rules x3::rule<class transform_list_class, mapnik::transform_list> transform_list_rule("transform list"); x3::rule<class transform_node_class, mapnik::transform_node> transform_node_rule("transform node"); x3::rule<class matrix_node_class, mapnik::matrix_node> matrix("matrix node"); x3::rule<class translate_node_class, mapnik::translate_node> translate("translate node"); x3::rule<class scale_node_class, mapnik::scale_node> scale("scale node"); x3::rule<class rotate_node_class, mapnik::rotate_node> rotate("rotate node"); x3::rule<class skewX_node_class, mapnik::skewX_node> skewX("skew X node"); x3::rule<class skewY_node_class, mapnik::skewY_node> skewY("skew Y node"); x3::rule<class expr_tag, mapnik::expr_node> expr("Expression"); x3::rule<class sep_expr_tag, mapnik::expr_node> sep_expr("Separated Expression"); // start auto const transform_def = transform_list_rule; auto const transform_list_rule_def = transform_node_rule % *lit(','); auto const transform_node_rule_def = matrix | translate | scale | rotate | skewX | skewY ; // number or attribute auto const atom = x3::rule<class atom_tag, expr_node> {} = double_[create_expr_node] ; // FIXME - ^ add feature attribute support e.g attr [ _val = construct<mapnik::attribute>(_1) ]; auto const sep_atom = x3::rule<class sep_atom_tag, expr_node> {} = -lit(',') >> double_[create_expr_node] ; auto const expr_def = expression_grammar(); // Individual arguments in lists containing one or more compound // expressions are separated by a comma. auto const sep_expr_def = lit(',') > expr ; // matrix(<a> <b> <c> <d> <e> <f>) auto const matrix_def = no_case[lit("matrix")] > '(' > ((atom >> sep_atom >> sep_atom >> sep_atom >> sep_atom >> sep_atom >> lit(')'))[construct_matrix] | (expr > sep_expr > sep_expr > sep_expr > sep_expr > sep_expr > lit(')'))[construct_matrix]) ; // translate(<tx> [<ty>]) auto const translate_def = no_case[lit("translate")] > lit('(') > (( atom >> -sep_atom >> lit(')'))[construct_translate] | ( expr > -sep_expr > lit(')'))[construct_translate] ); // scale(<sx> [<sy>]) auto const scale_def = no_case[lit("scale")] > lit('(') > (( atom >> -sep_atom >> lit(')'))[construct_scale] | ( expr > -sep_expr > lit(')'))[construct_scale] ); // rotate(<rotate-angle> [<cx> <cy>]) auto const rotate_def = no_case[lit("rotate")] > lit('(') > ((atom >> -sep_atom >> -sep_atom >> lit(')'))[construct_rotate] | (expr > -sep_expr > -sep_expr > lit(')'))[construct_rotate] ); // skewX(<skew-angle>) auto const skewX_def = no_case[lit("skewX")] > '(' > expr > ')'; // skewY(<skew-angle>) auto const skewY_def = no_case[lit("skewY")] > '(' > expr > ')'; BOOST_SPIRIT_DEFINE ( expr, sep_expr, transform, transform_list_rule, transform_node_rule, matrix, translate, scale, rotate, skewX, skewY); }} // ns namespace mapnik { grammar::transform_expression_grammar_type const& transform_expression_grammar() { return grammar::transform; } } #endif <commit_msg>cleanup<commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2016 Artem Pavlenko * * 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.1 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; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_TRANSFORM_GRAMMAR_X3_DEF_HPP #define MAPNIK_TRANSFORM_GRAMMAR_X3_DEF_HPP #include <mapnik/transform_expression.hpp> #include <mapnik/transform_expression_grammar_x3.hpp> #include <mapnik/expression_grammar_x3.hpp> #pragma GCC diagnostic push #include <mapnik/warning_ignore.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/fusion/include/adapt_struct.hpp> #pragma GCC diagnostic pop // skewX BOOST_FUSION_ADAPT_STRUCT(mapnik::skewX_node, (mapnik::expr_node, angle_)) // skewY BOOST_FUSION_ADAPT_STRUCT(mapnik::skewY_node, (mapnik::expr_node, angle_)) // Following specializations are required to avoid trasferring mapnik::skewX/Y nodes as underlying expressions // // template <typename Source, typename Dest> // inline void // move_to_plain(Source&& src, Dest& dest, mpl::true_) // src is a single-element tuple // { // dest = std::move(fusion::front(src)); // } // which will fail to compile with latest (more strict) `mapbox::variant` (boost_1_61) namespace boost { namespace spirit { namespace x3 { namespace traits { template <> inline void move_to<mapnik::skewX_node, mapnik::detail::transform_node>(mapnik::skewX_node && src, mapnik::detail::transform_node& dst) { dst = std::move(src); } template <> inline void move_to<mapnik::skewY_node, mapnik::detail::transform_node>(mapnik::skewY_node && src, mapnik::detail::transform_node& dst) { dst = std::move(src); } }}}} namespace mapnik { namespace grammar { namespace x3 = boost::spirit::x3; namespace ascii = boost::spirit::x3::ascii; // [http://www.w3.org/TR/SVG/coords.html#TransformAttribute] // The value of the ‘transform’ attribute is a <transform-list>, which // is defined as a list of transform definitions, which are applied in // the order provided. The individual transform definitions are // separated by whitespace and/or a comma. using x3::double_; using x3::no_skip; using x3::no_case; using x3::lit; auto const create_expr_node = [](auto const& ctx) { _val(ctx) = _attr(ctx); }; auto const construct_matrix = [] (auto const& ctx) { auto const& attr = _attr(ctx); auto const& a = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& b = boost::fusion::at<boost::mpl::int_<1>>(attr); auto const& c = boost::fusion::at<boost::mpl::int_<2>>(attr); auto const& d = boost::fusion::at<boost::mpl::int_<3>>(attr); auto const& e = boost::fusion::at<boost::mpl::int_<4>>(attr); auto const& f = boost::fusion::at<boost::mpl::int_<5>>(attr); _val(ctx) = mapnik::matrix_node(a, b, c, d, e, f); }; auto const construct_translate = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& dx = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& dy = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional _val(ctx) = mapnik::translate_node(dx, dy); }; auto const construct_scale = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& sx = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& sy = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional _val(ctx) = mapnik::scale_node(sx, sy); }; auto const construct_rotate = [](auto const& ctx) { auto const& attr = _attr(ctx); auto const& a = boost::fusion::at<boost::mpl::int_<0>>(attr); auto const& sx = boost::fusion::at<boost::mpl::int_<1>>(attr); //optional auto const& sy = boost::fusion::at<boost::mpl::int_<2>>(attr); //optional _val(ctx) = mapnik::rotate_node(a, sx, sy); }; // starting rule transform_expression_grammar_type const transform("transform"); // rules x3::rule<class transform_list_class, mapnik::transform_list> transform_list_rule("transform list"); x3::rule<class transform_node_class, mapnik::transform_node> transform_node_rule("transform node"); x3::rule<class matrix_node_class, mapnik::matrix_node> matrix("matrix node"); x3::rule<class translate_node_class, mapnik::translate_node> translate("translate node"); x3::rule<class scale_node_class, mapnik::scale_node> scale("scale node"); x3::rule<class rotate_node_class, mapnik::rotate_node> rotate("rotate node"); x3::rule<class skewX_node_class, mapnik::skewX_node> skewX("skew X node"); x3::rule<class skewY_node_class, mapnik::skewY_node> skewY("skew Y node"); x3::rule<class expr_tag, mapnik::expr_node> expr("Expression"); x3::rule<class sep_expr_tag, mapnik::expr_node> sep_expr("Separated Expression"); // start auto const transform_def = transform_list_rule; auto const transform_list_rule_def = transform_node_rule % *lit(','); auto const transform_node_rule_def = matrix | translate | scale | rotate | skewX | skewY ; // number or attribute auto const atom = x3::rule<class atom_tag, expr_node> {} = double_[create_expr_node] ; auto const sep_atom = x3::rule<class sep_atom_tag, expr_node> {} = -lit(',') >> double_[create_expr_node] ; auto const expr_def = expression_grammar(); // Individual arguments in lists containing one or more compound // expressions are separated by a comma. auto const sep_expr_def = lit(',') > expr ; // matrix(<a> <b> <c> <d> <e> <f>) auto const matrix_def = no_case[lit("matrix")] > '(' > ((atom >> sep_atom >> sep_atom >> sep_atom >> sep_atom >> sep_atom >> lit(')'))[construct_matrix] | (expr > sep_expr > sep_expr > sep_expr > sep_expr > sep_expr > lit(')'))[construct_matrix]) ; // translate(<tx> [<ty>]) auto const translate_def = no_case[lit("translate")] > lit('(') > (( atom >> -sep_atom >> lit(')'))[construct_translate] | ( expr > -sep_expr > lit(')'))[construct_translate] ); // scale(<sx> [<sy>]) auto const scale_def = no_case[lit("scale")] > lit('(') > (( atom >> -sep_atom >> lit(')'))[construct_scale] | ( expr > -sep_expr > lit(')'))[construct_scale] ); // rotate(<rotate-angle> [<cx> <cy>]) auto const rotate_def = no_case[lit("rotate")] > lit('(') > ((atom >> -sep_atom >> -sep_atom >> lit(')'))[construct_rotate] | (expr > -sep_expr > -sep_expr > lit(')'))[construct_rotate] ); // skewX(<skew-angle>) auto const skewX_def = no_case[lit("skewX")] > '(' > expr > ')'; // skewY(<skew-angle>) auto const skewY_def = no_case[lit("skewY")] > '(' > expr > ')'; BOOST_SPIRIT_DEFINE ( expr, sep_expr, transform, transform_list_rule, transform_node_rule, matrix, translate, scale, rotate, skewX, skewY); }} // ns namespace mapnik { grammar::transform_expression_grammar_type const& transform_expression_grammar() { return grammar::transform; } } #endif <|endoftext|>
<commit_before>#pragma once #include <vector> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { namespace lz78 { class BinarySortedTrie : public Algorithm, public LZ78Trie<factorid_t> { /* * The trie is not stored in standard form. Each node stores the pointer to its first child and a pointer to its next sibling (first as first come first served) */ std::vector<factorid_t> m_first_child; std::vector<factorid_t> m_next_sibling; std::vector<literal_t> m_literal; IF_STATS( size_t m_resizes = 0; size_t m_specialresizes = 0; ) public: inline static Meta meta() { Meta m("lz78trie", "binarysorted", "Lempel-Ziv 78 Sorted Binary Trie"); return m; } inline BinarySortedTrie(Env&& env, size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) { if(reserve > 0) { m_first_child.reserve(reserve); m_next_sibling.reserve(reserve); m_literal.reserve(reserve); } } node_t add_rootnode(uliteral_t c) override { m_first_child.push_back(undef_id); m_next_sibling.push_back(undef_id); m_literal.push_back(c); return size() - 1; } node_t get_rootnode(uliteral_t c) override { return c; } void clear() override { m_first_child.clear(); m_next_sibling.clear(); m_literal.clear(); } inline factorid_t new_node(uliteral_t c, const factorid_t m_first_child_id, const factorid_t m_next_sibling_id) { m_first_child.push_back(m_first_child_id); m_next_sibling.push_back(m_next_sibling_id); m_literal.push_back(c); return undef_id; } node_t find_or_insert(const node_t& parent_w, uliteral_t c) override { auto parent = parent_w.id(); const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary DCHECK_LT(parent, size()); if(m_first_child[parent] == undef_id) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, undef_id); } else { factorid_t node = m_first_child[parent]; if(m_literal[node] > c) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, node); } while(true) { // search the binary tree stored in parent (following left/right siblings) if(c == m_literal[node]) return node; if(m_next_sibling[node] == undef_id) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, undef_id); } const factorid_t nextnode = m_next_sibling[node]; if(m_literal[nextnode] > c) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, nextnode); } node = m_next_sibling[node]; if(m_first_child.capacity() == m_first_child.size()) { const size_t newbound = m_first_child.size()+lz78_expected_number_of_remaining_elements(size(),m_n,m_remaining_characters); if(newbound < m_first_child.size()*2 ) { m_first_child.reserve (newbound); m_next_sibling.reserve (newbound); m_literal.reserve (newbound); IF_STATS(++m_specialresizes); } IF_STATS(++m_resizes); } } } DCHECK(false); return undef_id; } factorid_t size() const override { return m_first_child.size(); } }; }} //ns <commit_msg>fix bug in sorted binary trie<commit_after>#pragma once #include <vector> #include <tudocomp/compressors/lz78/LZ78Trie.hpp> #include <tudocomp/Algorithm.hpp> namespace tdc { namespace lz78 { class BinarySortedTrie : public Algorithm, public LZ78Trie<factorid_t> { /* * The trie is not stored in standard form. Each node stores the pointer to its first child and a pointer to its next sibling (first as first come first served) */ std::vector<factorid_t> m_first_child; std::vector<factorid_t> m_next_sibling; std::vector<uliteral_t> m_literal; IF_STATS( size_t m_resizes = 0; size_t m_specialresizes = 0; ) public: inline static Meta meta() { Meta m("lz78trie", "binarysorted", "Lempel-Ziv 78 Sorted Binary Trie"); return m; } inline BinarySortedTrie(Env&& env, size_t n, const size_t& remaining_characters, factorid_t reserve = 0) : Algorithm(std::move(env)) , LZ78Trie(n,remaining_characters) { if(reserve > 0) { m_first_child.reserve(reserve); m_next_sibling.reserve(reserve); m_literal.reserve(reserve); } } node_t add_rootnode(uliteral_t c) override { m_first_child.push_back(undef_id); m_next_sibling.push_back(undef_id); m_literal.push_back(c); return size() - 1; } node_t get_rootnode(uliteral_t c) override { return c; } void clear() override { m_first_child.clear(); m_next_sibling.clear(); m_literal.clear(); } inline factorid_t new_node(uliteral_t c, const factorid_t m_first_child_id, const factorid_t m_next_sibling_id) { m_first_child.push_back(m_first_child_id); m_next_sibling.push_back(m_next_sibling_id); m_literal.push_back(c); return undef_id; } node_t find_or_insert(const node_t& parent_w, uliteral_t c) override { auto parent = parent_w.id(); const factorid_t newleaf_id = size(); //! if we add a new node, its index will be equal to the current size of the dictionary DCHECK_LT(parent, size()); if(m_first_child[parent] == undef_id) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, undef_id); } else { factorid_t node = m_first_child[parent]; if(m_literal[node] > c) { m_first_child[parent] = newleaf_id; return new_node(c, undef_id, node); } while(true) { // search the binary tree stored in parent (following left/right siblings) if(c == m_literal[node]) return node; if(m_next_sibling[node] == undef_id) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, undef_id); } const factorid_t nextnode = m_next_sibling[node]; if(m_literal[nextnode] > c) { m_next_sibling[node] = newleaf_id; return new_node(c, undef_id, nextnode); } node = m_next_sibling[node]; if(m_first_child.capacity() == m_first_child.size()) { const size_t newbound = m_first_child.size()+lz78_expected_number_of_remaining_elements(size(),m_n,m_remaining_characters); if(newbound < m_first_child.size()*2 ) { m_first_child.reserve (newbound); m_next_sibling.reserve (newbound); m_literal.reserve (newbound); IF_STATS(++m_specialresizes); } IF_STATS(++m_resizes); } } } DCHECK(false); return undef_id; } factorid_t size() const override { return m_first_child.size(); } }; }} //ns <|endoftext|>
<commit_before>/* * Copyright (c) 2014 David Wicks, sansumbrella.com * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. */ #pragma once namespace choreograph { // A motion describes a one-dimensional change through time. // These can be ease equations, always return the same value, or sample some data. Whatever you want. // For classic motion, EaseFn( 0 ) = 0, EaseFn( 1 ) = 1. // set( 0.0f ).move( ) // then again, might just make a curve struct that is callable and have a way to set its initial and final derivatives. typedef std::function<float (float)> EaseFn; struct Hold { float operator() ( float t ) const { return 0.0f; } }; struct LinearRamp { float operator() ( float t ) const { return t; } }; inline float easeNone( float t ) { return t; } //! A Position describes a point in time. template<typename T> struct Position { Position() = default; Position( const T &value, float time = 0.0f ): time( time ), value( value ) {} float time = 0.0f; T value; }; //! The default templated lerp function. template<typename T> T lerpT( const T &a, const T &b, float t ) { return a + (b - a) * t; } /** A Phrase is a part of a Sequence. It describes the motion between two positions. This is the essence of a Tween, with all values held internally. */ template<typename T> class Phrase { public: using LerpFn = std::function<T (const T&, const T&, float)>; Phrase( const T &end, float duration, const EaseFn &easeFn = &easeNone ): end( end, duration ), motion( easeFn ) {} Phrase( const Position<T> &start, const Position<T> &end, const EaseFn &easeFn = &easeNone ): start( start ), end( end ), motion( easeFn ) {} virtual ~Phrase() = default; //! Set start time to \a time. End time is adjusted to preserve duration. void shiftStartTimeTo( float time ) { float delta = time - start.time; start.time = time; end.time += delta; } //! Change start value to \a value. void setStartValue( const T &value ) { start.value = value; } //! Returns the value at the beginning of this phrase. inline const T& getStartValue() const { return start.value; } //! Returns the value at the end of this phrase. inline const T& getEndValue() const { return end.value; } //! Returns the time at the beginning of this phrase. inline float getStartTime() const { return start.time; } //! Returns the time at the end of this phrase. inline float getEndTime() const { return end.time; } //! Returns normalized time if t is in range [start.time, end.time]. inline float normalizeTime( float t ) const { return (t - start.time) / (end.time - start.time); } //! Returns the duration of this phrase. inline float getDuration() const { return end.time - start.time; } //! Returns the interpolated value at the given time. virtual T getValue( float atTime ) const { return lerpFn( start.value, end.value, motion( normalizeTime( atTime ) ) ); } private: Position<T> start; Position<T> end; EaseFn motion; LerpFn lerpFn = &lerpT<T>; }; template<typename T> using PhraseRef = std::shared_ptr<Phrase<T>>; /** Phrase with separately-interpolated components. Allows for the use of separate ease functions per component. All components must be of the same type. */ template<typename T> class Phrase2 : public Phrase<T> { public: Phrase2( const T &end, float duration, const EaseFn &ease_x, const EaseFn &ease_y ): Phrase<T>( end, duration ), motion_x( ease_x ), motion_y( ease_y ) {} Phrase2( const Position<T> &start, const Position<T> &end, const EaseFn &ease_x, const EaseFn &ease_y ): Phrase<T>( start, end ), motion_x( ease_x ), motion_y( ease_y ) {} //! Returns the interpolated value at the given time. T getValue( float atTime ) const override { float t = Phrase<T>::normalizeTime( atTime ); return T( componentLerpFn( Phrase<T>::getStartValue().x, Phrase<T>::getEndValue().x, motion_x( t ) ), componentLerpFn( Phrase<T>::getStartValue().y, Phrase<T>::getEndValue().y, motion_y( t ) ) ); } //! Set ease functions for first and second components. void setEase( const EaseFn &component_0, const EaseFn &component_1 ) { motion_x = component_0; motion_y = component_1; } private: using ComponentT = decltype( T().x ); // get the type of the x component; using ComponentLerpFn = std::function<ComponentT (const ComponentT&, const ComponentT&, float)>; ComponentLerpFn componentLerpFn = &lerpT<ComponentT>; EaseFn motion_x; EaseFn motion_y; }; /** A Sequence of motions. Our essential compositional tool, describing all the transformations to one element. A kind of platonic idea of an animation sequence; this describes a motion without giving it an output. */ template<typename T> class Sequence { public: // Sequences always need to have some valid value. Sequence() = delete; //! Construct a Sequence with an initial \a value. explicit Sequence( const T &value ): _initial_value( value ) {} T getValue( float atTime ); //! Set current value. An instantaneous hold. Sequence<T>& set( const T &value ) { if( _segments.empty() ) { _initial_value = value; } else { hold( value, 0.0f ); } return *this; } //! Returns a copy of this sequence. Useful if you want to make a base animation and modify that. std::shared_ptr<Sequence<T>> copy() const { return std::make_shared<Sequence<T>>( *this ); } //! Hold on current end value for \a duration seconds. Sequence<T>& wait( float duration ) { return hold( duration ); } //! Hold on current end value for \a duration seconds. Sequence<T>& hold( float duration ) { return hold( endValue(), duration ); } //! Hold on \a value for \a duration seconds. Sequence<T>& hold( const T &value, float duration ) { Position<T> start{ value, _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<Phrase<T>>( start, end, Hold() ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } //! Animate to \a value over \a duration seconds using \a ease easing. Sequence<T>& rampTo( const T &value, float duration, const EaseFn &ease = LinearRamp() ) { Position<T> start{ endValue(), _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<Phrase<T>>( start, end, ease ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } template<typename PhraseT, typename... Args> Sequence<T>& then( const T& value, float duration, Args... args ) { Position<T> start{ endValue(), _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<PhraseT>( start, end, args... ); // Would expect the following to make my dream user syntax work. // auto phrase = std::make_shared<PhraseT<T>>( start, end, args... ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } Sequence<T>& then( const PhraseRef<T>& phrase ) { phrase->setStartValue( endValue() ); phrase->shiftStartTimeTo( _duration ); _duration = phrase->getEndTime(); _segments.push_back( phrase ); return *this; } //! Sets the ease function of the last Phrase in the Sequence. Sequence<T>& ease( const EaseFn &easeFn ) { if( ! _segments.empty() ) { _segments.back().motion = easeFn; } return *this; } //! Returns the number of seconds required to move through all Phrases. float getDuration() const { return _duration; } //! Returns the value at the end of the Sequence. T endValue() const { return _segments.empty() ? _initial_value : _segments.back()->getEndValue(); } //! Returns the value at the beginning of the Sequence. T initialValue() const { return _initial_value; } private: std::vector<PhraseRef<T>> _segments; T _initial_value; float _duration = 0.0f; friend class Timeline; }; //! Returns the value of this sequence for a given point in time. // Would be nice to have a constant-time check (without a while loop). template<typename T> T Sequence<T>::getValue( float atTime ) { if( atTime < 0.0f ) { return _initial_value; } else if ( atTime >= _duration ) { return endValue(); } auto iter = _segments.begin(); while( iter < _segments.end() ) { if( (*iter)->getEndTime() > atTime ) { return (*iter)->getValue( atTime ); } ++iter; } // past the end, get the final value // this should be unreachable, given that we return early if time >= duration return endValue(); } template<typename T> using SequenceRef = std::shared_ptr<Sequence<T>>; } // namespace choreograph <commit_msg>Typedef for Phrase2v.<commit_after>/* * Copyright (c) 2014 David Wicks, sansumbrella.com * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 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. */ #pragma once namespace choreograph { // A motion describes a one-dimensional change through time. // These can be ease equations, always return the same value, or sample some data. Whatever you want. // For classic motion, EaseFn( 0 ) = 0, EaseFn( 1 ) = 1. // set( 0.0f ).move( ) // then again, might just make a curve struct that is callable and have a way to set its initial and final derivatives. typedef std::function<float (float)> EaseFn; struct Hold { float operator() ( float t ) const { return 0.0f; } }; struct LinearRamp { float operator() ( float t ) const { return t; } }; inline float easeNone( float t ) { return t; } //! A Position describes a point in time. template<typename T> struct Position { Position() = default; Position( const T &value, float time = 0.0f ): time( time ), value( value ) {} float time = 0.0f; T value; }; //! The default templated lerp function. template<typename T> T lerpT( const T &a, const T &b, float t ) { return a + (b - a) * t; } /** A Phrase is a part of a Sequence. It describes the motion between two positions. This is the essence of a Tween, with all values held internally. */ template<typename T> class Phrase { public: using LerpFn = std::function<T (const T&, const T&, float)>; Phrase( const T &end, float duration, const EaseFn &easeFn = &easeNone ): end( end, duration ), motion( easeFn ) {} Phrase( const Position<T> &start, const Position<T> &end, const EaseFn &easeFn = &easeNone ): start( start ), end( end ), motion( easeFn ) {} virtual ~Phrase() = default; //! Set start time to \a time. End time is adjusted to preserve duration. void shiftStartTimeTo( float time ) { float delta = time - start.time; start.time = time; end.time += delta; } //! Change start value to \a value. void setStartValue( const T &value ) { start.value = value; } //! Returns the value at the beginning of this phrase. inline const T& getStartValue() const { return start.value; } //! Returns the value at the end of this phrase. inline const T& getEndValue() const { return end.value; } //! Returns the time at the beginning of this phrase. inline float getStartTime() const { return start.time; } //! Returns the time at the end of this phrase. inline float getEndTime() const { return end.time; } //! Returns normalized time if t is in range [start.time, end.time]. inline float normalizeTime( float t ) const { return (t - start.time) / (end.time - start.time); } //! Returns the duration of this phrase. inline float getDuration() const { return end.time - start.time; } //! Returns the interpolated value at the given time. virtual T getValue( float atTime ) const { return lerpFn( start.value, end.value, motion( normalizeTime( atTime ) ) ); } private: Position<T> start; Position<T> end; EaseFn motion; LerpFn lerpFn = &lerpT<T>; }; template<typename T> using PhraseRef = std::shared_ptr<Phrase<T>>; /** Phrase with separately-interpolated components. Allows for the use of separate ease functions per component. All components must be of the same type. */ template<typename T> class Phrase2 : public Phrase<T> { public: Phrase2( const T &end, float duration, const EaseFn &ease_x, const EaseFn &ease_y ): Phrase<T>( end, duration ), motion_x( ease_x ), motion_y( ease_y ) {} Phrase2( const Position<T> &start, const Position<T> &end, const EaseFn &ease_x, const EaseFn &ease_y ): Phrase<T>( start, end ), motion_x( ease_x ), motion_y( ease_y ) {} //! Returns the interpolated value at the given time. T getValue( float atTime ) const override { float t = Phrase<T>::normalizeTime( atTime ); return T( componentLerpFn( Phrase<T>::getStartValue().x, Phrase<T>::getEndValue().x, motion_x( t ) ), componentLerpFn( Phrase<T>::getStartValue().y, Phrase<T>::getEndValue().y, motion_y( t ) ) ); } //! Set ease functions for first and second components. void setEase( const EaseFn &component_0, const EaseFn &component_1 ) { motion_x = component_0; motion_y = component_1; } private: using ComponentT = decltype( T().x ); // get the type of the x component; using ComponentLerpFn = std::function<ComponentT (const ComponentT&, const ComponentT&, float)>; ComponentLerpFn componentLerpFn = &lerpT<ComponentT>; EaseFn motion_x; EaseFn motion_y; }; using Phrase2v = Phrase2<ci::vec2>; /** A Sequence of motions. Our essential compositional tool, describing all the transformations to one element. A kind of platonic idea of an animation sequence; this describes a motion without giving it an output. */ template<typename T> class Sequence { public: // Sequences always need to have some valid value. Sequence() = delete; //! Construct a Sequence with an initial \a value. explicit Sequence( const T &value ): _initial_value( value ) {} T getValue( float atTime ); //! Set current value. An instantaneous hold. Sequence<T>& set( const T &value ) { if( _segments.empty() ) { _initial_value = value; } else { hold( value, 0.0f ); } return *this; } //! Returns a copy of this sequence. Useful if you want to make a base animation and modify that. std::shared_ptr<Sequence<T>> copy() const { return std::make_shared<Sequence<T>>( *this ); } //! Hold on current end value for \a duration seconds. Sequence<T>& wait( float duration ) { return hold( duration ); } //! Hold on current end value for \a duration seconds. Sequence<T>& hold( float duration ) { return hold( endValue(), duration ); } //! Hold on \a value for \a duration seconds. Sequence<T>& hold( const T &value, float duration ) { Position<T> start{ value, _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<Phrase<T>>( start, end, Hold() ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } //! Animate to \a value over \a duration seconds using \a ease easing. Sequence<T>& rampTo( const T &value, float duration, const EaseFn &ease = LinearRamp() ) { Position<T> start{ endValue(), _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<Phrase<T>>( start, end, ease ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } template<typename PhraseT, typename... Args> Sequence<T>& then( const T& value, float duration, Args... args ) { Position<T> start{ endValue(), _duration }; Position<T> end{ value, _duration + duration }; auto phrase = std::make_shared<PhraseT>( start, end, args... ); // Would expect the following to make my dream user syntax work. // auto phrase = std::make_shared<PhraseT<T>>( start, end, args... ); _segments.push_back( phrase ); _duration = phrase->getEndTime(); return *this; } Sequence<T>& then( const PhraseRef<T>& phrase ) { phrase->setStartValue( endValue() ); phrase->shiftStartTimeTo( _duration ); _duration = phrase->getEndTime(); _segments.push_back( phrase ); return *this; } //! Sets the ease function of the last Phrase in the Sequence. Sequence<T>& ease( const EaseFn &easeFn ) { if( ! _segments.empty() ) { _segments.back().motion = easeFn; } return *this; } //! Returns the number of seconds required to move through all Phrases. float getDuration() const { return _duration; } //! Returns the value at the end of the Sequence. T endValue() const { return _segments.empty() ? _initial_value : _segments.back()->getEndValue(); } //! Returns the value at the beginning of the Sequence. T initialValue() const { return _initial_value; } private: std::vector<PhraseRef<T>> _segments; T _initial_value; float _duration = 0.0f; friend class Timeline; }; //! Returns the value of this sequence for a given point in time. // Would be nice to have a constant-time check (without a while loop). template<typename T> T Sequence<T>::getValue( float atTime ) { if( atTime < 0.0f ) { return _initial_value; } else if ( atTime >= _duration ) { return endValue(); } auto iter = _segments.begin(); while( iter < _segments.end() ) { if( (*iter)->getEndTime() > atTime ) { return (*iter)->getValue( atTime ); } ++iter; } // past the end, get the final value // this should be unreachable, given that we return early if time >= duration return endValue(); } template<typename T> using SequenceRef = std::shared_ptr<Sequence<T>>; } // namespace choreograph <|endoftext|>
<commit_before>//===-- RISCVELFObjectWriter.cpp - RISCV ELF Writer -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCTargetDesc/RISCVMCTargetDesc.h" #include "llvm/MC/MCELFObjectWriter.h" #include "llvm/MC/MCFixup.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class RISCVELFObjectWriter : public MCELFObjectTargetWriter { public: RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit); ~RISCVELFObjectWriter() override; protected: unsigned getRelocType(MCContext &Ctx, const MCValue &Target, const MCFixup &Fixup, bool IsPCRel) const override; }; } RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit) : MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV, /*HasRelocationAddend*/ false) {} RISCVELFObjectWriter::~RISCVELFObjectWriter() {} unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target, const MCFixup &Fixup, bool IsPCRel) const { // Determine the type of the relocation switch ((unsigned)Fixup.getKind()) { default: llvm_unreachable("invalid fixup kind!"); } } MCObjectWriter *llvm::createRISCVELFObjectWriter(raw_pwrite_stream &OS, uint8_t OSABI, bool Is64Bit) { MCELFObjectTargetWriter *MOTW = new RISCVELFObjectWriter(OSABI, Is64Bit); return createELFObjectWriter(MOTW, OS, /*IsLittleEndian*/ true); } <commit_msg>Removing a switch statement that contains a default label, but no case labels. Silences an MSVC warning; NFC.<commit_after>//===-- RISCVELFObjectWriter.cpp - RISCV ELF Writer -----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "MCTargetDesc/RISCVMCTargetDesc.h" #include "llvm/MC/MCELFObjectWriter.h" #include "llvm/MC/MCFixup.h" #include "llvm/Support/ErrorHandling.h" using namespace llvm; namespace { class RISCVELFObjectWriter : public MCELFObjectTargetWriter { public: RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit); ~RISCVELFObjectWriter() override; protected: unsigned getRelocType(MCContext &Ctx, const MCValue &Target, const MCFixup &Fixup, bool IsPCRel) const override; }; } RISCVELFObjectWriter::RISCVELFObjectWriter(uint8_t OSABI, bool Is64Bit) : MCELFObjectTargetWriter(Is64Bit, OSABI, ELF::EM_RISCV, /*HasRelocationAddend*/ false) {} RISCVELFObjectWriter::~RISCVELFObjectWriter() {} unsigned RISCVELFObjectWriter::getRelocType(MCContext &Ctx, const MCValue &Target, const MCFixup &Fixup, bool IsPCRel) const { llvm_unreachable("invalid fixup kind!"); } MCObjectWriter *llvm::createRISCVELFObjectWriter(raw_pwrite_stream &OS, uint8_t OSABI, bool Is64Bit) { MCELFObjectTargetWriter *MOTW = new RISCVELFObjectWriter(OSABI, Is64Bit); return createELFObjectWriter(MOTW, OS, /*IsLittleEndian*/ true); } <|endoftext|>
<commit_before>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas ([email protected]) * */ #include <algorithm> #include "bm_sim/fields.h" int Field::extract(const char *data, int hdr_offset) { if(hdr_offset == 0 && nbits % 8 == 0) { std::copy(data, data + nbytes, bytes.begin()); if(arith) sync_value(); return nbits; } int field_offset = (nbytes << 3) - nbits; int i; // necessary to ensure correct behavior when shifting right (no sign extension) unsigned char *udata = (unsigned char *) data; int offset = hdr_offset - field_offset; if (offset == 0) { std::copy(udata, udata + nbytes, bytes.begin()); bytes[0] &= (0xFF >> field_offset); } else if (offset > 0) { /* shift left */ for (i = 0; i < nbytes - 1; i++) { bytes[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset)); } bytes[0] &= (0xFF >> field_offset); bytes[i] = udata[i] << offset; if((hdr_offset + nbits) > (nbytes << 3)) { bytes[i] |= (udata[i + 1] >> (8 - offset)); } } else { /* shift right */ offset = -offset; bytes[0] = udata[0] >> offset; for (i = 1; i < nbytes; i++) { bytes[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset); } } if(arith) sync_value(); return nbits; } int Field::deparse(char *data, int hdr_offset) const { if(hdr_offset == 0 && nbits % 8 == 0) { std::copy(bytes.begin(), bytes.end(), data); return nbits; } int field_offset = (nbytes << 3) - nbits; int hdr_bytes = (hdr_offset + nbits + 7) / 8; int i; // zero out bits we are going to write in data[0] data[0] &= (~(0xFF >> hdr_offset)); int offset = field_offset - hdr_offset; if (offset == 0) { std::copy(bytes.begin() + 1, bytes.begin() + hdr_bytes, data + 1); data[0] |= bytes[0]; } else if (offset > 0) { /* shift left */ /* this assumes that the packet was memset to 0, TODO: improve */ for (i = 0; i < hdr_bytes - 1; i++) { data[i] |= (bytes[i] << offset) | (bytes[i + 1] >> (8 - offset)); } int tail_offset = (hdr_bytes << 3) - (hdr_offset + nbits); data[i] &= ((1 << tail_offset) - 1); data[i] |= bytes[i] << offset; if((field_offset + nbits) > (hdr_bytes << 3)) { data[i] |= (bytes[i + 1] >> (8 - offset)); } } else { /* shift right */ offset = -offset; data[0] |= (bytes[0] >> offset); if(hdr_bytes == 1) return nbits; for (i = 1; i < hdr_bytes - 1; i++) { data[i] = (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset); } int tail_offset = (hdr_bytes >> 3) - (hdr_offset + nbits); data[i] &= ((1 << tail_offset) - 1); data[i] |= (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset); } return nbits; } <commit_msg>fixed bug in deparser (yesterday's fix was wrong)<commit_after>/* Copyright 2013-present Barefoot Networks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Antonin Bas ([email protected]) * */ #include <algorithm> #include "bm_sim/fields.h" int Field::extract(const char *data, int hdr_offset) { if(hdr_offset == 0 && nbits % 8 == 0) { std::copy(data, data + nbytes, bytes.begin()); if(arith) sync_value(); return nbits; } int field_offset = (nbytes << 3) - nbits; int i; // necessary to ensure correct behavior when shifting right (no sign extension) unsigned char *udata = (unsigned char *) data; int offset = hdr_offset - field_offset; if (offset == 0) { std::copy(udata, udata + nbytes, bytes.begin()); bytes[0] &= (0xFF >> field_offset); } else if (offset > 0) { /* shift left */ for (i = 0; i < nbytes - 1; i++) { bytes[i] = (udata[i] << offset) | (udata[i + 1] >> (8 - offset)); } bytes[0] &= (0xFF >> field_offset); bytes[i] = udata[i] << offset; if((hdr_offset + nbits) > (nbytes << 3)) { bytes[i] |= (udata[i + 1] >> (8 - offset)); } } else { /* shift right */ offset = -offset; bytes[0] = udata[0] >> offset; for (i = 1; i < nbytes; i++) { bytes[i] = (udata[i - 1] << (8 - offset)) | (udata[i] >> offset); } } if(arith) sync_value(); return nbits; } int Field::deparse(char *data, int hdr_offset) const { if(hdr_offset == 0 && nbits % 8 == 0) { std::copy(bytes.begin(), bytes.end(), data); return nbits; } int field_offset = (nbytes << 3) - nbits; int hdr_bytes = (hdr_offset + nbits + 7) / 8; int i; // zero out bits we are going to write in data[0] data[0] &= (~(0xFF >> hdr_offset)); int offset = field_offset - hdr_offset; if (offset == 0) { std::copy(bytes.begin() + 1, bytes.begin() + hdr_bytes, data + 1); data[0] |= bytes[0]; } else if (offset > 0) { /* shift left */ /* this assumes that the packet was memset to 0, TODO: improve */ for (i = 0; i < hdr_bytes - 1; i++) { data[i] |= (bytes[i] << offset) | (bytes[i + 1] >> (8 - offset)); } int tail_offset = (hdr_bytes << 3) - (hdr_offset + nbits); data[i] &= ((1 << tail_offset) - 1); data[i] |= bytes[i] << offset; if((field_offset + nbits) > (hdr_bytes << 3)) { data[i] |= (bytes[i + 1] >> (8 - offset)); } } else { /* shift right */ offset = -offset; data[0] |= (bytes[0] >> offset); if(nbytes == 1) return nbits; for (i = 1; i < hdr_bytes - 1; i++) { data[i] = (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset); } int tail_offset = (hdr_bytes >> 3) - (hdr_offset + nbits); data[i] &= ((1 << tail_offset) - 1); data[i] |= (bytes[i - 1] << (8 - offset)) | (bytes[i] >> offset); } return nbits; } <|endoftext|>
<commit_before>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors // Peng Xiao, [email protected] // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other oclMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors as is and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace std; #ifdef HAVE_CLAMDFFT //////////////////////////////////////////////////////////////////////////// // Dft PARAM_TEST_CASE(Dft, cv::Size, int) { cv::Size dft_size; int dft_flags; virtual void SetUp() { dft_size = GET_PARAM(0); dft_flags = GET_PARAM(1); } }; TEST_P(Dft, C2C) { cv::Mat a = randomMat(dft_size, CV_32FC2, 0.0, 100.0); cv::Mat b_gold; cv::ocl::oclMat d_b; cv::dft(a, b_gold, dft_flags); cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags); EXPECT_MAT_NEAR(b_gold, cv::Mat(d_b), a.size().area() * 1e-4); } TEST_P(Dft, R2C) { cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 100.0); cv::Mat b_gold, b_gold_roi; cv::ocl::oclMat d_b, d_c; cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags); cv::dft(a, b_gold, cv::DFT_COMPLEX_OUTPUT | dft_flags); b_gold_roi = b_gold(cv::Rect(0, 0, d_b.cols, d_b.rows)); EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4); cv::Mat c_gold; cv::dft(b_gold, c_gold, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE); EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4); } TEST_P(Dft, R2CthenC2R) { cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 10.0); cv::ocl::oclMat d_b, d_c; cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), 0); cv::ocl::dft(d_b, d_c, a.size(), cv::DFT_SCALE | cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT); EXPECT_MAT_NEAR(a, d_c, a.size().area() * 1e-4); } INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Dft, testing::Combine( testing::Values(cv::Size(2, 3), cv::Size(5, 4), cv::Size(25, 20), cv::Size(512, 1), cv::Size(1024, 768)), testing::Values(0, (int)cv::DFT_ROWS, (int)cv::DFT_SCALE) )); //////////////////////////////////////////////////////////////////////////// // MulSpectrums PARAM_TEST_CASE(MulSpectrums, cv::Size, DftFlags, bool) { cv::Size size; int flag; bool ccorr; cv::Mat a, b; virtual void SetUp() { size = GET_PARAM(0); flag = GET_PARAM(1); ccorr = GET_PARAM(2); a = randomMat(size, CV_32FC2); b = randomMat(size, CV_32FC2); } }; TEST_P(MulSpectrums, Simple) { cv::ocl::oclMat c; cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, 1.0, ccorr); cv::Mat c_gold; cv::mulSpectrums(a, b, c_gold, flag, ccorr); EXPECT_MAT_NEAR(c_gold, c, 1e-2, ""); } TEST_P(MulSpectrums, Scaled) { float scale = 1.f / size.area(); cv::ocl::oclMat c; cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, scale, ccorr); cv::Mat c_gold; cv::mulSpectrums(a, b, c_gold, flag, ccorr); c_gold.convertTo(c_gold, c_gold.type(), scale); EXPECT_MAT_NEAR(c_gold, c, 1e-2, ""); } INSTANTIATE_TEST_CASE_P(OCL_ImgProc, MulSpectrums, testing::Combine( DIFFERENT_SIZES, testing::Values(DftFlags(0)), testing::Values(false, true))); //////////////////////////////////////////////////////// // Convolve void static convolveDFT(const cv::Mat& A, const cv::Mat& B, cv::Mat& C, bool ccorr = false) { // reallocate the output array if needed C.create(std::abs(A.rows - B.rows) + 1, std::abs(A.cols - B.cols) + 1, A.type()); cv::Size dftSize; // compute the size of DFT transform dftSize.width = cv::getOptimalDFTSize(A.cols + B.cols - 1); dftSize.height = cv::getOptimalDFTSize(A.rows + B.rows - 1); // allocate temporary buffers and initialize them with 0s cv::Mat tempA(dftSize, A.type(), cv::Scalar::all(0)); cv::Mat tempB(dftSize, B.type(), cv::Scalar::all(0)); // copy A and B to the top-left corners of tempA and tempB, respectively cv::Mat roiA(tempA, cv::Rect(0, 0, A.cols, A.rows)); A.copyTo(roiA); cv::Mat roiB(tempB, cv::Rect(0, 0, B.cols, B.rows)); B.copyTo(roiB); // now transform the padded A & B in-place; // use "nonzeroRows" hint for faster processing cv::dft(tempA, tempA, 0, A.rows); cv::dft(tempB, tempB, 0, B.rows); // multiply the spectrums; // the function handles packed spectrum representations well cv::mulSpectrums(tempA, tempB, tempA, 0, ccorr); // transform the product back from the frequency domain. // Even though all the result rows will be non-zero, // you need only the first C.rows of them, and thus you // pass nonzeroRows == C.rows cv::dft(tempA, tempA, cv::DFT_INVERSE + cv::DFT_SCALE, C.rows); // now copy the result back to C. tempA(cv::Rect(0, 0, C.cols, C.rows)).copyTo(C); } IMPLEMENT_PARAM_CLASS(KSize, int); IMPLEMENT_PARAM_CLASS(Ccorr, bool); PARAM_TEST_CASE(Convolve_DFT, cv::Size, KSize, Ccorr) { cv::Size size; int ksize; bool ccorr; cv::Mat src; cv::Mat kernel; cv::Mat dst_gold; virtual void SetUp() { size = GET_PARAM(0); ksize = GET_PARAM(1); ccorr = GET_PARAM(2); } }; TEST_P(Convolve_DFT, Accuracy) { cv::Mat src = randomMat(size, CV_32FC1, 0.0, 100.0); cv::Mat kernel = randomMat(cv::Size(ksize, ksize), CV_32FC1, 0.0, 1.0); cv::ocl::oclMat dst; cv::ocl::convolve(cv::ocl::oclMat(src), cv::ocl::oclMat(kernel), dst, ccorr); cv::Mat dst_gold; convolveDFT(src, kernel, dst_gold, ccorr); EXPECT_MAT_NEAR(dst, dst_gold, 1e-1, ""); } #define DIFFERENT_CONVOLVE_SIZES testing::Values(cv::Size(251, 257), cv::Size(113, 113), cv::Size(200, 480), cv::Size(1300, 1300)) INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Convolve_DFT, testing::Combine( DIFFERENT_CONVOLVE_SIZES, testing::Values(KSize(19), KSize(23), KSize(45)), testing::Values(Ccorr(true)/*, Ccorr(false)*/))); // false ccorr cannot pass for some instances #endif // HAVE_CLAMDFFT <commit_msg>Warning fixes<commit_after>/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved. // Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // @Authors // Peng Xiao, [email protected] // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other oclMaterials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors as is and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" using namespace std; #ifdef HAVE_CLAMDFFT //////////////////////////////////////////////////////////////////////////// // Dft PARAM_TEST_CASE(Dft, cv::Size, int) { cv::Size dft_size; int dft_flags; virtual void SetUp() { dft_size = GET_PARAM(0); dft_flags = GET_PARAM(1); } }; TEST_P(Dft, C2C) { cv::Mat a = randomMat(dft_size, CV_32FC2, 0.0, 100.0); cv::Mat b_gold; cv::ocl::oclMat d_b; cv::dft(a, b_gold, dft_flags); cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags); EXPECT_MAT_NEAR(b_gold, cv::Mat(d_b), a.size().area() * 1e-4); } TEST_P(Dft, R2C) { cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 100.0); cv::Mat b_gold, b_gold_roi; cv::ocl::oclMat d_b, d_c; cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), dft_flags); cv::dft(a, b_gold, cv::DFT_COMPLEX_OUTPUT | dft_flags); b_gold_roi = b_gold(cv::Rect(0, 0, d_b.cols, d_b.rows)); EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4); cv::Mat c_gold; cv::dft(b_gold, c_gold, cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT | cv::DFT_SCALE); EXPECT_MAT_NEAR(b_gold_roi, cv::Mat(d_b), a.size().area() * 1e-4); } TEST_P(Dft, R2CthenC2R) { cv::Mat a = randomMat(dft_size, CV_32FC1, 0.0, 10.0); cv::ocl::oclMat d_b, d_c; cv::ocl::dft(cv::ocl::oclMat(a), d_b, a.size(), 0); cv::ocl::dft(d_b, d_c, a.size(), cv::DFT_SCALE | cv::DFT_INVERSE | cv::DFT_REAL_OUTPUT); EXPECT_MAT_NEAR(a, d_c, a.size().area() * 1e-4); } INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Dft, testing::Combine( testing::Values(cv::Size(2, 3), cv::Size(5, 4), cv::Size(25, 20), cv::Size(512, 1), cv::Size(1024, 768)), testing::Values(0, (int)cv::DFT_ROWS, (int)cv::DFT_SCALE) )); //////////////////////////////////////////////////////////////////////////// // MulSpectrums PARAM_TEST_CASE(MulSpectrums, cv::Size, DftFlags, bool) { cv::Size size; int flag; bool ccorr; cv::Mat a, b; virtual void SetUp() { size = GET_PARAM(0); flag = GET_PARAM(1); ccorr = GET_PARAM(2); a = randomMat(size, CV_32FC2); b = randomMat(size, CV_32FC2); } }; TEST_P(MulSpectrums, Simple) { cv::ocl::oclMat c; cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, 1.0, ccorr); cv::Mat c_gold; cv::mulSpectrums(a, b, c_gold, flag, ccorr); EXPECT_MAT_NEAR(c_gold, c, 1e-2); } TEST_P(MulSpectrums, Scaled) { float scale = 1.f / size.area(); cv::ocl::oclMat c; cv::ocl::mulSpectrums(cv::ocl::oclMat(a), cv::ocl::oclMat(b), c, flag, scale, ccorr); cv::Mat c_gold; cv::mulSpectrums(a, b, c_gold, flag, ccorr); c_gold.convertTo(c_gold, c_gold.type(), scale); EXPECT_MAT_NEAR(c_gold, c, 1e-2); } INSTANTIATE_TEST_CASE_P(OCL_ImgProc, MulSpectrums, testing::Combine( DIFFERENT_SIZES, testing::Values(DftFlags(0)), testing::Values(false, true))); //////////////////////////////////////////////////////// // Convolve void static convolveDFT(const cv::Mat& A, const cv::Mat& B, cv::Mat& C, bool ccorr = false) { // reallocate the output array if needed C.create(std::abs(A.rows - B.rows) + 1, std::abs(A.cols - B.cols) + 1, A.type()); cv::Size dftSize; // compute the size of DFT transform dftSize.width = cv::getOptimalDFTSize(A.cols + B.cols - 1); dftSize.height = cv::getOptimalDFTSize(A.rows + B.rows - 1); // allocate temporary buffers and initialize them with 0s cv::Mat tempA(dftSize, A.type(), cv::Scalar::all(0)); cv::Mat tempB(dftSize, B.type(), cv::Scalar::all(0)); // copy A and B to the top-left corners of tempA and tempB, respectively cv::Mat roiA(tempA, cv::Rect(0, 0, A.cols, A.rows)); A.copyTo(roiA); cv::Mat roiB(tempB, cv::Rect(0, 0, B.cols, B.rows)); B.copyTo(roiB); // now transform the padded A & B in-place; // use "nonzeroRows" hint for faster processing cv::dft(tempA, tempA, 0, A.rows); cv::dft(tempB, tempB, 0, B.rows); // multiply the spectrums; // the function handles packed spectrum representations well cv::mulSpectrums(tempA, tempB, tempA, 0, ccorr); // transform the product back from the frequency domain. // Even though all the result rows will be non-zero, // you need only the first C.rows of them, and thus you // pass nonzeroRows == C.rows cv::dft(tempA, tempA, cv::DFT_INVERSE + cv::DFT_SCALE, C.rows); // now copy the result back to C. tempA(cv::Rect(0, 0, C.cols, C.rows)).copyTo(C); } IMPLEMENT_PARAM_CLASS(KSize, int); IMPLEMENT_PARAM_CLASS(Ccorr, bool); PARAM_TEST_CASE(Convolve_DFT, cv::Size, KSize, Ccorr) { cv::Size size; int ksize; bool ccorr; cv::Mat src; cv::Mat kernel; cv::Mat dst_gold; virtual void SetUp() { size = GET_PARAM(0); ksize = GET_PARAM(1); ccorr = GET_PARAM(2); } }; TEST_P(Convolve_DFT, Accuracy) { cv::Mat src = randomMat(size, CV_32FC1, 0.0, 100.0); cv::Mat kernel = randomMat(cv::Size(ksize, ksize), CV_32FC1, 0.0, 1.0); cv::ocl::oclMat dst; cv::ocl::convolve(cv::ocl::oclMat(src), cv::ocl::oclMat(kernel), dst, ccorr); cv::Mat dst_gold; convolveDFT(src, kernel, dst_gold, ccorr); EXPECT_MAT_NEAR(dst, dst_gold, 1e-1); } #define DIFFERENT_CONVOLVE_SIZES testing::Values(cv::Size(251, 257), cv::Size(113, 113), cv::Size(200, 480), cv::Size(1300, 1300)) INSTANTIATE_TEST_CASE_P(OCL_ImgProc, Convolve_DFT, testing::Combine( DIFFERENT_CONVOLVE_SIZES, testing::Values(KSize(19), KSize(23), KSize(45)), testing::Values(Ccorr(true)/*, Ccorr(false)*/))); // false ccorr cannot pass for some instances #endif // HAVE_CLAMDFFT <|endoftext|>
<commit_before>// Copyright (c) 2009 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 "net/spdy/spdy_session_pool.h" #include "base/logging.h" #include "net/spdy/spdy_session.h" namespace net { // The maximum number of sessions to open to a single domain. static const size_t kMaxSessionsPerDomain = 1; int SpdySessionPool::g_max_sessions_per_domain = kMaxSessionsPerDomain; SpdySessionPool::SpdySessionPool() {} SpdySessionPool::~SpdySessionPool() { CloseAllSessions(); } scoped_refptr<SpdySession> SpdySessionPool::Get( const HostPortPair& host_port_pair, HttpNetworkSession* session) { scoped_refptr<SpdySession> spdy_session; SpdySessionList* list = GetSessionList(host_port_pair); if (list) { if (list->size() >= static_cast<unsigned int>(g_max_sessions_per_domain)) { spdy_session = list->front(); list->pop_front(); } } else { list = AddSessionList(host_port_pair); } DCHECK(list); if (!spdy_session) spdy_session = new SpdySession(host_port_pair, session); DCHECK(spdy_session); list->push_back(spdy_session); DCHECK_LE(list->size(), static_cast<unsigned int>(g_max_sessions_per_domain)); return spdy_session; } scoped_refptr<SpdySession> SpdySessionPool::GetSpdySessionFromSSLSocket( const HostPortPair& host_port_pair, HttpNetworkSession* session, ClientSocketHandle* connection) { SpdySessionList* list = GetSessionList(host_port_pair); if (!list) list = AddSessionList(host_port_pair); DCHECK(list->empty()); scoped_refptr<SpdySession> spdy_session( new SpdySession(host_port_pair, session)); spdy_session->InitializeWithSSLSocket(connection); list->push_back(spdy_session); return spdy_session; } bool SpdySessionPool::HasSession(const HostPortPair& host_port_pair) const { if (GetSessionList(host_port_pair)) return true; return false; } void SpdySessionPool::Remove(const scoped_refptr<SpdySession>& session) { SpdySessionList* list = GetSessionList(session->host_port_pair()); CHECK(list); list->remove(session); if (list->empty()) RemoveSessionList(session->host_port_pair()); } SpdySessionPool::SpdySessionList* SpdySessionPool::AddSessionList(const HostPortPair& host_port_pair) { DCHECK(sessions_.find(host_port_pair) == sessions_.end()); return sessions_[host_port_pair] = new SpdySessionList(); } SpdySessionPool::SpdySessionList* SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) { SpdySessionsMap::iterator it = sessions_.find(host_port_pair); if (it == sessions_.end()) return NULL; return it->second; } const SpdySessionPool::SpdySessionList* SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) const { SpdySessionsMap::const_iterator it = sessions_.find(host_port_pair); if (it == sessions_.end()) return NULL; return it->second; } void SpdySessionPool::RemoveSessionList(const HostPortPair& host_port_pair) { SpdySessionList* list = GetSessionList(host_port_pair); if (list) { delete list; sessions_.erase(host_port_pair); } else { DCHECK(false) << "removing orphaned session list"; } } void SpdySessionPool::CloseAllSessions() { while (sessions_.size()) { SpdySessionList* list = sessions_.begin()->second; DCHECK(list); sessions_.erase(sessions_.begin()->first); while (list->size()) { scoped_refptr<SpdySession> session = list->front(); list->pop_front(); session->CloseAllStreams(net::ERR_ABORTED); } delete list; } } } // namespace net <commit_msg>With the GOAWAY code we now can have a case where we attempt to remove the session from the pool twice. Recover, instead of abort, on that case.<commit_after>// Copyright (c) 2009 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 "net/spdy/spdy_session_pool.h" #include "base/logging.h" #include "net/spdy/spdy_session.h" namespace net { // The maximum number of sessions to open to a single domain. static const size_t kMaxSessionsPerDomain = 1; int SpdySessionPool::g_max_sessions_per_domain = kMaxSessionsPerDomain; SpdySessionPool::SpdySessionPool() {} SpdySessionPool::~SpdySessionPool() { CloseAllSessions(); } scoped_refptr<SpdySession> SpdySessionPool::Get( const HostPortPair& host_port_pair, HttpNetworkSession* session) { scoped_refptr<SpdySession> spdy_session; SpdySessionList* list = GetSessionList(host_port_pair); if (list) { if (list->size() >= static_cast<unsigned int>(g_max_sessions_per_domain)) { spdy_session = list->front(); list->pop_front(); } } else { list = AddSessionList(host_port_pair); } DCHECK(list); if (!spdy_session) spdy_session = new SpdySession(host_port_pair, session); DCHECK(spdy_session); list->push_back(spdy_session); DCHECK_LE(list->size(), static_cast<unsigned int>(g_max_sessions_per_domain)); return spdy_session; } scoped_refptr<SpdySession> SpdySessionPool::GetSpdySessionFromSSLSocket( const HostPortPair& host_port_pair, HttpNetworkSession* session, ClientSocketHandle* connection) { SpdySessionList* list = GetSessionList(host_port_pair); if (!list) list = AddSessionList(host_port_pair); DCHECK(list->empty()); scoped_refptr<SpdySession> spdy_session( new SpdySession(host_port_pair, session)); spdy_session->InitializeWithSSLSocket(connection); list->push_back(spdy_session); return spdy_session; } bool SpdySessionPool::HasSession(const HostPortPair& host_port_pair) const { if (GetSessionList(host_port_pair)) return true; return false; } void SpdySessionPool::Remove(const scoped_refptr<SpdySession>& session) { SpdySessionList* list = GetSessionList(session->host_port_pair()); if (!list) return; list->remove(session); if (list->empty()) RemoveSessionList(session->host_port_pair()); } SpdySessionPool::SpdySessionList* SpdySessionPool::AddSessionList(const HostPortPair& host_port_pair) { DCHECK(sessions_.find(host_port_pair) == sessions_.end()); return sessions_[host_port_pair] = new SpdySessionList(); } SpdySessionPool::SpdySessionList* SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) { SpdySessionsMap::iterator it = sessions_.find(host_port_pair); if (it == sessions_.end()) return NULL; return it->second; } const SpdySessionPool::SpdySessionList* SpdySessionPool::GetSessionList(const HostPortPair& host_port_pair) const { SpdySessionsMap::const_iterator it = sessions_.find(host_port_pair); if (it == sessions_.end()) return NULL; return it->second; } void SpdySessionPool::RemoveSessionList(const HostPortPair& host_port_pair) { SpdySessionList* list = GetSessionList(host_port_pair); if (list) { delete list; sessions_.erase(host_port_pair); } else { DCHECK(false) << "removing orphaned session list"; } } void SpdySessionPool::CloseAllSessions() { while (sessions_.size()) { SpdySessionList* list = sessions_.begin()->second; DCHECK(list); sessions_.erase(sessions_.begin()->first); while (list->size()) { scoped_refptr<SpdySession> session = list->front(); list->pop_front(); session->CloseAllStreams(net::ERR_ABORTED); } delete list; } } } // namespace net <|endoftext|>
<commit_before>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided 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 <Chaos/Base/Platform.h> #include <Chaos/Base/Types.h> #include <cstring> #include <iostream> #include <memory> #include <string> #include <thread> #include <vector> #include "buffer.h" #include "primitive.h" #include "address.h" #include "socket.h" #include "acceptor.h" #include "socket_service.h" void echo_tcp_server(void) { netpp::SocketService service; #if defined(CHAOS_POSIX) netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555)); #else netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555)); #endif acceptor.set_non_blocking(true); std::vector<std::unique_ptr<std::thread>> threads; netpp::TcpSocket conn(service); acceptor.async_accept(conn, [&threads, &acceptor, &conn](const std::error_code& ec) { if (!ec) { threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) { std::error_code ec; std::vector<char> buf(1024); for (;;) { auto n = conn.read_some(netpp::buffer(buf)); if (n > 0) conn.write_some(netpp::buffer(buf, n)); else break; } conn.close(); }, std::move(conn))); } }); service.run(); for (auto& t : threads) t->join(); } void echo_tcp_client(void) { netpp::SocketService service; netpp::TcpSocket s(service, netpp::Tcp::v4()); s.set_non_blocking(true); s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555)); std::string line; std::vector<char> buf(1024); while (std::getline(std::cin, line)) { if (line == "quit") break; s.write(netpp::buffer(line)); buf.assign(buf.size(), 0); if (s.read(netpp::buffer(buf)) > 0) std::cout << "echo read: " << buf.data() << std::endl; else break; } s.close(); } void echo_udp_server(void) { netpp::SocketService service; netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555)); s.set_non_blocking(true); std::vector<char> buf(1024); for (;;) { netpp::Address addr(netpp::IP::v4()); auto n = s.read_from(netpp::buffer(buf), addr); if (n > 0) s.write_to(netpp::buffer(buf, n), addr); else break; } s.close(); } void echo_udp_client(void) { netpp::SocketService service; netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4()); s.set_non_blocking(true); s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555)); std::string line; std::vector<char> buf(1024); while (std::getline(std::cin, line)) { if (line == "quit") break; s.write(netpp::buffer(line)); buf.assign(buf.size(), 0); if (s.read(netpp::buffer(buf)) > 0) std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl; } s.close(); } void echo_sample(const char* c) { netpp::startup(); if (std::strcmp(c, "ts") == 0) echo_tcp_server(); else if (std::strcmp(c, "tc") == 0) echo_tcp_client(); else if (std::strcmp(c, "us") == 0) echo_udp_server(); else if (std::strcmp(c, "uc") == 0) echo_udp_client(); netpp::cleanup(); } int main(int argc, char* argv[]) { CHAOS_UNUSED(argc), CHAOS_UNUSED(argv); if (argc > 1) echo_sample(argv[1]); return 0; } <commit_msg>:construction: chore(demo): updated the demo using netpp<commit_after>// Copyright (c) 2017 ASMlover. 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 ofconditions 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 materialsprovided 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 <Chaos/Base/Platform.h> #include <Chaos/Base/Types.h> #include <cstring> #include <iostream> #include <memory> #include <string> #include <thread> #include <vector> #include "buffer.h" #include "primitive.h" #include "address.h" #include "socket.h" #include "acceptor.h" #include "socket_service.h" class TcpConnection : private Chaos::UnCopyable , public std::enable_shared_from_this<TcpConnection> { netpp::TcpSocket socket_; std::vector<char> buffer_; static constexpr std::size_t kMaxBuffer = 1024; void do_read(void) { auto self(shared_from_this()); socket_.async_read_some(netpp::buffer(buffer_), [this, self](const std::error_code& ec, std::size_t n) { if (!ec) do_write(n); }); } void do_write(std::size_t n) { auto self(shared_from_this()); socket_.async_write_some(netpp::buffer(buffer_, n), [this, self](const std::error_code& ec, std::size_t) { if (!ec) do_read(); }); } public: TcpConnection(netpp::TcpSocket&& s) : socket_(std::move(s)) , buffer_(kMaxBuffer) { } void start(void) { do_read(); } }; class EchoTcpServer : private Chaos::UnCopyable { netpp::Acceptor acceptor_; netpp::TcpSocket socket_; void do_accept(void) { acceptor_.async_accept(socket_, [this](const std::error_code& ec) { if (!ec) std::make_shared<TcpConnection>(std::move(socket_)); do_accept(); }); } public: EchoTcpServer(netpp::SocketService& service, std::uint16_t port) #if defined(CHAOS_POSIX) : acceptor_(service, netpp::Address(netpp::IP::v6(), port)) #else : acceptor_(service, netpp::Address(netpp::IP::v4(), port)) #endif , socket_(service) { acceptor_.set_non_blocking(true); } void start(void) { do_accept(); } }; void echo_tcp_server(void) { netpp::SocketService service; EchoTcpServer server(service, 5555); server.start(); // #if defined(CHAOS_POSIX) // netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v6(), 5555)); // #else // netpp::Acceptor acceptor(service, netpp::Address(netpp::IP::v4(), 5555)); // #endif // acceptor.set_non_blocking(true); // std::vector<std::unique_ptr<std::thread>> threads; // netpp::TcpSocket conn(service); // acceptor.async_accept(conn, // [&threads, &acceptor, &conn](const std::error_code& ec) { // if (!ec) { // threads.emplace_back(new std::thread([](netpp::TcpSocket&& conn) { // std::error_code ec; // std::vector<char> buf(1024); // for (;;) { // auto n = conn.read_some(netpp::buffer(buf)); // if (n > 0) // conn.write_some(netpp::buffer(buf, n)); // else // break; // } // conn.close(); // }, std::move(conn))); // } // }); service.run(); // for (auto& t : threads) // t->join(); } void echo_tcp_client(void) { netpp::SocketService service; netpp::TcpSocket s(service, netpp::Tcp::v4()); s.set_non_blocking(true); s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555)); std::string line; std::vector<char> buf(1024); while (std::getline(std::cin, line)) { if (line == "quit") break; s.write(netpp::buffer(line)); buf.assign(buf.size(), 0); if (s.read(netpp::buffer(buf)) > 0) std::cout << "echo read: " << buf.data() << std::endl; else break; } s.close(); } void echo_udp_server(void) { netpp::SocketService service; netpp::UdpSocket s(service, netpp::Address(netpp::IP::v4(), 5555)); s.set_non_blocking(true); std::vector<char> buf(1024); for (;;) { netpp::Address addr(netpp::IP::v4()); auto n = s.read_from(netpp::buffer(buf), addr); if (n > 0) s.write_to(netpp::buffer(buf, n), addr); else break; } s.close(); } void echo_udp_client(void) { netpp::SocketService service; netpp::UdpSocket s(service, netpp::UdpSocket::ProtocolType::v4()); s.set_non_blocking(true); s.connect(netpp::Address(netpp::IP::v4(), "127.0.0.1", 5555)); std::string line; std::vector<char> buf(1024); while (std::getline(std::cin, line)) { if (line == "quit") break; s.write(netpp::buffer(line)); buf.assign(buf.size(), 0); if (s.read(netpp::buffer(buf)) > 0) std::cout << "from{127.0.0.1:5555} read: " << buf.data() << std::endl; } s.close(); } void echo_sample(const char* c) { netpp::startup(); if (std::strcmp(c, "ts") == 0) echo_tcp_server(); else if (std::strcmp(c, "tc") == 0) echo_tcp_client(); else if (std::strcmp(c, "us") == 0) echo_udp_server(); else if (std::strcmp(c, "uc") == 0) echo_udp_client(); netpp::cleanup(); } int main(int argc, char* argv[]) { CHAOS_UNUSED(argc), CHAOS_UNUSED(argv); if (argc > 1) echo_sample(argv[1]); return 0; } <|endoftext|>
<commit_before>#include "dllist.cpp" template <typename T> class DoubleLinkedChain : public DoubleLinkedList<T> { bool ownsItems = true; public: DoubleLinkedChain(): front(NULL), back(NULL) {} DoubleLinkedChain(const DoubleLinkedList& l): front(l.front), back(l.back), ownsItems(false) {} DoubleLinkedChain& operator=(const DoubleLinkedList& l) { if (&other != this) { if (ownsItems) clean(); front = l.front; back = l.back; ownsItems = false; } return *this; } ~DoubleLinkedChain() { if (ownsItems) clean(); } void attachNext(const I& cur, const I& next) { if (cur.ptr && !cur.ptr->next) cur.ptr->next = next.ptr; } void attachPrev(const I& cur, const I& prev) { if (cur.ptr && !cur.ptr->prev) cur.ptr->prev = prev.ptr; } }; <commit_msg>backup before major refactoring<commit_after>#include "dllist.cpp" template <typename T> class DoubleLinkedChain : public DoubleLinkedList<T> { bool ownsItems = true; public: DoubleLinkedChain(): front(NULL), back(NULL) {} DoubleLinkedChain(const DoubleLinkedList& l): front(l.front), back(l.back), ownsItems(false) {} DoubleLinkedChain& operator=(const DoubleLinkedList& l) { if (&other != this) { if (ownsItems) clean(); front = l.front; back = l.back; ownsItems = false; } return *this; } ~DoubleLinkedChain() { if (ownsItems) clean(); } void attachAtBegin(const I& it) { if (it && front) { front->prev = it.ptr; I begin = front; while (begin) begin--; front = begin.ptr; } } void attachAtEnd(const I& it) { if (it && back) { back->next = it.ptr; I end = back; while (end) end++; back = end.ptr; } } void attachAtPrev(const I& it, const I& prev) { if (it && prev && !it.ptr->prev) it.ptr->prev = prev.ptr; } void attachAtNext(const I& it, const I& next) { if (it && next && !it.ptr->next) it.ptr->next = next.ptr; } }; <|endoftext|>
<commit_before><commit_msg>remove all variables for each step in dataman<commit_after><|endoftext|>
<commit_before>#include "QmitkFunctionalityCoordinator.h" #include "QmitkFunctionality.h" #include <QmitkStdMultiWidgetEditor.h> #include <berryPlatformUI.h> #include <berryIWorkbenchPage.h> QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator() : m_StandaloneFuntionality(NULL) { } void QmitkFunctionalityCoordinator::SetWindow( berry::IWorkbenchWindow::Pointer window ) { m_Window = window; if(window.IsNotNull()) { window->GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this)); window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } } QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator() { } berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const { return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED | | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED; } void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); // change the active standalone functionality this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer partRef ) { // nothing to do here: see PartActivated() } void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it is available now if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetAvailable(*(partRef ->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget())); } } else { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality } } } void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it not available any more if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget())); (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence } } else { // check for functionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { // deactivate on close ( the standalone functionality may still be activated ) this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); // and set pointer to 0 if(m_StandaloneFuntionality == _QmitkFunctionality.GetPointer()) m_StandaloneFuntionality = 0; m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality // call PartClosed on the QmitkFunctionality _QmitkFunctionality->ClosePartProxy(); //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden() } } } void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality != 0) { _QmitkFunctionality->SetVisible(false); _QmitkFunctionality->Hidden(); // try to deactivate on hide (if is activated) this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // activate Functionality if just one Standalone Functionality is visible (old one gets deactivated) if(m_VisibleStandaloneFunctionalities.size() == 1) this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } } void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { _QmitkFunctionality->SetVisible(true); _QmitkFunctionality->Visible(); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.insert(_QmitkFunctionality.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if(m_VisibleStandaloneFunctionalities.size() == 1) this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } } void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( QmitkFunctionality* functionality ) { if(functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality()) { // deactivate old one if necessary this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality); m_StandaloneFuntionality = functionality; // call activated on this functionality m_StandaloneFuntionality->SetActivated(true); m_StandaloneFuntionality->Activated(); } } void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(QmitkFunctionality* functionality) { if(functionality && functionality->IsActivated()) { functionality->SetActivated(false); functionality->Deactivated(); } } void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer window ) { if(window.IsNotNull()) { window->GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this)); window->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this)); } } void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window ) { }<commit_msg>COMP (#3225): Removed unnecessary |<commit_after>#include "QmitkFunctionalityCoordinator.h" #include "QmitkFunctionality.h" #include <QmitkStdMultiWidgetEditor.h> #include <berryPlatformUI.h> #include <berryIWorkbenchPage.h> QmitkFunctionalityCoordinator::QmitkFunctionalityCoordinator() : m_StandaloneFuntionality(NULL) { } void QmitkFunctionalityCoordinator::SetWindow( berry::IWorkbenchWindow::Pointer window ) { m_Window = window; if(window.IsNotNull()) { window->GetWorkbench()->AddWindowListener(berry::IWindowListener::Pointer(this)); window->GetPartService()->AddPartListener(berry::IPartListener::Pointer(this)); } } QmitkFunctionalityCoordinator::~QmitkFunctionalityCoordinator() { } berry::IPartListener::Events::Types QmitkFunctionalityCoordinator::GetPartEventTypes() const { return berry::IPartListener::Events::ACTIVATED | berry::IPartListener::Events::DEACTIVATED | berry::IPartListener::Events::CLOSED | berry::IPartListener::Events::HIDDEN | berry::IPartListener::Events::VISIBLE | berry::IPartListener::Events::OPENED; } void QmitkFunctionalityCoordinator::PartActivated( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); // change the active standalone functionality this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } void QmitkFunctionalityCoordinator::PartDeactivated( berry::IWorkbenchPartReference::Pointer partRef ) { // nothing to do here: see PartActivated() } void QmitkFunctionalityCoordinator::PartOpened( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it is available now if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetAvailable(*(partRef ->GetPart(false).Cast<QmitkStdMultiWidgetEditor>()->GetStdMultiWidget())); } } else { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { m_Functionalities.insert(_QmitkFunctionality.GetPointer()); // save as opened functionality } } } void QmitkFunctionalityCoordinator::PartClosed( berry::IWorkbenchPartReference::Pointer partRef ) { // check for multiwidget and inform views that it not available any more if ( partRef->GetId() == QmitkStdMultiWidgetEditor::EDITOR_ID ) { QmitkStdMultiWidgetEditor::Pointer stdMultiWidgetEditor = partRef->GetPart(false).Cast<QmitkStdMultiWidgetEditor>(); for (std::set<QmitkFunctionality*>::iterator it = m_Functionalities.begin() ; it != m_Functionalities.end(); it++) { (*it)->StdMultiWidgetClosed(*(stdMultiWidgetEditor->GetStdMultiWidget())); (*it)->StdMultiWidgetNotAvailable(); // deprecated call, provided for consistence } } else { // check for functionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { // deactivate on close ( the standalone functionality may still be activated ) this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); // and set pointer to 0 if(m_StandaloneFuntionality == _QmitkFunctionality.GetPointer()) m_StandaloneFuntionality = 0; m_Functionalities.erase(_QmitkFunctionality.GetPointer()); // remove as opened functionality // call PartClosed on the QmitkFunctionality _QmitkFunctionality->ClosePartProxy(); //m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // remove if necessary (should be done before in PartHidden() } } } void QmitkFunctionalityCoordinator::PartHidden( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality != 0) { _QmitkFunctionality->SetVisible(false); _QmitkFunctionality->Hidden(); // try to deactivate on hide (if is activated) this->DeactivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.erase(_QmitkFunctionality.GetPointer()); // activate Functionality if just one Standalone Functionality is visible (old one gets deactivated) if(m_VisibleStandaloneFunctionalities.size() == 1) this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } } void QmitkFunctionalityCoordinator::PartVisible( berry::IWorkbenchPartReference::Pointer partRef ) { // Check for QmitkFunctionality QmitkFunctionality::Pointer _QmitkFunctionality = partRef->GetPart(false).Cast<QmitkFunctionality>(); if(_QmitkFunctionality.IsNotNull()) { _QmitkFunctionality->SetVisible(true); _QmitkFunctionality->Visible(); // tracking of Visible Standalone Functionalities m_VisibleStandaloneFunctionalities.insert(_QmitkFunctionality.GetPointer()); // activate Functionality if just one Standalone Functionality is visible if(m_VisibleStandaloneFunctionalities.size() == 1) this->ActivateStandaloneFunctionality(_QmitkFunctionality.GetPointer()); } } void QmitkFunctionalityCoordinator::ActivateStandaloneFunctionality( QmitkFunctionality* functionality ) { if(functionality && !functionality->IsActivated() && functionality->IsExclusiveFunctionality()) { // deactivate old one if necessary this->DeactivateStandaloneFunctionality(m_StandaloneFuntionality); m_StandaloneFuntionality = functionality; // call activated on this functionality m_StandaloneFuntionality->SetActivated(true); m_StandaloneFuntionality->Activated(); } } void QmitkFunctionalityCoordinator::DeactivateStandaloneFunctionality(QmitkFunctionality* functionality) { if(functionality && functionality->IsActivated()) { functionality->SetActivated(false); functionality->Deactivated(); } } void QmitkFunctionalityCoordinator::WindowClosed( berry::IWorkbenchWindow::Pointer window ) { if(window.IsNotNull()) { window->GetWorkbench()->RemoveWindowListener(berry::IWindowListener::Pointer(this)); window->GetPartService()->RemovePartListener(berry::IPartListener::Pointer(this)); } } void QmitkFunctionalityCoordinator::WindowOpened( berry::IWorkbenchWindow::Pointer window ) { }<|endoftext|>
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/accessibility/magnification_manager.h" #include "ash/magnifier/magnification_controller.h" #include "ash/magnifier/partial_magnification_controller.h" #include "ash/shell.h" #include "ash/system/tray/system_tray_notifier.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/prefs/pref_member.h" #include "base/prefs/pref_service.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" namespace chromeos { namespace { const double kInitialMagnifiedScale = 2.0; static MagnificationManager* g_magnification_manager = NULL; } class MagnificationManagerImpl : public MagnificationManager, public content::NotificationObserver { public: MagnificationManagerImpl() : first_time_update_(true), profile_(NULL), type_(ash::kDefaultMagnifierType), enabled_(false) { registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } virtual ~MagnificationManagerImpl() { CHECK(this == g_magnification_manager); } // MagnificationManager implimentation: virtual bool IsMagnifierEnabled() const OVERRIDE { return enabled_; } virtual ash::MagnifierType GetMagnifierType() const OVERRIDE { return type_; } virtual void SetMagnifierEnabled(bool enabled) OVERRIDE { // This method may be invoked even when the other magnifier settings (e.g. // type or scale) are changed, so we need to call magnification controller // even if |enabled| is unchanged. Only if |enabled| is false and the // magnifier is already disabled, we are sure that we don't need to reflect // the new settings right now because the magnifier keeps disabled. if (!enabled && !enabled_) return; enabled_ = enabled; if (profile_) { PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); if (enabled != prefs->GetBoolean(prefs::kScreenMagnifierEnabled)) { prefs->SetBoolean(prefs::kScreenMagnifierEnabled, enabled); prefs->CommitPendingWrite(); } } NotifyMagnifierChanged(); if (type_ == ash::MAGNIFIER_FULL) { ash::Shell::GetInstance()->magnification_controller()->SetEnabled( enabled_); } else { ash::Shell::GetInstance()->partial_magnification_controller()->SetEnabled( enabled_); } } virtual void SetMagnifierType(ash::MagnifierType type) OVERRIDE { if (type_ == type) return; DCHECK(type == ash::MAGNIFIER_FULL || type == ash::MAGNIFIER_PARTIAL); type_ = ash::MAGNIFIER_FULL; // (leave out for full magnifier) if (profile_) { PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); prefs->SetInteger(prefs::kScreenMagnifierType, type); prefs->CommitPendingWrite(); } NotifyMagnifierChanged(); } virtual void SaveScreenMagnifierScale(double scale) OVERRIDE { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); DCHECK(profile->GetPrefs()); profile->GetPrefs()->SetDouble(prefs::kScreenMagnifierScale, scale); } virtual double GetSavedScreenMagnifierScale() const OVERRIDE { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); DCHECK(profile->GetPrefs()); if (profile->GetPrefs()->HasPrefPath(prefs::kScreenMagnifierScale)) return profile->GetPrefs()->GetDouble(prefs::kScreenMagnifierScale); return std::numeric_limits<double>::min(); } private: void NotifyMagnifierChanged() { accessibility::AccessibilityStatusEventDetails details( enabled_, type_, ash::A11Y_NOTIFICATION_NONE); content::NotificationService::current()->Notify( chrome::NOTIFICATION_CROS_ACCESSIBILITY_TOGGLE_SCREEN_MAGNIFIER, content::NotificationService::AllSources(), content::Details<accessibility::AccessibilityStatusEventDetails>( &details)); } bool IsMagnifierEnabledFromPref() { if (!profile_) return false; DCHECK(profile_->GetPrefs()); return profile_->GetPrefs()->GetBoolean(prefs::kScreenMagnifierEnabled); } ash::MagnifierType GetMagnifierTypeFromPref() { return ash::MAGNIFIER_FULL; } void SetProfile(Profile* profile) { if (pref_change_registrar_) { pref_change_registrar_.reset(); } if (profile) { pref_change_registrar_.reset(new PrefChangeRegistrar); pref_change_registrar_->Init(profile->GetPrefs()); pref_change_registrar_->Add( prefs::kScreenMagnifierEnabled, base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref, base::Unretained(this))); pref_change_registrar_->Add( prefs::kScreenMagnifierType, base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref, base::Unretained(this))); } profile_ = profile; UpdateMagnifierStatusFromPref(); } void UpdateMagnifierStatusFromPref() { bool enabled = IsMagnifierEnabledFromPref(); if (!enabled) { SetMagnifierEnabled(enabled); SetMagnifierType(GetMagnifierTypeFromPref()); } else { SetMagnifierType(GetMagnifierTypeFromPref()); SetMagnifierEnabled(enabled); } } // content::NotificationObserver implimentation: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { switch (type) { // When entering the login screen or non-guest desktop. case chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE: case chrome::NOTIFICATION_SESSION_STARTED: { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); if (!profile->IsGuestSession()) SetProfile(profile); break; } // When entering guest desktop, no NOTIFICATION_SESSION_STARTED event is // fired, so we use NOTIFICATION_PROFILE_CREATED event instead. case chrome::NOTIFICATION_PROFILE_CREATED: { Profile* profile = content::Source<Profile>(source).ptr(); if (profile->IsGuestSession()) SetProfile(profile); break; } case chrome::NOTIFICATION_PROFILE_DESTROYED: { SetProfile(NULL); break; } } } bool first_time_update_; Profile* profile_; ash::MagnifierType type_; bool enabled_; content::NotificationRegistrar registrar_; scoped_ptr<PrefChangeRegistrar> pref_change_registrar_; DISALLOW_COPY_AND_ASSIGN(MagnificationManagerImpl); }; // static void MagnificationManager::Initialize() { CHECK(g_magnification_manager == NULL); g_magnification_manager = new MagnificationManagerImpl(); } // static void MagnificationManager::Shutdown() { CHECK(g_magnification_manager); delete g_magnification_manager; g_magnification_manager = NULL; } // static MagnificationManager* MagnificationManager::Get() { return g_magnification_manager; } } // namespace chromeos <commit_msg>Magnifier: Ignore Off-The-Record profile.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/accessibility/magnification_manager.h" #include "ash/magnifier/magnification_controller.h" #include "ash/magnifier/partial_magnification_controller.h" #include "ash/shell.h" #include "ash/system/tray/system_tray_notifier.h" #include "base/memory/scoped_ptr.h" #include "base/memory/singleton.h" #include "base/prefs/pref_member.h" #include "base/prefs/pref_service.h" #include "chrome/browser/chromeos/login/user_manager.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/pref_names.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_observer.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_service.h" namespace chromeos { namespace { const double kInitialMagnifiedScale = 2.0; static MagnificationManager* g_magnification_manager = NULL; } class MagnificationManagerImpl : public MagnificationManager, public content::NotificationObserver { public: MagnificationManagerImpl() : first_time_update_(true), profile_(NULL), type_(ash::kDefaultMagnifierType), enabled_(false) { registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_SESSION_STARTED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); registrar_.Add(this, chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE, content::NotificationService::AllSources()); } virtual ~MagnificationManagerImpl() { CHECK(this == g_magnification_manager); } // MagnificationManager implimentation: virtual bool IsMagnifierEnabled() const OVERRIDE { return enabled_; } virtual ash::MagnifierType GetMagnifierType() const OVERRIDE { return type_; } virtual void SetMagnifierEnabled(bool enabled) OVERRIDE { // This method may be invoked even when the other magnifier settings (e.g. // type or scale) are changed, so we need to call magnification controller // even if |enabled| is unchanged. Only if |enabled| is false and the // magnifier is already disabled, we are sure that we don't need to reflect // the new settings right now because the magnifier keeps disabled. if (!enabled && !enabled_) return; enabled_ = enabled; if (profile_) { PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); if (enabled != prefs->GetBoolean(prefs::kScreenMagnifierEnabled)) { prefs->SetBoolean(prefs::kScreenMagnifierEnabled, enabled); prefs->CommitPendingWrite(); } } NotifyMagnifierChanged(); if (type_ == ash::MAGNIFIER_FULL) { ash::Shell::GetInstance()->magnification_controller()->SetEnabled( enabled_); } else { ash::Shell::GetInstance()->partial_magnification_controller()->SetEnabled( enabled_); } } virtual void SetMagnifierType(ash::MagnifierType type) OVERRIDE { if (type_ == type) return; DCHECK(type == ash::MAGNIFIER_FULL || type == ash::MAGNIFIER_PARTIAL); type_ = ash::MAGNIFIER_FULL; // (leave out for full magnifier) if (profile_) { PrefService* prefs = profile_->GetPrefs(); DCHECK(prefs); prefs->SetInteger(prefs::kScreenMagnifierType, type); prefs->CommitPendingWrite(); } NotifyMagnifierChanged(); } virtual void SaveScreenMagnifierScale(double scale) OVERRIDE { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); DCHECK(profile->GetPrefs()); profile->GetPrefs()->SetDouble(prefs::kScreenMagnifierScale, scale); } virtual double GetSavedScreenMagnifierScale() const OVERRIDE { Profile* profile = ProfileManager::GetDefaultProfileOrOffTheRecord(); DCHECK(profile->GetPrefs()); if (profile->GetPrefs()->HasPrefPath(prefs::kScreenMagnifierScale)) return profile->GetPrefs()->GetDouble(prefs::kScreenMagnifierScale); return std::numeric_limits<double>::min(); } private: void NotifyMagnifierChanged() { accessibility::AccessibilityStatusEventDetails details( enabled_, type_, ash::A11Y_NOTIFICATION_NONE); content::NotificationService::current()->Notify( chrome::NOTIFICATION_CROS_ACCESSIBILITY_TOGGLE_SCREEN_MAGNIFIER, content::NotificationService::AllSources(), content::Details<accessibility::AccessibilityStatusEventDetails>( &details)); } bool IsMagnifierEnabledFromPref() { if (!profile_) return false; DCHECK(profile_->GetPrefs()); return profile_->GetPrefs()->GetBoolean(prefs::kScreenMagnifierEnabled); } ash::MagnifierType GetMagnifierTypeFromPref() { return ash::MAGNIFIER_FULL; } void SetProfile(Profile* profile) { if (pref_change_registrar_) { pref_change_registrar_.reset(); } if (profile) { pref_change_registrar_.reset(new PrefChangeRegistrar); pref_change_registrar_->Init(profile->GetPrefs()); pref_change_registrar_->Add( prefs::kScreenMagnifierEnabled, base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref, base::Unretained(this))); pref_change_registrar_->Add( prefs::kScreenMagnifierType, base::Bind(&MagnificationManagerImpl::UpdateMagnifierStatusFromPref, base::Unretained(this))); } profile_ = profile; UpdateMagnifierStatusFromPref(); } void UpdateMagnifierStatusFromPref() { bool enabled = IsMagnifierEnabledFromPref(); if (!enabled) { SetMagnifierEnabled(enabled); SetMagnifierType(GetMagnifierTypeFromPref()); } else { SetMagnifierType(GetMagnifierTypeFromPref()); SetMagnifierEnabled(enabled); } } // content::NotificationObserver implimentation: virtual void Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) OVERRIDE { switch (type) { // When entering the login screen or non-guest desktop. case chrome::NOTIFICATION_LOGIN_WEBUI_VISIBLE: case chrome::NOTIFICATION_SESSION_STARTED: { Profile* profile = ProfileManager::GetDefaultProfile(); if (!profile->IsGuestSession()) SetProfile(profile); break; } // When entering guest desktop, no NOTIFICATION_SESSION_STARTED event is // fired, so we use NOTIFICATION_PROFILE_CREATED event instead. case chrome::NOTIFICATION_PROFILE_CREATED: { Profile* profile = content::Source<Profile>(source).ptr(); if (profile->IsGuestSession() && !profile->IsOffTheRecord()) { SetProfile(profile); // In guest mode, 2 non-OTR profiles are created. We should use the // first one, not second one. registrar_.Remove(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); } break; } case chrome::NOTIFICATION_PROFILE_DESTROYED: { SetProfile(NULL); break; } } } bool first_time_update_; Profile* profile_; ash::MagnifierType type_; bool enabled_; content::NotificationRegistrar registrar_; scoped_ptr<PrefChangeRegistrar> pref_change_registrar_; DISALLOW_COPY_AND_ASSIGN(MagnificationManagerImpl); }; // static void MagnificationManager::Initialize() { CHECK(g_magnification_manager == NULL); g_magnification_manager = new MagnificationManagerImpl(); } // static void MagnificationManager::Shutdown() { CHECK(g_magnification_manager); delete g_magnification_manager; g_magnification_manager = NULL; } // static MagnificationManager* MagnificationManager::Get() { return g_magnification_manager; } } // namespace chromeos <|endoftext|>
<commit_before>// Copyright (c) 2010 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/stringprintf.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class ExtensionGalleryInstallApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } bool RunInstallTest(const std::string& page) { std::string base_url = base::StringPrintf( "http://www.example.com:%u/files/extensions/", test_server()->host_port_pair().port()); std::string testing_install_base_url = base_url; testing_install_base_url += "good.crx"; CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, testing_install_base_url); std::string page_url = base_url; page_url += "api_test/extension_gallery_install/" + page; return RunPageTest(page_url.c_str()); } }; // http://crbug.com/55642 - failing on XP. #if defined (OS_WIN) #define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall #else #define MAYBE_InstallAndUninstall InstallAndUninstall #endif IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, MAYBE_InstallAndUninstall) { host_resolver()->AddRule("www.example.com", "127.0.0.1"); ASSERT_TRUE(test_server()->Start()); BeginInstallFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(RunInstallTest("test.html")); ASSERT_TRUE(RunInstallTest("complete_without_begin.html")); ASSERT_TRUE(RunInstallTest("invalid_begin.html")); BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } <commit_msg>Add some extra debugging info for a flaky test.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/stringprintf.h" #if defined (OS_WIN) #include "base/win/windows_version.h" #endif // defined (OS_WIN) #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_webstore_private_api.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/ui_test_utils.h" #include "net/base/mock_host_resolver.h" class ExtensionGalleryInstallApiTest : public ExtensionApiTest { public: void SetUpCommandLine(CommandLine* command_line) { ExtensionApiTest::SetUpCommandLine(command_line); command_line->AppendSwitchASCII(switches::kAppsGalleryURL, "http://www.example.com"); } bool RunInstallTest(const std::string& page) { std::string base_url = base::StringPrintf( "http://www.example.com:%u/files/extensions/", test_server()->host_port_pair().port()); std::string testing_install_base_url = base_url; testing_install_base_url += "good.crx"; CommandLine::ForCurrentProcess()->AppendSwitchASCII( switches::kAppsGalleryUpdateURL, testing_install_base_url); std::string page_url = base_url; page_url += "api_test/extension_gallery_install/" + page; return RunPageTest(page_url.c_str()); } }; namespace { bool RunningOnXP() { #if defined (OS_WIN) return GetVersion() < base::win::VERSION_VISTA; #else return false; #endif // defined (OS_WIN) } } // namespace // TODO(asargent) - for some reason this test occasionally fails on XP, // but not other versions of windows. http://crbug.com/55642 #if defined (OS_WIN) #define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall #else #define MAYBE_InstallAndUninstall InstallAndUninstall #endif IN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest, MAYBE_InstallAndUninstall) { if (RunningOnXP()) { LOG(INFO) << "Adding host resolver rule"; } host_resolver()->AddRule("www.example.com", "127.0.0.1"); if (RunningOnXP()) { LOG(INFO) << "Starting test server"; } ASSERT_TRUE(test_server()->Start()); if (RunningOnXP()) { LOG(INFO) << "Starting tests without user gesture checking"; } BeginInstallFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(RunInstallTest("test.html")); ASSERT_TRUE(RunInstallTest("complete_without_begin.html")); ASSERT_TRUE(RunInstallTest("invalid_begin.html")); if (RunningOnXP()) { LOG(INFO) << "Starting tests with user gesture checking"; } BeginInstallFunction::SetIgnoreUserGestureForTests(false); ASSERT_TRUE(RunInstallTest("no_user_gesture.html")); } <|endoftext|>
<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This test performs a series false positive checks using a list of URLs // against a known set of SafeBrowsing data. // // It uses a normal SafeBrowsing database to create a bloom filter where it // looks up all the URLs in the url file. A URL that has a prefix found in the // bloom filter and found in the database is considered a hit: a valid lookup // that will result in a gethash request. A URL that has a prefix found in the // bloom filter but not in the database is a miss: a false positive lookup that // will result in an unnecessary gethash request. // // By varying the size of the bloom filter and using a constant set of // SafeBrowsing data, we can check a known set of URLs against the filter and // determine the false positive rate. // // False positive calculation usage: // $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives // --filter-start=<integer> // --filter-steps=<integer> // --filter-verbose // // --filter-start: The filter multiplier to begin with. This represents the // number of bits per prefix of memory to use in the filter. // The default value is identical to the current SafeBrowsing // database value. // --filter-steps: The number of iterations to run, with each iteration // increasing the filter multiplier by 1. The default value // is 1. // --filter-verbose: Used to print out the hit / miss results per URL. // --filter-csv: The URL file contains information about the number of // unique views (the popularity) of each URL. See the format // description below. // // // Hash compute time usage: // $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime // --filter-num-checks=<integer> // // --filter-num-checks: The number of hash look ups to perform on the bloom // filter. The default is 10 million. // // Data files: // chrome/test/data/safe_browsing/filter/database // chrome/test/data/safe_browsing/filter/urls // // database: A normal SafeBrowsing database. // urls: A text file containing a list of URLs, one per line. If the option // --filter-csv is specified, the format of each line in the file is // <url>,<weight> where weight is an integer indicating the number of // unique views for the URL. #include <algorithm> #include <fstream> #include <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/rand_util.h" #include "base/sha2.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/time.h" #include "chrome/browser/safe_browsing/bloom_filter.h" #include "chrome/browser/safe_browsing/safe_browsing_util.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/sqlite_compiled_statement.h" #include "chrome/common/sqlite_utils.h" #include "googleurl/src/gurl.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; namespace { // Ensures the SafeBrowsing database is closed properly. class ScopedPerfDatabase { public: explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {} ~ScopedPerfDatabase() { sqlite3_close(db_); } private: sqlite3* db_; DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase); }; // Command line flags. const char kFilterVerbose[] = "filter-verbose"; const char kFilterStart[] = "filter-start"; const char kFilterSteps[] = "filter-steps"; const char kFilterCsv[] = "filter-csv"; const char kFilterNumChecks[] = "filter-num-checks"; // Number of hash checks to make during performance testing. static const int kNumHashChecks = 10000000; // Returns the path to the data used in this test, relative to the top of the // source directory. FilePath GetFullDataPath() { FilePath full_path; CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path)); full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing")); full_path = full_path.Append(FILE_PATH_LITERAL("filter")); CHECK(file_util::PathExists(full_path)); return full_path; } // Constructs a bloom filter of the appropriate size from the provided prefixes. void BuildBloomFilter(int size_multiplier, const std::vector<SBPrefix>& prefixes, BloomFilter** bloom_filter) { // Create a BloomFilter with the specified size. const int key_count = std::max(static_cast<int>(prefixes.size()), BloomFilter::kBloomFilterMinSize); const int filter_size = key_count * size_multiplier; *bloom_filter = new BloomFilter(filter_size); // Add the prefixes to it. for (size_t i = 0; i < prefixes.size(); ++i) (*bloom_filter)->Insert(prefixes[i]); std::cout << "Bloom filter with prefixes: " << prefixes.size() << ", multiplier: " << size_multiplier << ", size (bytes): " << (*bloom_filter)->size() << std::endl; } // Reads the set of add prefixes contained in a SafeBrowsing database into a // sorted array suitable for fast searching. This takes significantly less time // to look up a given prefix than performing SQL queries. bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) { FilePath database_file = path.Append(FILE_PATH_LITERAL("database")); sqlite3* db = NULL; if (sqlite_utils::OpenSqliteDb(database_file, &db) != SQLITE_OK) { sqlite3_close(db); return false; } ScopedPerfDatabase database(db); scoped_ptr<SqliteStatementCache> sql_cache(new SqliteStatementCache(db)); // Get the number of items in the add_prefix table. std::string sql = "SELECT COUNT(*) FROM add_prefix"; SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str()); if (!count_statement.is_valid()) return false; if (count_statement->step() != SQLITE_ROW) return false; const int count = count_statement->column_int(0); // Load them into a prefix vector and sort prefixes->reserve(count); sql = "SELECT prefix FROM add_prefix"; SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str()); if (!prefix_statement.is_valid()) return false; while (prefix_statement->step() == SQLITE_ROW) prefixes->push_back(prefix_statement->column_int(0)); DCHECK(static_cast<int>(prefixes->size()) == count); sort(prefixes->begin(), prefixes->end()); return true; } // Generates all legal SafeBrowsing prefixes for the specified URL, and returns // the set of Prefixes that exist in the bloom filter. The function returns the // number of host + path combinations checked. int GeneratePrefixHits(const std::string url, BloomFilter* bloom_filter, std::vector<SBPrefix>* prefixes) { GURL url_check(url); std::vector<std::string> hosts; if (url_check.HostIsIPAddress()) { hosts.push_back(url_check.host()); } else { safe_browsing_util::GenerateHostsToCheck(url_check, &hosts); } std::vector<std::string> paths; safe_browsing_util::GeneratePathsToCheck(url_check, &paths); for (size_t i = 0; i < hosts.size(); ++i) { for (size_t j = 0; j < paths.size(); ++j) { SBPrefix prefix; base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix)); if (bloom_filter->Exists(prefix)) prefixes->push_back(prefix); } } return hosts.size() * paths.size(); } // Binary search of sorted prefixes. bool IsPrefixInDatabase(SBPrefix prefix, const std::vector<SBPrefix>& prefixes) { if (prefixes.empty()) return false; int low = 0; int high = prefixes.size() - 1; while (low <= high) { int mid = ((unsigned int)low + (unsigned int)high) >> 1; SBPrefix prefix_mid = prefixes[mid]; if (prefix_mid == prefix) return true; if (prefix_mid < prefix) low = mid + 1; else high = mid - 1; } return false; } // Construct a bloom filter with the given prefixes and multiplier, and test the // false positive rate (misses) against a URL list. void CalculateBloomFilterFalsePositives( int size_multiplier, const FilePath& data_dir, const std::vector<SBPrefix>& prefix_list) { BloomFilter* bloom_filter = NULL; BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter); scoped_refptr<BloomFilter> scoped_filter(bloom_filter); // Read in data file line at a time. FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls")); std::ifstream url_stream(url_file.value().c_str()); // Keep track of stats int hits = 0; int misses = 0; int weighted_hits = 0; int weighted_misses = 0; int url_count = 0; int prefix_count = 0; // Print out volumes of data (per URL hit and miss information). bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose); bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv); std::string url; while (std::getline(url_stream, url)) { ++url_count; // Handle a format that contains URLs weighted by unique views. int weight = 1; if (use_weights) { std::string::size_type pos = url.find_last_of(","); if (pos != std::string::npos) { base::StringToInt(url.begin() + pos + 1, url.end(), &weight); url = url.substr(0, pos); } } // See if the URL is in the bloom filter. std::vector<SBPrefix> prefixes; prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes); // See if the prefix is actually in the database (in-memory prefix list). for (size_t i = 0; i < prefixes.size(); ++i) { if (IsPrefixInDatabase(prefixes[i], prefix_list)) { ++hits; weighted_hits += weight; if (verbose) { std::cout << "Hit for URL: " << url << " (prefix = " << prefixes[i] << ")" << std::endl; } } else { ++misses; weighted_misses += weight; if (verbose) { std::cout << "Miss for URL: " << url << " (prefix = " << prefixes[i] << ")" << std::endl; } } } } // Print out the results for this test. std::cout << "URLs checked: " << url_count << ", prefix compares: " << prefix_count << ", hits: " << hits << ", misses: " << misses; if (use_weights) { std::cout << ", weighted hits: " << weighted_hits << ", weighted misses: " << weighted_misses; } std::cout << std::endl; } } // namespace // This test can take several minutes to perform its calculations, so it should // be disabled until you need to run it. TEST(SafeBrowsingBloomFilter, FalsePositives) { std::vector<SBPrefix> prefix_list; FilePath data_dir = GetFullDataPath(); ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list)); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); int start = BloomFilter::kBloomFilterSizeRatio; if (cmd_line.HasSwitch(kFilterStart)) { ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart), &start)); } int steps = 1; if (cmd_line.HasSwitch(kFilterSteps)) { ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps), &steps)); } int stop = start + steps; for (int multiplier = start; multiplier < stop; ++multiplier) CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list); } // Computes the time required for performing a number of look ups in a bloom // filter. This is useful for measuring the performance of new hash functions. TEST(SafeBrowsingBloomFilter, HashTime) { // Read the data from the database. std::vector<SBPrefix> prefix_list; FilePath data_dir = GetFullDataPath(); ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list)); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); int num_checks = kNumHashChecks; if (cmd_line.HasSwitch(kFilterNumChecks)) { ASSERT_TRUE( base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterNumChecks), &num_checks)); } // Populate the bloom filter and measure the time. BloomFilter* bloom_filter = NULL; Time populate_before = Time::Now(); BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio, prefix_list, &bloom_filter); TimeDelta populate = Time::Now() - populate_before; // Check a large number of random prefixes against the filter. int hits = 0; Time check_before = Time::Now(); for (int i = 0; i < num_checks; ++i) { uint32 prefix = static_cast<uint32>(base::RandUint64()); if (bloom_filter->Exists(prefix)) ++hits; } TimeDelta check = Time::Now() - check_before; int64 time_per_insert = populate.InMicroseconds() / static_cast<int>(prefix_list.size()); int64 time_per_check = check.InMicroseconds() / num_checks; std::cout << "Time results for checks: " << num_checks << ", prefixes: " << prefix_list.size() << ", populate time (ms): " << populate.InMilliseconds() << ", check time (ms): " << check.InMilliseconds() << ", hits: " << hits << ", per-populate (us): " << time_per_insert << ", per-check (us): " << time_per_check << std::endl; } <commit_msg>Cleanup: Remove sqlite_utils.h from filter_false_positive_perftest.cc.<commit_after>// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // This test performs a series false positive checks using a list of URLs // against a known set of SafeBrowsing data. // // It uses a normal SafeBrowsing database to create a bloom filter where it // looks up all the URLs in the url file. A URL that has a prefix found in the // bloom filter and found in the database is considered a hit: a valid lookup // that will result in a gethash request. A URL that has a prefix found in the // bloom filter but not in the database is a miss: a false positive lookup that // will result in an unnecessary gethash request. // // By varying the size of the bloom filter and using a constant set of // SafeBrowsing data, we can check a known set of URLs against the filter and // determine the false positive rate. // // False positive calculation usage: // $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives // --filter-start=<integer> // --filter-steps=<integer> // --filter-verbose // // --filter-start: The filter multiplier to begin with. This represents the // number of bits per prefix of memory to use in the filter. // The default value is identical to the current SafeBrowsing // database value. // --filter-steps: The number of iterations to run, with each iteration // increasing the filter multiplier by 1. The default value // is 1. // --filter-verbose: Used to print out the hit / miss results per URL. // --filter-csv: The URL file contains information about the number of // unique views (the popularity) of each URL. See the format // description below. // // // Hash compute time usage: // $ ./perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime // --filter-num-checks=<integer> // // --filter-num-checks: The number of hash look ups to perform on the bloom // filter. The default is 10 million. // // Data files: // chrome/test/data/safe_browsing/filter/database // chrome/test/data/safe_browsing/filter/urls // // database: A normal SafeBrowsing database. // urls: A text file containing a list of URLs, one per line. If the option // --filter-csv is specified, the format of each line in the file is // <url>,<weight> where weight is an integer indicating the number of // unique views for the URL. #include <algorithm> #include <fstream> #include <vector> #include "app/sql/statement.h" #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/rand_util.h" #include "base/sha2.h" #include "base/string_number_conversions.h" #include "base/string_util.h" #include "base/time.h" #include "chrome/browser/safe_browsing/bloom_filter.h" #include "chrome/browser/safe_browsing/safe_browsing_util.h" #include "chrome/common/chrome_paths.h" #include "googleurl/src/gurl.h" #include "testing/gtest/include/gtest/gtest.h" using base::Time; using base::TimeDelta; namespace { // Command line flags. const char kFilterVerbose[] = "filter-verbose"; const char kFilterStart[] = "filter-start"; const char kFilterSteps[] = "filter-steps"; const char kFilterCsv[] = "filter-csv"; const char kFilterNumChecks[] = "filter-num-checks"; // Number of hash checks to make during performance testing. const int kNumHashChecks = 10000000; // Returns the path to the data used in this test, relative to the top of the // source directory. FilePath GetFullDataPath() { FilePath full_path; CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path)); full_path = full_path.Append(FILE_PATH_LITERAL("safe_browsing")); full_path = full_path.Append(FILE_PATH_LITERAL("filter")); CHECK(file_util::PathExists(full_path)); return full_path; } // Constructs a bloom filter of the appropriate size from the provided prefixes. void BuildBloomFilter(int size_multiplier, const std::vector<SBPrefix>& prefixes, BloomFilter** bloom_filter) { // Create a BloomFilter with the specified size. const int key_count = std::max(static_cast<int>(prefixes.size()), BloomFilter::kBloomFilterMinSize); const int filter_size = key_count * size_multiplier; *bloom_filter = new BloomFilter(filter_size); // Add the prefixes to it. for (size_t i = 0; i < prefixes.size(); ++i) (*bloom_filter)->Insert(prefixes[i]); std::cout << "Bloom filter with prefixes: " << prefixes.size() << ", multiplier: " << size_multiplier << ", size (bytes): " << (*bloom_filter)->size() << std::endl; } // Reads the set of add prefixes contained in a SafeBrowsing database into a // sorted array suitable for fast searching. This takes significantly less time // to look up a given prefix than performing SQL queries. bool ReadDatabase(const FilePath& path, std::vector<SBPrefix>* prefixes) { FilePath database_file = path.Append(FILE_PATH_LITERAL("database")); sql::Connection db; if (!db.Open(database_file)) return false; // Get the number of items in the add_prefix table. const char* query = "SELECT COUNT(*) FROM add_prefix"; sql::Statement count_statement(db.GetCachedStatement(SQL_FROM_HERE, query)); if (!count_statement) return false; if (!count_statement.Step()) return false; const int count = count_statement.ColumnInt(0); // Load them into a prefix vector and sort. prefixes->reserve(count); query = "SELECT prefix FROM add_prefix"; sql::Statement prefix_statement(db.GetCachedStatement(SQL_FROM_HERE, query)); if (!prefix_statement) return false; while (prefix_statement.Step()) prefixes->push_back(prefix_statement.ColumnInt(0)); DCHECK(static_cast<int>(prefixes->size()) == count); sort(prefixes->begin(), prefixes->end()); return true; } // Generates all legal SafeBrowsing prefixes for the specified URL, and returns // the set of Prefixes that exist in the bloom filter. The function returns the // number of host + path combinations checked. int GeneratePrefixHits(const std::string url, BloomFilter* bloom_filter, std::vector<SBPrefix>* prefixes) { GURL url_check(url); std::vector<std::string> hosts; if (url_check.HostIsIPAddress()) { hosts.push_back(url_check.host()); } else { safe_browsing_util::GenerateHostsToCheck(url_check, &hosts); } std::vector<std::string> paths; safe_browsing_util::GeneratePathsToCheck(url_check, &paths); for (size_t i = 0; i < hosts.size(); ++i) { for (size_t j = 0; j < paths.size(); ++j) { SBPrefix prefix; base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix)); if (bloom_filter->Exists(prefix)) prefixes->push_back(prefix); } } return hosts.size() * paths.size(); } // Binary search of sorted prefixes. bool IsPrefixInDatabase(SBPrefix prefix, const std::vector<SBPrefix>& prefixes) { if (prefixes.empty()) return false; int low = 0; int high = prefixes.size() - 1; while (low <= high) { int mid = ((unsigned int)low + (unsigned int)high) >> 1; SBPrefix prefix_mid = prefixes[mid]; if (prefix_mid == prefix) return true; if (prefix_mid < prefix) low = mid + 1; else high = mid - 1; } return false; } // Construct a bloom filter with the given prefixes and multiplier, and test the // false positive rate (misses) against a URL list. void CalculateBloomFilterFalsePositives( int size_multiplier, const FilePath& data_dir, const std::vector<SBPrefix>& prefix_list) { BloomFilter* bloom_filter = NULL; BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter); scoped_refptr<BloomFilter> scoped_filter(bloom_filter); // Read in data file line at a time. FilePath url_file = data_dir.Append(FILE_PATH_LITERAL("urls")); std::ifstream url_stream(url_file.value().c_str()); // Keep track of stats int hits = 0; int misses = 0; int weighted_hits = 0; int weighted_misses = 0; int url_count = 0; int prefix_count = 0; // Print out volumes of data (per URL hit and miss information). bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose); bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv); std::string url; while (std::getline(url_stream, url)) { ++url_count; // Handle a format that contains URLs weighted by unique views. int weight = 1; if (use_weights) { std::string::size_type pos = url.find_last_of(","); if (pos != std::string::npos) { base::StringToInt(url.begin() + pos + 1, url.end(), &weight); url = url.substr(0, pos); } } // See if the URL is in the bloom filter. std::vector<SBPrefix> prefixes; prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes); // See if the prefix is actually in the database (in-memory prefix list). for (size_t i = 0; i < prefixes.size(); ++i) { if (IsPrefixInDatabase(prefixes[i], prefix_list)) { ++hits; weighted_hits += weight; if (verbose) { std::cout << "Hit for URL: " << url << " (prefix = " << prefixes[i] << ")" << std::endl; } } else { ++misses; weighted_misses += weight; if (verbose) { std::cout << "Miss for URL: " << url << " (prefix = " << prefixes[i] << ")" << std::endl; } } } } // Print out the results for this test. std::cout << "URLs checked: " << url_count << ", prefix compares: " << prefix_count << ", hits: " << hits << ", misses: " << misses; if (use_weights) { std::cout << ", weighted hits: " << weighted_hits << ", weighted misses: " << weighted_misses; } std::cout << std::endl; } } // namespace // This test can take several minutes to perform its calculations, so it should // be disabled until you need to run it. TEST(SafeBrowsingBloomFilter, FalsePositives) { std::vector<SBPrefix> prefix_list; FilePath data_dir = GetFullDataPath(); ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list)); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); int start = BloomFilter::kBloomFilterSizeRatio; if (cmd_line.HasSwitch(kFilterStart)) { ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterStart), &start)); } int steps = 1; if (cmd_line.HasSwitch(kFilterSteps)) { ASSERT_TRUE(base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterSteps), &steps)); } int stop = start + steps; for (int multiplier = start; multiplier < stop; ++multiplier) CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list); } // Computes the time required for performing a number of look ups in a bloom // filter. This is useful for measuring the performance of new hash functions. TEST(SafeBrowsingBloomFilter, HashTime) { // Read the data from the database. std::vector<SBPrefix> prefix_list; FilePath data_dir = GetFullDataPath(); ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list)); const CommandLine& cmd_line = *CommandLine::ForCurrentProcess(); int num_checks = kNumHashChecks; if (cmd_line.HasSwitch(kFilterNumChecks)) { ASSERT_TRUE( base::StringToInt(cmd_line.GetSwitchValueASCII(kFilterNumChecks), &num_checks)); } // Populate the bloom filter and measure the time. BloomFilter* bloom_filter = NULL; Time populate_before = Time::Now(); BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio, prefix_list, &bloom_filter); TimeDelta populate = Time::Now() - populate_before; // Check a large number of random prefixes against the filter. int hits = 0; Time check_before = Time::Now(); for (int i = 0; i < num_checks; ++i) { uint32 prefix = static_cast<uint32>(base::RandUint64()); if (bloom_filter->Exists(prefix)) ++hits; } TimeDelta check = Time::Now() - check_before; int64 time_per_insert = populate.InMicroseconds() / static_cast<int>(prefix_list.size()); int64 time_per_check = check.InMicroseconds() / num_checks; std::cout << "Time results for checks: " << num_checks << ", prefixes: " << prefix_list.size() << ", populate time (ms): " << populate.InMilliseconds() << ", check time (ms): " << check.InMilliseconds() << ", hits: " << hits << ", per-populate (us): " << time_per_insert << ", per-check (us): " << time_per_check << std::endl; } <|endoftext|>
<commit_before>/************************************************************************** * * Copyright 2008-2010 VMware, 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. * **************************************************************************/ /* * Image I/O. */ #ifndef _IMAGE_HPP_ #define _IMAGE_HPP_ #include <iostream> namespace image { enum ChannelType { TYPE_UNORM8 = 0, TYPE_FLOAT }; class Image { public: unsigned width; unsigned height; unsigned channels; ChannelType channelType; unsigned bytesPerPixel; // Flipped vertically or not bool flipped; // Pixels in RGBA format unsigned char *pixels; inline Image(unsigned w, unsigned h, unsigned c = 4, bool f = false, ChannelType t = TYPE_UNORM8) : width(w), height(h), channels(c), channelType(t), bytesPerPixel(channels * (t == TYPE_FLOAT ? 4 : 1)), flipped(f), pixels(new unsigned char[h*w*c]) {} inline ~Image() { delete [] pixels; } // Absolute stride inline unsigned _stride() const { return width*bytesPerPixel; } inline unsigned char *start(void) { return flipped ? pixels + (height - 1)*_stride() : pixels; } inline const unsigned char *start(void) const { return flipped ? pixels + (height - 1)*_stride() : pixels; } inline unsigned char *end(void) { return flipped ? pixels - _stride() : pixels + height*_stride(); } inline const unsigned char *end(void) const { return flipped ? pixels - _stride() : pixels + height*_stride(); } inline signed stride(void) const { return flipped ? -(signed)_stride() : _stride(); } bool writeBMP(const char *filename) const; void writePNM(std::ostream &os, const char *comment = NULL) const; bool writePNM(const char *filename, const char *comment = NULL) const; bool writePNG(std::ostream &os) const; bool writePNG(const char *filename) const; void writeRAW(std::ostream &os) const; bool writeRAW(const char *filename) const; }; Image * readPNG(std::istream &is); Image * readPNG(const char *filename); const char * readPNMHeader(const char *buffer, size_t size, unsigned *channels, unsigned *width, unsigned *height); } /* namespace image */ #endif /* _IMAGE_HPP_ */ <commit_msg>image: Fix allocation of floating point images.<commit_after>/************************************************************************** * * Copyright 2008-2010 VMware, 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. * **************************************************************************/ /* * Image I/O. */ #ifndef _IMAGE_HPP_ #define _IMAGE_HPP_ #include <iostream> namespace image { enum ChannelType { TYPE_UNORM8 = 0, TYPE_FLOAT }; class Image { public: unsigned width; unsigned height; unsigned channels; ChannelType channelType; unsigned bytesPerPixel; // Flipped vertically or not bool flipped; // Pixels in RGBA format unsigned char *pixels; inline Image(unsigned w, unsigned h, unsigned c = 4, bool f = false, ChannelType t = TYPE_UNORM8) : width(w), height(h), channels(c), channelType(t), bytesPerPixel(channels * (t == TYPE_FLOAT ? 4 : 1)), flipped(f), pixels(new unsigned char[h*w*bytesPerPixel]) {} inline ~Image() { delete [] pixels; } // Absolute stride inline unsigned _stride() const { return width*bytesPerPixel; } inline unsigned char *start(void) { return flipped ? pixels + (height - 1)*_stride() : pixels; } inline const unsigned char *start(void) const { return flipped ? pixels + (height - 1)*_stride() : pixels; } inline unsigned char *end(void) { return flipped ? pixels - _stride() : pixels + height*_stride(); } inline const unsigned char *end(void) const { return flipped ? pixels - _stride() : pixels + height*_stride(); } inline signed stride(void) const { return flipped ? -(signed)_stride() : _stride(); } bool writeBMP(const char *filename) const; void writePNM(std::ostream &os, const char *comment = NULL) const; bool writePNM(const char *filename, const char *comment = NULL) const; bool writePNG(std::ostream &os) const; bool writePNG(const char *filename) const; void writeRAW(std::ostream &os) const; bool writeRAW(const char *filename) const; }; Image * readPNG(std::istream &is); Image * readPNG(const char *filename); const char * readPNMHeader(const char *buffer, size_t size, unsigned *channels, unsigned *width, unsigned *height); } /* namespace image */ #endif /* _IMAGE_HPP_ */ <|endoftext|>
<commit_before>#ifndef READER_H #define READER_H #include <istream> #include <string> #include "objects.hpp" // #include <vector> #include "symbols.hpp" // /* // * Intermediate bytecode representation constructed by the reader // * The execution engine should assemble it in a representation suitable // * for execution. // */ // // the argument of a bytecode // class BytecodeArg { public: virtual ~BytecodeArg() {}}; // /* // * a simple argument is a value that can fit in a pointer // * it could be an int, a scaled int, an offset, a character, a pointer // * to a Symbol, etc. // */ // class SimpleArg : public BytecodeArg { // private: // Object::ref val; // public: // SimpleArg() {} // template <class T> // void setVal(T v) { val = Object::to_ref(v); } // Object::ref getVal() { return val; } // }; // // a single bytecode // typedef std::pair<Symbol*, BytecodeArg*> bytecode; // /* // * bytecode sequence // * owns all the bytecode args and frees them // */ // class BytecodeSeq : public std::vector<bytecode>, public BytecodeArg { // public: // ~BytecodeSeq() {} // }; // /* // * Argument of bytecode that takes a simple argument and a sequence // */ // class SimpleArgAndSeq : public BytecodeArg { // private: // SimpleArg *sa; // BytecodeSeq *seq; // public: // SimpleArgAndSeq(SimpleArg *s, BytecodeSeq *bs) : sa(s), seq(bs) {} // ~SimpleArgAndSeq() { // delete seq; // delete sa; // } // SimpleArg* getSimple() { return sa; } // BytecodeSeq* getSeq() { return seq; } // }; // // exception thrown by the reader // class ReadError : public std::string { // public: // ReadError(const char *str) : std::string(str) {} // }; // /* // * Bytecode reader // * extends bc with a bytecode read from in // */ // static std::istream& operator>>(std::istream & in, BytecodeSeq & bc) { return in; } class Process; // leaves read bytecode on the stack void read_bytecode(Process & proc, std::istream & in); void read_sequence(Process & proc, std::istream & in); // simple printer for debugging std::ostream& operator<<(std::ostream & out, Object::ref obj); #endif // READER_H <commit_msg>reader.hpp: removed useless code<commit_after>#ifndef READER_H #define READER_H #include <istream> #include <string> #include "objects.hpp" #include "symbols.hpp" class Process; // leaves read bytecode on the stack void read_bytecode(Process & proc, std::istream & in); void read_sequence(Process & proc, std::istream & in); // simple printer for debugging std::ostream& operator<<(std::ostream & out, Object::ref obj); #endif // READER_H <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: pm_index.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2003-06-30 15:27:10 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #include <precomp.h> #include "pm_index.hxx" // NOT FULLY DEFINED SERVICES #include <ary/cpp/c_disply.hxx> #include <ary/cpp/c_class.hxx> #include <ary/cpp/c_define.hxx> #include <ary/cpp/c_enum.hxx> #include <ary/cpp/c_tydef.hxx> #include <ary/cpp/c_funct.hxx> #include <ary/cpp/c_macro.hxx> #include <ary/cpp/c_namesp.hxx> #include <ary/cpp/c_vari.hxx> #include <ary/cpp/c_enuval.hxx> #include <ary/info/codeinfo.hxx> #include "aryattrs.hxx" #include "hd_chlst.hxx" #include "hd_docu.hxx" #include "html_kit.hxx" #include "navibar.hxx" #include "opageenv.hxx" #include "pagemake.hxx" #include "strconst.hxx" using namespace csi; namespace { inline const char * F_CK_Text( ary::cpp::E_ClassKey i_eCK ) { switch (i_eCK) { case ary::cpp::CK_class: return "class"; case ary::cpp::CK_struct: return "struct"; case ary::cpp::CK_union: return "union"; } // end switch return ""; } template <class CE> inline const char * F_OwnerType( const CE & i_rData, const ary::cpp::DisplayGate & i_rGate ) { if ( i_rData.Protection() == ary::cpp::PROTECT_global ) return "namespace "; const ary::cpp::Class * pClass = dynamic_cast< const ary::cpp::Class* >( i_rGate.Find_Ce(i_rData.Owner()) ); if (pClass != 0) return F_CK_Text(pClass->ClassKey()); return ""; } } // anonymous namespace PageMaker_Index::PageMaker_Index( PageDisplay & io_rPage, char i_c ) : SpecializedPageMaker(io_rPage), pNavi(0), c(i_c), pCurIndex(0) { } PageMaker_Index::~PageMaker_Index() { } void PageMaker_Index::MakePage() { pNavi = new NavigationBar( Env(), NavigationBar::LOC_Index ); Write_NavBar(); Write_TopArea(); Write_CompleteAlphabeticalList(); } void PageMaker_Index::Display_Namespace( const ary::cpp::Namespace & i_rData ) { Write_CeIndexEntry( i_rData, "namespace", "namespace" ); } void PageMaker_Index::Display_Class( const ary::cpp::Class & i_rData ) { // KORR_FUTURE // Really throw out all anonymous classes from index? if ( strncmp(i_rData.LocalName().c_str()+1,"_Anonymous",10) == 0 ) return; Write_CeIndexEntry( i_rData, F_CK_Text(i_rData.ClassKey()), F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Enum( const ary::cpp::Enum & i_rData ) { Write_CeIndexEntry( i_rData, "enum", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Typedef( const ary::cpp::Typedef & i_rData ) { Write_CeIndexEntry( i_rData, "typedef", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Function( const ary::cpp::Function & i_rData ) { Write_CeIndexEntry( i_rData, "function", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Variable( const ary::cpp::Variable & i_rData ) { Write_CeIndexEntry( i_rData, "variable", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_EnumValue( const ary::cpp::EnumValue & i_rData ) { Write_CeIndexEntry( i_rData, "enum value", "" ); } void PageMaker_Index::Display_Define( const ary::cpp::Define & i_rData ) { udmstri sFileName; pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2CppDefinition(Env(), i_rData) ) >> *new html::Bold << i_rData.DefinedName() << " - define"; // KORR FUTURE // pCurIndex->Term() // << " - " // << " define in file " // << sFileName; pCurIndex->Def() << " "; } void PageMaker_Index::Display_Macro( const ary::cpp::Macro & i_rData ) { udmstri sFileName; pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2CppDefinition(Env(), i_rData) ) >> *new html::Bold << i_rData.DefinedName() << " - macro"; // KORR FUTURE // pCurIndex->Term() // << " - " // << " macro in file " // << sFileName; pCurIndex->Def() << " "; } void PageMaker_Index::Write_NavBar() { pNavi->Write( CurOut() ); CurOut() << new html::HorizontalLine; } const udmstri C_sAlphabet( "<a href=\"index-1.html\"><B>A</B></a> <a href=\"index-2.html\"><B>B</B></a> <a href=\"index-3.html\"><B>C</B></a> <a href=\"index-4.html\"><B>D</B></a> <a href=\"index-5.html\"><B>E</B></a> " "<a href=\"index-6.html\"><B>F</B></a> <a href=\"index-7.html\"><B>G</B></a> <a href=\"index-8.html\"><B>H</B></a> <a href=\"index-9.html\"><B>I</B></a> <a href=\"index-10.html\"><B>J</B></a> " "<a href=\"index-11.html\"><B>K</B></a> <a href=\"index-12.html\"><B>L</B></a> <a href=\"index-13.html\"><B>M</B></a> <a href=\"index-14.html\"><B>N</B></a> <a href=\"index-15.html\"><B>O</B></a> " "<a href=\"index-16.html\"><B>P</B></a> <a href=\"index-17.html\"><B>Q</B></a> <a href=\"index-18.html\"><B>R</B></a> <a href=\"index-19.html\"><B>S</B></a> <a href=\"index-20.html\"><B>T</B></a> " "<a href=\"index-21.html\"><B>U</B></a> <a href=\"index-22.html\"><B>V</B></a> <a href=\"index-23.html\"><B>W</B></a> <a href=\"index-24.html\"><B>X</B></a> <a href=\"index-25.html\"><B>Y</B></a> " "<a href=\"index-26.html\"><B>Z</B></a> <a href=\"index-27.html\"><B>_</B></a>" ); void PageMaker_Index::Write_TopArea() { udmstri sLetter(&c, 1); adcdisp::PageTitle_Std fTitle; fTitle( CurOut(), "Global Index", sLetter ); CurOut() >>* new html::Paragraph << new html::AlignAttr("center") << new xml::XmlCode(C_sAlphabet); CurOut() << new html::HorizontalLine; } void PageMaker_Index::Write_CompleteAlphabeticalList() { std::vector<ary::Rid> aThisPagesItems; const ary::cpp::DisplayGate & rGate = Env().Gate(); static char sBegin[] = "X"; static char sEnd[] = "Y"; switch ( c ) { case 'Z': sBegin[0] = 'Z'; sEnd[0] = '_'; break; case '_': sBegin[0] = '_'; sEnd[0] = '0'; break; default: sBegin[0] = c; sEnd[0] = char(c + 1); break; } uintt nCount = rGate.Get_AlphabeticalList( aThisPagesItems, sBegin, sEnd ); if (nCount > 0 ) { adcdisp::IndexList aIndex(CurOut()); pCurIndex = &aIndex; std::vector<ary::Rid>::const_iterator itEnd = aThisPagesItems.end(); for ( std::vector<ary::Rid>::const_iterator it = aThisPagesItems.begin(); it != itEnd; ++it ) { const ary::RepositoryEntity * pRe = rGate.Find_Re( *it ); if ( pRe != 0 ) pRe->StoreAt(*this); } // end for pCurIndex = 0; } // endif (nCount > 0) } void PageMaker_Index::Write_CeIndexEntry( const ary::CodeEntity & i_rCe, const char * i_sType, const char * i_sOwnerType ) { if ( Ce_IsInternal(i_rCe) ) return; static csv::StreamStr aQualification(500); const ary::CodeEntity & rOwner = Env().Gate().Ref_Ce(i_rCe.Owner()); pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2Ce(Env(), i_rCe) ) >> *new html::Bold << i_rCe.LocalName(); pCurIndex->Term() << " - " << i_sType; if ( rOwner.Owner() != 0 ) { aQualification.seekp(0); Env().Gate().Get_QualifiedName( aQualification, rOwner.LocalName(), rOwner.Owner() ); pCurIndex->Term() << " in " << i_sOwnerType << " " << aQualification.c_str(); } pCurIndex->Def() << " "; } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.96); FILE MERGED 2005/09/05 13:10:50 rt 1.4.96.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: pm_index.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-07 17:36:19 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <precomp.h> #include "pm_index.hxx" // NOT FULLY DEFINED SERVICES #include <ary/cpp/c_disply.hxx> #include <ary/cpp/c_class.hxx> #include <ary/cpp/c_define.hxx> #include <ary/cpp/c_enum.hxx> #include <ary/cpp/c_tydef.hxx> #include <ary/cpp/c_funct.hxx> #include <ary/cpp/c_macro.hxx> #include <ary/cpp/c_namesp.hxx> #include <ary/cpp/c_vari.hxx> #include <ary/cpp/c_enuval.hxx> #include <ary/info/codeinfo.hxx> #include "aryattrs.hxx" #include "hd_chlst.hxx" #include "hd_docu.hxx" #include "html_kit.hxx" #include "navibar.hxx" #include "opageenv.hxx" #include "pagemake.hxx" #include "strconst.hxx" using namespace csi; namespace { inline const char * F_CK_Text( ary::cpp::E_ClassKey i_eCK ) { switch (i_eCK) { case ary::cpp::CK_class: return "class"; case ary::cpp::CK_struct: return "struct"; case ary::cpp::CK_union: return "union"; } // end switch return ""; } template <class CE> inline const char * F_OwnerType( const CE & i_rData, const ary::cpp::DisplayGate & i_rGate ) { if ( i_rData.Protection() == ary::cpp::PROTECT_global ) return "namespace "; const ary::cpp::Class * pClass = dynamic_cast< const ary::cpp::Class* >( i_rGate.Find_Ce(i_rData.Owner()) ); if (pClass != 0) return F_CK_Text(pClass->ClassKey()); return ""; } } // anonymous namespace PageMaker_Index::PageMaker_Index( PageDisplay & io_rPage, char i_c ) : SpecializedPageMaker(io_rPage), pNavi(0), c(i_c), pCurIndex(0) { } PageMaker_Index::~PageMaker_Index() { } void PageMaker_Index::MakePage() { pNavi = new NavigationBar( Env(), NavigationBar::LOC_Index ); Write_NavBar(); Write_TopArea(); Write_CompleteAlphabeticalList(); } void PageMaker_Index::Display_Namespace( const ary::cpp::Namespace & i_rData ) { Write_CeIndexEntry( i_rData, "namespace", "namespace" ); } void PageMaker_Index::Display_Class( const ary::cpp::Class & i_rData ) { // KORR_FUTURE // Really throw out all anonymous classes from index? if ( strncmp(i_rData.LocalName().c_str()+1,"_Anonymous",10) == 0 ) return; Write_CeIndexEntry( i_rData, F_CK_Text(i_rData.ClassKey()), F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Enum( const ary::cpp::Enum & i_rData ) { Write_CeIndexEntry( i_rData, "enum", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Typedef( const ary::cpp::Typedef & i_rData ) { Write_CeIndexEntry( i_rData, "typedef", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Function( const ary::cpp::Function & i_rData ) { Write_CeIndexEntry( i_rData, "function", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_Variable( const ary::cpp::Variable & i_rData ) { Write_CeIndexEntry( i_rData, "variable", F_OwnerType(i_rData, Env().Gate()) ); } void PageMaker_Index::Display_EnumValue( const ary::cpp::EnumValue & i_rData ) { Write_CeIndexEntry( i_rData, "enum value", "" ); } void PageMaker_Index::Display_Define( const ary::cpp::Define & i_rData ) { udmstri sFileName; pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2CppDefinition(Env(), i_rData) ) >> *new html::Bold << i_rData.DefinedName() << " - define"; // KORR FUTURE // pCurIndex->Term() // << " - " // << " define in file " // << sFileName; pCurIndex->Def() << " "; } void PageMaker_Index::Display_Macro( const ary::cpp::Macro & i_rData ) { udmstri sFileName; pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2CppDefinition(Env(), i_rData) ) >> *new html::Bold << i_rData.DefinedName() << " - macro"; // KORR FUTURE // pCurIndex->Term() // << " - " // << " macro in file " // << sFileName; pCurIndex->Def() << " "; } void PageMaker_Index::Write_NavBar() { pNavi->Write( CurOut() ); CurOut() << new html::HorizontalLine; } const udmstri C_sAlphabet( "<a href=\"index-1.html\"><B>A</B></a> <a href=\"index-2.html\"><B>B</B></a> <a href=\"index-3.html\"><B>C</B></a> <a href=\"index-4.html\"><B>D</B></a> <a href=\"index-5.html\"><B>E</B></a> " "<a href=\"index-6.html\"><B>F</B></a> <a href=\"index-7.html\"><B>G</B></a> <a href=\"index-8.html\"><B>H</B></a> <a href=\"index-9.html\"><B>I</B></a> <a href=\"index-10.html\"><B>J</B></a> " "<a href=\"index-11.html\"><B>K</B></a> <a href=\"index-12.html\"><B>L</B></a> <a href=\"index-13.html\"><B>M</B></a> <a href=\"index-14.html\"><B>N</B></a> <a href=\"index-15.html\"><B>O</B></a> " "<a href=\"index-16.html\"><B>P</B></a> <a href=\"index-17.html\"><B>Q</B></a> <a href=\"index-18.html\"><B>R</B></a> <a href=\"index-19.html\"><B>S</B></a> <a href=\"index-20.html\"><B>T</B></a> " "<a href=\"index-21.html\"><B>U</B></a> <a href=\"index-22.html\"><B>V</B></a> <a href=\"index-23.html\"><B>W</B></a> <a href=\"index-24.html\"><B>X</B></a> <a href=\"index-25.html\"><B>Y</B></a> " "<a href=\"index-26.html\"><B>Z</B></a> <a href=\"index-27.html\"><B>_</B></a>" ); void PageMaker_Index::Write_TopArea() { udmstri sLetter(&c, 1); adcdisp::PageTitle_Std fTitle; fTitle( CurOut(), "Global Index", sLetter ); CurOut() >>* new html::Paragraph << new html::AlignAttr("center") << new xml::XmlCode(C_sAlphabet); CurOut() << new html::HorizontalLine; } void PageMaker_Index::Write_CompleteAlphabeticalList() { std::vector<ary::Rid> aThisPagesItems; const ary::cpp::DisplayGate & rGate = Env().Gate(); static char sBegin[] = "X"; static char sEnd[] = "Y"; switch ( c ) { case 'Z': sBegin[0] = 'Z'; sEnd[0] = '_'; break; case '_': sBegin[0] = '_'; sEnd[0] = '0'; break; default: sBegin[0] = c; sEnd[0] = char(c + 1); break; } uintt nCount = rGate.Get_AlphabeticalList( aThisPagesItems, sBegin, sEnd ); if (nCount > 0 ) { adcdisp::IndexList aIndex(CurOut()); pCurIndex = &aIndex; std::vector<ary::Rid>::const_iterator itEnd = aThisPagesItems.end(); for ( std::vector<ary::Rid>::const_iterator it = aThisPagesItems.begin(); it != itEnd; ++it ) { const ary::RepositoryEntity * pRe = rGate.Find_Re( *it ); if ( pRe != 0 ) pRe->StoreAt(*this); } // end for pCurIndex = 0; } // endif (nCount > 0) } void PageMaker_Index::Write_CeIndexEntry( const ary::CodeEntity & i_rCe, const char * i_sType, const char * i_sOwnerType ) { if ( Ce_IsInternal(i_rCe) ) return; static csv::StreamStr aQualification(500); const ary::CodeEntity & rOwner = Env().Gate().Ref_Ce(i_rCe.Owner()); pCurIndex->AddEntry(); pCurIndex->Term() >> *new html::Link( Link2Ce(Env(), i_rCe) ) >> *new html::Bold << i_rCe.LocalName(); pCurIndex->Term() << " - " << i_sType; if ( rOwner.Owner() != 0 ) { aQualification.seekp(0); Env().Gate().Get_QualifiedName( aQualification, rOwner.LocalName(), rOwner.Owner() ); pCurIndex->Term() << " in " << i_sOwnerType << " " << aQualification.c_str(); } pCurIndex->Def() << " "; } <|endoftext|>
<commit_before>/* * Created by kunjesh virani on 7 February, 2017 * On the Platform Linux (Ubuntu Xenial xerus) 64bit * */ /* * Description * * This file contain the code of native activity with very simple and basic use of EGL and OpenGL ES libraries. */ #include <android_native_app_glue.h> #include <android/log.h> #include <EGL/egl.h> #include <GLES/gl.h> #include "linedraw.h" #define LOGW(x...) __android_log_print(ANDROID_LOG_WARN, "OnlyBlankNativeActivity",x) struct egl { EGLDisplay display; EGLSurface surface; EGLContext context; }; linedraw lineDraw; // calling a class which is defined in "linedraw" class. static void egl_init(struct android_app* app, struct egl* egl) { // below is the code for attributes of EGL which will be stored in configurations (config). const EGLint attributes[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE }; // declare the several variables which will assigned to main egl struct members EGLint format, numConfigs; EGLDisplay display; EGLContext context; EGLSurface surface; EGLConfig config; // first get the EGL display connection. display = eglGetDisplay(EGL_DEFAULT_DISPLAY); // after getting display connection must initialize the EGL eglInitialize(display, 0, 0); // when initialization will complete egl take a watch for choosing its configuration. // below function will save the choosen configuration in config and return the number of configuration in numConfig. eglChooseConfig(display, attributes, &config, 1, &numConfigs); // get the choosen configurations and set the format for native display. eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); // Set the geometry of native window via format returned. ANativeWindow_setBuffersGeometry(app->window, 0, 0, format); // Initialize the surface and context of EGL for render the rendering API like OpenGL ES.. surface = eglCreateWindowSurface(display, config, app->window, 0); context = eglCreateContext(display, config, 0, 0); // make the surface and context active to the current thread which will be used in the process. eglMakeCurrent(display, surface, surface, context); egl->display = display; egl->surface = surface; egl->context = context; } static void engine_for_draw(struct egl* egl) { if(egl->display == NULL) return; glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); lineDraw.draw(); // calling a class member function. // this will post the color buffer created vua glClearColor() to native window. // without use of below code will output nothing except blank screen, and will not generate error. eglSwapBuffers(egl->display, egl->surface); } static void engine_terminate(struct egl* egl) { if(egl->display != EGL_NO_DISPLAY) { eglMakeCurrent(egl->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if(egl->surface != EGL_NO_SURFACE) eglDestroySurface(egl->display, egl->surface); if(egl->context != EGL_NO_CONTEXT) eglDestroyContext(egl->display, egl->context); eglTerminate(egl->display); } egl->display = EGL_NO_DISPLAY; egl->surface = EGL_NO_SURFACE; egl->context = EGL_NO_CONTEXT; } // below function for control display via various commands static void handle_command_android(struct android_app* app, int32_t cmd) { struct egl* egl = (struct egl*)app->userData; switch (cmd) { case APP_CMD_INIT_WINDOW: egl_init(app, egl); engine_for_draw(egl); LOGW("App Window has been initiated.."); break; case APP_CMD_TERM_WINDOW: engine_terminate(egl); LOGW("App Window has been terminated.."); break; case APP_CMD_SAVE_STATE: // here sometime you have to remove the termination code from here due to large number of drawing in 1 or 2 seconds. // using termination code here will manage the usage of RAM when application's activity has been paused. engine_terminate(egl); LOGW("App window's state has been saved.. or Window has been minimized"); break; default: break; } } static int32_t handle_input_android(struct android_app* app, AInputEvent* event) { // below code is for catch handle input. if(AInputEvent_getType(event)==AINPUT_EVENT_TYPE_MOTION) { LOGW("Coordinates X = %f, Y = %f ", AMotionEvent_getX(event,0), AMotionEvent_getY(event,0)); return 1; } return 0; } // below code is for android_main() which is the entry point of our execution. void android_main(struct android_app* app_state) { // below code is for determine that glue is not stripped, because if it is stripped it will remove the module android_native_app_glue.o which will stop the execution. So use of app_dummy() function will embed it. app_dummy(); // below variable declaration is for catch the events and process it. struct egl egl; // memset(&egl, 0, sizeof(egl)); int events; app_state->userData = &egl; app_state->onAppCmd = handle_command_android; app_state->onInputEvent = handle_input_android; while(1) { struct android_poll_source* source; while(ALooper_pollAll(-1, NULL, &events, (void**)&source)>=0) { if(source != NULL) source->process(app_state, source); if(app_state->destroyRequested != 0) { LOGW("We are exiting from app."); return; } } } } <commit_msg>Update native-lib.cpp<commit_after>/* * Created by KV on 7 February, 2017 * On the Platform Linux (Ubuntu Xenial xerus) 64bit * * [email protected] */ /* * Description * * This file contain the code of native activity with very simple and basic use of EGL and OpenGL ES libraries. */ #include <android_native_app_glue.h> #include <android/log.h> #include <EGL/egl.h> #include <GLES/gl.h> #include "linedraw.h" #define LOGW(x...) __android_log_print(ANDROID_LOG_WARN, "OnlyBlankNativeActivity",x) struct egl { EGLDisplay display; EGLSurface surface; EGLContext context; }; linedraw lineDraw; // calling a class which is defined in "linedraw" class. static void egl_init(struct android_app* app, struct egl* egl) { // below is the code for attributes of EGL which will be stored in configurations (config). const EGLint attributes[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE }; // declare the several variables which will assigned to main egl struct members EGLint format, numConfigs; EGLDisplay display; EGLContext context; EGLSurface surface; EGLConfig config; // first get the EGL display connection. display = eglGetDisplay(EGL_DEFAULT_DISPLAY); // after getting display connection must initialize the EGL eglInitialize(display, 0, 0); // when initialization will complete egl take a watch for choosing its configuration. // below function will save the choosen configuration in config and return the number of configuration in numConfig. eglChooseConfig(display, attributes, &config, 1, &numConfigs); // get the choosen configurations and set the format for native display. eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); // Set the geometry of native window via format returned. ANativeWindow_setBuffersGeometry(app->window, 0, 0, format); // Initialize the surface and context of EGL for render the rendering API like OpenGL ES.. surface = eglCreateWindowSurface(display, config, app->window, 0); context = eglCreateContext(display, config, 0, 0); // make the surface and context active to the current thread which will be used in the process. eglMakeCurrent(display, surface, surface, context); egl->display = display; egl->surface = surface; egl->context = context; } static void engine_for_draw(struct egl* egl) { if(egl->display == NULL) return; glClearColor(0.0, 0.0, 0.0, 1.0); glClear(GL_COLOR_BUFFER_BIT); lineDraw.draw(); // calling a class member function. // this will post the color buffer created vua glClearColor() to native window. // without use of below code will output nothing except blank screen, and will not generate error. eglSwapBuffers(egl->display, egl->surface); } static void engine_terminate(struct egl* egl) { if(egl->display != EGL_NO_DISPLAY) { eglMakeCurrent(egl->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if(egl->surface != EGL_NO_SURFACE) eglDestroySurface(egl->display, egl->surface); if(egl->context != EGL_NO_CONTEXT) eglDestroyContext(egl->display, egl->context); eglTerminate(egl->display); } egl->display = EGL_NO_DISPLAY; egl->surface = EGL_NO_SURFACE; egl->context = EGL_NO_CONTEXT; } // below function for control display via various commands static void handle_command_android(struct android_app* app, int32_t cmd) { struct egl* egl = (struct egl*)app->userData; switch (cmd) { case APP_CMD_INIT_WINDOW: egl_init(app, egl); engine_for_draw(egl); LOGW("App Window has been initiated.."); break; case APP_CMD_TERM_WINDOW: engine_terminate(egl); LOGW("App Window has been terminated.."); break; case APP_CMD_SAVE_STATE: // here sometime you have to remove the termination code from here due to large number of drawing in 1 or 2 seconds. // using termination code here will manage the usage of RAM when application's activity has been paused. engine_terminate(egl); LOGW("App window's state has been saved.. or Window has been minimized"); break; default: break; } } static int32_t handle_input_android(struct android_app* app, AInputEvent* event) { // below code is for catch handle input. if(AInputEvent_getType(event)==AINPUT_EVENT_TYPE_MOTION) { LOGW("Coordinates X = %f, Y = %f ", AMotionEvent_getX(event,0), AMotionEvent_getY(event,0)); return 1; } return 0; } // below code is for android_main() which is the entry point of our execution. void android_main(struct android_app* app_state) { // below code is for determine that glue is not stripped, because if it is stripped it will remove the module android_native_app_glue.o which will stop the execution. So use of app_dummy() function will embed it. app_dummy(); // below variable declaration is for catch the events and process it. struct egl egl; // memset(&egl, 0, sizeof(egl)); int events; app_state->userData = &egl; app_state->onAppCmd = handle_command_android; app_state->onInputEvent = handle_input_android; while(1) { struct android_poll_source* source; while(ALooper_pollAll(-1, NULL, &events, (void**)&source)>=0) { if(source != NULL) source->process(app_state, source); if(app_state->destroyRequested != 0) { LOGW("We are exiting from app."); return; } } } } <|endoftext|>
<commit_before>/** * @file SimulationTest.cpp * @author <a href="mailto:[email protected]">Benjamin Schlotter</a> * Implementation of class SimulationTest */ #include "SimulationTest.h" using namespace naoth; using namespace std; SimulationTest::SimulationTest() { simulationModule = registerModule<Simulation>(std::string("Simulation"), true); DEBUG_REQUEST_REGISTER("SimulationTest:draw_decision","draw_decision", false); //Set Rotation globRot = 0.0; } SimulationTest::~SimulationTest(){} void SimulationTest::execute() { DEBUG_REQUEST("SimulationTest:draw_decision", globRot = globRot+1.0; // hack static std::vector<Vector3d> function; function.clear(); // ball just in front of the robot getBallModel().position = Vector2d(150, 0); getBallModel().valid = true; getBallModel().setFrameInfoWhenBallWasSeen(getFrameInfo()); getRobotPose().isValid = true; // iterate over robot pose functionMulticolor.clear(); Pose2D p(0.0, getFieldInfo().carpetRect.min()); for(p.translation.x = getFieldInfo().carpetRect.min().x; p.translation.x < getFieldInfo().carpetRect.max().x; p.translation.x += 200) { for(p.translation.y = getFieldInfo().carpetRect.min().y; p.translation.y < getFieldInfo().carpetRect.max().y; p.translation.y += 200) { MultiColorValue v(KickActionModel::numOfActions); v.position = p*getBallModel().position; //Draw the ball position later for(size_t i=0;i<10;i++) { p.rotation = Math::fromDegrees(globRot); getRobotPose() = p; simulationModule->execute(); v.values[getKickActionModel().bestAction]++; } functionMulticolor.push_back(v); } } draw_function_multicolor(functionMulticolor); //draw_function(function); ); }//end execute void SimulationTest::draw_function(const std::vector<Vector3d>& function) const { if(function.empty()) { return; } double maxValue = function.front().z; double minValue = function.front().z; for(size_t i = 0; i < function.size(); ++i) { if(function[i].z > maxValue) { maxValue = function[i].z; } else if(function[i].z < minValue) { minValue = function[i].z; } } if(maxValue - minValue == 0) return; FIELD_DRAWING_CONTEXT; Color white(1.0,1.0,1.0,0.0); // transparent Color black(0.0,0.0,0.0,1.0); for(size_t i = 0; i < function.size(); ++i) { double t = (function[i].z - minValue) / (maxValue - minValue); //Color color = black*t + white*(1-t); Color color; if(function[i].z == 0){ color = Color(1.0,1.0,1.0,0.7); //White - None } else if(function[i].z == 1){ color = Color(255.0/255,172.0/255,18.0/255,0.7); //orange - kick_short } else if(function[i].z == 2){ color = Color(232.0/255,43.0/255,0.0/255,0.7); //red - kick_long } else if(function[i].z == 3){ color = Color(0.0/255,13.0/255,191.0/255,0.7); //blue - sidekick_left } else if(function[i].z == 4){ color = Color(0.0/255,191.0/255,51.0/255,0.7);//green - sidekick_right } PEN(color, 20); FILLBOX(function[i].x - 50, function[i].y - 50, function[i].x+50, function[i].y+50); } //Draw Arrow instead Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); }//end draw_closest_points void SimulationTest::draw_difference(const std::vector<Vector3d>& function)const{ if(function.empty()) { return; } double maxValue = function.front().z; double minValue = function.front().z; for(size_t i = 0; i < function.size(); ++i) { if(function[i].z > maxValue) { maxValue = function[i].z; } else if(function[i].z < minValue) { minValue = function[i].z; } } if(maxValue - minValue == 0) return; FIELD_DRAWING_CONTEXT; Color white(1.0,1.0,1.0,0.0); // transparent Color black(0.0,0.0,0.0,1.0); for(size_t i = 0; i < function.size(); ++i) { Color color; //Test for difference of kick decisions if(function[i].z == 0) { color = Color(1.0,1.0,1.0,0.7);//White Kick Decision is the same } else if(function[i].z == 1) { color = Color(0.0,0.0,0.0,0.7); //Black - Kick Decision is not the same } PEN(color, 20); FILLBOX(function[i].x - 50, function[i].y - 50, function[i].x+50, function[i].y+50); } //Draw Arrow Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); } void SimulationTest::draw_function_multicolor(const std::vector<SimulationTest::MultiColorValue>& function) const { if(function.empty()) { return; } FIELD_DRAWING_CONTEXT; std::vector<Color> colors; colors.push_back(Color(1.0,1.0,0.0,0.7)); //none colors.push_back(Color(255.0/255,172.0/255,18.0/255,0.7));//short colors.push_back(Color(232.0/255,43.0/255,0.0/255,0.7)); //long colors.push_back(Color(0.0/255,13.0/255,191.0/255,0.7)); //left colors.push_back(Color(0.0/255,191.0/255,51.0/255,0.7)); //right for(size_t i = 0; i < function.size(); ++i) { const MultiColorValue& v = function[i]; double sum = 0; for(size_t j = 0; j < v.values.size(); ++j) { sum += v.values[j]; } Color color(0.0,0.0,0.0,0.0); for(size_t j = 0; j < v.values.size(); ++j) { color += v.values[j]/sum*colors[j]; } PEN(color, 0); FILLBOX(v.position.x - 100, v.position.y - 100, v.position.x+100, v.position.y+100); } //Draw Arrow Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); }<commit_msg>cleanup<commit_after>/** * @file SimulationTest.cpp * @author <a href="mailto:[email protected]">Benjamin Schlotter</a> * Implementation of class SimulationTest */ #include "SimulationTest.h" using namespace naoth; using namespace std; SimulationTest::SimulationTest() { simulationModule = registerModule<Simulation>(std::string("Simulation"), true); DEBUG_REQUEST_REGISTER("SimulationTest:draw_decision","draw_decision", false); //Set Rotation globRot = 0.0; } SimulationTest::~SimulationTest(){} void SimulationTest::execute() { DEBUG_REQUEST("SimulationTest:draw_decision", globRot = globRot+1.0; // hack static std::vector<Vector3d> function; function.clear(); // ball just in front of the robot getBallModel().position = Vector2d(150, 0); getBallModel().valid = true; getBallModel().setFrameInfoWhenBallWasSeen(getFrameInfo()); getRobotPose().isValid = true; // iterate over robot pose functionMulticolor.clear(); Vector2d p(getFieldInfo().carpetRect.min()); for(p.x = getFieldInfo().carpetRect.min().x; p.x < getFieldInfo().carpetRect.max().x; p.x += 200) { for(p.y = getFieldInfo().carpetRect.min().y; p.y < getFieldInfo().carpetRect.max().y; p.y += 200) { MultiColorValue v(KickActionModel::numOfActions); v.position = p; //Draw the ball position later for(size_t i=0; i<10; ++i) { getRobotPose().translation = p; getRobotPose().rotation = Math::fromDegrees(globRot); simulationModule->execute(); v.values[getKickActionModel().bestAction]++; } functionMulticolor.push_back(v); } } draw_function_multicolor(functionMulticolor); //draw_function(function); ); }//end execute void SimulationTest::draw_function(const std::vector<Vector3d>& function) const { if(function.empty()) { return; } double maxValue = function.front().z; double minValue = function.front().z; for(size_t i = 0; i < function.size(); ++i) { if(function[i].z > maxValue) { maxValue = function[i].z; } else if(function[i].z < minValue) { minValue = function[i].z; } } if(maxValue - minValue == 0) return; FIELD_DRAWING_CONTEXT; Color white(1.0,1.0,1.0,0.0); // transparent Color black(0.0,0.0,0.0,1.0); for(size_t i = 0; i < function.size(); ++i) { double t = (function[i].z - minValue) / (maxValue - minValue); //Color color = black*t + white*(1-t); Color color; if(function[i].z == 0){ color = Color(1.0,1.0,1.0,0.7); //White - None } else if(function[i].z == 1){ color = Color(255.0/255,172.0/255,18.0/255,0.7); //orange - kick_short } else if(function[i].z == 2){ color = Color(232.0/255,43.0/255,0.0/255,0.7); //red - kick_long } else if(function[i].z == 3){ color = Color(0.0/255,13.0/255,191.0/255,0.7); //blue - sidekick_left } else if(function[i].z == 4){ color = Color(0.0/255,191.0/255,51.0/255,0.7);//green - sidekick_right } PEN(color, 20); FILLBOX(function[i].x - 50, function[i].y - 50, function[i].x+50, function[i].y+50); } //Draw Arrow instead Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); }//end draw_closest_points void SimulationTest::draw_difference(const std::vector<Vector3d>& function)const{ if(function.empty()) { return; } double maxValue = function.front().z; double minValue = function.front().z; for(size_t i = 0; i < function.size(); ++i) { if(function[i].z > maxValue) { maxValue = function[i].z; } else if(function[i].z < minValue) { minValue = function[i].z; } } if(maxValue - minValue == 0) return; FIELD_DRAWING_CONTEXT; Color white(1.0,1.0,1.0,0.0); // transparent Color black(0.0,0.0,0.0,1.0); for(size_t i = 0; i < function.size(); ++i) { Color color; //Test for difference of kick decisions if(function[i].z == 0) { color = Color(1.0,1.0,1.0,0.7);//White Kick Decision is the same } else if(function[i].z == 1) { color = Color(0.0,0.0,0.0,0.7); //Black - Kick Decision is not the same } PEN(color, 20); FILLBOX(function[i].x - 50, function[i].y - 50, function[i].x+50, function[i].y+50); } //Draw Arrow Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); } void SimulationTest::draw_function_multicolor(const std::vector<SimulationTest::MultiColorValue>& function) const { if(function.empty()) { return; } FIELD_DRAWING_CONTEXT; std::vector<Color> colors; colors.push_back(Color(1.0,1.0,0.0,0.7)); //none colors.push_back(Color(255.0/255,172.0/255,18.0/255,0.7));//short colors.push_back(Color(232.0/255,43.0/255,0.0/255,0.7)); //long colors.push_back(Color(0.0/255,13.0/255,191.0/255,0.7)); //left colors.push_back(Color(0.0/255,191.0/255,51.0/255,0.7)); //right for(size_t i = 0; i < function.size(); ++i) { const MultiColorValue& v = function[i]; double sum = 0; for(size_t j = 0; j < v.values.size(); ++j) { sum += v.values[j]; } Color color(0.0,0.0,0.0,0.0); for(size_t j = 0; j < v.values.size(); ++j) { color += v.values[j]/sum*colors[j]; } PEN(color, 0); FILLBOX(v.position.x - 100, v.position.y - 100, v.position.x+100, v.position.y+100); } //Draw Arrow Pose2D q; q.translation.x = 0.0; q.translation.y = 0.0; q.rotation = Math::fromDegrees(globRot); Vector2d ArrowStart = q * Vector2d(0, 0); Vector2d ArrowEnd = q * Vector2d(500, 0); PEN("000000", 50); ARROW(ArrowStart.x,ArrowStart.y,ArrowEnd.x,ArrowEnd.y); }<|endoftext|>
<commit_before>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/sundials_interface.h> #include <deal2lkit/imex_stepper.h> #ifdef D2K_WITH_SUNDIALS #include <deal.II/base/utilities.h> #include <deal.II/lac/block_vector.h> #ifdef DEAL_II_WITH_TRILINOS #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/trilinos_parallel_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #endif #include <deal.II/base/utilities.h> #include <iostream> #include <iomanip> #ifdef DEAL_II_WITH_MPI #include <nvector/nvector_parallel.h> #endif using namespace dealii; D2K_NAMESPACE_OPEN template <typename VEC> IMEXStepper<VEC>::IMEXStepper(SundialsInterface<VEC> &interface, const double &step_size, const double &initial_time, const double &final_time) : ParameterAcceptor("IMEX Parameters"), interface(interface), step_size(step_size), initial_time(initial_time), final_time(final_time), pout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)==0) { abs_tol = 1e-6; rel_tol = 1e-8; output_period = 1; newton_alpha = 1.0; max_outer_non_linear_iterations = 5; max_inner_non_linear_iterations = 3; } template <typename VEC> void IMEXStepper<VEC>::declare_parameters(ParameterHandler &prm) { add_parameter(prm, &step_size, "Step size", std::to_string(step_size), Patterns::Double()); add_parameter(prm, &abs_tol, "Absolute error tolerance", std::to_string(abs_tol), Patterns::Double()); add_parameter(prm, &rel_tol, "Relative error tolerance", std::to_string(rel_tol), Patterns::Double()); add_parameter(prm, &initial_time, "Initial time", std::to_string(initial_time), Patterns::Double()); add_parameter(prm, &final_time, "Final time", std::to_string(final_time), Patterns::Double()); add_parameter(prm, &output_period, "Intervals between outputs", std::to_string(output_period), Patterns::Integer()); add_parameter(prm, &max_outer_non_linear_iterations, "Maximum number of outer nonlinear iterations", std::to_string(max_outer_non_linear_iterations), Patterns::Integer(), "At each outer iteration the Jacobian is updated if it is set that the \n" "Jacobian is continuously updated and a cycle of inner iterations is \n" "perfomed."); add_parameter(prm, &max_inner_non_linear_iterations, "Maximum number of inner nonlinear iterations", std::to_string(max_inner_non_linear_iterations), Patterns::Integer(), "At each inner iteration the Jacobian is NOT updated."); add_parameter(prm, &newton_alpha, "Newton relaxation parameter", std::to_string(newton_alpha), Patterns::Double()); add_parameter(prm, &update_jacobian_continuously, "Update continuously Jacobian", "true", Patterns::Bool()); } template <typename VEC> unsigned int IMEXStepper<VEC>::start_ode(VEC &solution, VEC &solution_dot) { AssertDimension(solution.size(), interface.n_dofs()); unsigned int step_number = 0; auto previous_solution = interface.create_new_vector(); auto solution_update = interface.create_new_vector(); auto residual = interface.create_new_vector(); auto rhs = interface.create_new_vector(); *previous_solution = solution; double t = initial_time; double alpha; // check if it is a stationary problem if (initial_time == final_time) alpha = 0.0; else alpha = 1./step_size; interface.output_step( 0, solution, solution_dot, 0, step_size); // Initialization of the state of the boolean variable // responsible to keep track of the requirement that the // system's Jacobian be updated. bool update_Jacobian = true; bool restart=false; // The overall cycle over time begins here. for (; t<=final_time+1e-15; t+= step_size, ++step_number) { pout << "Time = " << t << std::endl; // Implicit Euler scheme. solution_dot = solution; solution_dot -= *previous_solution; solution_dot *= alpha; // Initialization of two counters for the monitoring of // progress of the nonlinear solver. unsigned int inner_iter = 0; unsigned int outer_iter = 0; unsigned int nonlin_iter = 0; interface.residual(t, solution, solution_dot, *residual); double res_norm = 0.0; double solution_norm = 0.0; if (abs_tol>0.0||rel_tol>0.0) res_norm = interface.vector_norm(*residual); if (rel_tol>0.0) solution_norm = interface.vector_norm(solution); // The nonlinear solver iteration cycle begins here. while (outer_iter < max_outer_non_linear_iterations && res_norm > abs_tol && res_norm > rel_tol*solution_norm) { outer_iter += 1; if (update_Jacobian == true) { interface.setup_jacobian(t, solution, solution_dot, *residual, alpha); } inner_iter = 0; while (inner_iter < max_inner_non_linear_iterations && res_norm > abs_tol && res_norm > rel_tol*solution_norm) { inner_iter += 1; *rhs = *residual; *rhs *= -1.0; interface.solve_jacobian_system(t, solution, solution_dot, *residual, alpha, *rhs, *solution_update); solution.sadd(1.0, newton_alpha, *solution_update); // Implicit Euler scheme. solution_dot = solution; solution_dot -= *previous_solution; solution_dot *= alpha; interface.residual(t, solution, solution_dot, *residual); if (abs_tol>0.0||rel_tol>0.0) res_norm = interface.vector_norm(*solution_update); if (rel_tol>0.0) solution_norm = interface.vector_norm(solution); } nonlin_iter += inner_iter; if (std::fabs(res_norm) < abs_tol || std::fabs(res_norm) < rel_tol*solution_norm) { pout << std::endl << " " << std::setw(19) << std::scientific << res_norm << " (converged in " << nonlin_iter << " iterations)\n\n" << std::endl; break; // Break of the while cycle ... after this a time advancement happens. } else if (outer_iter == max_outer_non_linear_iterations) { pout << std::endl << " " << std::setw(19) << std::scientific << res_norm << " (not converged in " << std::setw(3) << nonlin_iter << " iterations)\n\n" << std::endl; AssertThrow(false, ExcMessage ("No convergence in nonlinear solver")); } } // The nonlinear solver iteration cycle ends here. restart = interface.solver_should_restart(t,step_number,step_size,solution,solution_dot); if (restart) { previous_solution->reinit(solution,false); solution_update->reinit(solution,false); residual->reinit(solution,false); rhs->reinit(solution,false); t -= step_size; --step_number; } else { if ((step_number % output_period) == 0) interface.output_step(t, solution, solution_dot, step_number, step_size); } *previous_solution = solution; update_Jacobian = update_jacobian_continuously; } // End of the cycle over time. return 0; } D2K_NAMESPACE_CLOSE template class deal2lkit::IMEXStepper<BlockVector<double> >; #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::Vector>; template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::BlockVector>; #endif #endif #endif <commit_msg>new pointers<commit_after>//----------------------------------------------------------- // // Copyright (C) 2015 by the deal2lkit authors // // This file is part of the deal2lkit library. // // The deal2lkit library is free software; you can use it, 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.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal2lkit distribution. // //----------------------------------------------------------- #include <deal2lkit/sundials_interface.h> #include <deal2lkit/imex_stepper.h> #ifdef D2K_WITH_SUNDIALS #include <deal.II/base/utilities.h> #include <deal.II/lac/block_vector.h> #ifdef DEAL_II_WITH_TRILINOS #include <deal.II/lac/trilinos_block_vector.h> #include <deal.II/lac/trilinos_parallel_block_vector.h> #include <deal.II/lac/trilinos_vector.h> #endif #include <deal.II/base/utilities.h> #include <iostream> #include <iomanip> #ifdef DEAL_II_WITH_MPI #include <nvector/nvector_parallel.h> #endif using namespace dealii; D2K_NAMESPACE_OPEN template <typename VEC> IMEXStepper<VEC>::IMEXStepper(SundialsInterface<VEC> &interface, const double &step_size, const double &initial_time, const double &final_time) : ParameterAcceptor("IMEX Parameters"), interface(interface), step_size(step_size), initial_time(initial_time), final_time(final_time), pout(std::cout, Utilities::MPI::this_mpi_process(MPI_COMM_WORLD)==0) { abs_tol = 1e-6; rel_tol = 1e-8; output_period = 1; newton_alpha = 1.0; max_outer_non_linear_iterations = 5; max_inner_non_linear_iterations = 3; } template <typename VEC> void IMEXStepper<VEC>::declare_parameters(ParameterHandler &prm) { add_parameter(prm, &step_size, "Step size", std::to_string(step_size), Patterns::Double()); add_parameter(prm, &abs_tol, "Absolute error tolerance", std::to_string(abs_tol), Patterns::Double()); add_parameter(prm, &rel_tol, "Relative error tolerance", std::to_string(rel_tol), Patterns::Double()); add_parameter(prm, &initial_time, "Initial time", std::to_string(initial_time), Patterns::Double()); add_parameter(prm, &final_time, "Final time", std::to_string(final_time), Patterns::Double()); add_parameter(prm, &output_period, "Intervals between outputs", std::to_string(output_period), Patterns::Integer()); add_parameter(prm, &max_outer_non_linear_iterations, "Maximum number of outer nonlinear iterations", std::to_string(max_outer_non_linear_iterations), Patterns::Integer(), "At each outer iteration the Jacobian is updated if it is set that the \n" "Jacobian is continuously updated and a cycle of inner iterations is \n" "perfomed."); add_parameter(prm, &max_inner_non_linear_iterations, "Maximum number of inner nonlinear iterations", std::to_string(max_inner_non_linear_iterations), Patterns::Integer(), "At each inner iteration the Jacobian is NOT updated."); add_parameter(prm, &newton_alpha, "Newton relaxation parameter", std::to_string(newton_alpha), Patterns::Double()); add_parameter(prm, &update_jacobian_continuously, "Update continuously Jacobian", "true", Patterns::Bool()); } template <typename VEC> unsigned int IMEXStepper<VEC>::start_ode(VEC &solution, VEC &solution_dot) { AssertDimension(solution.size(), interface.n_dofs()); unsigned int step_number = 0; auto previous_solution = interface.create_new_vector(); auto solution_update = interface.create_new_vector(); auto residual = interface.create_new_vector(); auto rhs = interface.create_new_vector(); *previous_solution = solution; double t = initial_time; double alpha; // check if it is a stationary problem if (initial_time == final_time) alpha = 0.0; else alpha = 1./step_size; interface.output_step( 0, solution, solution_dot, 0, step_size); // Initialization of the state of the boolean variable // responsible to keep track of the requirement that the // system's Jacobian be updated. bool update_Jacobian = true; bool restart=false; // The overall cycle over time begins here. for (; t<=final_time+1e-15; t+= step_size, ++step_number) { pout << "Time = " << t << std::endl; // Implicit Euler scheme. solution_dot = solution; solution_dot -= *previous_solution; solution_dot *= alpha; // Initialization of two counters for the monitoring of // progress of the nonlinear solver. unsigned int inner_iter = 0; unsigned int outer_iter = 0; unsigned int nonlin_iter = 0; interface.residual(t, solution, solution_dot, *residual); double res_norm = 0.0; double solution_norm = 0.0; if (abs_tol>0.0||rel_tol>0.0) res_norm = interface.vector_norm(*residual); if (rel_tol>0.0) solution_norm = interface.vector_norm(solution); // The nonlinear solver iteration cycle begins here. while (outer_iter < max_outer_non_linear_iterations && res_norm > abs_tol && res_norm > rel_tol*solution_norm) { outer_iter += 1; if (update_Jacobian == true) { interface.setup_jacobian(t, solution, solution_dot, *residual, alpha); } inner_iter = 0; while (inner_iter < max_inner_non_linear_iterations && res_norm > abs_tol && res_norm > rel_tol*solution_norm) { inner_iter += 1; *rhs = *residual; *rhs *= -1.0; interface.solve_jacobian_system(t, solution, solution_dot, *residual, alpha, *rhs, *solution_update); solution.sadd(1.0, newton_alpha, *solution_update); // Implicit Euler scheme. solution_dot = solution; solution_dot -= *previous_solution; solution_dot *= alpha; interface.residual(t, solution, solution_dot, *residual); if (abs_tol>0.0||rel_tol>0.0) res_norm = interface.vector_norm(*solution_update); if (rel_tol>0.0) solution_norm = interface.vector_norm(solution); } nonlin_iter += inner_iter; if (std::fabs(res_norm) < abs_tol || std::fabs(res_norm) < rel_tol*solution_norm) { pout << std::endl << " " << std::setw(19) << std::scientific << res_norm << " (converged in " << nonlin_iter << " iterations)\n\n" << std::endl; break; // Break of the while cycle ... after this a time advancement happens. } else if (outer_iter == max_outer_non_linear_iterations) { pout << std::endl << " " << std::setw(19) << std::scientific << res_norm << " (not converged in " << std::setw(3) << nonlin_iter << " iterations)\n\n" << std::endl; AssertThrow(false, ExcMessage ("No convergence in nonlinear solver")); } } // The nonlinear solver iteration cycle ends here. restart = interface.solver_should_restart(t,step_number,step_size,solution,solution_dot); if (restart) { previous_solution = interface.create_new_vector(); solution_update = interface.create_new_vector(); residual = interface.create_new_vector(); rhs = interface.create_new_vector(); t -= step_size; --step_number; } else { if ((step_number % output_period) == 0) interface.output_step(t, solution, solution_dot, step_number, step_size); } *previous_solution = solution; update_Jacobian = update_jacobian_continuously; } // End of the cycle over time. return 0; } D2K_NAMESPACE_CLOSE template class deal2lkit::IMEXStepper<BlockVector<double> >; #ifdef DEAL_II_WITH_MPI #ifdef DEAL_II_WITH_TRILINOS template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::Vector>; template class deal2lkit::IMEXStepper<TrilinosWrappers::MPI::BlockVector>; #endif #endif #endif <|endoftext|>
<commit_before><commit_msg>This CL fixes issue 17468 - Regression: Extra white rectangle showing when mouse hovering on every web page<commit_after><|endoftext|>
<commit_before>#include "worker.h" #include <QTextStream> Worker::Worker(QObject *parent) : QObject(parent){} void Worker::worker_slot_loadFile(QFile *file) { QString line = ""; QString text = ""; QTextStream in(file); while (!in.atEnd()) { line = in.readLine(); text.append(line + "\n"); } in.flush(); file->close(); text.remove(text.lastIndexOf("\n"),1); emit worker_signal_appendText(text); } <commit_msg>Update worker.cpp<commit_after>#include "worker.h" #include <QTextStream> #include <QDebug> Worker::Worker(QObject *parent) : QObject(parent){ giFileSize = 0; } void Worker::worker_slot_loadFile(QFile *file) { QString line = ""; QString text = ""; QTextStream in(file); while (!in.atEnd()) { line = in.readLine(); text.append(line + "\n"); } in.flush(); file->close(); text.remove(text.lastIndexOf("\n"),1); emit worker_signal_appendText(text); } void Worker::worker_slot_tailFile(QFile *file) { if(file->size() > giFileSize) { int liDiff = file->size() - giFileSize; if(file->open(QIODevice::ReadOnly | QIODevice::Text)) { if(file->seek(giFileSize)) { QString lsText = QString(file->read(liDiff)); emit worker_signal_insertText(lsText); giFileSize = file->size(); } file->close(); } } else { giFileSize = file->size(); } } void Worker::worker_slot_setCurrentFileSize(int aiFileSize) { this->giFileSize = aiFileSize; } <|endoftext|>
<commit_before>#if !defined(_IMAPSESSION_HPP_INCLUDED_) #define _IMAPSESSION_HPP_INCLUDED_ #include <iostream> #include <map> #include <string> #include <stdint.h> #include <libcppserver/insensitive.hpp> #include <libcppserver/internetsession.hpp> #include <libcppserver/internetserver.hpp> #include <libcppserver/sessiondriver.hpp> #include "imapuser.hpp" #include "namespace.hpp" #include "sasl.hpp" #include "mailsearch.hpp" #include "mailmessage.hpp" class ImapMaster; class SessionDriver; class MailSearch; class MailMessage; enum ImapState { ImapNotAuthenticated = 0, ImapAuthenticated, ImapSelected, ImapLogoff }; enum ImapStringState { ImapStringGood, ImapStringBad, ImapStringPending }; /*--------------------------------------------------------------------------------------*/ //* Imap */ /*--------------------------------------------------------------------------------------*/ class ImapSession; typedef enum { IMAP_OK, IMAP_NO, IMAP_BAD, IMAP_NOTDONE, IMAP_NO_WITH_PAUSE, IMAP_MBOX_ERROR, IMAP_IN_LITERAL, IMAP_TRY_AGAIN } IMAP_RESULTS; #define MAX_RESPONSE_STRING_LENGTH 80 #define IMAP_BUFFER_LEN 8192 typedef struct { bool levels[ImapLogoff+1]; bool sendUpdatedStatus; // The flag is a bit of an odd duck. It's here because I need to pass what essentially amounts to random bools to the // handler. It means different things for different methods. // It distinguishes subscribe (flag = true) from unsubscribe (flag = false) // It distinguishes list (flag = true) from lsub (flag = false) // It distinguishes examine (flag = true) from select (flag = false) // It distinguishes uid (flag = true) from copy, close, search, fetch, and store (flag = false) bool flag; IMAP_RESULTS (ImapSession::*handler)(uint8_t *data, size_t dataLen, size_t &parsingAt, bool flag); } symbol; typedef std::map<insensitiveString, symbol> IMAPSYMBOLS; class ImapSession : public InternetSession { public: ImapSession(ImapMaster *master, SessionDriver *driver, InternetServer *server); virtual ~ImapSession(); static void BuildSymbolTables(void); void ReceiveData(uint8_t* pData, size_t dwDataLen ); void AsynchronousEvent(void); ImapMaster *GetMaster(void) const { return m_master; } InternetServer *GetServer(void) const { return m_server; } SessionDriver *GetDriver(void) const { return m_driver; }; time_t GetLastCommandTime() const { return m_lastCommandTime; } ImapState GetState(void) const { return m_state; } const ImapUser *GetUser(void) const { return m_userData; } // ReceiveData processes data as it comes it. It's primary job is to chop the incoming data into // lines and to pass each line to HandleOneLine, which is the core command processor for the system void HandleOneLine(uint8_t *pData, size_t dwDataLen); void DoRetry(void); void IdleTimeout(void); private: // These are configuration items bool m_LoginDisabled; static bool m_anonymousEnabled; unsigned m_failedLoginPause; SessionDriver *m_driver; MailStore::MAIL_STORE_RESULT m_mboxErrorCode; // These constitute the session's state enum ImapState m_state; IMAP_RESULTS (ImapSession::*m_currentHandler)(uint8_t *data, const size_t dataLen, size_t &parsingAt, bool flag); bool m_flag; uint32_t m_mailFlags; uint8_t *m_lineBuffer; // This buffers the incoming data into lines to be processed uint32_t m_lineBuffPtr, m_lineBuffLen; // As lines come in from the outside world, they are processed into m_bBuffer, which holds // them until the entire command has been received at which point it can be processed, often // by the *Execute() methods. uint8_t *m_parseBuffer; uint32_t m_parseBuffLen; uint32_t m_parsePointer; // This points past the end of what's been put into the parse buffer // This is associated with handling appends size_t m_appendingUid; Namespace *m_store; char m_responseCode[MAX_RESPONSE_STRING_LENGTH+1]; char m_responseText[MAX_RESPONSE_STRING_LENGTH+1]; uint32_t m_commandString, m_arguments; uint32_t m_parseStage; uint32_t m_literalLength; bool m_usesUid; // These are used to send live updates in case the mailbox is accessed by multiple client simultaneously uint32_t m_currentNextUid, m_currentMessageCount; uint32_t m_currentRecentCount, m_currentUnseen, m_currentUidValidity; static IMAPSYMBOLS m_symbols; // This creates a properly formatted capability string based on the current state and configuration // of the IMAP server std::string BuildCapabilityString(void); // This sends the untagged responses associated with selecting a mailbox void SendSelectData(const std::string &mailbox, bool isReadWrite); // This appends data to the Parse Buffer, extending the parse buffer as necessary. void AddToParseBuffer(const uint8_t *data, size_t length, bool bNulTerminate = true); IMAP_RESULTS LoginHandlerExecute(); IMAP_RESULTS SearchKeyParse(uint8_t *data, size_t dataLen, size_t &parsingAt); IMAP_RESULTS SearchHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS StoreHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS FetchHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS CopyHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); size_t ReadEmailFlags(uint8_t *data, const size_t dataLen, size_t &parsingAt, bool &okay); bool UpdateSearchTerms(MailSearch &searchTerm, size_t &tokenPointer, bool isSubExpression); bool MsnSequenceSet(SEARCH_RESULT &r_srVector, size_t &tokenPointer); bool UidSequenceSet(SEARCH_RESULT &r_srVector, size_t &tokenPointer); bool UpdateSearchTerm(MailSearch &searchTerm, size_t &tokenPointer); IMAP_RESULTS SelectHandlerExecute(bool isReadWrite = true); IMAP_RESULTS CreateHandlerExecute(); IMAP_RESULTS DeleteHandlerExecute(); IMAP_RESULTS RenameHandlerExecute(); IMAP_RESULTS SubscribeHandlerExecute(bool isSubscribe); IMAP_RESULTS ListHandlerExecute(bool listAll); IMAP_RESULTS StatusHandlerExecute(uint8_t *data, size_t dataLen, size_t parsingAt); IMAP_RESULTS AppendHandlerExecute(uint8_t *data, size_t dataLen, size_t &parsingAt); IMAP_RESULTS SearchHandlerExecute(bool usingUid); IMAP_RESULTS FetchHandlerExecute(bool usingUid); IMAP_RESULTS CopyHandlerExecute(bool usingUid); void atom(uint8_t *data, const size_t dataLen, size_t &parsingAt); enum ImapStringState astring(uint8_t *pData, const size_t dataLen, size_t &parsingAt, bool makeUppercase, const char *additionalChars); std::string FormatTaggedResponse(IMAP_RESULTS status, bool sendUpdatedStatus); // This is what is called if a command is unrecognized or if a command is not implemented IMAP_RESULTS UnimplementedHandler(); // What follows are the handlers for the various IMAP command. These are grouped similarly to the // way the commands are grouped in RFC-3501. They all have identical function signatures so that // they can be called indirectly through a function pointer returned from the command map. IMAP_RESULTS CapabilityHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS NoopHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS LogoutHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS StarttlsHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS AuthenticateHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS LoginHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS NamespaceHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SelectHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool isReadOnly); IMAP_RESULTS CreateHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS DeleteHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS RenameHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SubscribeHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool isSubscribe); IMAP_RESULTS ListHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool listAll); IMAP_RESULTS StatusHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS AppendHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS CheckHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS CloseHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS ExpungeHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SearchHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS FetchHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS StoreHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS CopyHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS UidHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); // These are for fetches, which are special because they can generate arbitrarily large responses void FetchResponseFlags(uint32_t flags); void FetchResponseInternalDate(const MailMessage *message); void FetchResponseRfc822(unsigned long uid, const MailMessage *message); void FetchResponseRfc822Header(unsigned long uid, const MailMessage *message); void FetchResponseRfc822Size(const MailMessage *message); void FetchResponseRfc822Text(unsigned long uid, const MailMessage *message); void FetchResponseEnvelope(const MailMessage *message); void FetchResponseBodyStructure(const MailMessage *message); void FetchResponseBody(const MailMessage *message); void FetchResponseUid(unsigned long uid); void SendMessageChunk(unsigned long uid, size_t offset, size_t length); ImapUser *m_userData; ImapMaster *m_master; InternetServer *m_server; Sasl *m_auth; time_t m_lastCommandTime; NUMBER_SET m_purgedMessages; bool m_sendUpdatedStatus; unsigned m_retries; unsigned m_maxRetries; unsigned m_retryDelay; }; #endif //_IMAPSESSION_HPP_INCLUDED_ <commit_msg>ReceiveData is really a virtual function.<commit_after>#if !defined(_IMAPSESSION_HPP_INCLUDED_) #define _IMAPSESSION_HPP_INCLUDED_ #include <iostream> #include <map> #include <string> #include <stdint.h> #include <libcppserver/insensitive.hpp> #include <libcppserver/internetsession.hpp> #include <libcppserver/internetserver.hpp> #include <libcppserver/sessiondriver.hpp> #include "imapuser.hpp" #include "namespace.hpp" #include "sasl.hpp" #include "mailsearch.hpp" #include "mailmessage.hpp" class ImapMaster; class SessionDriver; class MailSearch; class MailMessage; enum ImapState { ImapNotAuthenticated = 0, ImapAuthenticated, ImapSelected, ImapLogoff }; enum ImapStringState { ImapStringGood, ImapStringBad, ImapStringPending }; /*--------------------------------------------------------------------------------------*/ //* Imap */ /*--------------------------------------------------------------------------------------*/ class ImapSession; typedef enum { IMAP_OK, IMAP_NO, IMAP_BAD, IMAP_NOTDONE, IMAP_NO_WITH_PAUSE, IMAP_MBOX_ERROR, IMAP_IN_LITERAL, IMAP_TRY_AGAIN } IMAP_RESULTS; #define MAX_RESPONSE_STRING_LENGTH 80 #define IMAP_BUFFER_LEN 8192 typedef struct { bool levels[ImapLogoff+1]; bool sendUpdatedStatus; // The flag is a bit of an odd duck. It's here because I need to pass what essentially amounts to random bools to the // handler. It means different things for different methods. // It distinguishes subscribe (flag = true) from unsubscribe (flag = false) // It distinguishes list (flag = true) from lsub (flag = false) // It distinguishes examine (flag = true) from select (flag = false) // It distinguishes uid (flag = true) from copy, close, search, fetch, and store (flag = false) bool flag; IMAP_RESULTS (ImapSession::*handler)(uint8_t *data, size_t dataLen, size_t &parsingAt, bool flag); } symbol; typedef std::map<insensitiveString, symbol> IMAPSYMBOLS; class ImapSession : public InternetSession { public: ImapSession(ImapMaster *master, SessionDriver *driver, InternetServer *server); virtual ~ImapSession(); static void BuildSymbolTables(void); virtual void ReceiveData(uint8_t* pData, size_t dwDataLen ); void AsynchronousEvent(void); ImapMaster *GetMaster(void) const { return m_master; } InternetServer *GetServer(void) const { return m_server; } SessionDriver *GetDriver(void) const { return m_driver; }; time_t GetLastCommandTime() const { return m_lastCommandTime; } ImapState GetState(void) const { return m_state; } const ImapUser *GetUser(void) const { return m_userData; } // ReceiveData processes data as it comes it. It's primary job is to chop the incoming data into // lines and to pass each line to HandleOneLine, which is the core command processor for the system void HandleOneLine(uint8_t *pData, size_t dwDataLen); void DoRetry(void); void IdleTimeout(void); private: // These are configuration items bool m_LoginDisabled; static bool m_anonymousEnabled; unsigned m_failedLoginPause; SessionDriver *m_driver; MailStore::MAIL_STORE_RESULT m_mboxErrorCode; // These constitute the session's state enum ImapState m_state; IMAP_RESULTS (ImapSession::*m_currentHandler)(uint8_t *data, const size_t dataLen, size_t &parsingAt, bool flag); bool m_flag; uint32_t m_mailFlags; uint8_t *m_lineBuffer; // This buffers the incoming data into lines to be processed uint32_t m_lineBuffPtr, m_lineBuffLen; // As lines come in from the outside world, they are processed into m_bBuffer, which holds // them until the entire command has been received at which point it can be processed, often // by the *Execute() methods. uint8_t *m_parseBuffer; uint32_t m_parseBuffLen; uint32_t m_parsePointer; // This points past the end of what's been put into the parse buffer // This is associated with handling appends size_t m_appendingUid; Namespace *m_store; char m_responseCode[MAX_RESPONSE_STRING_LENGTH+1]; char m_responseText[MAX_RESPONSE_STRING_LENGTH+1]; uint32_t m_commandString, m_arguments; uint32_t m_parseStage; uint32_t m_literalLength; bool m_usesUid; // These are used to send live updates in case the mailbox is accessed by multiple client simultaneously uint32_t m_currentNextUid, m_currentMessageCount; uint32_t m_currentRecentCount, m_currentUnseen, m_currentUidValidity; static IMAPSYMBOLS m_symbols; // This creates a properly formatted capability string based on the current state and configuration // of the IMAP server std::string BuildCapabilityString(void); // This sends the untagged responses associated with selecting a mailbox void SendSelectData(const std::string &mailbox, bool isReadWrite); // This appends data to the Parse Buffer, extending the parse buffer as necessary. void AddToParseBuffer(const uint8_t *data, size_t length, bool bNulTerminate = true); IMAP_RESULTS LoginHandlerExecute(); IMAP_RESULTS SearchKeyParse(uint8_t *data, size_t dataLen, size_t &parsingAt); IMAP_RESULTS SearchHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS StoreHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS FetchHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); IMAP_RESULTS CopyHandlerInternal(uint8_t *data, size_t dataLen, size_t &parsingAt, bool usingUid); size_t ReadEmailFlags(uint8_t *data, const size_t dataLen, size_t &parsingAt, bool &okay); bool UpdateSearchTerms(MailSearch &searchTerm, size_t &tokenPointer, bool isSubExpression); bool MsnSequenceSet(SEARCH_RESULT &r_srVector, size_t &tokenPointer); bool UidSequenceSet(SEARCH_RESULT &r_srVector, size_t &tokenPointer); bool UpdateSearchTerm(MailSearch &searchTerm, size_t &tokenPointer); IMAP_RESULTS SelectHandlerExecute(bool isReadWrite = true); IMAP_RESULTS CreateHandlerExecute(); IMAP_RESULTS DeleteHandlerExecute(); IMAP_RESULTS RenameHandlerExecute(); IMAP_RESULTS SubscribeHandlerExecute(bool isSubscribe); IMAP_RESULTS ListHandlerExecute(bool listAll); IMAP_RESULTS StatusHandlerExecute(uint8_t *data, size_t dataLen, size_t parsingAt); IMAP_RESULTS AppendHandlerExecute(uint8_t *data, size_t dataLen, size_t &parsingAt); IMAP_RESULTS SearchHandlerExecute(bool usingUid); IMAP_RESULTS FetchHandlerExecute(bool usingUid); IMAP_RESULTS CopyHandlerExecute(bool usingUid); void atom(uint8_t *data, const size_t dataLen, size_t &parsingAt); enum ImapStringState astring(uint8_t *pData, const size_t dataLen, size_t &parsingAt, bool makeUppercase, const char *additionalChars); std::string FormatTaggedResponse(IMAP_RESULTS status, bool sendUpdatedStatus); // This is what is called if a command is unrecognized or if a command is not implemented IMAP_RESULTS UnimplementedHandler(); // What follows are the handlers for the various IMAP command. These are grouped similarly to the // way the commands are grouped in RFC-3501. They all have identical function signatures so that // they can be called indirectly through a function pointer returned from the command map. IMAP_RESULTS CapabilityHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS NoopHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS LogoutHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS StarttlsHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS AuthenticateHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS LoginHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS NamespaceHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SelectHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool isReadOnly); IMAP_RESULTS CreateHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS DeleteHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS RenameHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SubscribeHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool isSubscribe); IMAP_RESULTS ListHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool listAll); IMAP_RESULTS StatusHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS AppendHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS CheckHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS CloseHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS ExpungeHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); IMAP_RESULTS SearchHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS FetchHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS StoreHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS CopyHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool useUid); IMAP_RESULTS UidHandler(uint8_t *data, size_t dataLen, size_t &parsingAt, bool unused); // These are for fetches, which are special because they can generate arbitrarily large responses void FetchResponseFlags(uint32_t flags); void FetchResponseInternalDate(const MailMessage *message); void FetchResponseRfc822(unsigned long uid, const MailMessage *message); void FetchResponseRfc822Header(unsigned long uid, const MailMessage *message); void FetchResponseRfc822Size(const MailMessage *message); void FetchResponseRfc822Text(unsigned long uid, const MailMessage *message); void FetchResponseEnvelope(const MailMessage *message); void FetchResponseBodyStructure(const MailMessage *message); void FetchResponseBody(const MailMessage *message); void FetchResponseUid(unsigned long uid); void SendMessageChunk(unsigned long uid, size_t offset, size_t length); ImapUser *m_userData; ImapMaster *m_master; InternetServer *m_server; Sasl *m_auth; time_t m_lastCommandTime; NUMBER_SET m_purgedMessages; bool m_sendUpdatedStatus; unsigned m_retries; unsigned m_maxRetries; unsigned m_retryDelay; }; #endif //_IMAPSESSION_HPP_INCLUDED_ <|endoftext|>
<commit_before>AliAnalysisTaskSEVertexingHF *AddTaskVertexingHFFilter(TString configPWG3d2h="$ALICE_ROOT/PWGHF/vertexingHF/ConfigVertexingHF_Pb_AllCent_NoLS_PIDLc.C", Bool_t registerFile=kFALSE) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskVertexingHFFilter", "No analysis manager to connect to."); return NULL; } gROOT->LoadMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/AddTaskVertexingHF.C"); // TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data())); TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("ConfigVertexingHF.C")); AliAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF(); // Now we need to keep in sync with the ESD filter if (!taskvertexingHF) ::Warning("AddTaskVertexingHFFilter", "AliAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED"); if(registerFile) mgr->RegisterExtraFile("AliAOD.VertexingHF.root"); taskvertexingHF->SelectCollisionCandidates(0); mgr->AddTask(taskvertexingHF); return taskvertexingHF; } <commit_msg>Change default value of one argument<commit_after>AliAnalysisTaskSEVertexingHF *AddTaskVertexingHFFilter(TString configPWG3d2h="$ALICE_ROOT/PWGHF/vertexingHF/ConfigVertexingHF_Pb_AllCent_NoLS_PIDLc.C", Bool_t registerFile=kTRUE) { // Get the pointer to the existing analysis manager via the static access method. //============================================================================== AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { ::Error("AddTaskVertexingHFFilter", "No analysis manager to connect to."); return NULL; } gROOT->LoadMacro("$ALICE_ROOT/PWGHF/vertexingHF/macros/AddTaskVertexingHF.C"); // TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("%s/ConfigVertexingHF.C", train_name.Data())); TFile::Cp(gSystem->ExpandPathName(configPWG3d2h.Data()), Form("ConfigVertexingHF.C")); AliAnalysisTaskSEVertexingHF *taskvertexingHF = AddTaskVertexingHF(); // Now we need to keep in sync with the ESD filter if (!taskvertexingHF) ::Warning("AddTaskVertexingHFFilter", "AliAnalysisTaskSEVertexingHF cannot run for this train conditions - EXCLUDED"); if(registerFile) mgr->RegisterExtraFile("AliAOD.VertexingHF.root"); taskvertexingHF->SelectCollisionCandidates(0); mgr->AddTask(taskvertexingHF); return taskvertexingHF; } <|endoftext|>
<commit_before>#include <opencv/highgui.h> #include <opencv/cv.h> #include <iostream> #include <stdlib.h> #define WINDOW_NAME "WebCam Feed" int const FPS = 50; int main(){ cv::VideoCapture cap(0); if(!cap.isOpened()){ std::cerr << "could not initialize video capture." << std::endl; return EXIT_FAILURE; } cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE); while(true){ // capture loop cv::Mat frame; if(!cap.read(frame)){ std::cerr << "error reading frame from cam feed" << std::endl; return EXIT_FAILURE; } cv::imshow(WINDOW_NAME, frame); switch(cv::waitKey(1000 / FPS)){ //read key event case 27: //ESC return EXIT_SUCCESS; break; default: //do nothing break; } } return EXIT_SUCCESS; } <commit_msg>write video to file<commit_after>#include <opencv/highgui.h> #include <opencv/cv.h> #include <iostream> #include <stdlib.h> #define WINDOW_NAME "WebCam Feed" #define FILE_NAME "test.avi" int const FOURCC = CV_FOURCC('D','I','V','3'); int const FPS = 25; int main(){ std::cout << "SPACEBAR: Toggle recording" << std::endl; std::cout << "ESC: Quit programm" << std::endl; cv::VideoCapture cap(0); if(!cap.isOpened()){ std::cerr << "could not initialize video capture." << std::endl; return EXIT_FAILURE; } cv::Size const FRAME_SIZE(cap.get(CV_CAP_PROP_FRAME_WIDTH), cap.get(CV_CAP_PROP_FRAME_HEIGHT)); cv::VideoWriter writer(FILE_NAME, FOURCC, FPS, FRAME_SIZE); if(!writer.isOpened()){ std::cerr << "error opening videowriter" << std::endl; return EXIT_FAILURE; } cv::namedWindow(WINDOW_NAME, CV_WINDOW_AUTOSIZE); cv::Mat frame; bool recording = true; while(true){ // capture loop if(!cap.read(frame)){ std::cerr << "error reading frame from cam feed" << std::endl; return EXIT_FAILURE; } if(recording){ writer.write(frame); cv::putText(frame, "[REC]", cv::Point(0, 20), 1, 1, cv::Scalar(0,0,255)); } cv::imshow(WINDOW_NAME, frame); switch(cv::waitKey(1000 / FPS)){ //read key event case 27: //ESC return EXIT_SUCCESS; break; case 32: // SPACEBAR recording = !recording; break; default: //do nothing break; } } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include "mergeduniverselogger.h" #include <QDateTime> MergedUniverseLogger::MergedUniverseLogger() : QObject(nullptr), m_file(nullptr) { //reserve a bit more than max length for sACNView1 format - see levelsChanged() m_stringBuffer.reserve(3000); } MergedUniverseLogger::~MergedUniverseLogger() { //listener memory is dealt with externally closeFile(); } void MergedUniverseLogger::start(QString fileName, QSharedPointer<sACNListener>listener) { m_elapsedTimer.start(); setUpFile(fileName); m_listener = listener; connect(m_listener.data(), &sACNListener::levelsChanged, this, &MergedUniverseLogger::levelsChanged); } void MergedUniverseLogger::stop() { disconnect(m_listener.data(), 0, this, 0); closeFile(); } void MergedUniverseLogger::levelsChanged() { //Must have valid stream and listener set up via start() //Also possible that this is getting called as we're wrapping up in stop() if(!m_stream || !m_listener) { return; } //Following sACNView1 format //MM/DD/YYYY HH:mm:SS AP,0.0000,[0,]x512 //log levels to file auto levels = m_listener->mergedLevels(); m_stringBuffer.clear(); m_stringBuffer.append(QDateTime::currentDateTime().toString("M/d/yyyy h:mm:ss AP,")); m_stringBuffer.append(QString::number((double)m_elapsedTimer.elapsed()/1000, 'f', 4)); for(auto level : levels) { m_stringBuffer.append(','); m_stringBuffer.append(QString::number(level.level)); } m_stringBuffer.append('\n'); *m_stream << m_stringBuffer; } void MergedUniverseLogger::setUpFile(QString fileName) { Q_ASSERT(m_file == nullptr); m_file = new QFile(fileName); m_file->open(QIODevice::WriteOnly | QIODevice::Truncate); m_stream = new QTextStream(m_file); } void MergedUniverseLogger::closeFile() { //finish out m_stream->flush(); if(m_file->isOpen()) { m_file->close(); } delete m_stream; m_file->deleteLater(); m_stream = nullptr; m_file = nullptr; } <commit_msg>Fix crash when pressing Stop after starting log to file<commit_after>#include "mergeduniverselogger.h" #include <QDateTime> MergedUniverseLogger::MergedUniverseLogger() : QObject(nullptr), m_file(nullptr) { //reserve a bit more than max length for sACNView1 format - see levelsChanged() m_stringBuffer.reserve(3000); } MergedUniverseLogger::~MergedUniverseLogger() { //listener memory is dealt with externally closeFile(); } void MergedUniverseLogger::start(QString fileName, QSharedPointer<sACNListener>listener) { m_elapsedTimer.start(); setUpFile(fileName); m_listener = listener; connect(m_listener.data(), &sACNListener::levelsChanged, this, &MergedUniverseLogger::levelsChanged); } void MergedUniverseLogger::stop() { disconnect(m_listener.data(), 0, this, 0); closeFile(); } void MergedUniverseLogger::levelsChanged() { //Must have valid stream and listener set up via start() //Also possible that this is getting called as we're wrapping up in stop() if(!m_stream || !m_listener) { return; } //Following sACNView1 format //MM/DD/YYYY HH:mm:SS AP,0.0000,[0,]x512 //log levels to file auto levels = m_listener->mergedLevels(); m_stringBuffer.clear(); m_stringBuffer.append(QDateTime::currentDateTime().toString("M/d/yyyy h:mm:ss AP,")); m_stringBuffer.append(QString::number((double)m_elapsedTimer.elapsed()/1000, 'f', 4)); for(auto level : levels) { m_stringBuffer.append(','); m_stringBuffer.append(QString::number(level.level)); } m_stringBuffer.append('\n'); *m_stream << m_stringBuffer; } void MergedUniverseLogger::setUpFile(QString fileName) { Q_ASSERT(m_file == nullptr); m_file = new QFile(fileName); m_file->open(QIODevice::WriteOnly | QIODevice::Truncate); m_stream = new QTextStream(m_file); } void MergedUniverseLogger::closeFile() { if(!m_file) { //already finished - bail out Q_ASSERT(m_stream == nullptr); return; } //finish out m_stream->flush(); if(m_file->isOpen()) { m_file->close(); } delete m_stream; m_file->deleteLater(); m_stream = nullptr; m_file = nullptr; } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include <vw/Cartography/PointImageManipulation.h> #include <vw/Cartography/GeoTransform.h> #include <vw/Cartography/MapTransform.h> #include <vw/Image/MaskViews.h> #include <vw/Camera/CameraModel.h> namespace vw { namespace cartography { MapTransform::MapTransform( vw::camera::CameraModel const* cam, GeoReference const& image_georef, GeoReference const& dem_georef, boost::shared_ptr<DiskImageResource> dem_rsrc ) : m_cam(cam), m_image_georef(image_georef), m_dem_georef(dem_georef), m_dem(dem_rsrc) { if ( dem_rsrc->has_nodata_read() ) m_point_cloud = geo_transform( geodetic_to_cartesian( dem_to_geodetic( create_mask( m_dem, dem_rsrc->nodata_read()), m_dem_georef ), m_dem_georef.datum() ), m_dem_georef, m_image_georef, ValueEdgeExtension<Vector3>( Vector3() ), BicubicInterpolation()); else m_point_cloud = geo_transform( geodetic_to_cartesian( dem_to_geodetic( m_dem, m_dem_georef ), m_dem_georef.datum() ), m_dem_georef, m_image_georef, ValueEdgeExtension<Vector3>( Vector3() ), BicubicInterpolation()); } vw::Vector2 MapTransform::reverse(const vw::Vector2 &p) const { double NaN = std::numeric_limits<double>::quiet_NaN(); // If possible, we will interpolate into the cached point cloud ImageViewRef<Vector3> interp_point_cloud = interpolate(m_point_cloud_cache, BicubicInterpolation(), ZeroEdgeExtension()); // Avoid interpolating close to edges BBox2i shrank_bbox = m_cache_size; shrank_bbox.contract(BicubicInterpolation::pixel_buffer); Vector3 xyz = shrank_bbox.contains( p ) ? interp_point_cloud(p.x() - m_cache_size.min().x(), p.y() - m_cache_size.min().y()): m_point_cloud(p.x(),p.y()); // The case when xyz does not have data if (xyz == Vector3()) return vw::Vector2(NaN, NaN); try{ return m_cam->point_to_pixel(xyz); }catch(...){} return vw::Vector2(NaN, NaN); } // This function will be called whenever we start to apply the // transform in a tile. It computes and caches the point cloud at // each pixel in the tile, to be used later when we iterate over // pixels. vw::BBox2i MapTransform::reverse_bbox( vw::BBox2i const& bbox ) const { cache_dem( bbox ); vw::BBox2i out_box = vw::TransformBase<MapTransform>::reverse_bbox( bbox ); if (out_box.empty()) return vw::BBox2i(0, 0, 1, 1); return out_box; } void MapTransform::cache_dem( vw::BBox2i const& bbox ) const { m_cache_size = bbox; // For bicubic interpolation later m_cache_size.expand(BicubicInterpolation::pixel_buffer); m_point_cloud_cache = crop( m_point_cloud, m_cache_size ); } // Duplicate code we use for map_project. MapTransform2::MapTransform2( vw::camera::CameraModel const* cam, GeoReference const& image_georef, GeoReference const& dem_georef, boost::shared_ptr<DiskImageResource> dem_rsrc, vw::Vector2i image_size) : m_cam(cam), m_image_georef(image_georef), m_dem_georef(dem_georef), m_dem_rsrc(dem_rsrc), m_dem(dem_rsrc), m_image_size(image_size), m_has_nodata(false), m_nodata(std::numeric_limits<double>::quiet_NaN() ){ m_has_nodata = dem_rsrc->has_nodata_read(); if (m_has_nodata) m_nodata = dem_rsrc->nodata_read(); if (m_image_size != Vector2(-1, -1)) m_invalid_pix = Vector2(-1e6, -1e6); // for mapproject else m_invalid_pix = Vector2(-1, -1); // for stereo } vw::Vector2 MapTransform2::reverse(const vw::Vector2 &p) const { if (m_img_cache_box.contains(p)){ PixelMask<Vector2> v = m_cache_interp_mask(p.x() - m_img_cache_box.min().x(), p.y() - m_img_cache_box.min().y()); if (is_valid(v)) return v.child(); else return m_invalid_pix; } int b = BicubicInterpolation::pixel_buffer; Vector2 lonlat = m_image_georef.pixel_to_lonlat(p); Vector2 dem_pix = m_dem_georef.lonlat_to_pixel(lonlat); if (dem_pix[0] < b - 1 || dem_pix[0] >= m_dem.cols() - b || dem_pix[1] < b - 1 || dem_pix[1] >= m_dem.rows() - b ){ // No DEM data return m_invalid_pix; } Vector2 sdem_pix = dem_pix - m_dem_cache_box.min(); // since we cropped the DEM if (m_dem_cache_box.empty() || sdem_pix[0] < b - 1 || sdem_pix[0] >= m_cropped_dem.cols() - b || sdem_pix[1] < b - 1 || sdem_pix[1] >= m_cropped_dem.rows() - b ){ // Cache miss. Will not happen often. BBox2i box; box.min() = floor(p) - Vector2(1, 1); box.max() = ceil(p) + Vector2(1, 1); cache_dem(box); return reverse(p); } PixelMask<float> h = m_interp_dem(sdem_pix[0], sdem_pix[1]); if (!is_valid(h)) return m_invalid_pix; Vector3 xyz = m_dem_georef.datum().geodetic_to_cartesian (Vector3(lonlat[0], lonlat[1], h.child())); Vector2 pt; try{ pt = m_cam->point_to_pixel(xyz); if ( (m_image_size != Vector2i(-1, -1)) && (pt[0] < b - 1 || pt[0] >= m_image_size[0] - b || pt[1] < b - 1 || pt[1] >= m_image_size[1] - b) ){ // Won't be able to interpolate into image in transform(...) return m_invalid_pix; } }catch(...){ // If a point failed to project return m_invalid_pix; } return pt; } void MapTransform2::cache_dem(vw::BBox2i const& bbox) const{ BBox2 dbox; dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.min().x(),bbox.min().y()) ) )); // Top left dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.max().x()-1,bbox.min().y()) ) )); // Top right dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.min().x(),bbox.max().y()-1) ) )); // Bottom left dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.max().x()-1,bbox.max().y()-1) ) )); // Bottom right // A lot of care is needed here when going from real box to int // box, and if in doubt, better expand more rather than less. dbox.expand(1); m_dem_cache_box = grow_bbox_to_int(dbox); m_dem_cache_box.expand(BicubicInterpolation::pixel_buffer); // for interp m_dem_cache_box.crop(bounding_box(m_dem)); // Read the dem in memory for speed. m_cropped_dem = crop(m_dem, m_dem_cache_box); if (m_has_nodata){ m_masked_dem = create_mask(m_cropped_dem, m_nodata); }else{ m_masked_dem = pixel_cast< PixelMask<float> >(m_cropped_dem); } m_interp_dem = interpolate(m_masked_dem, BicubicInterpolation(), ZeroEdgeExtension()); } // This function will be called whenever we start to apply the // transform in a tile. It computes and caches the point cloud at // each pixel in the tile, to be used later when we iterate over // pixels. vw::BBox2i MapTransform2::reverse_bbox( vw::BBox2i const& bbox ) const { // Custom reverse_bbox() function which can handle invalid pixels. if (!m_cached_rv_box.empty()) return m_cached_rv_box; cache_dem(bbox); // Cache the reverse transform m_img_cache_box = BBox2i(); BBox2i local_cache_box = bbox; local_cache_box.expand(BicubicInterpolation::pixel_buffer); // for interpolation m_cache.set_size(local_cache_box.width(), local_cache_box.height()); vw::BBox2 out_box; for( int32 y=local_cache_box.min().y(); y<local_cache_box.max().y(); ++y ){ for( int32 x=local_cache_box.min().x(); x<local_cache_box.max().x(); ++x ){ Vector2 p = reverse( Vector2(x,y) ); m_cache(x - local_cache_box.min().x(), y - local_cache_box.min().y()) = p; if (p == m_invalid_pix) continue; if (bbox.contains(Vector2i(x, y))) out_box.grow( p ); } } out_box = grow_bbox_to_int( out_box ); // Must happen after all calls to reverse finished. m_img_cache_box = local_cache_box; m_cache_interp_mask = interpolate(create_mask(m_cache, m_invalid_pix), BicubicInterpolation(), ZeroEdgeExtension()); // Need the check below as to not try to create images with // negative dimensions. if (out_box.empty()) out_box = vw::BBox2i(0, 0, 0, 0); m_cached_rv_box = out_box; return m_cached_rv_box; } }} // namespace vw::cartography <commit_msg>MapTransform: Indent<commit_after>// __BEGIN_LICENSE__ // Copyright (c) 2009-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NGT platform is 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. // __END_LICENSE__ #include <vw/Cartography/PointImageManipulation.h> #include <vw/Cartography/GeoTransform.h> #include <vw/Cartography/MapTransform.h> #include <vw/Image/MaskViews.h> #include <vw/Camera/CameraModel.h> namespace vw { namespace cartography { MapTransform::MapTransform( vw::camera::CameraModel const* cam, GeoReference const& image_georef, GeoReference const& dem_georef, boost::shared_ptr<DiskImageResource> dem_rsrc ) : m_cam(cam), m_image_georef(image_georef), m_dem_georef(dem_georef), m_dem(dem_rsrc) { if ( dem_rsrc->has_nodata_read() ) m_point_cloud = geo_transform (geodetic_to_cartesian (dem_to_geodetic( create_mask( m_dem, dem_rsrc->nodata_read()), m_dem_georef ), m_dem_georef.datum() ), m_dem_georef, m_image_georef, ValueEdgeExtension<Vector3>( Vector3() ), BicubicInterpolation()); else m_point_cloud = geo_transform (geodetic_to_cartesian (dem_to_geodetic( m_dem, m_dem_georef ), m_dem_georef.datum() ), m_dem_georef, m_image_georef, ValueEdgeExtension<Vector3>( Vector3() ), BicubicInterpolation()); } vw::Vector2 MapTransform::reverse(const vw::Vector2 &p) const { double NaN = std::numeric_limits<double>::quiet_NaN(); // If possible, we will interpolate into the cached point cloud ImageViewRef<Vector3> interp_point_cloud = interpolate(m_point_cloud_cache, BicubicInterpolation(), ZeroEdgeExtension()); // Avoid interpolating close to edges BBox2i shrank_bbox = m_cache_size; shrank_bbox.contract(BicubicInterpolation::pixel_buffer); Vector3 xyz = shrank_bbox.contains( p ) ? interp_point_cloud(p.x() - m_cache_size.min().x(), p.y() - m_cache_size.min().y()): m_point_cloud(p.x(),p.y()); // The case when xyz does not have data if (xyz == Vector3()) return vw::Vector2(NaN, NaN); try{ return m_cam->point_to_pixel(xyz); }catch(...){} return vw::Vector2(NaN, NaN); } // This function will be called whenever we start to apply the // transform in a tile. It computes and caches the point cloud at // each pixel in the tile, to be used later when we iterate over // pixels. vw::BBox2i MapTransform::reverse_bbox( vw::BBox2i const& bbox ) const { cache_dem( bbox ); vw::BBox2i out_box = vw::TransformBase<MapTransform>::reverse_bbox( bbox ); if (out_box.empty()) return vw::BBox2i(0, 0, 1, 1); return out_box; } void MapTransform::cache_dem( vw::BBox2i const& bbox ) const { m_cache_size = bbox; // For bicubic interpolation later m_cache_size.expand(BicubicInterpolation::pixel_buffer); m_point_cloud_cache = crop( m_point_cloud, m_cache_size ); } // Duplicate code we use for map_project. MapTransform2::MapTransform2( vw::camera::CameraModel const* cam, GeoReference const& image_georef, GeoReference const& dem_georef, boost::shared_ptr<DiskImageResource> dem_rsrc, vw::Vector2i image_size) : m_cam(cam), m_image_georef(image_georef), m_dem_georef(dem_georef), m_dem_rsrc(dem_rsrc), m_dem(dem_rsrc), m_image_size(image_size), m_has_nodata(false), m_nodata(std::numeric_limits<double>::quiet_NaN() ){ m_has_nodata = dem_rsrc->has_nodata_read(); if (m_has_nodata) m_nodata = dem_rsrc->nodata_read(); if (m_image_size != Vector2(-1, -1)) m_invalid_pix = Vector2(-1e6, -1e6); // for mapproject else m_invalid_pix = Vector2(-1, -1); // for stereo } vw::Vector2 MapTransform2::reverse(const vw::Vector2 &p) const { if (m_img_cache_box.contains(p)){ PixelMask<Vector2> v = m_cache_interp_mask(p.x() - m_img_cache_box.min().x(), p.y() - m_img_cache_box.min().y()); if (is_valid(v)) return v.child(); else return m_invalid_pix; } int b = BicubicInterpolation::pixel_buffer; Vector2 lonlat = m_image_georef.pixel_to_lonlat(p); Vector2 dem_pix = m_dem_georef.lonlat_to_pixel(lonlat); if (dem_pix[0] < b - 1 || dem_pix[0] >= m_dem.cols() - b || dem_pix[1] < b - 1 || dem_pix[1] >= m_dem.rows() - b ){ // No DEM data return m_invalid_pix; } Vector2 sdem_pix = dem_pix - m_dem_cache_box.min(); // since we cropped the DEM if (m_dem_cache_box.empty() || sdem_pix[0] < b - 1 || sdem_pix[0] >= m_cropped_dem.cols() - b || sdem_pix[1] < b - 1 || sdem_pix[1] >= m_cropped_dem.rows() - b ){ // Cache miss. Will not happen often. BBox2i box; box.min() = floor(p) - Vector2(1, 1); box.max() = ceil(p) + Vector2(1, 1); cache_dem(box); return reverse(p); } PixelMask<float> h = m_interp_dem(sdem_pix[0], sdem_pix[1]); if (!is_valid(h)) return m_invalid_pix; Vector3 xyz = m_dem_georef.datum().geodetic_to_cartesian (Vector3(lonlat[0], lonlat[1], h.child())); Vector2 pt; try{ pt = m_cam->point_to_pixel(xyz); if ( (m_image_size != Vector2i(-1, -1)) && (pt[0] < b - 1 || pt[0] >= m_image_size[0] - b || pt[1] < b - 1 || pt[1] >= m_image_size[1] - b) ){ // Won't be able to interpolate into image in transform(...) return m_invalid_pix; } }catch(...){ // If a point failed to project return m_invalid_pix; } return pt; } void MapTransform2::cache_dem(vw::BBox2i const& bbox) const{ BBox2 dbox; dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.min().x(),bbox.min().y()) ) )); // Top left dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.max().x()-1,bbox.min().y()) ) )); // Top right dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.min().x(),bbox.max().y()-1) ) )); // Bottom left dbox.grow( m_dem_georef.lonlat_to_pixel(m_image_georef.pixel_to_lonlat( Vector2(bbox.max().x()-1,bbox.max().y()-1) ) )); // Bottom right // A lot of care is needed here when going from real box to int // box, and if in doubt, better expand more rather than less. dbox.expand(1); m_dem_cache_box = grow_bbox_to_int(dbox); m_dem_cache_box.expand(BicubicInterpolation::pixel_buffer); // for interp m_dem_cache_box.crop(bounding_box(m_dem)); // Read the dem in memory for speed. m_cropped_dem = crop(m_dem, m_dem_cache_box); if (m_has_nodata){ m_masked_dem = create_mask(m_cropped_dem, m_nodata); }else{ m_masked_dem = pixel_cast< PixelMask<float> >(m_cropped_dem); } m_interp_dem = interpolate(m_masked_dem, BicubicInterpolation(), ZeroEdgeExtension()); } // This function will be called whenever we start to apply the // transform in a tile. It computes and caches the point cloud at // each pixel in the tile, to be used later when we iterate over // pixels. vw::BBox2i MapTransform2::reverse_bbox( vw::BBox2i const& bbox ) const { // Custom reverse_bbox() function which can handle invalid pixels. if (!m_cached_rv_box.empty()) return m_cached_rv_box; cache_dem(bbox); // Cache the reverse transform m_img_cache_box = BBox2i(); BBox2i local_cache_box = bbox; local_cache_box.expand(BicubicInterpolation::pixel_buffer); // for interpolation m_cache.set_size(local_cache_box.width(), local_cache_box.height()); vw::BBox2 out_box; for( int32 y=local_cache_box.min().y(); y<local_cache_box.max().y(); ++y ){ for( int32 x=local_cache_box.min().x(); x<local_cache_box.max().x(); ++x ){ Vector2 p = reverse( Vector2(x,y) ); m_cache(x - local_cache_box.min().x(), y - local_cache_box.min().y()) = p; if (p == m_invalid_pix) continue; if (bbox.contains(Vector2i(x, y))) out_box.grow( p ); } } out_box = grow_bbox_to_int( out_box ); // Must happen after all calls to reverse finished. m_img_cache_box = local_cache_box; m_cache_interp_mask = interpolate(create_mask(m_cache, m_invalid_pix), BicubicInterpolation(), ZeroEdgeExtension()); // Need the check below as to not try to create images with // negative dimensions. if (out_box.empty()) out_box = vw::BBox2i(0, 0, 0, 0); m_cached_rv_box = out_box; return m_cached_rv_box; } }} // namespace vw::cartography <|endoftext|>
<commit_before>#include "compress_keyword_encoding.h" #include "bytebuffer.h" #include <stdexcept> #include <sstream> #include <map> #include <unordered_map> std::string initializeSymbols() { std::string s; for(int i = 0; i < 127; ++i) s += i; return s; } static std::string symbols = initializeSymbols(); bool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output) { const char * inChars = (const char *)input.Data(); size_t symIndex; char c; for(size_t i=0; i < input.Size(); ++i) { c = inChars[i]; if((symIndex = symbols.find(c)) != std::string::npos) symbols.erase(symbols.begin() + symIndex); } std::map<std::string, unsigned int>::iterator it; std::map<std::string, unsigned int> stringFrequencies; std::istringstream in((char *)input.Data()); std::string temp; while(in.good()) { in >> temp; it = stringFrequencies.find(temp); if(it != stringFrequencies.end()) ++it->second; else stringFrequencies.insert(it, std::make_pair(temp, 1)); } std::map<unsigned int, std::vector<std::string>> reverseStringFrequencies; std::map<unsigned int, std::vector<std::string>>::iterator it1; for (const auto& elem: stringFrequencies) { it1 = reverseStringFrequencies.find(elem.second); if (it1 != reverseStringFrequencies.end()) { it1->second.push_back(elem.first); } else { it1 = reverseStringFrequencies.insert(it1, std::make_pair(elem.second, std::vector<std::string>())); it1->second.push_back(elem.first); } } std::unordered_map<std::string, char> encodedStrings; std::unordered_map<std::string, char>::iterator encodedStringsIt; it1 = reverseStringFrequencies.begin(); for(std::string::iterator it_s = symbols.begin(); it_s != symbols.end() && it1 != reverseStringFrequencies.end(); ++it_s, ++it1) for(size_t i=0; i < it1->second.size(); ++i, ++it_s) { encodedStrings.insert(std::make_pair(it1->second[i], *it_s)); if(it_s == symbols.end()) break; } output.WriteDynInt(encodedStrings.size()); for(encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt) { output.WriteUInt8(encodedStringsIt->second); output.WriteString(encodedStringsIt->first); } in = std::istringstream((char *)input.Data()); std::ostringstream out; while(in.good()) { in >> temp; if((encodedStringsIt = encodedStrings.find(temp)) != encodedStrings.end()) output.WriteString(std::string(1,encodedStringsIt->second)); else output.WriteString(temp); } return true; } bool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output) { ByteBuffer* hack = const_cast<ByteBuffer*>(&input); std::unordered_map<char, std::string> encodedSymbols; std::unordered_map<char, std::string>::iterator encodedSymbolsIt; int numTableEntries; numTableEntries = hack->ReadDynInt(); char symbol; std::string expression; for(; numTableEntries > 0; --numTableEntries) { symbol = (char)hack->ReadUInt8(); expression = hack->ReadString(); encodedSymbols.insert(std::make_pair(symbol, expression)); } std::string temp; do { temp = hack->ReadString(); if(temp.size() > 0 && (encodedSymbolsIt = encodedSymbols.find(temp.at(0))) != encodedSymbols.end()) output.WriteString(encodedSymbolsIt->second); else output.WriteString(temp); } while(hack->CanRead()); return true; } <commit_msg>Fix keyword encoding<commit_after>#include "compress_keyword_encoding.h" #include "bytebuffer.h" #include <stdexcept> #include <sstream> #include <map> #include <unordered_map> #include <iostream> std::string initializeSymbols() { std::string s; for(int i = 0; i < 127; ++i) s += i; return s; } bool CompressKeywordEncoding::CompressImpl(const ByteBuffer& input, ByteBuffer& output) { std::string symbols = initializeSymbols(); const char * inChars = (const char *)input.Data(); size_t symIndex; char c; for(size_t i=0; i < input.Size(); ++i) { c = inChars[i]; if((symIndex = symbols.find(c)) != std::string::npos) symbols.erase(symbols.begin() + symIndex); } std::map<std::string, unsigned int>::iterator it; std::map<std::string, unsigned int> stringFrequencies; std::istringstream in((char *)input.Data()); std::string temp; while(in.good()) { in >> temp; it = stringFrequencies.find(temp); if(it != stringFrequencies.end()) ++it->second; else stringFrequencies.insert(it, std::make_pair(temp, 1)); } std::map<unsigned int, std::vector<std::string>> reverseStringFrequencies; std::map<unsigned int, std::vector<std::string>>::iterator it1; for (const auto& elem: stringFrequencies) { it1 = reverseStringFrequencies.find(elem.second); if (it1 != reverseStringFrequencies.end()) { it1->second.push_back(elem.first); } else { it1 = reverseStringFrequencies.insert(it1, std::make_pair(elem.second, std::vector<std::string>())); it1->second.push_back(elem.first); } } std::unordered_map<std::string, char> encodedStrings; std::unordered_map<std::string, char>::iterator encodedStringsIt; std::map<unsigned int, std::vector<std::string>>::reverse_iterator it2 = reverseStringFrequencies.rbegin(); for (size_t i = 0; i < symbols.size() && it2 != reverseStringFrequencies.rend(); ++i, ++it2) { for (size_t j = 0; j < it2->second.size(); ++j, ++i) { if (i < symbols.size()) encodedStrings.insert(std::make_pair(it2->second[j], symbols[i])); } } output.WriteDynInt(encodedStrings.size()); for(encodedStringsIt = encodedStrings.begin(); encodedStringsIt != encodedStrings.end(); ++encodedStringsIt) { output.WriteUInt8(encodedStringsIt->second); output.WriteString(encodedStringsIt->first); } in = std::istringstream((char *)input.Data()); std::string str = in.str(); std::ostringstream out; //int end = input.Data()[input.Size() - 1]; while (in.good()) { std::streamoff prev = in.tellg(); in >> temp; std::streamoff after = in.tellg(); if ((encodedStringsIt = encodedStrings.find(temp)) != encodedStrings.end()) output.WriteString(std::string(1,encodedStringsIt->second)); else output.WriteString(temp); if (after != -1) output.WriteDynInt(after - prev - temp.size()); else output.WriteDynInt(input.Size() - prev - temp.size() - 1); } return true; } bool CompressKeywordEncoding::DecompressImpl(const ByteBuffer& input, ByteBuffer& output) { ByteBuffer* hack = const_cast<ByteBuffer*>(&input); std::unordered_map<char, std::string> encodedSymbols; std::unordered_map<char, std::string>::iterator encodedSymbolsIt; size_t numTableEntries = hack->ReadDynInt(); for(; numTableEntries > 0; --numTableEntries) encodedSymbols.insert(std::make_pair((char)hack->ReadUInt8(), hack->ReadString())); std::stringstream str; std::string temp; while (hack->CanRead()) { temp = hack->ReadString(); size_t spaceCount = hack->ReadDynInt(); for (size_t i = 0; i < spaceCount; ++i) str << ' '; if (temp.size() > 0 && (encodedSymbolsIt = encodedSymbols.find(temp.at(0))) != encodedSymbols.end()) str << encodedSymbolsIt->second; else str << temp; }; std::string r = str.str(); output.WriteBuffer(r.c_str(), r.size()); return true; } <|endoftext|>
<commit_before>// Copyright 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 /* This larger example shows how to use the MPIDistributedDevice to write an * interactive rendering application, which shows a UI on rank 0 and uses * all ranks in the MPI world for data loading and rendering. Each rank * generates a local sub-piece of spheres data, e.g., as if rendering some * large distributed dataset. */ #include <imgui.h> #include <mpi.h> #include <array> #include <iterator> #include <memory> #include <random> #include "GLFWDistribOSPRayWindow.h" #include "ospray/ospray_cpp.h" #include "ospray/ospray_cpp/ext/rkcommon.h" using namespace ospray; using namespace rkcommon; using namespace rkcommon::math; // Generate the rank's local spheres within its assigned grid cell, and // return the bounds of this grid cell cpp::Instance makeLocalSpheres( const int mpiRank, const int mpiWorldSize, box3f &bounds); int main(int argc, char **argv) { int mpiThreadCapability = 0; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &mpiThreadCapability); if (mpiThreadCapability != MPI_THREAD_MULTIPLE && mpiThreadCapability != MPI_THREAD_SERIALIZED) { fprintf(stderr, "OSPRay requires the MPI runtime to support thread " "multiple or thread serialized.\n"); return 1; } int mpiRank = 0; int mpiWorldSize = 0; MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiWorldSize); std::cout << "OSPRay rank " << mpiRank << "/" << mpiWorldSize << "\n"; // load the MPI module, and select the MPI distributed device. Here we // do not call ospInit, as we want to explicitly pick the distributed // device. This can also be done by passing --osp:mpi-distributed when // using ospInit, however if the user doesn't pass this argument your // application will likely not behave as expected ospLoadModule("mpi"); { cpp::Device mpiDevice("mpiDistributed"); mpiDevice.commit(); mpiDevice.setCurrent(); // set an error callback to catch any OSPRay errors and exit the application ospDeviceSetErrorCallback( mpiDevice.handle(), [](void *, OSPError error, const char *errorDetails) { std::cerr << "OSPRay error: " << errorDetails << std::endl; exit(error); }, nullptr); // all ranks specify the same rendering parameters, with the exception of // the data to be rendered, which is distributed among the ranks box3f regionBounds; cpp::Instance spheres = makeLocalSpheres(mpiRank, mpiWorldSize, regionBounds); // create the "world" model which will contain all of our geometries cpp::World world; world.setParam("instance", cpp::CopiedData(spheres)); /* * Note: We've taken care that all the generated spheres are completely * within the bounds, and we don't have ghost data or portions of speres * to clip off. Thus we actually don't need to set region at all in * this tutorial. Example: * world.setParam("region", cpp::CopiedData(regionBounds)); */ world.commit(); // create OSPRay renderer cpp::Renderer renderer("mpiRaycast"); // create and setup an ambient light std::array<cpp::Light, 2> lights = { cpp::Light("ambient"), cpp::Light("distant")}; lights[0].commit(); lights[1].setParam("direction", vec3f(-1.f, -1.f, 0.5f)); lights[1].commit(); renderer.setParam("lights", cpp::CopiedData(lights)); renderer.setParam("aoSamples", 1); // create a GLFW OSPRay window: this object will create and manage the // OSPRay frame buffer and camera directly auto glfwOSPRayWindow = std::unique_ptr<GLFWDistribOSPRayWindow>(new GLFWDistribOSPRayWindow( vec2i{1024, 768}, box3f(vec3f(-1.f), vec3f(1.f)), world, renderer)); int spp = 1; int currentSpp = 1; if (mpiRank == 0) { glfwOSPRayWindow->registerImGuiCallback( [&]() { ImGui::SliderInt("pixelSamples", &spp, 1, 64); }); } glfwOSPRayWindow->registerDisplayCallback( [&](GLFWDistribOSPRayWindow *win) { // Send the UI changes out to the other ranks so we can synchronize // how many samples per-pixel we're taking MPI_Bcast(&spp, 1, MPI_INT, 0, MPI_COMM_WORLD); if (spp != currentSpp) { currentSpp = spp; renderer.setParam("pixelSamples", spp); win->addObjectToCommit(renderer.handle()); } }); // start the GLFW main loop, which will continuously render glfwOSPRayWindow->mainLoop(); } // cleanly shut OSPRay down ospShutdown(); MPI_Finalize(); return 0; } bool computeDivisor(int x, int &divisor) { int upperBound = std::sqrt(x); for (int i = 2; i <= upperBound; ++i) { if (x % i == 0) { divisor = i; return true; } } return false; } // Compute an X x Y x Z grid to have 'num' grid cells, // only gives a nice grid for numbers with even factors since // we don't search for factors of the number, we just try dividing by two vec3i computeGrid(int num) { vec3i grid(1); int axis = 0; int divisor = 0; while (computeDivisor(num, divisor)) { grid[axis] *= divisor; num /= divisor; axis = (axis + 1) % 3; } if (num != 1) { grid[axis] *= num; } return grid; } cpp::Instance makeLocalSpheres( const int mpiRank, const int mpiWorldSize, box3f &bounds) { const float sphereRadius = 0.1; std::vector<vec3f> spheres(50); // To simulate loading a shared dataset all ranks generate the same // sphere data. std::random_device rd; std::mt19937 rng(rd()); const vec3i grid = computeGrid(mpiWorldSize); const vec3i brickId(mpiRank % grid.x, (mpiRank / grid.x) % grid.y, mpiRank / (grid.x * grid.y)); // The grid is over the [-1, 1] box const vec3f brickSize = vec3f(2.0) / vec3f(grid); const vec3f brickLower = brickSize * brickId - vec3f(1.f); const vec3f brickUpper = brickSize * brickId - vec3f(1.f) + brickSize; bounds.lower = brickLower; bounds.upper = brickUpper; // Generate spheres within the box padded by the radius, so we don't need // to worry about ghost bounds std::uniform_real_distribution<float> distX( brickLower.x + sphereRadius, brickUpper.x - sphereRadius); std::uniform_real_distribution<float> distY( brickLower.y + sphereRadius, brickUpper.y - sphereRadius); std::uniform_real_distribution<float> distZ( brickLower.z + sphereRadius, brickUpper.z - sphereRadius); for (auto &s : spheres) { s.x = distX(rng); s.y = distY(rng); s.z = distZ(rng); } cpp::Geometry sphereGeom("sphere"); sphereGeom.setParam("radius", sphereRadius); sphereGeom.setParam("sphere.position", cpp::CopiedData(spheres)); sphereGeom.commit(); vec3f color(0.f, 0.f, (mpiRank + 1.f) / mpiWorldSize); cpp::Material material(nullptr, "obj"); material.setParam("kd", color); material.commit(); cpp::GeometricModel model(sphereGeom); model.setParam("material", material); model.commit(); cpp::Group group; group.setParam("geometry", cpp::CopiedData(model)); group.commit(); cpp::Instance instance(group); instance.commit(); return instance; } <commit_msg>Fix parameter to C++ Material wrapper, must be empty str not null<commit_after>// Copyright 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 /* This larger example shows how to use the MPIDistributedDevice to write an * interactive rendering application, which shows a UI on rank 0 and uses * all ranks in the MPI world for data loading and rendering. Each rank * generates a local sub-piece of spheres data, e.g., as if rendering some * large distributed dataset. */ #include <imgui.h> #include <mpi.h> #include <array> #include <iterator> #include <memory> #include <random> #include "GLFWDistribOSPRayWindow.h" #include "ospray/ospray_cpp.h" #include "ospray/ospray_cpp/ext/rkcommon.h" using namespace ospray; using namespace rkcommon; using namespace rkcommon::math; // Generate the rank's local spheres within its assigned grid cell, and // return the bounds of this grid cell cpp::Instance makeLocalSpheres( const int mpiRank, const int mpiWorldSize, box3f &bounds); int main(int argc, char **argv) { int mpiThreadCapability = 0; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &mpiThreadCapability); if (mpiThreadCapability != MPI_THREAD_MULTIPLE && mpiThreadCapability != MPI_THREAD_SERIALIZED) { fprintf(stderr, "OSPRay requires the MPI runtime to support thread " "multiple or thread serialized.\n"); return 1; } int mpiRank = 0; int mpiWorldSize = 0; MPI_Comm_rank(MPI_COMM_WORLD, &mpiRank); MPI_Comm_size(MPI_COMM_WORLD, &mpiWorldSize); std::cout << "OSPRay rank " << mpiRank << "/" << mpiWorldSize << "\n"; // load the MPI module, and select the MPI distributed device. Here we // do not call ospInit, as we want to explicitly pick the distributed // device. This can also be done by passing --osp:mpi-distributed when // using ospInit, however if the user doesn't pass this argument your // application will likely not behave as expected ospLoadModule("mpi"); { cpp::Device mpiDevice("mpiDistributed"); mpiDevice.commit(); mpiDevice.setCurrent(); // set an error callback to catch any OSPRay errors and exit the application ospDeviceSetErrorCallback( mpiDevice.handle(), [](void *, OSPError error, const char *errorDetails) { std::cerr << "OSPRay error: " << errorDetails << std::endl; exit(error); }, nullptr); // all ranks specify the same rendering parameters, with the exception of // the data to be rendered, which is distributed among the ranks box3f regionBounds; cpp::Instance spheres = makeLocalSpheres(mpiRank, mpiWorldSize, regionBounds); // create the "world" model which will contain all of our geometries cpp::World world; world.setParam("instance", cpp::CopiedData(spheres)); /* * Note: We've taken care that all the generated spheres are completely * within the bounds, and we don't have ghost data or portions of speres * to clip off. Thus we actually don't need to set region at all in * this tutorial. Example: * world.setParam("region", cpp::CopiedData(regionBounds)); */ world.commit(); // create OSPRay renderer cpp::Renderer renderer("mpiRaycast"); // create and setup an ambient light std::array<cpp::Light, 2> lights = { cpp::Light("ambient"), cpp::Light("distant")}; lights[0].commit(); lights[1].setParam("direction", vec3f(-1.f, -1.f, 0.5f)); lights[1].commit(); renderer.setParam("lights", cpp::CopiedData(lights)); renderer.setParam("aoSamples", 1); // create a GLFW OSPRay window: this object will create and manage the // OSPRay frame buffer and camera directly auto glfwOSPRayWindow = std::unique_ptr<GLFWDistribOSPRayWindow>(new GLFWDistribOSPRayWindow( vec2i{1024, 768}, box3f(vec3f(-1.f), vec3f(1.f)), world, renderer)); int spp = 1; int currentSpp = 1; if (mpiRank == 0) { glfwOSPRayWindow->registerImGuiCallback( [&]() { ImGui::SliderInt("pixelSamples", &spp, 1, 64); }); } glfwOSPRayWindow->registerDisplayCallback( [&](GLFWDistribOSPRayWindow *win) { // Send the UI changes out to the other ranks so we can synchronize // how many samples per-pixel we're taking MPI_Bcast(&spp, 1, MPI_INT, 0, MPI_COMM_WORLD); if (spp != currentSpp) { currentSpp = spp; renderer.setParam("pixelSamples", spp); win->addObjectToCommit(renderer.handle()); } }); // start the GLFW main loop, which will continuously render glfwOSPRayWindow->mainLoop(); } // cleanly shut OSPRay down ospShutdown(); MPI_Finalize(); return 0; } bool computeDivisor(int x, int &divisor) { int upperBound = std::sqrt(x); for (int i = 2; i <= upperBound; ++i) { if (x % i == 0) { divisor = i; return true; } } return false; } // Compute an X x Y x Z grid to have 'num' grid cells, // only gives a nice grid for numbers with even factors since // we don't search for factors of the number, we just try dividing by two vec3i computeGrid(int num) { vec3i grid(1); int axis = 0; int divisor = 0; while (computeDivisor(num, divisor)) { grid[axis] *= divisor; num /= divisor; axis = (axis + 1) % 3; } if (num != 1) { grid[axis] *= num; } return grid; } cpp::Instance makeLocalSpheres( const int mpiRank, const int mpiWorldSize, box3f &bounds) { const float sphereRadius = 0.1; std::vector<vec3f> spheres(50); // To simulate loading a shared dataset all ranks generate the same // sphere data. std::random_device rd; std::mt19937 rng(rd()); const vec3i grid = computeGrid(mpiWorldSize); const vec3i brickId(mpiRank % grid.x, (mpiRank / grid.x) % grid.y, mpiRank / (grid.x * grid.y)); // The grid is over the [-1, 1] box const vec3f brickSize = vec3f(2.0) / vec3f(grid); const vec3f brickLower = brickSize * brickId - vec3f(1.f); const vec3f brickUpper = brickSize * brickId - vec3f(1.f) + brickSize; bounds.lower = brickLower; bounds.upper = brickUpper; // Generate spheres within the box padded by the radius, so we don't need // to worry about ghost bounds std::uniform_real_distribution<float> distX( brickLower.x + sphereRadius, brickUpper.x - sphereRadius); std::uniform_real_distribution<float> distY( brickLower.y + sphereRadius, brickUpper.y - sphereRadius); std::uniform_real_distribution<float> distZ( brickLower.z + sphereRadius, brickUpper.z - sphereRadius); for (auto &s : spheres) { s.x = distX(rng); s.y = distY(rng); s.z = distZ(rng); } cpp::Geometry sphereGeom("sphere"); sphereGeom.setParam("radius", sphereRadius); sphereGeom.setParam("sphere.position", cpp::CopiedData(spheres)); sphereGeom.commit(); vec3f color(0.f, 0.f, (mpiRank + 1.f) / mpiWorldSize); cpp::Material material("", "obj"); material.setParam("kd", color); material.commit(); cpp::GeometricModel model(sphereGeom); model.setParam("material", material); model.commit(); cpp::Group group; group.setParam("geometry", cpp::CopiedData(model)); group.commit(); cpp::Instance instance(group); instance.commit(); return instance; } <|endoftext|>
<commit_before>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb( Bool_t getFromAlien = kFALSE, TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C", TString libFile="LMEECutLib_dsekihat.C", UInt_t trigger = AliVEvent::kINT7, const Int_t CenMin = 0, const Int_t CenMax = 10, const TString pileupcut = "_woPU",//can be "_woPU", "_onlyPU","" const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;EvtGenDecay;Pythia CC_0;Pythia BB_0;Pythia B_0;", const TString calibFileName = "", const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root" ){ // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_dsekihat_ElectronEfficiencyV2_PbPb", "No analysis manager found."); return 0; } //TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); TString configBasePath("./"); if (!gSystem->AccessPathName(configFile) && !gSystem->AccessPathName(libFile) ) { printf("Configfile already present\n"); configBasePath=Form("%s/",gSystem->pwd()); } else if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + configFile); TString libFilePath(configBasePath + libFile); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); //if (!gROOT->GetListOfClasses()->FindObject("LMEECutLib")) { // printf("Load library now\n"); // gROOT->LoadMacro(libFilePath.Data()); // //gROOT->AddClass(LMEECutLib::Class()); //} //if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_dsekihat_ElectronEfficiencyV2_PbPb")) { // printf("Load macro now\n"); // gROOT->LoadMacro(configFilePath.Data()); //} TString suffix = ""; if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffix = "_CC_BB"; else if(generators.Contains("Pythia CC")) suffix = "_CC"; else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffix = "_BB"; else if(generators.Contains("pizero")) suffix = "_LF"; else suffix = ""; // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data())); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); const Int_t nEC = Int_t(gROOT->ProcessLine("GetNEC()") );//event cuts const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") );//track cuts const Int_t nPC = Int_t(gROOT->ProcessLine("GetNPID()"));//pid cuts for (Int_t iec=0; iec<nEC; ++iec){ for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipc=0; ipc<nPC; ++ipc){ AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d)",iec,itc,ipc))); task->AddTrackCuts(filter); } } } //It is important to apply pileup cuts at "task" level in M.C. for efficiency. (i.e. Both denominator and nominator has to be taken into account in exactly the same events.) // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 //if(pileupcut == ""){ // printf("analyze all events in M.C.\n"); //} //else if(pileupcut.Contains("woPU")){ // printf("analyze only in clean events in M.C.\n"); // TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()")); // dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMinCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent); //} //else if(pileupcut.Contains("onlyPU")){ // printf("analyze only in pileup events in M.C.\n"); // TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()")); // dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMaxCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent); //} //else{ // printf("Nothing with pileup cut in M.C.\n"); // printf("analyze all events in M.C.\n"); //} printf("analyze all events in M.C.\n"); dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->Print(); // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // Set minimum and maximum values for pairing task->SetKinematicCuts(0.2, 10, -0.8, +0.8); // Set Binning task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1, +1, 20); task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); const Int_t Nmee = 195; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110; i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<126; i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 2.7 GeV/c2, every 0.1 GeV/c2 for(Int_t i=126;i<176; i++) mee[i] = 0.01 * (i-126) + 2.7;//from 2.7 to 3.2 GeV/c2, every 0.01 GeV/c2 for J/psi for(Int_t i=176;i<Nmee;i++) mee[i] = 0.1 * (i-176) + 3.2;//from 3.2 to 5 GeV/c2, every 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 146; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<50 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.49 GeV/c, every 0.01 GeV/c for(Int_t i=50 ;i<NpTee ;i++) pTee[i] = 0.1 * (i- 50) + 0.5;//from 0.5 to 10 GeV/c, evety 0.1 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); task->SetPhiVBinsLinear(0, TMath::Pi(), 100); task->SetFillPhiV(kFALSE); task->SetSmearGenerated(kFALSE); task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000); task->SetResolutionRelPtBinsLinear ( 0, 2, 400); task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200); task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200); task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200); // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // Pairing related config task->SetDoPairing(kTRUE); task->SetULSandLS(kTRUE); task->SetDeactivateLS(kFALSE); cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); task->SetResolutionFile(resolutionFilename , "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename); task->SetCentralityFile(centralityFilename , "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/" + centralityFilename); if(cocktailFilename != "") task->SetDoCocktailWeighting(kTRUE); task->SetCocktailWeighting(cocktailFilename, "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename); // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name //set PID map for ITS TOF in MC. TFile *rootfile = 0x0; if(calibFileName != "") rootfile = TFile::Open(calibFileName,"READ"); if(rootfile && rootfile->IsOpen()){ TH3D *h3mean_ITS = (TH3D*)rootfile->Get("h3mean_ITS"); TH3D *h3width_ITS = (TH3D*)rootfile->Get("h3width_ITS"); h3mean_ITS ->SetDirectory(0); h3width_ITS->SetDirectory(0); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3mean_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3width_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta ); TH3D *h3mean_TOF = (TH3D*)rootfile->Get("h3mean_TOF"); TH3D *h3width_TOF = (TH3D*)rootfile->Get("h3width_TOF"); h3mean_TOF ->SetDirectory(0); h3width_TOF->SetDirectory(0); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3mean_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3width_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); rootfile->Close(); } TString outlistname = Form("Efficiency_dsekihat%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data()); //const TString fileName = AliAnalysisManager::GetCommonFileName(); const TString fileName = outname; //const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; } <commit_msg>PWGDQ/LMEE: update AddTask.C<commit_after>AliAnalysisTaskElectronEfficiencyV2* AddTask_dsekihat_ElectronEfficiencyV2_PbPb( Bool_t getFromAlien = kFALSE, TString configFile="Config_dsekihat_ElectronEfficiencyV2_PbPb.C", TString libFile="LMEECutLib_dsekihat.C", UInt_t trigger = AliVEvent::kINT7, const Int_t CenMin = 0, const Int_t CenMax = 10, const TString pileupcut = "_woPU",//can be "_woPU", "_onlyPU","" const TString generators = "pizero_0;eta_1;etaprime_2;rho_3;omega_4;phi_5;jpsi_6;EvtGenDecay;Pythia CC_0;Pythia BB_0;Pythia B_0;", const TString calibFileName = "", const std::string resolutionFilename ="", const std::string cocktailFilename ="", const std::string centralityFilename ="", const TString outname = "LMEE.root" ){ // Configuring Analysis Manager AliAnalysisManager* mgr = AliAnalysisManager::GetAnalysisManager(); if (!mgr) { Error("AddTask_dsekihat_ElectronEfficiencyV2_PbPb", "No analysis manager found."); return 0; } //TString configBasePath("$ALICE_PHYSICS/PWGDQ/dielectron/macrosLMEE/"); TString configBasePath("./"); if (!gSystem->AccessPathName(configFile) && !gSystem->AccessPathName(libFile) ) { printf("Configfile already present\n"); configBasePath=Form("%s/",gSystem->pwd()); } else if(getFromAlien && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",configFile.Data()))) && (!gSystem->Exec(Form("alien_cp alien:///alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/macrosLMEE/%s .",libFile.Data()))) ){ configBasePath=Form("%s/",gSystem->pwd()); } TString configFilePath(configBasePath + configFile); TString libFilePath(configBasePath + libFile); std::cout << "Configpath: " << configFilePath << std::endl; std::cout << "Libpath: " << libFilePath << std::endl; gROOT->LoadMacro(libFilePath.Data());//library first gROOT->LoadMacro(configFilePath.Data()); //if (!gROOT->GetListOfClasses()->FindObject("LMEECutLib")) { // printf("Load library now\n"); // gROOT->LoadMacro(libFilePath.Data()); // //gROOT->AddClass(LMEECutLib::Class()); //} //if (!gROOT->GetListOfGlobalFunctions()->FindObject("Config_dsekihat_ElectronEfficiencyV2_PbPb")) { // printf("Load macro now\n"); // gROOT->LoadMacro(configFilePath.Data()); //} TString suffix = ""; if(generators.Contains("Pythia CC") && (generators.Contains("Pythia BB") || generators.Contains("Pythia B"))) suffix = "_CC_BB"; else if(generators.Contains("Pythia CC")) suffix = "_CC"; else if(generators.Contains("Pythia BB") || generators.Contains("Pythia B")) suffix = "_BB"; else if(generators.Contains("pizero")) suffix = "_LF"; else suffix = ""; // Creating an instance of the task AliAnalysisTaskElectronEfficiencyV2* task = new AliAnalysisTaskElectronEfficiencyV2(Form("TaskElectronEfficiencyV2%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data())); gROOT->GetListOfSpecials()->Add(task);//this is only for ProcessLine(AddMCSignal); const Int_t nEC = Int_t(gROOT->ProcessLine("GetNEC()") );//event cuts const Int_t nTC = Int_t(gROOT->ProcessLine("GetNTC()") );//track cuts const Int_t nPC = Int_t(gROOT->ProcessLine("GetNPID()"));//pid cuts for (Int_t iec=0; iec<nEC; ++iec){ for (Int_t itc=0; itc<nTC; ++itc){ for (Int_t ipc=0; ipc<nPC; ++ipc){ AliAnalysisFilter *filter = reinterpret_cast<AliAnalysisFilter*>(gROOT->ProcessLine(Form("Config_dsekihat_ElectronEfficiencyV2_PbPb(%d,%d,%d)",iec,itc,ipc))); task->AddTrackCuts(filter); } } } //It is important to apply pileup cuts at "task" level in M.C. for efficiency. (i.e. Both denominator and nominator has to be taken into account in exactly the same events.) // Event selection. Is the same for all the different cutsettings task->SetEnablePhysicsSelection(kTRUE);//always ON in Run2 analyses for both data and MC. task->SetTriggerMask(trigger); task->SetEventFilter(reinterpret_cast<AliDielectronEventCuts*>(gROOT->ProcessLine(Form("LMEECutLib::SetupEventCuts(%f,%f,%d,\"%s\")",(Float_t)CenMin,(Float_t)CenMax,kTRUE,"V0M"))));//kTRUE is for Run2 task->SetRejectParticleFromOOB(kTRUE); //if(pileupcut == ""){ // printf("analyze all events in M.C.\n"); //} //else if(pileupcut.Contains("woPU")){ // printf("analyze only in clean events in M.C.\n"); // TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()")); // dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMinCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent); //} //else if(pileupcut.Contains("onlyPU")){ // printf("analyze only in pileup events in M.C.\n"); // TF1 *f1pu = reinterpret_cast<TF1*>(gROOT->ProcessLine("LMEECutLib::SetupPileupCuts()")); // dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->SetMaxCorrCutFunction(f1pu, AliDielectronVarManager::kNTPCclsEvent, AliDielectronVarManager::kNSDDSSDclsEvent); //} //else{ // printf("Nothing with pileup cut in M.C.\n"); // printf("analyze all events in M.C.\n"); //} printf("analyze all events in M.C.\n"); dynamic_cast<AliDielectronEventCuts*>(task->GetEventFilter())->Print(); // Set minimum and maximum values of generated tracks. Only used to save computing power. // Do not set here your analysis pt-cuts task->SetMinPtGen(0.1); task->SetMaxPtGen(1e+10); task->SetMinEtaGen(-1.5); task->SetMaxEtaGen(+1.5); // Set minimum and maximum values for pairing task->SetKinematicCuts(0.2, 10, -0.8, +0.8); // Set Binning task->SetPtBinsLinear (0, 10, 100); task->SetEtaBinsLinear (-1, +1, 20); task->SetPhiBinsLinear (0, TMath::TwoPi(), 36); task->SetThetaBinsLinear(0, TMath::TwoPi(), 60); const Int_t Nmee = 195; Double_t mee[Nmee] = {}; for(Int_t i=0 ;i<110; i++) mee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 1.1 GeV/c2, every 0.01 GeV/c2 for(Int_t i=110;i<126; i++) mee[i] = 0.1 * (i-110) + 1.1;//from 1.1 to 2.7 GeV/c2, every 0.1 GeV/c2 for(Int_t i=126;i<176; i++) mee[i] = 0.01 * (i-126) + 2.7;//from 2.7 to 3.2 GeV/c2, every 0.01 GeV/c2 for J/psi for(Int_t i=176;i<Nmee;i++) mee[i] = 0.1 * (i-176) + 3.2;//from 3.2 to 5 GeV/c2, every 0.1 GeV/c2 std::vector<double> v_mee(mee,std::end(mee)); const Int_t NpTee = 146; Double_t pTee[NpTee] = {}; for(Int_t i=0 ;i<50 ;i++) pTee[i] = 0.01 * (i- 0) + 0.0;//from 0 to 0.49 GeV/c, every 0.01 GeV/c for(Int_t i=50 ;i<NpTee ;i++) pTee[i] = 0.1 * (i- 50) + 0.5;//from 0.5 to 10 GeV/c, evety 0.1 GeV/c std::vector<double> v_pTee(pTee,std::end(pTee)); task->SetMassBins(v_mee); task->SetPairPtBins(v_pTee); task->SetPhiVBinsLinear(0, TMath::Pi(), 100); task->SetFillPhiV(kFALSE); task->SetSmearGenerated(kFALSE); task->SetResolutionDeltaPtBinsLinear( -10, +10, 2000); task->SetResolutionRelPtBinsLinear ( 0, 2, 400); task->SetResolutionEtaBinsLinear (-0.4, +0.4, 200); task->SetResolutionPhiBinsLinear (-0.4, +0.4, 200); task->SetResolutionThetaBinsLinear (-0.4, +0.4, 200); // Set MCSignal and Cutsetting to fill the support histograms task->SetSupportHistoMCSignalAndCutsetting(0,0);//fill support histograms for first MCsignal and first cutsetting // Pairing related config task->SetDoPairing(kTRUE); task->SetULSandLS(kTRUE); task->SetDeactivateLS(kFALSE); cout<<"Efficiency based on MC generators: " << generators <<endl; TString generatorsPair=generators; task->SetGeneratorMCSignalName(generatorsPair); task->SetGeneratorULSSignalName(generators); task->SetResolutionFile(resolutionFilename , "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/resolution/" + resolutionFilename); task->SetCentralityFile(centralityFilename , "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/centrality/" + centralityFilename); if(cocktailFilename != "") task->SetDoCocktailWeighting(kTRUE); task->SetCocktailWeighting(cocktailFilename, "/alice/cern.ch/user/d/dsekihat/PWGDQ/dielectron/cocktail/" + cocktailFilename); // Add MCSignals. Can be set to see differences of: // e.g. secondaries and primaries. or primaries from charm and resonances gROOT->ProcessLine(Form("AddSingleLegMCSignal(%s)",task->GetName()));//not task itself, task name gROOT->ProcessLine(Form("AddPairMCSignal(%s)" ,task->GetName()));//not task itself, task name //set PID map for ITS TOF in MC. TFile *rootfile = 0x0; if(calibFileName != "") rootfile = TFile::Open(calibFileName,"READ"); if(rootfile && rootfile->IsOpen()){ TH3D *h3mean_ITS = (TH3D*)rootfile->Get("h3mean_ITS"); TH3D *h3width_ITS = (TH3D*)rootfile->Get("h3width_ITS"); h3mean_ITS ->SetDirectory(0); h3width_ITS->SetDirectory(0); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3mean_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, h3width_ITS, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta ); TH3D *h3mean_TOF = (TH3D*)rootfile->Get("h3mean_TOF"); TH3D *h3width_TOF = (TH3D*)rootfile->Get("h3width_TOF"); h3mean_TOF ->SetDirectory(0); h3width_TOF->SetDirectory(0); task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3mean_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); task->SetWidthCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, h3width_TOF, AliDielectronVarManager::kNSDDSSDclsEvent, AliDielectronVarManager::kPIn, AliDielectronVarManager::kEta); rootfile->Close(); } TString outlistname = Form("Efficiency_dsekihat%s_Cen%d_%d_kINT7%s",suffix.Data(),CenMin,CenMax,pileupcut.Data()); //const TString fileName = AliAnalysisManager::GetCommonFileName(); const TString fileName = outname; //const TString dirname = Form("PWGDQ_LMEE_ElectronEfficiencyV2_Cen%d_%d_kINT7",CenMin,CenMax); mgr->AddTask(task); mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer()); mgr->ConnectOutput(task, 1, mgr->CreateContainer(outlistname, TList::Class(), AliAnalysisManager::kOutputContainer, Form("%s",fileName.Data()))); return task; } <|endoftext|>
<commit_before>#ifndef OBJECTS_H #define OBJECTS_H /* Defines an Object::ref type, which is a tagged pointer type. Usage: Object::ref x = Object::to_ref(1);//smallint Object::ref y = Object::to_ref(new(hp) Generic()); //object if(is_a<int>(x)) { std::cout << "x = " << as_a<int>(x) << std::endl; } if(is_a<Generic*>(y)) { std::cout << "y.field = " << as_a<Generic*>(y)->field << std::endl; } */ #include<stdint.h> #include<climits> #include"unichars.hpp" #include"workarounds.hpp" class Generic; class Symbol; class Cons; class Closure; class KClosure; namespace Object { /*----------------------------------------------------------------------------- Declare -----------------------------------------------------------------------------*/ class ref; template<typename T> struct tag_traits; /*assume we won't ever need more than 7 bits of tag*/ typedef unsigned char tag_type; template<typename T> static inline ref to_ref(T); template<typename T> static inline bool _is_a(ref); template<typename T> static inline T _as_a(ref); static inline ref t(void); static inline bool _is_t(ref); static inline ref nil(void); static inline bool _is_nil(ref); static inline ref from_a_scaled_int(int); static inline int to_a_scaled_int(ref); } void throw_TypeError(Object::ref, char const*); void throw_RangeError(char const*); template<typename T> static inline bool is_a(Object::ref); template<typename T> static inline T as_a(Object::ref); static inline bool is_t(Object::ref); size_t hash_is(Object::ref); namespace Object { /*----------------------------------------------------------------------------- Configuration -----------------------------------------------------------------------------*/ static const unsigned char tag_bits = 2;// can bump up to 3 maybe... template<> struct tag_traits<int> { static const tag_type tag = 0x1; }; template<> struct tag_traits<Generic*> { static const tag_type tag = 0x0; }; template<> struct tag_traits<Symbol*> { static const tag_type tag = 0x2; }; template<> struct tag_traits<UnicodeChar> { static const tag_type tag = 0x3; }; /*----------------------------------------------------------------------------- Provided information -----------------------------------------------------------------------------*/ static const tag_type alignment = 1 << tag_bits; static const tag_type tag_mask = alignment - 1; /*the real range is the smaller of the range of intptr_t shifted down by tag bits, or the range of the `int' type */ static const intptr_t smallint_min = (sizeof(int) >= sizeof(intptr_t)) ? INTPTR_MIN >> tag_bits : /*otherwise*/ INT_MIN; static const intptr_t smallint_max = (sizeof(int) >= sizeof(intptr_t)) ? INTPTR_MAX >> tag_bits : /*otherwise*/ INT_MAX; /*value for "t"*/ static const intptr_t t_value = ~((intptr_t) tag_mask); /*----------------------------------------------------------------------------- The tagged pointer type -----------------------------------------------------------------------------*/ /*stefano prefers to use: typedef void* ref; or maybe: typedef intptr_t ref; I may change this later on, but for now I want to see whether the conceptual separation will help and if compilers, in general, will be smart enough to optimize away the structure. */ class ref { private: intptr_t dat; ref(intptr_t x) : dat(x) {} public: ref(void) : dat(0) {} inline bool operator==(ref b) { return dat == b.dat; } inline bool operator!=(ref b) { return dat != b.dat; } inline bool operator!(void) { return dat == 0; } /*safe bool idiom*/ typedef intptr_t (ref::*unspecified_bool_type); inline operator unspecified_bool_type(void) const { return dat != 0 ? &ref::dat : 0; } template<typename T> friend ref to_ref(T); template<typename T> friend bool _is_a(ref); template<typename T> friend T _as_a(ref); friend int to_a_scaled_int(ref); friend ref from_a_scaled_int(int); friend ref t(void); friend bool _is_t(ref); friend size_t (::hash_is)(Object::ref); }; /*----------------------------------------------------------------------------- Tagged pointer factories -----------------------------------------------------------------------------*/ template<typename T> static inline ref to_ref(T x) { /* default to Generic* */ return to_ref<Generic*>(x); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<Generic*>(Generic* x) { intptr_t tmp = reinterpret_cast<intptr_t>(x); #ifdef DEBUG if(tmp & tag_mask != 0) { throw_RangeError("Misaligned pointer"); } #endif return ref(tmp + tag_traits<Generic*>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<Symbol*>(Symbol* x) { intptr_t tmp = reinterpret_cast<intptr_t>(x); #ifdef DEBUG if(tmp & tag_mask != 0) { throw_RangeError("Misaligned pointer"); } #endif return ref(tmp + tag_traits<Symbol*>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<int>(int x) { #ifdef DEBUG #if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN) if(x < smallint_min || x > smallint_max) { throw_RangeError( "int out of range of smallint" ); } #endif #endif intptr_t tmp = (((intptr_t) x) << tag_bits); return ref(tmp + tag_traits<int>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<UnicodeChar>(UnicodeChar x) { intptr_t tmp = x.dat << tag_bits; return ref(tmp + tag_traits<UnicodeChar>::tag); } /*no checking, even in debug mode... achtung!*/ /*This function is used to convert an int computed using Object::to_a_scaled_int back to an Object::ref. It is not intended to be used for any other int's. This function is intended for optimized smallint mathematics. */ static inline ref from_a_scaled_int(int x) { return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag); } static inline ref nil(void) { return ref(); } static inline ref t(void) { return ref(t_value); } /*----------------------------------------------------------------------------- Tagged pointer checking -----------------------------------------------------------------------------*/ static inline bool _is_nil(ref obj) { return !obj; } static inline bool _is_t(ref obj) { return obj.dat == t_value; } template<typename T> static inline bool _is_a(ref obj) { if(tag_traits<T>::tag != 0x0) { return (obj.dat & tag_mask) == tag_traits<T>::tag; } else { return (obj.dat & tag_mask) == tag_traits<T>::tag && !_is_nil(obj) && !_is_t(obj); } } /*----------------------------------------------------------------------------- Tagged pointer referencing -----------------------------------------------------------------------------*/ template<typename T> static inline T _as_a(ref obj) { #ifdef DEBUG if(!_is_a<T>(obj)) { throw_TypeError(obj, "incorrect type for pointer" ); } #endif intptr_t tmp = obj.dat; return reinterpret_cast<T>(tmp - tag_traits<T>::tag); /*use subtraction instead of masking, in order to allow smart compilers to merge a field access with the tag removal. i.e. the pointers are pointers to structures, so they will be accessed via fields, and in all probability those fields will be at some offset from the actual structure address, meaning that the processor itself will perform an addition to access the field. The smart compiler can then merge the addition of the field offset with the subtraction of the tag. */ } template<> STATIC_INLINE_SPECIALIZATION int _as_a<int>(ref obj) { #ifdef DEBUG if(!_is_a<int>(obj)) { throw_TypeError(obj, "incorrect type for small integer" ); } #endif intptr_t tmp = obj.dat; return (int)(tmp >> tag_bits); } template<> STATIC_INLINE_SPECIALIZATION UnicodeChar _as_a<UnicodeChar>(ref obj) { uint32_t tmp = obj.dat; return UnicodeChar(tmp >> tag_bits); } /*no checking, even in debug mode... achtung!*/ /*This function is used to convert a smallint Object::ref to a useable int that is equal to the "real" int, shifted to the left by the number of tag bits (i.e. scaled). It should be used only for optimizing smallint math operations. */ static inline int to_a_scaled_int(ref obj) { intptr_t tmp = obj.dat; return (int)((tmp - tag_traits<int>::tag)>>tag_bits); /*use subtraction instead of masking, again to allow smart compilers to merge tag adding and subtracting. For example the typical case would be something like: Object::ref result = Object::from_a_scaled_int( Object::to_a_scaled_int(a) + Object::to_a_scaled_int(b) ); The above case can be reduced by the compiler to: intptr_t result = (tag_traits<int>::tag + a - tag_traits<int>::tag + b - tag_traits<int>::tag ); It can then do some maths and cancel out a tag: intptr_t result = a + b - tag_traits<int>::tag; */ } /*----------------------------------------------------------------------------- Utility -----------------------------------------------------------------------------*/ static inline size_t round_up_to_alignment(size_t x) { return (x & tag_mask) ? (x + alignment - (x & tag_mask)) : /*otherwise*/ x ; } } /*----------------------------------------------------------------------------- Reflectors outside of the namespace -----------------------------------------------------------------------------*/ template<typename T> static inline bool is_a(Object::ref obj) { return Object::_is_a<T>(obj); } template<typename T> static inline T as_a(Object::ref obj) { return Object::_as_a<T>(obj); } static inline bool is_nil(Object::ref obj) { return Object::_is_nil(obj); } static inline bool is_t(Object::ref obj) { return Object::_is_t(obj); } #endif //OBJECTS_H <commit_msg>inc/objects.hpp: Made comparison functions `const`<commit_after>#ifndef OBJECTS_H #define OBJECTS_H /* Defines an Object::ref type, which is a tagged pointer type. Usage: Object::ref x = Object::to_ref(1);//smallint Object::ref y = Object::to_ref(new(hp) Generic()); //object if(is_a<int>(x)) { std::cout << "x = " << as_a<int>(x) << std::endl; } if(is_a<Generic*>(y)) { std::cout << "y.field = " << as_a<Generic*>(y)->field << std::endl; } */ #include<stdint.h> #include<climits> #include"unichars.hpp" #include"workarounds.hpp" class Generic; class Symbol; class Cons; class Closure; class KClosure; namespace Object { /*----------------------------------------------------------------------------- Declare -----------------------------------------------------------------------------*/ class ref; template<typename T> struct tag_traits; /*assume we won't ever need more than 7 bits of tag*/ typedef unsigned char tag_type; template<typename T> static inline ref to_ref(T); template<typename T> static inline bool _is_a(ref); template<typename T> static inline T _as_a(ref); static inline ref t(void); static inline bool _is_t(ref); static inline ref nil(void); static inline bool _is_nil(ref); static inline ref from_a_scaled_int(int); static inline int to_a_scaled_int(ref); } void throw_TypeError(Object::ref, char const*); void throw_RangeError(char const*); template<typename T> static inline bool is_a(Object::ref); template<typename T> static inline T as_a(Object::ref); static inline bool is_t(Object::ref); size_t hash_is(Object::ref); namespace Object { /*----------------------------------------------------------------------------- Configuration -----------------------------------------------------------------------------*/ static const unsigned char tag_bits = 2;// can bump up to 3 maybe... template<> struct tag_traits<int> { static const tag_type tag = 0x1; }; template<> struct tag_traits<Generic*> { static const tag_type tag = 0x0; }; template<> struct tag_traits<Symbol*> { static const tag_type tag = 0x2; }; template<> struct tag_traits<UnicodeChar> { static const tag_type tag = 0x3; }; /*----------------------------------------------------------------------------- Provided information -----------------------------------------------------------------------------*/ static const tag_type alignment = 1 << tag_bits; static const tag_type tag_mask = alignment - 1; /*the real range is the smaller of the range of intptr_t shifted down by tag bits, or the range of the `int' type */ static const intptr_t smallint_min = (sizeof(int) >= sizeof(intptr_t)) ? INTPTR_MIN >> tag_bits : /*otherwise*/ INT_MIN; static const intptr_t smallint_max = (sizeof(int) >= sizeof(intptr_t)) ? INTPTR_MAX >> tag_bits : /*otherwise*/ INT_MAX; /*value for "t"*/ static const intptr_t t_value = ~((intptr_t) tag_mask); /*----------------------------------------------------------------------------- The tagged pointer type -----------------------------------------------------------------------------*/ /*stefano prefers to use: typedef void* ref; or maybe: typedef intptr_t ref; I may change this later on, but for now I want to see whether the conceptual separation will help and if compilers, in general, will be smart enough to optimize away the structure. */ class ref { private: intptr_t dat; ref(intptr_t x) : dat(x) {} public: ref(void) : dat(0) {} inline bool operator==(ref b) const { return dat == b.dat; } inline bool operator!=(ref b) const { return dat != b.dat; } inline bool operator!(void) const { return dat == 0; } /*safe bool idiom*/ typedef intptr_t (ref::*unspecified_bool_type); inline operator unspecified_bool_type(void) const { return dat != 0 ? &ref::dat : 0; } template<typename T> friend ref to_ref(T); template<typename T> friend bool _is_a(ref); template<typename T> friend T _as_a(ref); friend int to_a_scaled_int(ref); friend ref from_a_scaled_int(int); friend ref t(void); friend bool _is_t(ref); friend size_t (::hash_is)(Object::ref); }; /*----------------------------------------------------------------------------- Tagged pointer factories -----------------------------------------------------------------------------*/ template<typename T> static inline ref to_ref(T x) { /* default to Generic* */ return to_ref<Generic*>(x); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<Generic*>(Generic* x) { intptr_t tmp = reinterpret_cast<intptr_t>(x); #ifdef DEBUG if(tmp & tag_mask != 0) { throw_RangeError("Misaligned pointer"); } #endif return ref(tmp + tag_traits<Generic*>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<Symbol*>(Symbol* x) { intptr_t tmp = reinterpret_cast<intptr_t>(x); #ifdef DEBUG if(tmp & tag_mask != 0) { throw_RangeError("Misaligned pointer"); } #endif return ref(tmp + tag_traits<Symbol*>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<int>(int x) { #ifdef DEBUG #if (INT_MAX >= INTPTR_MAX) || (INT_MIN <= INTPTR_MIN) if(x < smallint_min || x > smallint_max) { throw_RangeError( "int out of range of smallint" ); } #endif #endif intptr_t tmp = (((intptr_t) x) << tag_bits); return ref(tmp + tag_traits<int>::tag); } template<> STATIC_INLINE_SPECIALIZATION ref to_ref<UnicodeChar>(UnicodeChar x) { intptr_t tmp = x.dat << tag_bits; return ref(tmp + tag_traits<UnicodeChar>::tag); } /*no checking, even in debug mode... achtung!*/ /*This function is used to convert an int computed using Object::to_a_scaled_int back to an Object::ref. It is not intended to be used for any other int's. This function is intended for optimized smallint mathematics. */ static inline ref from_a_scaled_int(int x) { return ref((((intptr_t) x)<<tag_bits) + tag_traits<int>::tag); } static inline ref nil(void) { return ref(); } static inline ref t(void) { return ref(t_value); } /*----------------------------------------------------------------------------- Tagged pointer checking -----------------------------------------------------------------------------*/ static inline bool _is_nil(ref obj) { return !obj; } static inline bool _is_t(ref obj) { return obj.dat == t_value; } template<typename T> static inline bool _is_a(ref obj) { if(tag_traits<T>::tag != 0x0) { return (obj.dat & tag_mask) == tag_traits<T>::tag; } else { return (obj.dat & tag_mask) == tag_traits<T>::tag && !_is_nil(obj) && !_is_t(obj); } } /*----------------------------------------------------------------------------- Tagged pointer referencing -----------------------------------------------------------------------------*/ template<typename T> static inline T _as_a(ref obj) { #ifdef DEBUG if(!_is_a<T>(obj)) { throw_TypeError(obj, "incorrect type for pointer" ); } #endif intptr_t tmp = obj.dat; return reinterpret_cast<T>(tmp - tag_traits<T>::tag); /*use subtraction instead of masking, in order to allow smart compilers to merge a field access with the tag removal. i.e. the pointers are pointers to structures, so they will be accessed via fields, and in all probability those fields will be at some offset from the actual structure address, meaning that the processor itself will perform an addition to access the field. The smart compiler can then merge the addition of the field offset with the subtraction of the tag. */ } template<> STATIC_INLINE_SPECIALIZATION int _as_a<int>(ref obj) { #ifdef DEBUG if(!_is_a<int>(obj)) { throw_TypeError(obj, "incorrect type for small integer" ); } #endif intptr_t tmp = obj.dat; return (int)(tmp >> tag_bits); } template<> STATIC_INLINE_SPECIALIZATION UnicodeChar _as_a<UnicodeChar>(ref obj) { uint32_t tmp = obj.dat; return UnicodeChar(tmp >> tag_bits); } /*no checking, even in debug mode... achtung!*/ /*This function is used to convert a smallint Object::ref to a useable int that is equal to the "real" int, shifted to the left by the number of tag bits (i.e. scaled). It should be used only for optimizing smallint math operations. */ static inline int to_a_scaled_int(ref obj) { intptr_t tmp = obj.dat; return (int)((tmp - tag_traits<int>::tag)>>tag_bits); /*use subtraction instead of masking, again to allow smart compilers to merge tag adding and subtracting. For example the typical case would be something like: Object::ref result = Object::from_a_scaled_int( Object::to_a_scaled_int(a) + Object::to_a_scaled_int(b) ); The above case can be reduced by the compiler to: intptr_t result = (tag_traits<int>::tag + a - tag_traits<int>::tag + b - tag_traits<int>::tag ); It can then do some maths and cancel out a tag: intptr_t result = a + b - tag_traits<int>::tag; */ } /*----------------------------------------------------------------------------- Utility -----------------------------------------------------------------------------*/ static inline size_t round_up_to_alignment(size_t x) { return (x & tag_mask) ? (x + alignment - (x & tag_mask)) : /*otherwise*/ x ; } } /*----------------------------------------------------------------------------- Reflectors outside of the namespace -----------------------------------------------------------------------------*/ template<typename T> static inline bool is_a(Object::ref obj) { return Object::_is_a<T>(obj); } template<typename T> static inline T as_a(Object::ref obj) { return Object::_as_a<T>(obj); } static inline bool is_nil(Object::ref obj) { return Object::_is_nil(obj); } static inline bool is_t(Object::ref obj) { return Object::_is_t(obj); } #endif //OBJECTS_H <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkGenericVertexAttributeMapping.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. =========================================================================*/ #include "vtkGenericVertexAttributeMapping.h" #include "vtkObjectFactory.h" #include <string> #include <vector> #include <vtksys/ios/sstream> class vtkGenericVertexAttributeMapping::vtkInternal { public: struct vtkInfo { std::string AttributeName; std::string ArrayName; int FieldAssociation; int Component; int TextureUnit; }; typedef std::vector<vtkInfo> VectorType; VectorType Mappings; }; vtkStandardNewMacro(vtkGenericVertexAttributeMapping); //---------------------------------------------------------------------------- vtkGenericVertexAttributeMapping::vtkGenericVertexAttributeMapping() { this->Internal = new vtkInternal(); } //---------------------------------------------------------------------------- vtkGenericVertexAttributeMapping::~vtkGenericVertexAttributeMapping() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::AddMapping( const char* attributeName, const char* arrayName, int fieldAssociation, int component) { if (!attributeName || !arrayName) { vtkErrorMacro("arrayName and attributeName cannot be null."); return; } if (this->RemoveMapping(attributeName)) { vtkWarningMacro("Replacing existsing mapping for attribute " << attributeName); } vtkInternal::vtkInfo info; info.AttributeName = attributeName; info.ArrayName = arrayName; info.FieldAssociation = fieldAssociation; info.Component = component; info.TextureUnit = -1; this->Internal->Mappings.push_back(info); } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::AddMapping( int unit, const char* arrayName, int fieldAssociation, int component) { vtksys_ios::ostringstream attributeName; attributeName << unit; if (this->RemoveMapping(attributeName.str().c_str())) { vtkWarningMacro("Replacing existsing mapping for attribute " << attributeName); } vtkInternal::vtkInfo info; info.AttributeName = attributeName.str().c_str(); info.ArrayName = arrayName; info.FieldAssociation = fieldAssociation; info.Component = component; info.TextureUnit = unit; this->Internal->Mappings.push_back(info); } //---------------------------------------------------------------------------- bool vtkGenericVertexAttributeMapping::RemoveMapping(const char* attributeName) { vtkInternal::VectorType::iterator iter; for (iter=this->Internal->Mappings.begin(); iter != this->Internal->Mappings.end(); ++iter) { if (iter->AttributeName == attributeName) { this->Internal->Mappings.erase(iter); return true; } } return false; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::RemoveAllMappings() { this->Internal->Mappings.clear(); } //---------------------------------------------------------------------------- unsigned int vtkGenericVertexAttributeMapping::GetNumberOfMappings() { return static_cast<unsigned int>(this->Internal->Mappings.size()); } //---------------------------------------------------------------------------- const char* vtkGenericVertexAttributeMapping::GetAttributeName(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].AttributeName.c_str(); } //---------------------------------------------------------------------------- const char* vtkGenericVertexAttributeMapping::GetArrayName(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].ArrayName.c_str(); } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetFieldAssociation(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].FieldAssociation; } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetComponent(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].Component; } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetTextureUnit(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].TextureUnit; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); vtkInternal::VectorType::iterator iter; for (iter=this->Internal->Mappings.begin(); iter != this->Internal->Mappings.end(); ++iter) { os << indent << "Mapping: " << iter->AttributeName.c_str() << ", " << iter->ArrayName.c_str() << ", " << iter->FieldAssociation << ", " << iter->Component << endl; } } <commit_msg>Fixed spelling in debug string.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkGenericVertexAttributeMapping.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. =========================================================================*/ #include "vtkGenericVertexAttributeMapping.h" #include "vtkObjectFactory.h" #include <string> #include <vector> #include <vtksys/ios/sstream> class vtkGenericVertexAttributeMapping::vtkInternal { public: struct vtkInfo { std::string AttributeName; std::string ArrayName; int FieldAssociation; int Component; int TextureUnit; }; typedef std::vector<vtkInfo> VectorType; VectorType Mappings; }; vtkStandardNewMacro(vtkGenericVertexAttributeMapping); //---------------------------------------------------------------------------- vtkGenericVertexAttributeMapping::vtkGenericVertexAttributeMapping() { this->Internal = new vtkInternal(); } //---------------------------------------------------------------------------- vtkGenericVertexAttributeMapping::~vtkGenericVertexAttributeMapping() { delete this->Internal; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::AddMapping( const char* attributeName, const char* arrayName, int fieldAssociation, int component) { if (!attributeName || !arrayName) { vtkErrorMacro("arrayName and attributeName cannot be null."); return; } if (this->RemoveMapping(attributeName)) { vtkWarningMacro("Replacing existing mapping for attribute " << attributeName); } vtkInternal::vtkInfo info; info.AttributeName = attributeName; info.ArrayName = arrayName; info.FieldAssociation = fieldAssociation; info.Component = component; info.TextureUnit = -1; this->Internal->Mappings.push_back(info); } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::AddMapping( int unit, const char* arrayName, int fieldAssociation, int component) { vtksys_ios::ostringstream attributeName; attributeName << unit; if (this->RemoveMapping(attributeName.str().c_str())) { vtkWarningMacro("Replacing existing mapping for attribute " << attributeName); } vtkInternal::vtkInfo info; info.AttributeName = attributeName.str().c_str(); info.ArrayName = arrayName; info.FieldAssociation = fieldAssociation; info.Component = component; info.TextureUnit = unit; this->Internal->Mappings.push_back(info); } //---------------------------------------------------------------------------- bool vtkGenericVertexAttributeMapping::RemoveMapping(const char* attributeName) { vtkInternal::VectorType::iterator iter; for (iter=this->Internal->Mappings.begin(); iter != this->Internal->Mappings.end(); ++iter) { if (iter->AttributeName == attributeName) { this->Internal->Mappings.erase(iter); return true; } } return false; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::RemoveAllMappings() { this->Internal->Mappings.clear(); } //---------------------------------------------------------------------------- unsigned int vtkGenericVertexAttributeMapping::GetNumberOfMappings() { return static_cast<unsigned int>(this->Internal->Mappings.size()); } //---------------------------------------------------------------------------- const char* vtkGenericVertexAttributeMapping::GetAttributeName(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].AttributeName.c_str(); } //---------------------------------------------------------------------------- const char* vtkGenericVertexAttributeMapping::GetArrayName(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].ArrayName.c_str(); } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetFieldAssociation(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].FieldAssociation; } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetComponent(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].Component; } //---------------------------------------------------------------------------- int vtkGenericVertexAttributeMapping::GetTextureUnit(unsigned int index) { if (index >= this->Internal->Mappings.size()) { vtkErrorMacro("Invalid index " << index); return 0; } return this->Internal->Mappings[index].TextureUnit; } //---------------------------------------------------------------------------- void vtkGenericVertexAttributeMapping::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); vtkInternal::VectorType::iterator iter; for (iter=this->Internal->Mappings.begin(); iter != this->Internal->Mappings.end(); ++iter) { os << indent << "Mapping: " << iter->AttributeName.c_str() << ", " << iter->ArrayName.c_str() << ", " << iter->FieldAssociation << ", " << iter->Component << endl; } } <|endoftext|>
<commit_before>// Copyright (c) 2008 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/compiler_specific.h" #include "base/lock.h" #include "base/platform_thread.h" #include "base/simple_thread.h" #include "base/thread_collision_warner.h" #include "testing/gtest/include/gtest/gtest.h" // '' : local class member function does not have a body MSVC_PUSH_DISABLE_WARNING(4822) namespace { // This is the asserter used with ThreadCollisionWarner instead of the default // DCheckAsserter. The method fail_state is used to know if a collision took // place. class AssertReporter : public base::AsserterBase { public: AssertReporter() : failed_(false) {} virtual void warn() { failed_ = true; } virtual ~AssertReporter() {} bool fail_state() const { return failed_; } void reset() { failed_ = false; } private: bool failed_; }; } // namespace TEST(ThreadCollisionTest, BookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK_THREAD_LOCKED(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK_THREAD_LOCKED(warner); EXPECT_FALSE(local_reporter->fail_state()); } } } TEST(ThreadCollisionTest, ScopedRecursiveBookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_RECURSIVE_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section again (allowed by DFAKE_SCOPED_RECURSIVE_LOCK) DFAKE_SCOPED_RECURSIVE_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } // Unpin section. // Check that section is not pinned { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } TEST(ThreadCollisionTest, ScopedBookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section again (not allowed by DFAKE_SCOPED_LOCK) DFAKE_SCOPED_LOCK(warner); #if !defined(NDEBUG) EXPECT_TRUE(local_reporter->fail_state()); #else EXPECT_FALSE(local_reporter->fail_state()); #endif // Reset the status of warner for further tests. local_reporter->reset(); } // Unpin section. } // Unpin section. { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } TEST(ThreadCollisionTest, MTBookCriticalSectionTest) { class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) #if !defined(NDEBUG) : push_pop_(asserter) { #else { delete asserter; #endif } void push(int value) { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); } int pop() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; class QueueUser : public base::DelegateSimpleThread::Delegate { public: explicit QueueUser(NonThreadSafeQueue& queue) : queue_(queue) {} virtual void Run() { queue_.push(0); queue_.pop(); } private: NonThreadSafeQueue& queue_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); QueueUser queue_user_a(queue); QueueUser queue_user_b(queue); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); #if !defined(NDEBUG) EXPECT_TRUE(local_reporter->fail_state()); #else EXPECT_FALSE(local_reporter->fail_state()); #endif } TEST(ThreadCollisionTest, MTScopedBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) #if !defined(NDEBUG) : push_pop_(asserter) { #else { delete asserter; #endif } void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_LOCK(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; class QueueUser : public base::DelegateSimpleThread::Delegate { public: explicit QueueUser(NonThreadSafeQueue& queue) : queue_(queue) {} virtual void Run() { queue_.push(0); queue_.pop(); } private: NonThreadSafeQueue& queue_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); QueueUser queue_user_a(queue); QueueUser queue_user_b(queue); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); #if !defined(NDEBUG) EXPECT_TRUE(local_reporter->fail_state()); #else EXPECT_FALSE(local_reporter->fail_state()); #endif } TEST(ThreadCollisionTest, MTSynchedScopedBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) #if !defined(NDEBUG) : push_pop_(asserter) { #else { delete asserter; #endif } void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_LOCK(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; // This time the QueueUser class protects the non thread safe queue with // a lock. class QueueUser : public base::DelegateSimpleThread::Delegate { public: QueueUser(NonThreadSafeQueue& queue, Lock& lock) : queue_(queue), lock_(lock) {} virtual void Run() { { AutoLock auto_lock(lock_); queue_.push(0); } { AutoLock auto_lock(lock_); queue_.pop(); } } private: NonThreadSafeQueue& queue_; Lock& lock_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); Lock lock; QueueUser queue_user_a(queue, lock); QueueUser queue_user_b(queue, lock); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_FALSE(local_reporter->fail_state()); } TEST(ThreadCollisionTest, MTSynchedScopedRecursiveBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) #if !defined(NDEBUG) : push_pop_(asserter) { #else { delete asserter; #endif } void push(int) { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); bar(); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); return 0; } void bar() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; // This time the QueueUser class protects the non thread safe queue with // a lock. class QueueUser : public base::DelegateSimpleThread::Delegate { public: QueueUser(NonThreadSafeQueue& queue, Lock& lock) : queue_(queue), lock_(lock) {} virtual void Run() { { AutoLock auto_lock(lock_); queue_.push(0); } { AutoLock auto_lock(lock_); queue_.bar(); } { AutoLock auto_lock(lock_); queue_.pop(); } } private: NonThreadSafeQueue& queue_; Lock& lock_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); Lock lock; QueueUser queue_user_a(queue, lock); QueueUser queue_user_b(queue, lock); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_FALSE(local_reporter->fail_state()); } <commit_msg>Reduce the amount of #ifdef. Review URL: http://codereview.chromium.org/18852<commit_after>// Copyright (c) 2008 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/compiler_specific.h" #include "base/lock.h" #include "base/platform_thread.h" #include "base/simple_thread.h" #include "base/thread_collision_warner.h" #include "testing/gtest/include/gtest/gtest.h" // '' : local class member function does not have a body MSVC_PUSH_DISABLE_WARNING(4822) #if defined(NDEBUG) // Would cause a memory leak otherwise. #undef DFAKE_MUTEX #define DFAKE_MUTEX(obj) scoped_ptr<base::AsserterBase> obj // In Release, we expect the AsserterBase::warn() to not happen. #define EXPECT_NDEBUG_FALSE_DEBUG_TRUE EXPECT_FALSE #else // In Debug, we expect the AsserterBase::warn() to happen. #define EXPECT_NDEBUG_FALSE_DEBUG_TRUE EXPECT_TRUE #endif namespace { // This is the asserter used with ThreadCollisionWarner instead of the default // DCheckAsserter. The method fail_state is used to know if a collision took // place. class AssertReporter : public base::AsserterBase { public: AssertReporter() : failed_(false) {} virtual void warn() { failed_ = true; } virtual ~AssertReporter() {} bool fail_state() const { return failed_; } void reset() { failed_ = false; } private: bool failed_; }; } // namespace TEST(ThreadCollisionTest, BookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK_THREAD_LOCKED(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK_THREAD_LOCKED(warner); EXPECT_FALSE(local_reporter->fail_state()); } } } TEST(ThreadCollisionTest, ScopedRecursiveBookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_RECURSIVE_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section again (allowed by DFAKE_SCOPED_RECURSIVE_LOCK) DFAKE_SCOPED_RECURSIVE_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } // Unpin section. // Check that section is not pinned { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } TEST(ThreadCollisionTest, ScopedBookCriticalSection) { AssertReporter* local_reporter = new AssertReporter(); base::ThreadCollisionWarner warner(local_reporter); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); { // Pin section again (not allowed by DFAKE_SCOPED_LOCK) DFAKE_SCOPED_LOCK(warner); EXPECT_NDEBUG_FALSE_DEBUG_TRUE(local_reporter->fail_state()); // Reset the status of warner for further tests. local_reporter->reset(); } // Unpin section. } // Unpin section. { // Pin section. DFAKE_SCOPED_LOCK(warner); EXPECT_FALSE(local_reporter->fail_state()); } // Unpin section. } TEST(ThreadCollisionTest, MTBookCriticalSectionTest) { class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) : push_pop_(asserter) { } void push(int value) { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); } int pop() { DFAKE_SCOPED_LOCK_THREAD_LOCKED(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; class QueueUser : public base::DelegateSimpleThread::Delegate { public: explicit QueueUser(NonThreadSafeQueue& queue) : queue_(queue) {} virtual void Run() { queue_.push(0); queue_.pop(); } private: NonThreadSafeQueue& queue_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); QueueUser queue_user_a(queue); QueueUser queue_user_b(queue); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_NDEBUG_FALSE_DEBUG_TRUE(local_reporter->fail_state()); } TEST(ThreadCollisionTest, MTScopedBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) : push_pop_(asserter) { } void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_LOCK(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; class QueueUser : public base::DelegateSimpleThread::Delegate { public: explicit QueueUser(NonThreadSafeQueue& queue) : queue_(queue) {} virtual void Run() { queue_.push(0); queue_.pop(); } private: NonThreadSafeQueue& queue_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); QueueUser queue_user_a(queue); QueueUser queue_user_b(queue); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_NDEBUG_FALSE_DEBUG_TRUE(local_reporter->fail_state()); } TEST(ThreadCollisionTest, MTSynchedScopedBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) : push_pop_(asserter) { } void push(int value) { DFAKE_SCOPED_LOCK(push_pop_); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_LOCK(push_pop_); return 0; } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; // This time the QueueUser class protects the non thread safe queue with // a lock. class QueueUser : public base::DelegateSimpleThread::Delegate { public: QueueUser(NonThreadSafeQueue& queue, Lock& lock) : queue_(queue), lock_(lock) {} virtual void Run() { { AutoLock auto_lock(lock_); queue_.push(0); } { AutoLock auto_lock(lock_); queue_.pop(); } } private: NonThreadSafeQueue& queue_; Lock& lock_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); Lock lock; QueueUser queue_user_a(queue, lock); QueueUser queue_user_b(queue, lock); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_FALSE(local_reporter->fail_state()); } TEST(ThreadCollisionTest, MTSynchedScopedRecursiveBookCriticalSectionTest) { // Queue with a 5 seconds push execution time, hopefuly the two used threads // in the test will enter the push at same time. class NonThreadSafeQueue { public: explicit NonThreadSafeQueue(base::AsserterBase* asserter) : push_pop_(asserter) { } void push(int) { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); bar(); PlatformThread::Sleep(5000); } int pop() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); return 0; } void bar() { DFAKE_SCOPED_RECURSIVE_LOCK(push_pop_); } private: DFAKE_MUTEX(push_pop_); DISALLOW_COPY_AND_ASSIGN(NonThreadSafeQueue); }; // This time the QueueUser class protects the non thread safe queue with // a lock. class QueueUser : public base::DelegateSimpleThread::Delegate { public: QueueUser(NonThreadSafeQueue& queue, Lock& lock) : queue_(queue), lock_(lock) {} virtual void Run() { { AutoLock auto_lock(lock_); queue_.push(0); } { AutoLock auto_lock(lock_); queue_.bar(); } { AutoLock auto_lock(lock_); queue_.pop(); } } private: NonThreadSafeQueue& queue_; Lock& lock_; }; AssertReporter* local_reporter = new AssertReporter(); NonThreadSafeQueue queue(local_reporter); Lock lock; QueueUser queue_user_a(queue, lock); QueueUser queue_user_b(queue, lock); base::DelegateSimpleThread thread_a(&queue_user_a, "queue_user_thread_a"); base::DelegateSimpleThread thread_b(&queue_user_b, "queue_user_thread_b"); thread_a.Start(); thread_b.Start(); thread_a.Join(); thread_b.Join(); EXPECT_FALSE(local_reporter->fail_state()); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/interface/module.h" #include "webrtc/modules/utility/source/process_thread_impl.h" #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; class MockModule : public Module { public: MOCK_METHOD0(TimeUntilNextProcess, int64_t()); MOCK_METHOD0(Process, int32_t()); }; ACTION_P(SetEvent, event) { event->Set(); } ACTION_P(Increment, counter) { ++(*counter); } ACTION_P(SetTimestamp, ptr) { *ptr = TickTime::MillisecondTimestamp(); } TEST(ProcessThreadImpl, StartStop) { ProcessThreadImpl thread; EXPECT_EQ(0, thread.Start()); EXPECT_EQ(0, thread.Stop()); } TEST(ProcessThreadImpl, MultipleStartStop) { ProcessThreadImpl thread; for (int i = 0; i < 5; ++i) { EXPECT_EQ(0, thread.Start()); EXPECT_EQ(0, thread.Stop()); } } // Verifies that we get at least call back to Process() on the worker thread. TEST(ProcessThreadImpl, ProcessCall) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); ASSERT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventSignaled, event->Wait(100)); EXPECT_EQ(0, thread.Stop()); } // Same as ProcessCall except the module is registered before the // call to Start(). TEST(ProcessThreadImpl, ProcessCall2) { ProcessThreadImpl thread; rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); ASSERT_EQ(0, thread.RegisterModule(&module)); ASSERT_EQ(thread.Start(), 0); EXPECT_EQ(kEventSignaled, event->Wait(100)); EXPECT_EQ(thread.Stop(), 0); } // Tests setting up a module for callbacks and then unregister that module. // After unregistration, we should not receive any further callbacks. TEST(ProcessThreadImpl, Deregister) { ProcessThreadImpl thread; rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); int process_count = 0; MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Increment(&process_count), Return(0))) .WillRepeatedly(DoAll(Increment(&process_count), Return(0))); ASSERT_EQ(0, thread.RegisterModule(&module)); ASSERT_EQ(0, thread.Start()); EXPECT_EQ(kEventSignaled, event->Wait(100)); ASSERT_EQ(0, thread.DeRegisterModule(&module)); EXPECT_GE(process_count, 1); int count_after_deregister = process_count; // We shouldn't get any more callbacks. EXPECT_EQ(kEventTimeout, event->Wait(20)); EXPECT_EQ(count_after_deregister, process_count); EXPECT_EQ(0, thread.Stop()); } // Helper function for testing receiving a callback after a certain amount of // time. There's some variance of timing built into it to reduce chance of // flakiness on bots. void ProcessCallAfterAFewMs(int64_t milliseconds) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; int64_t start_time = 0; int64_t called_time = 0; EXPECT_CALL(module, TimeUntilNextProcess()) .WillOnce(DoAll(SetTimestamp(&start_time), Return(milliseconds))) .WillRepeatedly(Return(milliseconds)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetTimestamp(&called_time), SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); EXPECT_EQ(0, thread.RegisterModule(&module)); // Add a buffer of 50ms due to slowness of some trybots // (e.g. win_drmemory_light) EXPECT_EQ(kEventSignaled, event->Wait(milliseconds + 50)); ASSERT_EQ(0, thread.Stop()); ASSERT_GT(start_time, 0); ASSERT_GT(called_time, 0); // Use >= instead of > since due to rounding and timer accuracy (or lack // thereof), can make the test run in "0"ms time. EXPECT_GE(called_time, start_time); // Check for an acceptable range. uint32 diff = called_time - start_time; EXPECT_GE(diff, milliseconds - 15); EXPECT_LT(diff, milliseconds + 15); } TEST(ProcessThreadImpl, ProcessCallAfter5ms) { ProcessCallAfterAFewMs(5); } TEST(ProcessThreadImpl, ProcessCallAfter50ms) { ProcessCallAfterAFewMs(50); } TEST(ProcessThreadImpl, ProcessCallAfter200ms) { ProcessCallAfterAFewMs(200); } // Runs callbacks with the goal of getting up to 50 callbacks within a second // (on average 1 callback every 20ms). On real hardware, we're usually pretty // close to that, but the test bots that run on virtual machines, will // typically be in the range 30-40 callbacks. TEST(ProcessThreadImpl, MANUAL_Process50Times) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; int callback_count = 0; // Ask for a callback after 20ms. EXPECT_CALL(module, TimeUntilNextProcess()) .WillRepeatedly(Return(20)); EXPECT_CALL(module, Process()) .WillRepeatedly(DoAll(Increment(&callback_count), Return(0))); EXPECT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventTimeout, event->Wait(1000)); ASSERT_EQ(0, thread.Stop()); printf("Callback count: %i\n", callback_count); // Check that we got called back up to 50 times. // Some of the try bots run on slow virtual machines, so the lower bound // is much more relaxed to avoid flakiness. EXPECT_GE(callback_count, 25); EXPECT_LE(callback_count, 50); } // Tests that we can wake up the worker thread to give us a callback right // away when we know the thread is sleeping. TEST(ProcessThreadImpl, WakeUp) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> started(EventWrapper::Create()); rtc::scoped_ptr<EventWrapper> called(EventWrapper::Create()); MockModule module; int64_t start_time = 0; int64_t called_time = 0; // Ask for a callback after 1000ms first, then 0ms. EXPECT_CALL(module, TimeUntilNextProcess()) .WillOnce(DoAll(SetTimestamp(&start_time), SetEvent(started.get()), Return(1000))) .WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetTimestamp(&called_time), SetEvent(called.get()), Return(0))) .WillRepeatedly(Return(0)); EXPECT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventSignaled, started->Wait(100)); thread.WakeUp(&module); EXPECT_EQ(kEventSignaled, called->Wait(100)); ASSERT_EQ(0, thread.Stop()); ASSERT_GT(start_time, 0); ASSERT_GT(called_time, 0); EXPECT_GE(called_time, start_time); uint32 diff = called_time - start_time; // We should have been called back much quicker than 1sec. EXPECT_LE(diff, 100u); } } // namespace webrtc <commit_msg>Disable ProcessThread tests that are dependent on timing. Some of the bots are too slow for the tests to make much sense as they are.<commit_after>/* * Copyright (c) 2012 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "webrtc/modules/interface/module.h" #include "webrtc/modules/utility/source/process_thread_impl.h" #include "webrtc/system_wrappers/interface/tick_util.h" namespace webrtc { using ::testing::_; using ::testing::DoAll; using ::testing::InSequence; using ::testing::Invoke; using ::testing::Return; using ::testing::SetArgPointee; class MockModule : public Module { public: MOCK_METHOD0(TimeUntilNextProcess, int64_t()); MOCK_METHOD0(Process, int32_t()); }; ACTION_P(SetEvent, event) { event->Set(); } ACTION_P(Increment, counter) { ++(*counter); } ACTION_P(SetTimestamp, ptr) { *ptr = TickTime::MillisecondTimestamp(); } TEST(ProcessThreadImpl, StartStop) { ProcessThreadImpl thread; EXPECT_EQ(0, thread.Start()); EXPECT_EQ(0, thread.Stop()); } TEST(ProcessThreadImpl, MultipleStartStop) { ProcessThreadImpl thread; for (int i = 0; i < 5; ++i) { EXPECT_EQ(0, thread.Start()); EXPECT_EQ(0, thread.Stop()); } } // Verifies that we get at least call back to Process() on the worker thread. TEST(ProcessThreadImpl, ProcessCall) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); ASSERT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventSignaled, event->Wait(100)); EXPECT_EQ(0, thread.Stop()); } // Same as ProcessCall except the module is registered before the // call to Start(). TEST(ProcessThreadImpl, ProcessCall2) { ProcessThreadImpl thread; rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); ASSERT_EQ(0, thread.RegisterModule(&module)); ASSERT_EQ(thread.Start(), 0); EXPECT_EQ(kEventSignaled, event->Wait(100)); EXPECT_EQ(thread.Stop(), 0); } // Tests setting up a module for callbacks and then unregister that module. // After unregistration, we should not receive any further callbacks. TEST(ProcessThreadImpl, Deregister) { ProcessThreadImpl thread; rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); int process_count = 0; MockModule module; EXPECT_CALL(module, TimeUntilNextProcess()).WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetEvent(event.get()), Increment(&process_count), Return(0))) .WillRepeatedly(DoAll(Increment(&process_count), Return(0))); ASSERT_EQ(0, thread.RegisterModule(&module)); ASSERT_EQ(0, thread.Start()); EXPECT_EQ(kEventSignaled, event->Wait(100)); ASSERT_EQ(0, thread.DeRegisterModule(&module)); EXPECT_GE(process_count, 1); int count_after_deregister = process_count; // We shouldn't get any more callbacks. EXPECT_EQ(kEventTimeout, event->Wait(20)); EXPECT_EQ(count_after_deregister, process_count); EXPECT_EQ(0, thread.Stop()); } // Helper function for testing receiving a callback after a certain amount of // time. There's some variance of timing built into it to reduce chance of // flakiness on bots. void ProcessCallAfterAFewMs(int64_t milliseconds) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; int64_t start_time = 0; int64_t called_time = 0; EXPECT_CALL(module, TimeUntilNextProcess()) .WillOnce(DoAll(SetTimestamp(&start_time), Return(milliseconds))) .WillRepeatedly(Return(milliseconds)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetTimestamp(&called_time), SetEvent(event.get()), Return(0))) .WillRepeatedly(Return(0)); EXPECT_EQ(0, thread.RegisterModule(&module)); // Add a buffer of 50ms due to slowness of some trybots // (e.g. win_drmemory_light) EXPECT_EQ(kEventSignaled, event->Wait(milliseconds + 50)); ASSERT_EQ(0, thread.Stop()); ASSERT_GT(start_time, 0); ASSERT_GT(called_time, 0); // Use >= instead of > since due to rounding and timer accuracy (or lack // thereof), can make the test run in "0"ms time. EXPECT_GE(called_time, start_time); // Check for an acceptable range. uint32 diff = called_time - start_time; EXPECT_GE(diff, milliseconds - 15); EXPECT_LT(diff, milliseconds + 15); } // DISABLED for now since the virtual build bots are too slow :( // TODO(tommi): Fix. TEST(ProcessThreadImpl, DISABLED_ProcessCallAfter5ms) { ProcessCallAfterAFewMs(5); } // DISABLED for now since the virtual build bots are too slow :( // TODO(tommi): Fix. TEST(ProcessThreadImpl, DISABLED_ProcessCallAfter50ms) { ProcessCallAfterAFewMs(50); } // DISABLED for now since the virtual build bots are too slow :( // TODO(tommi): Fix. TEST(ProcessThreadImpl, DISABLED_ProcessCallAfter200ms) { ProcessCallAfterAFewMs(200); } // Runs callbacks with the goal of getting up to 50 callbacks within a second // (on average 1 callback every 20ms). On real hardware, we're usually pretty // close to that, but the test bots that run on virtual machines, will // typically be in the range 30-40 callbacks. // DISABLED for now since this can take up to 2 seconds to run on the slowest // build bots. // TODO(tommi): Fix. TEST(ProcessThreadImpl, DISABLED_Process50Times) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> event(EventWrapper::Create()); MockModule module; int callback_count = 0; // Ask for a callback after 20ms. EXPECT_CALL(module, TimeUntilNextProcess()) .WillRepeatedly(Return(20)); EXPECT_CALL(module, Process()) .WillRepeatedly(DoAll(Increment(&callback_count), Return(0))); EXPECT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventTimeout, event->Wait(1000)); ASSERT_EQ(0, thread.Stop()); printf("Callback count: %i\n", callback_count); // Check that we got called back up to 50 times. // Some of the try bots run on slow virtual machines, so the lower bound // is much more relaxed to avoid flakiness. EXPECT_GE(callback_count, 25); EXPECT_LE(callback_count, 50); } // Tests that we can wake up the worker thread to give us a callback right // away when we know the thread is sleeping. TEST(ProcessThreadImpl, WakeUp) { ProcessThreadImpl thread; ASSERT_EQ(0, thread.Start()); rtc::scoped_ptr<EventWrapper> started(EventWrapper::Create()); rtc::scoped_ptr<EventWrapper> called(EventWrapper::Create()); MockModule module; int64_t start_time = 0; int64_t called_time = 0; // Ask for a callback after 1000ms first, then 0ms. EXPECT_CALL(module, TimeUntilNextProcess()) .WillOnce(DoAll(SetTimestamp(&start_time), SetEvent(started.get()), Return(1000))) .WillRepeatedly(Return(0)); EXPECT_CALL(module, Process()) .WillOnce(DoAll(SetTimestamp(&called_time), SetEvent(called.get()), Return(0))) .WillRepeatedly(Return(0)); EXPECT_EQ(0, thread.RegisterModule(&module)); EXPECT_EQ(kEventSignaled, started->Wait(100)); thread.WakeUp(&module); EXPECT_EQ(kEventSignaled, called->Wait(100)); ASSERT_EQ(0, thread.Stop()); ASSERT_GT(start_time, 0); ASSERT_GT(called_time, 0); EXPECT_GE(called_time, start_time); uint32 diff = called_time - start_time; // We should have been called back much quicker than 1sec. EXPECT_LE(diff, 100u); } } // namespace webrtc <|endoftext|>
<commit_before> #include "../../Flare.h" #include "FlareShipStatus.h" #include "../../Player/FlareMenuManager.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8, 8, 32, 8)) [ SNew(SHorizontalBox) // Power icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Propulsion) ] // RCS icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_RCS) ] // Weapon icon + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(WeaponIndicator, SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Weapon) ] // Health + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(50) .VAlign(VAlign_Center) [ SNew(SProgressBar) .Percent(this, &SFlareShipStatus::GetGlobalHealth) .BorderPadding( FVector2D(0,0)) .Style(&Theme.ProgressBarStyle) ] ] ]; SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(UFlareSimulatedSpacecraft* Target) { TargetShip = Target; if (TargetShip) { SetVisibility(EVisibility::Visible); if (TargetShip->IsMilitary()) { WeaponIndicator->SetVisibility(EVisibility::Visible); } else { WeaponIndicator->SetVisibility(EVisibility::Hidden); } } else { SetVisibility(EVisibility::Hidden); } } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareShipStatus::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager && TargetShip) { FText Info; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Station-specific damage & info if (TargetShip->IsStation()) { // Structure Info = FText::Format(LOCTEXT("HealthInfoFormat", "Structure : {0}{1}%"), Info, FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetGlobalHealth()))); } // Ship-specific damage else { if (DamageSystem->IsStranded()) { Info = FText::Format(LOCTEXT("ShipStrandedFormat", "{0}This ship is stranded and can't exit the sector !\n"), Info); } if (DamageSystem->IsUncontrollable()) { Info = FText::Format(LOCTEXT("ShipUncontrollableFormat", "{0}This ship is uncontrollable and can't move in the local space !\n"), Info); } if (TargetShip->IsMilitary() && DamageSystem->IsDisarmed()) { Info = FText::Format(LOCTEXT("ShipDisarmedFormat", "{0}This ship is disarmed and unable to fight back !\n"), Info); } // Subsystems for (int32 Index = EFlareSubsystem::SYS_None + 1; Index <= EFlareSubsystem::SYS_Weapon; Index++) { if (Index == EFlareSubsystem::SYS_Weapon && !TargetShip->IsMilitary()) { continue; } Info = FText::Format(LOCTEXT("HealthInfoFormat", "{0}\n{1} : {2}%"), Info, UFlareSimulatedSpacecraftDamageSystem::GetSubsystemName((EFlareSubsystem::Type)Index), FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetSubsystemHealth((EFlareSubsystem::Type)Index, false)))); } } MenuManager->ShowTooltip(this, LOCTEXT("Status", "SPACECRAFT STATUS"), Info); } } void SFlareShipStatus::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } TOptional<float> SFlareShipStatus::GetGlobalHealth() const { if (TargetShip) { return TargetShip->GetDamageSystem()->GetGlobalHealth(); } else { return 0; } } FSlateColor SFlareShipStatus::GetIconColor(EFlareSubsystem::Type Type) const { FLinearColor Result = FLinearColor::Black; Result.A = 0.0f; // Ignore stations if (TargetShip && !TargetShip->IsStation()) { bool IsIncapacitated = false; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Only those are used (see above) switch (Type) { case EFlareSubsystem::SYS_Propulsion: IsIncapacitated = DamageSystem->IsStranded(); break; case EFlareSubsystem::SYS_RCS: IsIncapacitated = DamageSystem->IsUncontrollable(); break; case EFlareSubsystem::SYS_Weapon: IsIncapacitated = DamageSystem->IsDisarmed(); break; default: break; } // Show in red when disabled if (IsIncapacitated) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); Result = Theme.DamageColor; Result.A = 1.0f; } } return Result; } #undef LOCTEXT_NAMESPACE <commit_msg>#519 Fix spacecraft status format<commit_after> #include "../../Flare.h" #include "FlareShipStatus.h" #include "../../Player/FlareMenuManager.h" #define LOCTEXT_NAMESPACE "FlareShipStatus" /*---------------------------------------------------- Construct ----------------------------------------------------*/ void SFlareShipStatus::Construct(const FArguments& InArgs) { TargetShip = InArgs._Ship; const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); ChildSlot .VAlign(VAlign_Fill) .HAlign(HAlign_Fill) .Padding(FMargin(8, 8, 32, 8)) [ SNew(SHorizontalBox) // Power icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("Propulsion")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Propulsion) ] // RCS icon + SHorizontalBox::Slot() .AutoWidth() [ SNew(SImage) .Image(FFlareStyleSet::GetIcon("RCS")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_RCS) ] // Weapon icon + SHorizontalBox::Slot() .AutoWidth() [ SAssignNew(WeaponIndicator, SImage) .Image(FFlareStyleSet::GetIcon("Shell")) .ColorAndOpacity(this, &SFlareShipStatus::GetIconColor, EFlareSubsystem::SYS_Weapon) ] // Health + SHorizontalBox::Slot() .AutoWidth() [ SNew(SBox) .WidthOverride(50) .VAlign(VAlign_Center) [ SNew(SProgressBar) .Percent(this, &SFlareShipStatus::GetGlobalHealth) .BorderPadding( FVector2D(0,0)) .Style(&Theme.ProgressBarStyle) ] ] ]; SetVisibility(EVisibility::Hidden); } /*---------------------------------------------------- Interaction ----------------------------------------------------*/ void SFlareShipStatus::SetTargetShip(UFlareSimulatedSpacecraft* Target) { TargetShip = Target; if (TargetShip) { SetVisibility(EVisibility::Visible); if (TargetShip->IsMilitary()) { WeaponIndicator->SetVisibility(EVisibility::Visible); } else { WeaponIndicator->SetVisibility(EVisibility::Hidden); } } else { SetVisibility(EVisibility::Hidden); } } /*---------------------------------------------------- Callbacks ----------------------------------------------------*/ void SFlareShipStatus::OnMouseEnter(const FGeometry& MyGeometry, const FPointerEvent& MouseEvent) { SWidget::OnMouseEnter(MyGeometry, MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager && TargetShip) { FText Info; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Station-specific damage & info if (TargetShip->IsStation()) { // Structure Info = FText::Format(LOCTEXT("StationHealthInfoFormat", "Structure : {0}%"), FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetGlobalHealth()))); } // Ship-specific damage else { if (DamageSystem->IsStranded()) { Info = FText::Format(LOCTEXT("ShipStrandedFormat", "{0}This ship is stranded and can't exit the sector !\n"), Info); } if (DamageSystem->IsUncontrollable()) { Info = FText::Format(LOCTEXT("ShipUncontrollableFormat", "{0}This ship is uncontrollable and can't move in the local space !\n"), Info); } if (TargetShip->IsMilitary() && DamageSystem->IsDisarmed()) { Info = FText::Format(LOCTEXT("ShipDisarmedFormat", "{0}This ship is disarmed and unable to fight back !\n"), Info); } // Subsystems for (int32 Index = EFlareSubsystem::SYS_None + 1; Index <= EFlareSubsystem::SYS_Weapon; Index++) { if (Index == EFlareSubsystem::SYS_Weapon && !TargetShip->IsMilitary()) { continue; } Info = FText::Format(LOCTEXT("ShipHealthInfoFormat", "{0}\n{1} : {2}%"), Info, UFlareSimulatedSpacecraftDamageSystem::GetSubsystemName((EFlareSubsystem::Type)Index), FText::AsNumber(FMath::RoundToInt(100 * DamageSystem->GetSubsystemHealth((EFlareSubsystem::Type)Index, false)))); } } MenuManager->ShowTooltip(this, LOCTEXT("Status", "SPACECRAFT STATUS"), Info); } } void SFlareShipStatus::OnMouseLeave(const FPointerEvent& MouseEvent) { SWidget::OnMouseLeave(MouseEvent); AFlareMenuManager* MenuManager = AFlareMenuManager::GetSingleton(); if (MenuManager) { MenuManager->HideTooltip(this); } } TOptional<float> SFlareShipStatus::GetGlobalHealth() const { if (TargetShip) { return TargetShip->GetDamageSystem()->GetGlobalHealth(); } else { return 0; } } FSlateColor SFlareShipStatus::GetIconColor(EFlareSubsystem::Type Type) const { FLinearColor Result = FLinearColor::Black; Result.A = 0.0f; // Ignore stations if (TargetShip && !TargetShip->IsStation()) { bool IsIncapacitated = false; UFlareSimulatedSpacecraftDamageSystem* DamageSystem = TargetShip->GetDamageSystem(); // Only those are used (see above) switch (Type) { case EFlareSubsystem::SYS_Propulsion: IsIncapacitated = DamageSystem->IsStranded(); break; case EFlareSubsystem::SYS_RCS: IsIncapacitated = DamageSystem->IsUncontrollable(); break; case EFlareSubsystem::SYS_Weapon: IsIncapacitated = DamageSystem->IsDisarmed(); break; default: break; } // Show in red when disabled if (IsIncapacitated) { const FFlareStyleCatalog& Theme = FFlareStyleSet::GetDefaultTheme(); Result = Theme.DamageColor; Result.A = 1.0f; } } return Result; } #undef LOCTEXT_NAMESPACE <|endoftext|>
<commit_before>#include "JPetParamManager.h" #include <TFile.h> #include <boost/property_tree/xml_parser.hpp> using namespace std; JPetParamManager::JPetParamManager(): fBank(0) { /* */ } JPetParamManager::~JPetParamManager() { if (fBank) { delete fBank; fBank = 0; } } /// @param DBConfigFile configuration file with the database connection settings JPetParamManager::JPetParamManager(const char* dBConfigFile): fDBParamGetter(dBConfigFile), fBank(0) { } void JPetParamManager::getParametersFromDatabase(const int run) { if (fBank) { delete fBank; fBank = 0; } fBank = fDBParamGetter.generateParamBank(run); } bool JPetParamManager::saveParametersToFile(const char* filename) { TFile file(filename, "UPDATE"); if (!file.IsOpen()) { ERROR("Could not write to file."); return false; } file.cd(); file.WriteObject(fBank, "ParamBank"); return true; } bool JPetParamManager::saveParametersToFile(JPetWriter * writer) { if (!writer->isOpen()) { ERROR("Could not write parameters to file. The provided JPetWriter is closed."); return false; } writer->writeObject(fBank, "ParamBank"); return true; } bool JPetParamManager::readParametersFromFile(JPetReader * reader) { if (!reader->isOpen()) { ERROR("Cannot read parameters from file. The provided JPetReader is closed."); return false; } fBank = static_cast<JPetParamBank*>(reader->getObject("ParamBank")); if (!fBank) return false; return true; } bool JPetParamManager::readParametersFromFile(const char* filename) { TFile file(filename, "READ"); if (!file.IsOpen()) { ERROR("Could not read from file."); return false; } fBank = static_cast<JPetParamBank*>(file.Get("ParamBank")); if (!fBank) return false; return true; } void JPetParamManager::clearParameters() { assert(fBank); fBank->clear(); } void JPetParamManager::createXMLFile(const std::string &channelDataFileName, int channelOffset, int numberOfChannels) { using boost::property_tree::ptree; ptree pt; std::string debug = "OFF"; std::string dataSourceType = "TRB3_S"; std::string dataSourceTrbNetAddress = "8000"; std::string dataSourceHubAddress = "8000"; std::string dataSourceReferenceChannel = "0"; std::string dataSourceCorrectionFile = "raw"; pt.put("READOUT.DEBUG", debug); pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType); pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress); pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress); pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel); pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile); ptree &externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", ""); ptree &internalNode = externalNode.add("MODULE", ""); internalNode.put("TYPE", "LATTICE_TDC"); internalNode.put("TRBNET_ADDRESS", "e000"); internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels); internalNode.put("CHANNEL_OFFSET", channelOffset); internalNode.put("RESOLUTION", "100"); internalNode.put("MEASUREMENT_TYPE", "TDC"); write_xml(channelDataFileName, pt); } void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id) { fDBParamGetter.fillTOMBChannels(p_run_id, *fBank);//private (add friend) int TOMBChannelsSize = fBank->getTOMBChannelsSize(); int channelOffset = 0; int numberOfChannels = 0; if(TOMBChannelsSize) { for(unsigned int i=0;i<TOMBChannelsSize;++i) { if(i==0) { std::string description = fBank->getTOMBChannel(i).getDescription(); channelOffset = fDBParamGetter.getTOMBChannelFromDescription(description);//private (add friend) } ++numberOfChannels; } createXMLFile("out.xml", channelOffset, numberOfChannels); return; } ERROR("TOMBChannelsSize is equal to zero."); } <commit_msg>Change xml configuration file name.<commit_after>#include "JPetParamManager.h" #include <TFile.h> #include <boost/property_tree/xml_parser.hpp> using namespace std; JPetParamManager::JPetParamManager(): fBank(0) { /* */ } JPetParamManager::~JPetParamManager() { if (fBank) { delete fBank; fBank = 0; } } /// @param DBConfigFile configuration file with the database connection settings JPetParamManager::JPetParamManager(const char* dBConfigFile): fDBParamGetter(dBConfigFile), fBank(0) { } void JPetParamManager::getParametersFromDatabase(const int run) { if (fBank) { delete fBank; fBank = 0; } fBank = fDBParamGetter.generateParamBank(run); } bool JPetParamManager::saveParametersToFile(const char* filename) { TFile file(filename, "UPDATE"); if (!file.IsOpen()) { ERROR("Could not write to file."); return false; } file.cd(); file.WriteObject(fBank, "ParamBank"); return true; } bool JPetParamManager::saveParametersToFile(JPetWriter * writer) { if (!writer->isOpen()) { ERROR("Could not write parameters to file. The provided JPetWriter is closed."); return false; } writer->writeObject(fBank, "ParamBank"); return true; } bool JPetParamManager::readParametersFromFile(JPetReader * reader) { if (!reader->isOpen()) { ERROR("Cannot read parameters from file. The provided JPetReader is closed."); return false; } fBank = static_cast<JPetParamBank*>(reader->getObject("ParamBank")); if (!fBank) return false; return true; } bool JPetParamManager::readParametersFromFile(const char* filename) { TFile file(filename, "READ"); if (!file.IsOpen()) { ERROR("Could not read from file."); return false; } fBank = static_cast<JPetParamBank*>(file.Get("ParamBank")); if (!fBank) return false; return true; } void JPetParamManager::clearParameters() { assert(fBank); fBank->clear(); } void JPetParamManager::createXMLFile(const std::string &channelDataFileName, int channelOffset, int numberOfChannels) { using boost::property_tree::ptree; ptree pt; std::string debug = "OFF"; std::string dataSourceType = "TRB3_S"; std::string dataSourceTrbNetAddress = "8000"; std::string dataSourceHubAddress = "8000"; std::string dataSourceReferenceChannel = "0"; std::string dataSourceCorrectionFile = "raw"; pt.put("READOUT.DEBUG", debug); pt.put("READOUT.DATA_SOURCE.TYPE", dataSourceType); pt.put("READOUT.DATA_SOURCE.TRBNET_ADDRESS", dataSourceTrbNetAddress); pt.put("READOUT.DATA_SOURCE.HUB_ADDRESS", dataSourceHubAddress); pt.put("READOUT.DATA_SOURCE.REFERENCE_CHANNEL", dataSourceReferenceChannel); pt.put("READOUT.DATA_SOURCE.CORRECTION_FILE", dataSourceCorrectionFile); ptree &externalNode = pt.add("READOUT.DATA_SOURCE.MODULES", ""); ptree &internalNode = externalNode.add("MODULE", ""); internalNode.put("TYPE", "LATTICE_TDC"); internalNode.put("TRBNET_ADDRESS", "e000"); internalNode.put("NUMBER_OF_CHANNELS", numberOfChannels); internalNode.put("CHANNEL_OFFSET", channelOffset); internalNode.put("RESOLUTION", "100"); internalNode.put("MEASUREMENT_TYPE", "TDC"); write_xml(channelDataFileName, pt); } void JPetParamManager::getTOMBDataAndCreateXMLFile(const int p_run_id) { fDBParamGetter.fillTOMBChannels(p_run_id, *fBank);//private (add friend) int TOMBChannelsSize = fBank->getTOMBChannelsSize(); int channelOffset = 0; int numberOfChannels = 0; if(TOMBChannelsSize) { for(unsigned int i=0;i<TOMBChannelsSize;++i) { if(i==0) { std::string description = fBank->getTOMBChannel(i).getDescription(); channelOffset = fDBParamGetter.getTOMBChannelFromDescription(description);//private (add friend) } ++numberOfChannels; } createXMLFile("conf.xml", channelOffset, numberOfChannels); return; } ERROR("TOMBChannelsSize is equal to zero."); } <|endoftext|>
<commit_before>/** * @file * @brief Implementation of Geant4 deposition module * @remarks Based on code from Mathieu Benoit * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "DepositionGeant4Module.hpp" #include <limits> #include <string> #include <utility> #include <G4EmParameters.hh> #include <G4HadronicProcessStore.hh> #include <G4LogicalVolume.hh> #include <G4PhysListFactory.hh> #include <G4RadioactiveDecayPhysics.hh> #include <G4RunManager.hh> #include <G4StepLimiterPhysics.hh> #include <G4UImanager.hh> #include <G4UserLimits.hh> #include "G4FieldManager.hh" #include "G4TransportationManager.hh" #include "G4UniformMagField.hh" #include "core/config/exceptions.h" #include "core/geometry/GeometryManager.hpp" #include "core/module/exceptions.h" #include "core/utils/log.h" #include "objects/DepositedCharge.hpp" #include "tools/ROOT.h" #include "tools/geant4.h" #include "GeneratorActionG4.hpp" #include "SensitiveDetectorActionG4.hpp" #include "SetTrackInfoUserHookG4.hpp" #define G4_NUM_SEEDS 10 using namespace allpix; /** * Includes the particle source point to the geometry using \ref GeometryManager::addPoint. */ DepositionGeant4Module::DepositionGeant4Module(Configuration& config, Messenger* messenger, GeometryManager* geo_manager) : Module(config), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1), run_manager_g4_(nullptr) { // Create user limits for maximum step length in the sensor user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um"))); // Set default physics list config_.setDefault("physics_list", "FTFP_BERT_LIV"); config_.setDefault("source_type", "beam"); config_.setDefault<bool>("output_plots", false); config_.setDefault<int>("output_plots_scale", Units::get(100, "ke")); // Set alias for support of old particle source definition config_.setAlias("source_position", "beam_position"); config_.setAlias("source_energy", "beam_energy"); config_.setAlias("source_energy_spread", "beam_energy_spread"); // Add the particle source position to the geometry geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("source_position")); } /** * Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager. */ void DepositionGeant4Module::init() { // Load the G4 run manager (which is owned by the geometry builder) run_manager_g4_ = G4RunManager::GetRunManager(); if(run_manager_g4_ == nullptr) { throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder"); } // Suppress all output from G4 SUPPRESS_STREAM(G4cout); // Get UI manager for sending commands G4UImanager* ui_g4 = G4UImanager::GetUIpointer(); // Apply optional PAI model if(config_.get<bool>("enable_pai", false)) { LOG(TRACE) << "Enabling PAI model on all detectors"; G4EmParameters::Instance(); for(auto& detector : geo_manager_->getDetectors()) { // Get logical volume auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Create region G4Region* region = new G4Region(detector->getName() + "_sensor_region"); region->AddRootLogicalVolume(logical_volume.get()); auto pai_model = config_.get<std::string>("pai_model", "pai"); auto lcase_model = pai_model; std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower); if(lcase_model == "pai") { pai_model = "PAI"; } else if(lcase_model == "paiphoton") { pai_model = "PAIphoton"; } else { throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'"); } ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model); } } // Find the physics list G4PhysListFactory physListFactory; G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list")); if(physicsList == nullptr) { std::string message = "specified physics list does not exists"; std::vector<G4String> base_lists = physListFactory.AvailablePhysLists(); message += " (available base lists are "; for(auto& base_list : base_lists) { message += base_list; message += ", "; } message = message.substr(0, message.size() - 2); message += " with optional suffixes for electromagnetic lists "; std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM(); for(auto& em_list : em_lists) { if(em_list.empty()) { continue; } message += em_list; message += ", "; } message = message.substr(0, message.size() - 2); message += ")"; throw InvalidValueError(config_, "physics_list", message); } else { LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\""; } // Register a step limiter (uses the user limits defined earlier) physicsList->RegisterPhysics(new G4StepLimiterPhysics()); // Register radioactive decay physics lists physicsList->RegisterPhysics(new G4RadioactiveDecayPhysics()); // Set the range-cut off threshold for secondary production: double production_cut; if(config_.has("range_cut")) { production_cut = config_.get<double>("range_cut"); LOG(INFO) << "Setting configured G4 production cut to " << Units::display(production_cut, {"mm", "um"}); } else { // Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors double min_size = std::numeric_limits<double>::max(); std::string min_detector; for(auto& detector : geo_manager_->getDetectors()) { auto model = detector->getModel(); double prev_min_size = min_size; min_size = std::min({min_size, model->getPixelSize().x(), model->getPixelSize().y(), model->getSensorSize().z()}); if(min_size != prev_min_size) { min_detector = detector->getName(); } } production_cut = min_size / 5; LOG(INFO) << "Setting G4 production cut to " << Units::display(production_cut, {"mm", "um"}) << ", derived from properties of detector \"" << min_detector << "\""; } ui_g4->ApplyCommand("/run/setCut " + std::to_string(production_cut)); // Initialize the physics list LOG(TRACE) << "Initializing physics processes"; run_manager_g4_->SetUserInitialization(physicsList); run_manager_g4_->InitializePhysics(); // Initialize the full run manager to ensure correct state flags run_manager_g4_->Initialize(); // Build particle generator LOG(TRACE) << "Constructing particle source"; auto generator = new GeneratorActionG4(config_); run_manager_g4_->SetUserAction(generator); track_info_manager_ = std::make_unique<TrackInfoManager>(); // User hook to store additional information at track initialization and termination as well as custom track ids auto userTrackIDHook = new SetTrackInfoUserHookG4(track_info_manager_.get()); run_manager_g4_->SetUserAction(userTrackIDHook); if(geo_manager_->hasMagneticField()) { MagneticFieldType magnetic_field_type_ = geo_manager_->getMagneticFieldType(); if(magnetic_field_type_ == MagneticFieldType::CONSTANT) { ROOT::Math::XYZVector b_field = geo_manager_->getMagneticField(ROOT::Math::XYZPoint(0., 0., 0.)); G4MagneticField* magField = new G4UniformMagField(G4ThreeVector(b_field.x(), b_field.y(), b_field.z())); G4FieldManager* globalFieldMgr = G4TransportationManager::GetTransportationManager()->GetFieldManager(); globalFieldMgr->SetDetectorField(magField); globalFieldMgr->CreateChordFinder(magField); } else { throw ModuleError("Magnetic field enabled, but not constant. This can't be handled by this module yet."); } } // Get the creation energy for charge (default is silicon electron hole pair energy) auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV")); auto fano_factor = config_.get<double>("fano_factor", 0.115); // Loop through all detectors and set the sensitive detector action that handles the particle passage bool useful_deposition = false; for(auto& detector : geo_manager_->getDetectors()) { // Do not add sensitive detector for detectors that have no listeners for the deposited charges // FIXME Probably the MCParticle has to be checked as well if(!messenger_->hasReceiver(this, std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) { LOG(INFO) << "Not depositing charges in " << detector->getName() << " because there is no listener for its output"; continue; } useful_deposition = true; // Get model of the sensitive device auto sensitive_detector_action = new SensitiveDetectorActionG4( this, detector, messenger_, track_info_manager_.get(), charge_creation_energy, fano_factor, getRandomSeed()); auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Apply the user limits to this element logical_volume->SetUserLimits(user_limits_.get()); // Add the sensitive detector action logical_volume->SetSensitiveDetector(sensitive_detector_action); sensors_.push_back(sensitive_detector_action); // If requested, prepare output plots if(config_.get<bool>("output_plots")) { LOG(TRACE) << "Creating output plots"; // Plot axis are in kilo electrons - convert from framework units! int maximum = static_cast<int>(Units::convert(config_.get<int>("output_plots_scale"), "ke")); int nbins = 5 * maximum; // Create histograms if needed std::string plot_name = "deposited_charge_" + sensitive_detector_action->getName(); charge_per_event_[sensitive_detector_action->getName()] = new TH1D(plot_name.c_str(), "deposited charge per event;deposited charge [ke];events", nbins, 0, maximum); } } if(!useful_deposition) { LOG(ERROR) << "Not a single listener for deposited charges, module is useless!"; } // Disable verbose messages from processes ui_g4->ApplyCommand("/process/verbose 0"); ui_g4->ApplyCommand("/process/em/verbose 0"); ui_g4->ApplyCommand("/process/eLoss/verbose 0"); G4HadronicProcessStore::Instance()->SetVerbose(0); // Set the random seed for Geant4 generation // NOTE Assumes this is the only Geant4 module using random numbers std::string seed_command = "/random/setSeeds "; for(int i = 0; i < G4_NUM_SEEDS; ++i) { seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX)); if(i != G4_NUM_SEEDS - 1) { seed_command += " "; } } ui_g4->ApplyCommand(seed_command); // Release the output stream RELEASE_STREAM(G4cout); } void DepositionGeant4Module::run(unsigned int event_num) { // Suppress output stream if not in debugging mode IFLOG(DEBUG); else { SUPPRESS_STREAM(G4cout); } // Start a single event from the beam LOG(TRACE) << "Enabling beam"; run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1))); last_event_num_ = event_num; // Release the stream (if it was suspended) RELEASE_STREAM(G4cout); track_info_manager_->createMCTracks(); // Dispatch the necessary messages for(auto& sensor : sensors_) { sensor->dispatchMessages(); // Fill output plots if requested: if(config_.get<bool>("output_plots")) { double charge = static_cast<double>(Units::convert(sensor->getDepositedCharge(), "ke")); charge_per_event_[sensor->getName()]->Fill(charge); } } track_info_manager_->dispatchMessage(this, messenger_); track_info_manager_->resetTrackInfoManager(); } void DepositionGeant4Module::finalize() { size_t total_charges = 0; for(auto& sensor : sensors_) { total_charges += sensor->getTotalDepositedCharge(); } if(config_.get<bool>("output_plots")) { // Write histograms LOG(TRACE) << "Writing output plots to file"; for(auto& plot : charge_per_event_) { plot.second->Write(); } } // Print summary or warns if module did not output any charges if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) { size_t average_charge = total_charges / sensors_.size() / last_event_num_; LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of " << average_charge << " per sensor for every event)"; } else { LOG(WARNING) << "No charges deposited"; } } <commit_msg>Prepare Geant4 seeds before the SensitiveDetector to keep seed order<commit_after>/** * @file * @brief Implementation of Geant4 deposition module * @remarks Based on code from Mathieu Benoit * @copyright Copyright (c) 2017 CERN and the Allpix Squared authors. * This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md". * In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an * Intergovernmental Organization or submit itself to any jurisdiction. */ #include "DepositionGeant4Module.hpp" #include <limits> #include <string> #include <utility> #include <G4EmParameters.hh> #include <G4HadronicProcessStore.hh> #include <G4LogicalVolume.hh> #include <G4PhysListFactory.hh> #include <G4RadioactiveDecayPhysics.hh> #include <G4RunManager.hh> #include <G4StepLimiterPhysics.hh> #include <G4UImanager.hh> #include <G4UserLimits.hh> #include "G4FieldManager.hh" #include "G4TransportationManager.hh" #include "G4UniformMagField.hh" #include "core/config/exceptions.h" #include "core/geometry/GeometryManager.hpp" #include "core/module/exceptions.h" #include "core/utils/log.h" #include "objects/DepositedCharge.hpp" #include "tools/ROOT.h" #include "tools/geant4.h" #include "GeneratorActionG4.hpp" #include "SensitiveDetectorActionG4.hpp" #include "SetTrackInfoUserHookG4.hpp" #define G4_NUM_SEEDS 10 using namespace allpix; /** * Includes the particle source point to the geometry using \ref GeometryManager::addPoint. */ DepositionGeant4Module::DepositionGeant4Module(Configuration& config, Messenger* messenger, GeometryManager* geo_manager) : Module(config), messenger_(messenger), geo_manager_(geo_manager), last_event_num_(1), run_manager_g4_(nullptr) { // Create user limits for maximum step length in the sensor user_limits_ = std::make_unique<G4UserLimits>(config_.get<double>("max_step_length", Units::get(1.0, "um"))); // Set default physics list config_.setDefault("physics_list", "FTFP_BERT_LIV"); config_.setDefault("source_type", "beam"); config_.setDefault<bool>("output_plots", false); config_.setDefault<int>("output_plots_scale", Units::get(100, "ke")); // Set alias for support of old particle source definition config_.setAlias("source_position", "beam_position"); config_.setAlias("source_energy", "beam_energy"); config_.setAlias("source_energy_spread", "beam_energy_spread"); // Add the particle source position to the geometry geo_manager_->addPoint(config_.get<ROOT::Math::XYZPoint>("source_position")); } /** * Module depends on \ref GeometryBuilderGeant4Module loaded first, because it owns the pointer to the Geant4 run manager. */ void DepositionGeant4Module::init() { // Load the G4 run manager (which is owned by the geometry builder) run_manager_g4_ = G4RunManager::GetRunManager(); if(run_manager_g4_ == nullptr) { throw ModuleError("Cannot deposit charges using Geant4 without a Geant4 geometry builder"); } // Suppress all output from G4 SUPPRESS_STREAM(G4cout); // Get UI manager for sending commands G4UImanager* ui_g4 = G4UImanager::GetUIpointer(); // Apply optional PAI model if(config_.get<bool>("enable_pai", false)) { LOG(TRACE) << "Enabling PAI model on all detectors"; G4EmParameters::Instance(); for(auto& detector : geo_manager_->getDetectors()) { // Get logical volume auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Create region G4Region* region = new G4Region(detector->getName() + "_sensor_region"); region->AddRootLogicalVolume(logical_volume.get()); auto pai_model = config_.get<std::string>("pai_model", "pai"); auto lcase_model = pai_model; std::transform(lcase_model.begin(), lcase_model.end(), lcase_model.begin(), ::tolower); if(lcase_model == "pai") { pai_model = "PAI"; } else if(lcase_model == "paiphoton") { pai_model = "PAIphoton"; } else { throw InvalidValueError(config_, "pai_model", "model has to be either 'pai' or 'paiphoton'"); } ui_g4->ApplyCommand("/process/em/AddPAIRegion all " + region->GetName() + " " + pai_model); } } // Find the physics list G4PhysListFactory physListFactory; G4VModularPhysicsList* physicsList = physListFactory.GetReferencePhysList(config_.get<std::string>("physics_list")); if(physicsList == nullptr) { std::string message = "specified physics list does not exists"; std::vector<G4String> base_lists = physListFactory.AvailablePhysLists(); message += " (available base lists are "; for(auto& base_list : base_lists) { message += base_list; message += ", "; } message = message.substr(0, message.size() - 2); message += " with optional suffixes for electromagnetic lists "; std::vector<G4String> em_lists = physListFactory.AvailablePhysListsEM(); for(auto& em_list : em_lists) { if(em_list.empty()) { continue; } message += em_list; message += ", "; } message = message.substr(0, message.size() - 2); message += ")"; throw InvalidValueError(config_, "physics_list", message); } else { LOG(INFO) << "Using G4 physics list \"" << config_.get<std::string>("physics_list") << "\""; } // Register a step limiter (uses the user limits defined earlier) physicsList->RegisterPhysics(new G4StepLimiterPhysics()); // Register radioactive decay physics lists physicsList->RegisterPhysics(new G4RadioactiveDecayPhysics()); // Set the range-cut off threshold for secondary production: double production_cut; if(config_.has("range_cut")) { production_cut = config_.get<double>("range_cut"); LOG(INFO) << "Setting configured G4 production cut to " << Units::display(production_cut, {"mm", "um"}); } else { // Define the production cut as one fifth of the minimum size (thickness, pitch) among the detectors double min_size = std::numeric_limits<double>::max(); std::string min_detector; for(auto& detector : geo_manager_->getDetectors()) { auto model = detector->getModel(); double prev_min_size = min_size; min_size = std::min({min_size, model->getPixelSize().x(), model->getPixelSize().y(), model->getSensorSize().z()}); if(min_size != prev_min_size) { min_detector = detector->getName(); } } production_cut = min_size / 5; LOG(INFO) << "Setting G4 production cut to " << Units::display(production_cut, {"mm", "um"}) << ", derived from properties of detector \"" << min_detector << "\""; } ui_g4->ApplyCommand("/run/setCut " + std::to_string(production_cut)); // Initialize the physics list LOG(TRACE) << "Initializing physics processes"; run_manager_g4_->SetUserInitialization(physicsList); run_manager_g4_->InitializePhysics(); // Initialize the full run manager to ensure correct state flags run_manager_g4_->Initialize(); // Build particle generator LOG(TRACE) << "Constructing particle source"; auto generator = new GeneratorActionG4(config_); run_manager_g4_->SetUserAction(generator); track_info_manager_ = std::make_unique<TrackInfoManager>(); // User hook to store additional information at track initialization and termination as well as custom track ids auto userTrackIDHook = new SetTrackInfoUserHookG4(track_info_manager_.get()); run_manager_g4_->SetUserAction(userTrackIDHook); if(geo_manager_->hasMagneticField()) { MagneticFieldType magnetic_field_type_ = geo_manager_->getMagneticFieldType(); if(magnetic_field_type_ == MagneticFieldType::CONSTANT) { ROOT::Math::XYZVector b_field = geo_manager_->getMagneticField(ROOT::Math::XYZPoint(0., 0., 0.)); G4MagneticField* magField = new G4UniformMagField(G4ThreeVector(b_field.x(), b_field.y(), b_field.z())); G4FieldManager* globalFieldMgr = G4TransportationManager::GetTransportationManager()->GetFieldManager(); globalFieldMgr->SetDetectorField(magField); globalFieldMgr->CreateChordFinder(magField); } else { throw ModuleError("Magnetic field enabled, but not constant. This can't be handled by this module yet."); } } // Get the creation energy for charge (default is silicon electron hole pair energy) auto charge_creation_energy = config_.get<double>("charge_creation_energy", Units::get(3.64, "eV")); auto fano_factor = config_.get<double>("fano_factor", 0.115); // Prepare seeds for Geant4: // NOTE Assumes this is the only Geant4 module using random numbers std::string seed_command = "/random/setSeeds "; for(int i = 0; i < G4_NUM_SEEDS; ++i) { seed_command += std::to_string(static_cast<uint32_t>(getRandomSeed() % INT_MAX)); if(i != G4_NUM_SEEDS - 1) { seed_command += " "; } } // Loop through all detectors and set the sensitive detector action that handles the particle passage bool useful_deposition = false; for(auto& detector : geo_manager_->getDetectors()) { // Do not add sensitive detector for detectors that have no listeners for the deposited charges // FIXME Probably the MCParticle has to be checked as well if(!messenger_->hasReceiver(this, std::make_shared<DepositedChargeMessage>(std::vector<DepositedCharge>(), detector))) { LOG(INFO) << "Not depositing charges in " << detector->getName() << " because there is no listener for its output"; continue; } useful_deposition = true; // Get model of the sensitive device auto sensitive_detector_action = new SensitiveDetectorActionG4( this, detector, messenger_, track_info_manager_.get(), charge_creation_energy, fano_factor, getRandomSeed()); auto logical_volume = detector->getExternalObject<G4LogicalVolume>("sensor_log"); if(logical_volume == nullptr) { throw ModuleError("Detector " + detector->getName() + " has no sensitive device (broken Geant4 geometry)"); } // Apply the user limits to this element logical_volume->SetUserLimits(user_limits_.get()); // Add the sensitive detector action logical_volume->SetSensitiveDetector(sensitive_detector_action); sensors_.push_back(sensitive_detector_action); // If requested, prepare output plots if(config_.get<bool>("output_plots")) { LOG(TRACE) << "Creating output plots"; // Plot axis are in kilo electrons - convert from framework units! int maximum = static_cast<int>(Units::convert(config_.get<int>("output_plots_scale"), "ke")); int nbins = 5 * maximum; // Create histograms if needed std::string plot_name = "deposited_charge_" + sensitive_detector_action->getName(); charge_per_event_[sensitive_detector_action->getName()] = new TH1D(plot_name.c_str(), "deposited charge per event;deposited charge [ke];events", nbins, 0, maximum); } } if(!useful_deposition) { LOG(ERROR) << "Not a single listener for deposited charges, module is useless!"; } // Disable verbose messages from processes ui_g4->ApplyCommand("/process/verbose 0"); ui_g4->ApplyCommand("/process/em/verbose 0"); ui_g4->ApplyCommand("/process/eLoss/verbose 0"); G4HadronicProcessStore::Instance()->SetVerbose(0); // Set the random seed for Geant4 generation ui_g4->ApplyCommand(seed_command); // Release the output stream RELEASE_STREAM(G4cout); } void DepositionGeant4Module::run(unsigned int event_num) { // Suppress output stream if not in debugging mode IFLOG(DEBUG); else { SUPPRESS_STREAM(G4cout); } // Start a single event from the beam LOG(TRACE) << "Enabling beam"; run_manager_g4_->BeamOn(static_cast<int>(config_.get<unsigned int>("number_of_particles", 1))); last_event_num_ = event_num; // Release the stream (if it was suspended) RELEASE_STREAM(G4cout); track_info_manager_->createMCTracks(); // Dispatch the necessary messages for(auto& sensor : sensors_) { sensor->dispatchMessages(); // Fill output plots if requested: if(config_.get<bool>("output_plots")) { double charge = static_cast<double>(Units::convert(sensor->getDepositedCharge(), "ke")); charge_per_event_[sensor->getName()]->Fill(charge); } } track_info_manager_->dispatchMessage(this, messenger_); track_info_manager_->resetTrackInfoManager(); } void DepositionGeant4Module::finalize() { size_t total_charges = 0; for(auto& sensor : sensors_) { total_charges += sensor->getTotalDepositedCharge(); } if(config_.get<bool>("output_plots")) { // Write histograms LOG(TRACE) << "Writing output plots to file"; for(auto& plot : charge_per_event_) { plot.second->Write(); } } // Print summary or warns if module did not output any charges if(!sensors_.empty() && total_charges > 0 && last_event_num_ > 0) { size_t average_charge = total_charges / sensors_.size() / last_event_num_; LOG(INFO) << "Deposited total of " << total_charges << " charges in " << sensors_.size() << " sensor(s) (average of " << average_charge << " per sensor for every event)"; } else { LOG(WARNING) << "No charges deposited"; } } <|endoftext|>
<commit_before>// 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. #ifndef __STOUT_OS_MKTEMP_HPP__ #define __STOUT_OS_MKTEMP_HPP__ #include <stdlib.h> #include <string.h> #include <string> #include <stout/error.hpp> #include <stout/try.hpp> #ifdef __WINDOWS__ #include <stout/windows.hpp> // To be certain we're using the right `mkstemp`. #endif // __WINDOWS__ #include <stout/os/close.hpp> #include <stout/os/int_fd.hpp> namespace os { // Creates a temporary file using the specified path template. The // template may be any path with _6_ `Xs' appended to it, for example // /tmp/temp.XXXXXX. The trailing `Xs' are replaced with a unique // alphanumeric combination. inline Try<std::string> mktemp(const std::string& path = "/tmp/XXXXXX") { char* temp = new char[path.size() + 1]; ::memcpy(temp, path.c_str(), path.size() + 1); int_fd fd = ::mkstemp(temp); if (fd < 0) { delete[] temp; return ErrnoError(); } // We ignore the return value of close(). This is because users // calling this function are interested in the return value of // mkstemp(). Also an unsuccessful close() doesn't affect the file. os::close(fd); std::string result(temp); delete[] temp; return result; } } // namespace os { #endif // __STOUT_OS_MKTEMP_HPP__ <commit_msg>Stout: Made `os::mktemp` fully cross-platform.<commit_after>// 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. #ifndef __STOUT_OS_MKTEMP_HPP__ #define __STOUT_OS_MKTEMP_HPP__ #include <stdlib.h> #include <string.h> #include <string> #include <stout/error.hpp> #include <stout/path.hpp> #include <stout/try.hpp> #ifdef __WINDOWS__ #include <stout/windows.hpp> // To be certain we're using the right `mkstemp`. #endif // __WINDOWS__ #include <stout/os/close.hpp> #include <stout/os/int_fd.hpp> #include <stout/os/temp.hpp> namespace os { // Creates a temporary file using the specified path template. The // template may be any path with _6_ `Xs' appended to it, for example // /tmp/temp.XXXXXX. The trailing `Xs' are replaced with a unique // alphanumeric combination. inline Try<std::string> mktemp( const std::string& path = path::join(os::temp(), "XXXXXX")) { char* temp = new char[path.size() + 1]; ::memcpy(temp, path.c_str(), path.size() + 1); int_fd fd = ::mkstemp(temp); if (fd < 0) { delete[] temp; return ErrnoError(); } // We ignore the return value of close(). This is because users // calling this function are interested in the return value of // mkstemp(). Also an unsuccessful close() doesn't affect the file. os::close(fd); std::string result(temp); delete[] temp; return result; } } // namespace os { #endif // __STOUT_OS_MKTEMP_HPP__ <|endoftext|>
<commit_before>#include "estimation/jet/jet_ekf.hh" #include "estimation/jet/jet_rk4.hh" #include "sophus.hh" namespace estimation { namespace jet_filter { struct FiducialMeasurement { int fiducial_id = -1; SE3 fiducial_pose; }; State dynamics(const State& x, const double h) { const Parameters z = {}; return rk4_integrate(x, z, h); } class JetFilter { using Update = FilterStateUpdate<State>; using JetFilterState = FilterState<State>; public: JetFilter() : ekf_(dynamics) { const auto error_model = [](const State& x, const AccelMeasurement& z) -> jcc::Vec3 { const jcc::Vec3 g(0.0, 0.0, -9.81); const SE3 vehicle_from_sensor; const jcc::Vec3 expected_a_mpss = observe_accel(x.T_body_from_world, x.eps_dot, x.eps_ddot, vehicle_from_sensor, g); const jcc::Vec3 error = expected_a_mpss - z.observed_acceleration; return error; }; const ImuModel accel_model(error_model); // using ObservationFunction = // std::function<Update(const JetFilterState&, const AccelMeasurement&)>; imu_id_ = ekf_.add_model(accel_model); // fiducial_id_ = ekf_.add_model(fiducial_model); } void measure_imu(const AccelMeasurement& meas, const TimePoint& t) { ekf_.measure(meas, t, imu_id_); } // void measure_fiducial(const FiducialMeasurement& meas) { // ekf_.measure(meas, fiducial_id_); // } void free_run() { xp_.P.setZero(); xp_ = ekf_.service_all_measurements(xp_); } private: void observe_imu() const; void observe_fiducial() const; // void handle(int i) { // switch (i) { // case 0: // const FilterStateUpdate update = observe_imu(x, imu_measurements_.top()); // imu_measurements_.pop(); // break; // case 1: // const FilterStateUpdate update = // observe_fiducial(x, fiducial_measurements_.top()); // fiducial_measurements_.pop(); // break; // } // } private: JetEkf ekf_; JetFilterState xp_; int imu_id_ = -1; int fiducial_id_ = -1; }; void go() { const jcc::Vec3 g(0.0, 0.0, 0.0); const SO3 r_vehicle_from_sensor; const jcc::Vec3 t_vehicle_from_sensor = jcc::Vec3(0.0, 0.0, 1.0); const SE3 vehicle_from_sensor = SE3(r_vehicle_from_sensor, t_vehicle_from_sensor); State x; // x.eps_dot = VecNd<6>::Ones(); x.eps_dot[0] = 1.0; x.eps_dot[3] = 0.0; x.eps_dot[4] = 0.0; x.eps_dot[5] = 1.0; x.eps_ddot[2] = 0.0; x.eps_ddot[5] = 0.0; const auto res = observe_accel(x.T_body_from_world, x.eps_dot, x.eps_ddot, vehicle_from_sensor, g); std::cout << res.transpose() << std::endl; // JetFilter jf; // AccelMeasurement meas; // TimePoint start_time = {}; // for (int k = 0; k < 10; ++k) { // const TimePoint obs_time = to_duration(k * 0.1) + start_time; // jf.measure_imu(meas, obs_time); // } // jf.free_run(); } } // namespace jet_filter } // namespace estimation int main() { estimation::jet_filter::go(); }<commit_msg>Allow access to filter state in jet filter<commit_after>#include "estimation/jet/jet_ekf.hh" #include "estimation/jet/jet_rk4.hh" #include "sophus.hh" namespace estimation { namespace jet_filter { struct FiducialMeasurement { int fiducial_id = -1; SE3 fiducial_pose; }; Parameters get_parameters() { const jcc::Vec3 g(0.0, 0.0, 0.0); const SE3 vehicle_from_sensor; Parameters p; p.T_sensor_from_body = vehicle_from_sensor; return p; } State dynamics(const State& x, const double h) { const Parameters p = get_parameters(); return rk4_integrate(x, p, h); } jcc::Vec3 accel_error_model(const State& x, const AccelMeasurement& z) { const Parameters p = get_parameters(); const jcc::Vec3 expected_a_mpss = observe_accel(x, p); const jcc::Vec3 error = z.observed_acceleration - expected_a_mpss; return error; } class JetFilter { using Update = FilterStateUpdate<State>; using JetFilterState = FilterState<State>; public: JetFilter(const JetFilterState& xp0) : xp_(xp0), ekf_(dynamics) { const ImuModel accel_model(accel_error_model); imu_id_ = ekf_.add_model(accel_model); // fiducial_id_ = ekf_.add_model(fiducial_model); } void measure_imu(const AccelMeasurement& meas, const TimePoint& t) { ekf_.measure(meas, t, imu_id_); } // void measure_fiducial(const FiducialMeasurement& meas) { // ekf_.measure(meas, fiducial_id_); // } void free_run() { xp_ = ekf_.service_all_measurements(xp_); } const JetFilterState& state() const { return xp_; } private: void observe_imu() const; void observe_fiducial() const; private: JetFilterState xp_; JetEkf ekf_; int imu_id_ = -1; int fiducial_id_ = -1; }; void go() { // const Parameters p = get_parameters(); // const SO3 r_vehicle_from_sensor; // const jcc::Vec3 t_vehicle_from_sensor = jcc::Vec3(0.0, 0.0, 1.0); // const SE3 vehicle_from_sensor = SE3(r_vehicle_from_sensor, t_vehicle_from_sensor); // State x; // x.eps_ddot[1] = 1.0; // FilterState<State> xp0; xp0.P.setIdentity(); xp0.x.eps_ddot[0] = -0.9; JetFilter jf(xp0); AccelMeasurement meas; meas.observed_acceleration[0] = 2.0; // return; TimePoint start_time = {}; for (int k = 0; k < 10; ++k) { const TimePoint obs_time = to_duration(k * 0.5) + start_time; jf.measure_imu(meas, obs_time); jf.free_run(); const auto xp = jf.state(); std::cout << "Modelled Error: " << accel_error_model(xp.x, meas).transpose() << std::endl; const auto res = observe_accel(xp.x, get_parameters()); std::cout << "Expected Accel: " << res.transpose() << std::endl; } } } // namespace jet_filter } // namespace estimation int main() { estimation::jet_filter::go(); }<|endoftext|>
<commit_before>/* * Copyright (C) 2011 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. */ #include "config.h" #include "core/inspector/WorkerInspectorController.h" #include "InspectorBackendDispatcher.h" #include "InspectorFrontend.h" #include "core/inspector/InjectedScriptHost.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorConsoleAgent.h" #include "core/inspector/InspectorFrontendChannel.h" #include "core/inspector/InspectorHeapProfilerAgent.h" #include "core/inspector/InspectorProfilerAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InspectorStateClient.h" #include "core/inspector/InspectorTimelineAgent.h" #include "core/inspector/InstrumentingAgents.h" #include "core/inspector/WorkerConsoleAgent.h" #include "core/inspector/WorkerDebuggerAgent.h" #include "core/inspector/WorkerRuntimeAgent.h" #include "core/workers/WorkerGlobalScope.h" #include "core/workers/WorkerReportingProxy.h" #include "core/workers/WorkerThread.h" #include "wtf/PassOwnPtr.h" namespace WebCore { namespace { class PageInspectorProxy : public InspectorFrontendChannel { WTF_MAKE_FAST_ALLOCATED; public: explicit PageInspectorProxy(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) { } virtual ~PageInspectorProxy() { } private: virtual bool sendMessageToFrontend(const String& message) { m_workerGlobalScope->thread()->workerReportingProxy().postMessageToPageInspector(message); return true; } WorkerGlobalScope* m_workerGlobalScope; }; class WorkerStateClient : public InspectorStateClient { WTF_MAKE_FAST_ALLOCATED; public: WorkerStateClient(WorkerGlobalScope* context) : m_workerGlobalScope(context) { } virtual ~WorkerStateClient() { } private: virtual void updateInspectorStateCookie(const String& cookie) { m_workerGlobalScope->thread()->workerReportingProxy().updateInspectorStateCookie(cookie); } WorkerGlobalScope* m_workerGlobalScope; }; } WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) , m_stateClient(adoptPtr(new WorkerStateClient(workerGlobalScope))) , m_state(adoptPtr(new InspectorCompositeState(m_stateClient.get()))) , m_instrumentingAgents(InstrumentingAgents::create()) , m_injectedScriptManager(InjectedScriptManager::createForWorker()) , m_debugServer(adoptPtr(new WorkerScriptDebugServer(workerGlobalScope, WorkerDebuggerAgent::debuggerTaskMode))) { m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope)); OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0); OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get()); m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get())); m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), 0)); m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get())); m_agents.append(timelineAgent.release()); m_agents.append(consoleAgent.release()); m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), m_debugServer.get()); } WorkerInspectorController::~WorkerInspectorController() { m_instrumentingAgents->reset(); disconnectFrontend(); } void WorkerInspectorController::connectFrontend() { ASSERT(!m_frontend); m_state->unmute(); m_frontendChannel = adoptPtr(new PageInspectorProxy(m_workerGlobalScope)); m_frontend = adoptPtr(new InspectorFrontend(m_frontendChannel.get())); m_backendDispatcher = InspectorBackendDispatcher::create(m_frontendChannel.get()); m_agents.registerInDispatcher(m_backendDispatcher.get()); m_agents.setFrontend(m_frontend.get()); } void WorkerInspectorController::disconnectFrontend() { if (!m_frontend) return; m_backendDispatcher->clearFrontend(); m_backendDispatcher.clear(); // Destroying agents would change the state, but we don't want that. // Pre-disconnect state will be used to restore inspector agents. m_state->mute(); m_agents.clearFrontend(); m_frontend.clear(); m_frontendChannel.clear(); } void WorkerInspectorController::restoreInspectorStateFromCookie(const String& inspectorCookie) { ASSERT(!m_frontend); connectFrontend(); m_state->loadFromCookie(inspectorCookie); m_agents.restore(); } void WorkerInspectorController::dispatchMessageFromFrontend(const String& message) { if (m_backendDispatcher) m_backendDispatcher->dispatch(message); } void WorkerInspectorController::resume() { if (WorkerRuntimeAgent* runtimeAgent = m_instrumentingAgents->workerRuntimeAgent()) { ErrorString unused; runtimeAgent->run(&unused); } } } <commit_msg>Inline consoleAgent variable in WorkerInspectorController constructor<commit_after>/* * Copyright (C) 2011 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. */ #include "config.h" #include "core/inspector/WorkerInspectorController.h" #include "InspectorBackendDispatcher.h" #include "InspectorFrontend.h" #include "core/inspector/InjectedScriptHost.h" #include "core/inspector/InjectedScriptManager.h" #include "core/inspector/InspectorConsoleAgent.h" #include "core/inspector/InspectorFrontendChannel.h" #include "core/inspector/InspectorHeapProfilerAgent.h" #include "core/inspector/InspectorProfilerAgent.h" #include "core/inspector/InspectorState.h" #include "core/inspector/InspectorStateClient.h" #include "core/inspector/InspectorTimelineAgent.h" #include "core/inspector/InstrumentingAgents.h" #include "core/inspector/WorkerConsoleAgent.h" #include "core/inspector/WorkerDebuggerAgent.h" #include "core/inspector/WorkerRuntimeAgent.h" #include "core/workers/WorkerGlobalScope.h" #include "core/workers/WorkerReportingProxy.h" #include "core/workers/WorkerThread.h" #include "wtf/PassOwnPtr.h" namespace WebCore { namespace { class PageInspectorProxy : public InspectorFrontendChannel { WTF_MAKE_FAST_ALLOCATED; public: explicit PageInspectorProxy(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) { } virtual ~PageInspectorProxy() { } private: virtual bool sendMessageToFrontend(const String& message) { m_workerGlobalScope->thread()->workerReportingProxy().postMessageToPageInspector(message); return true; } WorkerGlobalScope* m_workerGlobalScope; }; class WorkerStateClient : public InspectorStateClient { WTF_MAKE_FAST_ALLOCATED; public: WorkerStateClient(WorkerGlobalScope* context) : m_workerGlobalScope(context) { } virtual ~WorkerStateClient() { } private: virtual void updateInspectorStateCookie(const String& cookie) { m_workerGlobalScope->thread()->workerReportingProxy().updateInspectorStateCookie(cookie); } WorkerGlobalScope* m_workerGlobalScope; }; } WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) , m_stateClient(adoptPtr(new WorkerStateClient(workerGlobalScope))) , m_state(adoptPtr(new InspectorCompositeState(m_stateClient.get()))) , m_instrumentingAgents(InstrumentingAgents::create()) , m_injectedScriptManager(InjectedScriptManager::createForWorker()) , m_debugServer(adoptPtr(new WorkerScriptDebugServer(workerGlobalScope, WorkerDebuggerAgent::debuggerTaskMode))) { m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope)); OwnPtr<InspectorTimelineAgent> timelineAgent = InspectorTimelineAgent::create(m_instrumentingAgents.get(), 0, 0, 0, 0, m_state.get(), InspectorTimelineAgent::WorkerInspector, 0); m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get())); m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), 0)); m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get())); m_agents.append(WorkerConsoleAgent::create(m_instrumentingAgents.get(), timelineAgent.get(), m_state.get(), m_injectedScriptManager.get())); m_agents.append(timelineAgent.release()); m_injectedScriptManager->injectedScriptHost()->init(m_instrumentingAgents.get(), m_debugServer.get()); } WorkerInspectorController::~WorkerInspectorController() { m_instrumentingAgents->reset(); disconnectFrontend(); } void WorkerInspectorController::connectFrontend() { ASSERT(!m_frontend); m_state->unmute(); m_frontendChannel = adoptPtr(new PageInspectorProxy(m_workerGlobalScope)); m_frontend = adoptPtr(new InspectorFrontend(m_frontendChannel.get())); m_backendDispatcher = InspectorBackendDispatcher::create(m_frontendChannel.get()); m_agents.registerInDispatcher(m_backendDispatcher.get()); m_agents.setFrontend(m_frontend.get()); } void WorkerInspectorController::disconnectFrontend() { if (!m_frontend) return; m_backendDispatcher->clearFrontend(); m_backendDispatcher.clear(); // Destroying agents would change the state, but we don't want that. // Pre-disconnect state will be used to restore inspector agents. m_state->mute(); m_agents.clearFrontend(); m_frontend.clear(); m_frontendChannel.clear(); } void WorkerInspectorController::restoreInspectorStateFromCookie(const String& inspectorCookie) { ASSERT(!m_frontend); connectFrontend(); m_state->loadFromCookie(inspectorCookie); m_agents.restore(); } void WorkerInspectorController::dispatchMessageFromFrontend(const String& message) { if (m_backendDispatcher) m_backendDispatcher->dispatch(message); } void WorkerInspectorController::resume() { if (WorkerRuntimeAgent* runtimeAgent = m_instrumentingAgents->workerRuntimeAgent()) { ErrorString unused; runtimeAgent->run(&unused); } } } <|endoftext|>
<commit_before>// Copyright 2015 Esri. // 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 <QSettings> #include <QGuiApplication> #include <QQuickView> #include <QCommandLineParser> #include <QDir> #ifdef Q_OS_WIN #include <Windows.h> #endif #include "MapQuickView.h" #include "FeatureLayerSelection.h" #include "ArcGISRuntimeEnvironment.h" using namespace Esri::ArcGISRuntime; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); #ifdef Q_OS_WIN // Force usage of OpenGL ES through ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); #endif // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<FeatureLayerSelection>("Esri.Samples", 1, 0, "FeatureLayerSelectionSample"); // Intialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); // Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Set the source view.setSource(QUrl("qrc:/Samples/Features/FeatureLayerSelection/FeatureLayerSelection.qml")); view.show(); return app.exec(); } <commit_msg>add missing include<commit_after>// Copyright 2015 Esri. // 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 <QSettings> #include <QGuiApplication> #include <QQuickView> #include <QCommandLineParser> #include <QDir> #ifdef Q_OS_WIN #include <Windows.h> #endif #include "MapQuickView.h" #include "FeatureLayerSelection.h" #include "ArcGISRuntimeEnvironment.h" #include <QQmlEngine> using namespace Esri::ArcGISRuntime; int main(int argc, char *argv[]) { QGuiApplication app(argc, argv); #ifdef Q_OS_WIN // Force usage of OpenGL ES through ANGLE on Windows QCoreApplication::setAttribute(Qt::AA_UseOpenGLES); #endif // Register the map view for QML qmlRegisterType<MapQuickView>("Esri.Samples", 1, 0, "MapView"); qmlRegisterType<FeatureLayerSelection>("Esri.Samples", 1, 0, "FeatureLayerSelectionSample"); // Intialize application view QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); // Add the import Path view.engine()->addImportPath(QDir(QCoreApplication::applicationDirPath()).filePath("qml")); // Set the source view.setSource(QUrl("qrc:/Samples/Features/FeatureLayerSelection/FeatureLayerSelection.qml")); view.show(); return app.exec(); } <|endoftext|>
<commit_before>#ifndef STAN_MATH_REV_FUN_MULTIPLY_LOG_HPP #define STAN_MATH_REV_FUN_MULTIPLY_LOG_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/fun/log.hpp> #include <stan/math/rev/fun/elt_multiply.hpp> #include <stan/math/rev/fun/multiply.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/multiply_log.hpp> #include <stan/math/prim/fun/is_any_nan.hpp> #include <cmath> namespace stan { namespace math { namespace internal { class multiply_log_vv_vari : public op_vv_vari { public: multiply_log_vv_vari(vari* avi, vari* bvi) : op_vv_vari(multiply_log(avi->val_, bvi->val_), avi, bvi) {} void chain() { using std::log; if (unlikely(is_any_nan(avi_->val_, bvi_->val_))) { avi_->adj_ = NOT_A_NUMBER; bvi_->adj_ = NOT_A_NUMBER; } else { avi_->adj_ += adj_ * log(bvi_->val_); bvi_->adj_ += adj_ * avi_->val_ / bvi_->val_; } } }; class multiply_log_vd_vari : public op_vd_vari { public: multiply_log_vd_vari(vari* avi, double b) : op_vd_vari(multiply_log(avi->val_, b), avi, b) {} void chain() { using std::log; if (unlikely(is_any_nan(avi_->val_, bd_))) { avi_->adj_ = NOT_A_NUMBER; } else { avi_->adj_ += adj_ * log(bd_); } } }; class multiply_log_dv_vari : public op_dv_vari { public: multiply_log_dv_vari(double a, vari* bvi) : op_dv_vari(multiply_log(a, bvi->val_), a, bvi) {} void chain() { bvi_->adj_ += adj_ * ad_ / bvi_->val_; } }; } // namespace internal /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to a is log(b). * The partial derivative with respect to b is a/b. * * @param a First variable. * @param b Second variable. * @return Value of a*log(b) */ inline var multiply_log(const var& a, const var& b) { return var(new internal::multiply_log_vv_vari(a.vi_, b.vi_)); } /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to a is log(b). * * @param a First variable. * @param b Second scalar. * @return Value of a*log(b) */ inline var multiply_log(const var& a, double b) { return var(new internal::multiply_log_vd_vari(a.vi_, b)); } /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to b is a/b. * * @param a First scalar. * @param b Second variable. * @return Value of a*log(b) */ inline var multiply_log(double a, const var& b) { if (a == 1.0) { return log(b); } return var(new internal::multiply_log_dv_vari(a, b.vi_)); } /** * Return the elementwise product `a * log(b)`. * * Both `T1` and `T2` are matrices, and one of `T1` or `T2` must be a * `var_value` * * @tparam T1 Type of first argument * @tparam T2 Type of second argument * @param a First argument * @param b Second argument * @return elementwise product of `a` and `log(b)` */ template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { if (!is_constant<T1>::value && !is_constant<T2>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var( (arena_a.val().array() * arena_b.val().array().log()).matrix(), [arena_a, arena_b](const auto& res) mutable { arena_a.adj().array() += res.adj().array() * arena_b.val().array().log(); arena_b.adj().array() += res.adj().array() * arena_a.val().array() / arena_b.val().array(); }); } else if (!is_constant<T1>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; auto arena_b_log = to_arena(value_of(b).array().log()); return make_callback_var((arena_a.val().array() * arena_b_log).matrix(), [arena_a, arena_b_log](const auto& res) mutable { arena_a.adj().array() += res.adj().array() * arena_b_log; }); } else { auto arena_a = to_arena(value_of(a)); arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var( (arena_a.array() * arena_b.val().array().log()).matrix(), [arena_a, arena_b](const auto& res) mutable { arena_b.adj().array() += res.adj().array() * arena_a.array() / arena_b.val().array(); }); } } /** * Return the product `a * log(b)`. * * @tparam T1 Type of matrix argument * @tparam T2 Type of scalar argument * @param a Matrix argument * @param b Scalar argument * @return Product of `a` and `log(b)` */ template <typename T1, typename T2, require_var_matrix_t<T1>* = nullptr, require_stan_scalar_t<T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { using std::log; if (!is_constant<T1>::value && !is_constant<T2>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; var arena_b = b; return make_callback_var( arena_a.val() * log(arena_b.val()), [arena_a, arena_b](const auto& res) mutable { arena_a.adj() += res.adj() * log(arena_b.val()); arena_b.adj() += (res.adj().array() * arena_a.val().array() / arena_b.val()) .sum(); }); } else if (!is_constant<T1>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; return make_callback_var(arena_a.val() * log(value_of(b)), [arena_a, b](const auto& res) mutable { arena_a.adj() += res.adj() * log(value_of(b)); }); } else { arena_t<promote_scalar_t<double, T1>> arena_a = value_of(a); var arena_b = b; return make_callback_var( arena_a * log(arena_b.val()), [arena_a, arena_b](const auto& res) mutable { arena_b.adj() += (res.adj().array() * arena_a.array() / arena_b.val()).sum(); }); } } /** * Return the product `a * log(b)`. * * @tparam T1 Type of scalar argument * @tparam T2 Type of matrix argument * @param a Scalar argument * @param b Matrix argument * @return Product of `a` and `log(b)` */ template <typename T1, typename T2, require_stan_scalar_t<T1>* = nullptr, require_var_matrix_t<T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { if (!is_constant<T1>::value && !is_constant<T2>::value) { var arena_a = a; arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var( (arena_a.val() * arena_b.val().array().log()).matrix(), [arena_a, arena_b](const auto& res) mutable { arena_a.adj() += (res.adj().array() * arena_b.val().array().log()).sum(); arena_b.adj().array() += res.adj().array() * arena_a.val() / arena_b.val().array(); }); } else if (!is_constant<T1>::value) { var arena_a = a; auto arena_b_log = to_arena(value_of(b).array().log()); return make_callback_var((arena_a.val() * arena_b_log).matrix(), [arena_a, arena_b_log](const auto& res) mutable { arena_a.adj() += (res.adj().array() * arena_b_log).sum(); }); } else { arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var( (value_of(a) * arena_b.val().array().log()).matrix(), [a, arena_b](const auto& res) mutable { arena_b.adj().array() += res.adj().array() * value_of(a) / arena_b.val().array(); }); } } } // namespace math } // namespace stan #endif <commit_msg>Added checks back to `multiply_log` (Issue #2101)<commit_after>#ifndef STAN_MATH_REV_FUN_MULTIPLY_LOG_HPP #define STAN_MATH_REV_FUN_MULTIPLY_LOG_HPP #include <stan/math/rev/meta.hpp> #include <stan/math/rev/core.hpp> #include <stan/math/rev/fun/log.hpp> #include <stan/math/rev/fun/elt_multiply.hpp> #include <stan/math/rev/fun/multiply.hpp> #include <stan/math/prim/fun/constants.hpp> #include <stan/math/prim/fun/multiply_log.hpp> #include <stan/math/prim/fun/is_any_nan.hpp> #include <cmath> namespace stan { namespace math { namespace internal { class multiply_log_vv_vari : public op_vv_vari { public: multiply_log_vv_vari(vari* avi, vari* bvi) : op_vv_vari(multiply_log(avi->val_, bvi->val_), avi, bvi) {} void chain() { using std::log; if (unlikely(is_any_nan(avi_->val_, bvi_->val_))) { avi_->adj_ = NOT_A_NUMBER; bvi_->adj_ = NOT_A_NUMBER; } else { avi_->adj_ += adj_ * log(bvi_->val_); if (bvi_->val_ == 0.0 && avi_->val_ == 0) { bvi_->adj_ += adj_ * INFTY; } else { bvi_->adj_ += adj_ * avi_->val_ / bvi_->val_; } } } }; class multiply_log_vd_vari : public op_vd_vari { public: multiply_log_vd_vari(vari* avi, double b) : op_vd_vari(multiply_log(avi->val_, b), avi, b) {} void chain() { using std::log; if (unlikely(is_any_nan(avi_->val_, bd_))) { avi_->adj_ = NOT_A_NUMBER; } else { avi_->adj_ += adj_ * log(bd_); } } }; class multiply_log_dv_vari : public op_dv_vari { public: multiply_log_dv_vari(double a, vari* bvi) : op_dv_vari(multiply_log(a, bvi->val_), a, bvi) {} void chain() { if (bvi_->val_ == 0.0 && ad_ == 0.0) { bvi_->adj_ += adj_ * INFTY; } else { bvi_->adj_ += adj_ * ad_ / bvi_->val_; } } }; } // namespace internal /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to a is log(b). * The partial derivative with respect to b is a/b. * * @param a First variable. * @param b Second variable. * @return Value of a*log(b) */ inline var multiply_log(const var& a, const var& b) { return var(new internal::multiply_log_vv_vari(a.vi_, b.vi_)); } /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to a is log(b). * * @param a First variable. * @param b Second scalar. * @return Value of a*log(b) */ inline var multiply_log(const var& a, double b) { return var(new internal::multiply_log_vd_vari(a.vi_, b)); } /** * Return the value of a*log(b). * * When both a and b are 0, the value returned is 0. * The partial derivative with respect to b is a/b. * * @param a First scalar. * @param b Second variable. * @return Value of a*log(b) */ inline var multiply_log(double a, const var& b) { if (a == 1.0) { return log(b); } return var(new internal::multiply_log_dv_vari(a, b.vi_)); } /** * Return the elementwise product `a * log(b)`. * * Both `T1` and `T2` are matrices, and one of `T1` or `T2` must be a * `var_value` * * @tparam T1 Type of first argument * @tparam T2 Type of second argument * @param a First argument * @param b Second argument * @return elementwise product of `a` and `log(b)` */ template <typename T1, typename T2, require_all_matrix_t<T1, T2>* = nullptr, require_any_var_matrix_t<T1, T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { check_matching_dims("multiply_log", "a", a, "b", b); if (!is_constant<T1>::value && !is_constant<T2>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var(multiply_log(arena_a.val(), arena_b.val()), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), arena_b.val().coeff(i, j)))) { arena_a.adj().coeffRef(i, j) = NOT_A_NUMBER; arena_b.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { arena_a.adj().coeffRef(i, j) += res.adj().coeff(i, j) * log(arena_b.val().coeff(i, j)); if (arena_b.val().coeff(i, j) == 0.0 && arena_a.val().coeff(i, j) == 0) { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * arena_a.val().coeff(i, j) / arena_b.val().coeff(i, j); } } } } }); } else if (!is_constant<T1>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; auto arena_b = to_arena(value_of(b)); return make_callback_var(multiply_log(arena_a.val(), arena_b), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), arena_b.coeff(i, j)))) { arena_a.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { arena_a.adj().coeffRef(i, j) += res.adj().coeff(i, j) * log(arena_b.coeff(i, j)); } } } }); } else { auto arena_a = to_arena(value_of(a)); arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var(multiply_log(arena_a, arena_b.val()), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), arena_b.val().coeff(i, j)))) { arena_b.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { if (arena_b.val().coeff(i, j) == 0.0 && arena_a.val().coeff(i, j) == 0) { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * arena_a.coeff(i, j) / arena_b.val().coeff(i, j); } } } } }); } } /** * Return the product `a * log(b)`. * * @tparam T1 Type of matrix argument * @tparam T2 Type of scalar argument * @param a Matrix argument * @param b Scalar argument * @return Product of `a` and `log(b)` */ template <typename T1, typename T2, require_var_matrix_t<T1>* = nullptr, require_stan_scalar_t<T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { using std::log; if (!is_constant<T1>::value && !is_constant<T2>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; var arena_b = b; return make_callback_var(multiply_log(arena_a.val(), arena_b.val()), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), arena_b.val()))) { arena_a.adj().coeffRef(i, j) = NOT_A_NUMBER; arena_b.adj() = NOT_A_NUMBER; } else { arena_a.adj().coeffRef(i, j) += res.adj().coeff(i, j) * log(arena_b.val()); if (arena_b.val() == 0.0 && arena_a.val().coeff(i, j) == 0) { arena_b.adj() += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj() += res.adj().coeff(i, j) * arena_a.val().coeff(i, j) / arena_b.val(); } } } } }); } else if (!is_constant<T1>::value) { arena_t<promote_scalar_t<var, T1>> arena_a = a; return make_callback_var(multiply_log(arena_a.val(), value_of(b)), [arena_a, b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), value_of(b)))) { arena_a.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { arena_a.adj().coeffRef(i, j) += res.adj().coeff(i, j) * log(value_of(b)); } } } }); } else { arena_t<promote_scalar_t<double, T1>> arena_a = value_of(a); var arena_b = b; return make_callback_var(multiply_log(arena_a, arena_b.val()), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val().coeff(i, j), arena_b.val()))) { arena_b.adj() = NOT_A_NUMBER; } else { if (arena_b.val() == 0.0 && arena_a.val().coeff(i, j) == 0) { arena_b.adj() += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj() += res.adj().coeff(i, j) * arena_a.val().coeff(i, j) / arena_b.val(); } } } } }); } } /** * Return the product `a * log(b)`. * * @tparam T1 Type of scalar argument * @tparam T2 Type of matrix argument * @param a Scalar argument * @param b Matrix argument * @return Product of `a` and `log(b)` */ template <typename T1, typename T2, require_stan_scalar_t<T1>* = nullptr, require_var_matrix_t<T2>* = nullptr> inline auto multiply_log(const T1& a, const T2& b) { if (!is_constant<T1>::value && !is_constant<T2>::value) { var arena_a = a; arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var(multiply_log(arena_a.val(), arena_b.val()), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val(), arena_b.val().coeff(i, j)))) { arena_a.adj() = NOT_A_NUMBER; arena_b.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { arena_a.adj() += res.adj().coeff(i, j) * log(arena_b.val().coeff(i, j)); if (arena_b.val().coeff(i, j) == 0.0 && arena_a.val() == 0) { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * arena_a.val() / arena_b.val().coeff(i, j); } } } } }); } else if (!is_constant<T1>::value) { var arena_a = a; auto arena_b = to_arena(value_of(b)); return make_callback_var(multiply_log(arena_a.val(), arena_b), [arena_a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(arena_a.val(), arena_b.val().coeff(i, j)))) { arena_a.adj() = NOT_A_NUMBER; } else { arena_a.adj() += res.adj().coeff(i, j) * log(arena_b.val().coeff(i, j)); } } } }); } else { arena_t<promote_scalar_t<var, T2>> arena_b = b; return make_callback_var(multiply_log(value_of(a), arena_b.val()), [a, arena_b](const auto& res) mutable { for(Eigen::Index j = 0; j < res.adj().cols(); ++j) { for(Eigen::Index i = 0; i < res.adj().rows(); ++i) { if (unlikely(is_any_nan(value_of(a), arena_b.val().coeff(i, j)))) { arena_b.adj().coeffRef(i, j) = NOT_A_NUMBER; } else { if (arena_b.val().coeff(i, j) == 0.0 && value_of(a) == 0) { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * INFTY; } else { arena_b.adj().coeffRef(i, j) += res.adj().coeff(i, j) * value_of(a) / arena_b.val().coeff(i, j); } } } } }); } } } // namespace math } // namespace stan #endif <|endoftext|>
<commit_before>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <cstddef> #include <cstring> #include <iostream> #include <memory> #include <ostream> #include <stdexcept> #include <rapidjson/document.h> #include <rapidjson/filereadstream.h> #include "cfile.h" #include "model.h" #include "sg.h" #include "vsnray_loader.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // Function declarations // void parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries); template <typename Object> std::shared_ptr<sg::node> parse_reference(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_transform(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_surface_properties(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_triangle_mesh(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_indexed_triangle_mesh(Object const& obj); //------------------------------------------------------------------------------------------------- // Parse nodes // void parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries) { parent->children().resize(entries.MemberCount()); size_t i = 0; for (auto const& c : entries.GetArray()) { auto const& obj = c.GetObject(); if (obj.HasMember("type")) { auto const& type_string = obj["type"]; if (strncmp(type_string.GetString(), "reference", 9) == 0) { parent->children().at(i++) = parse_reference(obj); } else if (strncmp(type_string.GetString(), "transform", 9) == 0) { parent->children().at(i++) = parse_transform(obj); } else if (strncmp(type_string.GetString(), "surface_properties", 18) == 0) { parent->children().at(i++) = parse_surface_properties(obj); } else if (strncmp(type_string.GetString(), "triangle_mesh", 13) == 0) { parent->children().at(i++) = parse_triangle_mesh(obj); } else if (strncmp(type_string.GetString(), "indexed_triangle_mesh", 21) == 0) { parent->children().at(i++) = parse_indexed_triangle_mesh(obj); } else { throw std::runtime_error(""); } } else { throw std::runtime_error(""); } } if (i != entries.MemberCount()) { throw std::runtime_error(""); } } template <typename Object> std::shared_ptr<sg::node> parse_reference(Object const& obj) { return std::make_shared<sg::node>(); } template <typename Object> std::shared_ptr<sg::node> parse_transform(Object const& obj) { auto transform = std::make_shared<sg::transform>(); if (obj.HasMember("matrix")) { auto const& mat = obj["matrix"]; int i = 0; for (auto const& item : mat.GetArray()) { transform->matrix().data()[i++] = item.GetFloat(); assert(i <= 16); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(transform, children); } return transform; } template <typename Object> std::shared_ptr<sg::node> parse_surface_properties(Object const& obj) { auto props = std::make_shared<sg::surface_properties>(); if (obj.HasMember("material")) { auto const& mat = obj["material"]; if (mat.HasMember("type")) { auto const& type_string = mat["type"]; if (strncmp(type_string.GetString(), "obj", 3) == 0) { auto obj = std::make_shared<sg::obj_material>(); if (mat.HasMember("ca")) { auto const& ca = mat["ca"]; vec3 clr; int i = 0; for (auto const& item : ca.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->ca = clr; } if (mat.HasMember("cd")) { auto const& cd = mat["cd"]; vec3 clr; int i = 0; for (auto const& item : cd.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->cd = clr; } if (mat.HasMember("cs")) { auto const& cs = mat["cs"]; vec3 clr; int i = 0; for (auto const& item : cs.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->cs = clr; } if (mat.HasMember("ce")) { auto const& ce = mat["ce"]; vec3 clr; int i = 0; for (auto const& item : ce.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->ce = clr; } props->material() = obj; } else { throw std::runtime_error(""); } } else { throw std::runtime_error(""); } } else { // Set default material (wavefront obj) auto obj = std::make_shared<sg::obj_material>(); props->material() = obj; } if (obj.HasMember("diffuse")) { // TODO: load from file #if 1 vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f); auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>(); tex->resize(1, 1); tex->set_address_mode(Wrap); tex->set_filter_mode(Nearest); tex->reset(&dummy_texel); props->add_texture(tex); #endif } else { // Set a dummy texture vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f); auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>(); tex->resize(1, 1); tex->set_address_mode(Wrap); tex->set_filter_mode(Nearest); tex->reset(&dummy_texel); props->add_texture(tex); } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(props, children); } return props; } template <typename Object> std::shared_ptr<sg::node> parse_triangle_mesh(Object const& obj) { auto mesh = std::make_shared<sg::triangle_mesh>(); if (obj.HasMember("vertices")) { auto const& verts = obj["vertices"]; vec3 v; int i = 0; for (auto const& item : verts.GetArray()) { v[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->vertices.emplace_back(v); } } } if (obj.HasMember("normals")) { auto const& normals = obj["normals"]; vec3 n; int i = 0; for (auto const& item : normals.GetArray()) { n[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->normals.emplace_back(n); } } } else { for (size_t i = 0; i < mesh->vertices.size(); i += 3) { vec3 v1 = mesh->vertices[i]; vec3 v2 = mesh->vertices[i + 1]; vec3 v3 = mesh->vertices[i + 2]; vec3 gn = normalize(cross(v2 - v1, v3 - v1)); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); } } if (obj.HasMember("tex_coords")) { auto const& tex_coords = obj["tex_coords"]; vec3 tc; int i = 0; for (auto const& item : tex_coords.GetArray()) { tc[i++ % 2] = item.GetFloat(); if (i % 2 == 0) { mesh->tex_coords.emplace_back(tc); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->tex_coords.emplace_back(0.0f, 0.0f); } } if (obj.HasMember("colors")) { auto const& colors = obj["colors"]; vector<3, unorm<8>> c; int i = 0; for (auto const& item : colors.GetArray()) { c[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->colors.emplace_back(c); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->colors.emplace_back(1.0f); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(mesh, children); } return mesh; } template <typename Object> std::shared_ptr<sg::node> parse_indexed_triangle_mesh(Object const& obj) { auto mesh = std::make_shared<sg::indexed_triangle_mesh>(); if (obj.HasMember("indices")) { auto const& indices = obj["indices"]; for (auto const& item : indices.GetArray()) { mesh->indices.push_back(item.GetInt()); } } if (obj.HasMember("vertices")) { auto const& verts = obj["vertices"]; vec3 v; int i = 0; for (auto const& item : verts.GetArray()) { v[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->vertices.emplace_back(v); } } } if (obj.HasMember("normals")) { auto const& normals = obj["normals"]; vec3 n; int i = 0; for (auto const& item : normals.GetArray()) { n[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->normals.emplace_back(n); } } } else { for (size_t i = 0; i < mesh->vertices.size(); i += 3) { vec3 v1 = mesh->vertices[i]; vec3 v2 = mesh->vertices[i + 1]; vec3 v3 = mesh->vertices[i + 2]; vec3 gn = normalize(cross(v2 - v1, v3 - v1)); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); } } if (obj.HasMember("tex_coords")) { auto const& tex_coords = obj["tex_coords"]; vec3 tc; int i = 0; for (auto const& item : tex_coords.GetArray()) { tc[i++ % 2] = item.GetFloat(); if (i % 2 == 0) { mesh->tex_coords.emplace_back(tc); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->tex_coords.emplace_back(0.0f, 0.0f); } } if (obj.HasMember("colors")) { auto const& colors = obj["colors"]; vector<3, unorm<8>> c; int i = 0; for (auto const& item : colors.GetArray()) { c[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->colors.emplace_back(c); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->colors.emplace_back(1.0f); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(mesh, children); } return mesh; } //------------------------------------------------------------------------------------------------- // Interface // void load_vsnray(std::string const& filename, model& mod) { std::vector<std::string> filenames(1); filenames[0] = filename; load_vsnray(filenames, mod); } void load_vsnray(std::vector<std::string> const& filenames, model& mod) { auto root = std::make_shared<sg::node>(); for (auto filename : filenames) { cfile file(filename, "r"); if (!file.good()) { std::cerr << "Cannot open " << filename << '\n'; return; } char buffer[65536]; rapidjson::FileReadStream frs(file.get(), buffer, sizeof(buffer)); rapidjson::Document doc; doc.ParseStream(frs); if (doc.HasMember("children")) { rapidjson::Value const& children = doc["children"]; parse_children(root, children); } } if (mod.scene_graph == nullptr) { mod.scene_graph = std::make_shared<sg::node>(); } mod.scene_graph->add_child(root); } } // visionaray <commit_msg>Parse camera nodes<commit_after>// This file is distributed under the MIT license. // See the LICENSE file for details. #include <cassert> #include <cstddef> #include <cstring> #include <iostream> #include <memory> #include <ostream> #include <stdexcept> #include <rapidjson/document.h> #include <rapidjson/filereadstream.h> #include "cfile.h" #include "model.h" #include "sg.h" #include "vsnray_loader.h" namespace visionaray { //------------------------------------------------------------------------------------------------- // Function declarations // void parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries); template <typename Object> std::shared_ptr<sg::node> parse_camera(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_reference(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_transform(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_surface_properties(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_triangle_mesh(Object const& obj); template <typename Object> std::shared_ptr<sg::node> parse_indexed_triangle_mesh(Object const& obj); //------------------------------------------------------------------------------------------------- // Parse nodes // void parse_children(std::shared_ptr<sg::node> parent, rapidjson::Value const& entries) { parent->children().resize(entries.MemberCount()); size_t i = 0; for (auto const& c : entries.GetArray()) { auto const& obj = c.GetObject(); if (obj.HasMember("type")) { auto const& type_string = obj["type"]; if (strncmp(type_string.GetString(), "camera", 6) == 0) { parent->children().at(i++) = parse_camera(obj); } else if (strncmp(type_string.GetString(), "reference", 9) == 0) { parent->children().at(i++) = parse_reference(obj); } else if (strncmp(type_string.GetString(), "transform", 9) == 0) { parent->children().at(i++) = parse_transform(obj); } else if (strncmp(type_string.GetString(), "surface_properties", 18) == 0) { parent->children().at(i++) = parse_surface_properties(obj); } else if (strncmp(type_string.GetString(), "triangle_mesh", 13) == 0) { parent->children().at(i++) = parse_triangle_mesh(obj); } else if (strncmp(type_string.GetString(), "indexed_triangle_mesh", 21) == 0) { parent->children().at(i++) = parse_indexed_triangle_mesh(obj); } else { throw std::runtime_error(""); } } else { throw std::runtime_error(""); } } if (i != entries.MemberCount()) { throw std::runtime_error(""); } } template <typename Object> std::shared_ptr<sg::node> parse_camera(Object const& obj) { auto cam = std::make_shared<sg::camera>(); vec3 eye(0.0f); if (obj.HasMember("eye")) { auto const& cam_eye = obj["eye"]; int i = 0; for (auto const& item : cam_eye.GetArray()) { eye[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } } vec3 center(0.0f); if (obj.HasMember("center")) { auto const& cam_center = obj["center"]; int i = 0; for (auto const& item : cam_center.GetArray()) { center[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } } vec3 up(0.0f); if (obj.HasMember("up")) { auto const& cam_up = obj["up"]; int i = 0; for (auto const& item : cam_up.GetArray()) { up[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } } float fovy = 0.0f; if (obj.HasMember("fovy")) { fovy = obj["fovy"].GetFloat(); } float znear = 0.0f; if (obj.HasMember("znear")) { znear = obj["znear"].GetFloat(); } float zfar = 0.0f; if (obj.HasMember("zfar")) { zfar = obj["zfar"].GetFloat(); } recti viewport; if (obj.HasMember("viewport")) { auto const& cam_viewport = obj["viewport"]; int i = 0; for (auto const& item : cam_viewport.GetArray()) { viewport.data()[i++] = item.GetInt(); } if (i != 4) { throw std::runtime_error(""); } } float lens_radius = 0.0f; if (obj.HasMember("lens_radius")) { lens_radius = obj["lens_radius"].GetFloat(); } float focal_distance = 0.0f; if (obj.HasMember("focal_distance")) { focal_distance = obj["focal_distance"].GetFloat(); } float aspect = viewport.w > 0 && viewport.h > 0 ? viewport.w / static_cast<float>(viewport.h) : 1; cam->perspective(fovy * constants::degrees_to_radians<float>(), aspect, znear, zfar); cam->set_viewport(viewport); cam->set_lens_radius(lens_radius); cam->set_focal_distance(focal_distance); cam->look_at(eye, center, up); if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(cam, children); } return cam; } template <typename Object> std::shared_ptr<sg::node> parse_reference(Object const& obj) { return std::make_shared<sg::node>(); } template <typename Object> std::shared_ptr<sg::node> parse_transform(Object const& obj) { auto transform = std::make_shared<sg::transform>(); if (obj.HasMember("matrix")) { auto const& mat = obj["matrix"]; int i = 0; for (auto const& item : mat.GetArray()) { transform->matrix().data()[i++] = item.GetFloat(); assert(i <= 16); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(transform, children); } return transform; } template <typename Object> std::shared_ptr<sg::node> parse_surface_properties(Object const& obj) { auto props = std::make_shared<sg::surface_properties>(); if (obj.HasMember("material")) { auto const& mat = obj["material"]; if (mat.HasMember("type")) { auto const& type_string = mat["type"]; if (strncmp(type_string.GetString(), "obj", 3) == 0) { auto obj = std::make_shared<sg::obj_material>(); if (mat.HasMember("ca")) { auto const& ca = mat["ca"]; vec3 clr; int i = 0; for (auto const& item : ca.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->ca = clr; } if (mat.HasMember("cd")) { auto const& cd = mat["cd"]; vec3 clr; int i = 0; for (auto const& item : cd.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->cd = clr; } if (mat.HasMember("cs")) { auto const& cs = mat["cs"]; vec3 clr; int i = 0; for (auto const& item : cs.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->cs = clr; } if (mat.HasMember("ce")) { auto const& ce = mat["ce"]; vec3 clr; int i = 0; for (auto const& item : ce.GetArray()) { clr[i++] = item.GetFloat(); } if (i != 3) { throw std::runtime_error(""); } obj->ce = clr; } props->material() = obj; } else { throw std::runtime_error(""); } } else { throw std::runtime_error(""); } } else { // Set default material (wavefront obj) auto obj = std::make_shared<sg::obj_material>(); props->material() = obj; } if (obj.HasMember("diffuse")) { // TODO: load from file #if 1 vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f); auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>(); tex->resize(1, 1); tex->set_address_mode(Wrap); tex->set_filter_mode(Nearest); tex->reset(&dummy_texel); props->add_texture(tex); #endif } else { // Set a dummy texture vector<4, unorm<8>> dummy_texel(1.0f, 1.0f, 1.0f, 1.0f); auto tex = std::make_shared<sg::texture2d<vector<4, unorm<8>>>>(); tex->resize(1, 1); tex->set_address_mode(Wrap); tex->set_filter_mode(Nearest); tex->reset(&dummy_texel); props->add_texture(tex); } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(props, children); } return props; } template <typename Object> std::shared_ptr<sg::node> parse_triangle_mesh(Object const& obj) { auto mesh = std::make_shared<sg::triangle_mesh>(); if (obj.HasMember("vertices")) { auto const& verts = obj["vertices"]; vec3 v; int i = 0; for (auto const& item : verts.GetArray()) { v[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->vertices.emplace_back(v); } } } if (obj.HasMember("normals")) { auto const& normals = obj["normals"]; vec3 n; int i = 0; for (auto const& item : normals.GetArray()) { n[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->normals.emplace_back(n); } } } else { for (size_t i = 0; i < mesh->vertices.size(); i += 3) { vec3 v1 = mesh->vertices[i]; vec3 v2 = mesh->vertices[i + 1]; vec3 v3 = mesh->vertices[i + 2]; vec3 gn = normalize(cross(v2 - v1, v3 - v1)); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); } } if (obj.HasMember("tex_coords")) { auto const& tex_coords = obj["tex_coords"]; vec3 tc; int i = 0; for (auto const& item : tex_coords.GetArray()) { tc[i++ % 2] = item.GetFloat(); if (i % 2 == 0) { mesh->tex_coords.emplace_back(tc); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->tex_coords.emplace_back(0.0f, 0.0f); } } if (obj.HasMember("colors")) { auto const& colors = obj["colors"]; vector<3, unorm<8>> c; int i = 0; for (auto const& item : colors.GetArray()) { c[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->colors.emplace_back(c); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->colors.emplace_back(1.0f); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(mesh, children); } return mesh; } template <typename Object> std::shared_ptr<sg::node> parse_indexed_triangle_mesh(Object const& obj) { auto mesh = std::make_shared<sg::indexed_triangle_mesh>(); if (obj.HasMember("indices")) { auto const& indices = obj["indices"]; for (auto const& item : indices.GetArray()) { mesh->indices.push_back(item.GetInt()); } } if (obj.HasMember("vertices")) { auto const& verts = obj["vertices"]; vec3 v; int i = 0; for (auto const& item : verts.GetArray()) { v[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->vertices.emplace_back(v); } } } if (obj.HasMember("normals")) { auto const& normals = obj["normals"]; vec3 n; int i = 0; for (auto const& item : normals.GetArray()) { n[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->normals.emplace_back(n); } } } else { for (size_t i = 0; i < mesh->vertices.size(); i += 3) { vec3 v1 = mesh->vertices[i]; vec3 v2 = mesh->vertices[i + 1]; vec3 v3 = mesh->vertices[i + 2]; vec3 gn = normalize(cross(v2 - v1, v3 - v1)); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); mesh->normals.emplace_back(gn); } } if (obj.HasMember("tex_coords")) { auto const& tex_coords = obj["tex_coords"]; vec3 tc; int i = 0; for (auto const& item : tex_coords.GetArray()) { tc[i++ % 2] = item.GetFloat(); if (i % 2 == 0) { mesh->tex_coords.emplace_back(tc); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->tex_coords.emplace_back(0.0f, 0.0f); } } if (obj.HasMember("colors")) { auto const& colors = obj["colors"]; vector<3, unorm<8>> c; int i = 0; for (auto const& item : colors.GetArray()) { c[i++ % 3] = item.GetFloat(); if (i % 3 == 0) { mesh->colors.emplace_back(c); } } } else { for (size_t i = 0; i < mesh->vertices.size(); ++i) { mesh->colors.emplace_back(1.0f); } } if (obj.HasMember("children")) { rapidjson::Value const& children = obj["children"]; parse_children(mesh, children); } return mesh; } //------------------------------------------------------------------------------------------------- // Interface // void load_vsnray(std::string const& filename, model& mod) { std::vector<std::string> filenames(1); filenames[0] = filename; load_vsnray(filenames, mod); } void load_vsnray(std::vector<std::string> const& filenames, model& mod) { auto root = std::make_shared<sg::node>(); for (auto filename : filenames) { cfile file(filename, "r"); if (!file.good()) { std::cerr << "Cannot open " << filename << '\n'; return; } char buffer[65536]; rapidjson::FileReadStream frs(file.get(), buffer, sizeof(buffer)); rapidjson::Document doc; doc.ParseStream(frs); if (doc.HasMember("children")) { rapidjson::Value const& children = doc["children"]; parse_children(root, children); } } if (mod.scene_graph == nullptr) { mod.scene_graph = std::make_shared<sg::node>(); } mod.scene_graph->add_child(root); } } // visionaray <|endoftext|>
<commit_before>/***************************************************************************** * volume.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * Olivier Teulière <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_aout.h> #include <vlc_playlist.h> #include "volume.hpp" Volume::Volume( intf_thread_t *pIntf ): VarPercent( pIntf ) { // Initial value audio_volume_t val; aout_VolumeGet( getIntf()->p_sys->p_playlist, &val ); VarPercent::set( val * 2.0 / AOUT_VOLUME_MAX ); } void Volume::set( float percentage ) { // Avoid looping forever... if( (int)(get() * AOUT_VOLUME_MAX) != (int)(percentage * AOUT_VOLUME_MAX) ) { VarPercent::set( percentage ); aout_VolumeSet( getIntf()->p_sys->p_playlist(), (int)(get() * AOUT_VOLUME_MAX / 2.0) ); } } string Volume::getAsStringPercent() const { int value = (int)(100. * VarPercent::get()); // 0 <= value <= 100, so we need 4 chars char *str = new char[4]; snprintf( str, 4, "%d", value ); string ret = str; delete[] str; return ret; } <commit_msg>skins: typo<commit_after>/***************************************************************************** * volume.cpp ***************************************************************************** * Copyright (C) 2003 the VideoLAN team * $Id$ * * Authors: Cyril Deguet <[email protected]> * Olivier Teulière <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <vlc_common.h> #include <vlc_aout.h> #include <vlc_playlist.h> #include "volume.hpp" Volume::Volume( intf_thread_t *pIntf ): VarPercent( pIntf ) { // Initial value audio_volume_t val; aout_VolumeGet( getIntf()->p_sys->p_playlist, &val ); VarPercent::set( val * 2.0 / AOUT_VOLUME_MAX ); } void Volume::set( float percentage ) { // Avoid looping forever... if( (int)(get() * AOUT_VOLUME_MAX) != (int)(percentage * AOUT_VOLUME_MAX) ) { VarPercent::set( percentage ); aout_VolumeSet( getIntf()->p_sys->p_playlist, (int)(get() * AOUT_VOLUME_MAX / 2.0) ); } } string Volume::getAsStringPercent() const { int value = (int)(100. * VarPercent::get()); // 0 <= value <= 100, so we need 4 chars char *str = new char[4]; snprintf( str, 4, "%d", value ); string ret = str; delete[] str; return ret; } <|endoftext|>
<commit_before>#include "nan.h" #include "marker-index.h" using namespace std; using namespace v8; class MarkerIndexWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructorTemplate = Nan::New<FunctionTemplate>(New); constructorTemplate->SetClassName( Nan::New<String>("MarkerIndex").ToLocalChecked()); constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1); constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("generateRandomNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(GenerateRandomNumber)->GetFunction()); constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("insert").ToLocalChecked(), Nan::New<FunctionTemplate>(Insert)->GetFunction()); row_key.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_key.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); module->Set(Nan::New("exports").ToLocalChecked(), constructorTemplate->GetFunction()); } private: static Nan::Persistent<String> row_key; static Nan::Persistent<String> column_key; static NAN_METHOD(New) { MarkerIndexWrapper *marker_index = new MarkerIndexWrapper(Local<Number>::Cast(info[0])); marker_index->Wrap(info.This()); } static NAN_METHOD(GenerateRandomNumber) { MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This()); int random = wrapper->marker_index.GenerateRandomNumber(); info.GetReturnValue().Set(Nan::New<v8::Number>(random)); } static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_key))); Local<Integer> row; if (!maybe_row.ToLocal(&row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_key))); Local<Integer> column; if (!maybe_column.ToLocal(&column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } return Nan::Just(Point( static_cast<unsigned>(row->Int32Value()), static_cast<unsigned>(column->Int32Value()) )); } static NAN_METHOD(Insert) { MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This()); Local<Integer> id; Nan::MaybeLocal<Integer> maybe_id = Nan::To<Integer>(info[0]); if (!maybe_id.ToLocal(&id)) { Nan::ThrowTypeError("Expected an integer marker id."); return; } Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[1])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[2])); if (start.IsJust() && end.IsJust()) { wrapper->marker_index.Insert(static_cast<unsigned>(id->Uint32Value()), start.FromJust(), end.FromJust()); } } MarkerIndexWrapper(v8::Local<v8::Number> seed) : marker_index{static_cast<unsigned>(seed->Int32Value())} {} MarkerIndex marker_index; }; Nan::Persistent<String> MarkerIndexWrapper::row_key; Nan::Persistent<String> MarkerIndexWrapper::column_key; NODE_MODULE(marker_index, MarkerIndexWrapper::Init) <commit_msg>Don't use NAN_METHOD macro<commit_after>#include "nan.h" #include "marker-index.h" using namespace std; using namespace v8; class MarkerIndexWrapper : public Nan::ObjectWrap { public: static void Init(Local<Object> exports, Local<Object> module) { Local<FunctionTemplate> constructorTemplate = Nan::New<FunctionTemplate>(New); constructorTemplate->SetClassName( Nan::New<String>("MarkerIndex").ToLocalChecked()); constructorTemplate->InstanceTemplate()->SetInternalFieldCount(1); constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("generateRandomNumber").ToLocalChecked(), Nan::New<FunctionTemplate>(GenerateRandomNumber)->GetFunction()); constructorTemplate->PrototypeTemplate()->Set(Nan::New<String>("insert").ToLocalChecked(), Nan::New<FunctionTemplate>(Insert)->GetFunction()); row_key.Reset(Nan::Persistent<String>(Nan::New("row").ToLocalChecked())); column_key.Reset(Nan::Persistent<String>(Nan::New("column").ToLocalChecked())); module->Set(Nan::New("exports").ToLocalChecked(), constructorTemplate->GetFunction()); } private: static Nan::Persistent<String> row_key; static Nan::Persistent<String> column_key; static void New(const Nan::FunctionCallbackInfo<Value> &info) { MarkerIndexWrapper *marker_index = new MarkerIndexWrapper(Local<Number>::Cast(info[0])); marker_index->Wrap(info.This()); } static void GenerateRandomNumber(const Nan::FunctionCallbackInfo<Value> &info) { MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This()); int random = wrapper->marker_index.GenerateRandomNumber(); info.GetReturnValue().Set(Nan::New<v8::Number>(random)); } static Nan::Maybe<Point> PointFromJS(Nan::MaybeLocal<Object> maybe_object) { Local<Object> object; if (!maybe_object.ToLocal(&object)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_row = Nan::To<Integer>(object->Get(Nan::New(row_key))); Local<Integer> row; if (!maybe_row.ToLocal(&row)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } Nan::MaybeLocal<Integer> maybe_column = Nan::To<Integer>(object->Get(Nan::New(column_key))); Local<Integer> column; if (!maybe_column.ToLocal(&column)) { Nan::ThrowTypeError("Expected an object with 'row' and 'column' properties."); return Nan::Nothing<Point>(); } return Nan::Just(Point( static_cast<unsigned>(row->Int32Value()), static_cast<unsigned>(column->Int32Value()) )); } static void Insert(const Nan::FunctionCallbackInfo<Value> &info) { MarkerIndexWrapper *wrapper = Nan::ObjectWrap::Unwrap<MarkerIndexWrapper>(info.This()); Local<Integer> id; Nan::MaybeLocal<Integer> maybe_id = Nan::To<Integer>(info[0]); if (!maybe_id.ToLocal(&id)) { Nan::ThrowTypeError("Expected an integer marker id."); return; } Nan::Maybe<Point> start = PointFromJS(Nan::To<Object>(info[1])); Nan::Maybe<Point> end = PointFromJS(Nan::To<Object>(info[2])); if (start.IsJust() && end.IsJust()) { wrapper->marker_index.Insert(static_cast<unsigned>(id->Uint32Value()), start.FromJust(), end.FromJust()); } } MarkerIndexWrapper(v8::Local<v8::Number> seed) : marker_index{static_cast<unsigned>(seed->Int32Value())} {} MarkerIndex marker_index; }; Nan::Persistent<String> MarkerIndexWrapper::row_key; Nan::Persistent<String> MarkerIndexWrapper::column_key; NODE_MODULE(marker_index, MarkerIndexWrapper::Init) <|endoftext|>