blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
3c3a0e5c5881e858b6eed94354fc7fba8b3e65fd
b180c871e6f14661c7e37fe53540b07a9748399e
/AllCasting_explictTypeConversion/main.cpp
8ad0d5794c124657a1275452baf7030697fea842
[]
no_license
lizhang101/CPP
c269995936a8c6bf6a4b195082f424ac0de9bc77
2abe40dbc9bfcf83f56b499adcdd477c51306211
refs/heads/master
2020-12-09T02:07:25.547138
2020-03-24T01:26:43
2020-03-24T01:26:43
233,160,525
0
0
null
null
null
null
UTF-8
C++
false
false
5,581
cpp
#include <iostream> class dog{}; class yellowdog{}; //############################################################################ /* * All Castings Considered * * * Type Conversion: * 1. Implicit Type Conversion * 2. Explicit Type Conversion - Casting */ /* * 1. static_cast */ int i = 9; float f = static_cast<float>(i); // convert OBJECT from one type to another dog d1 = static_cast<dog>(string("Bob")); // Type conversion needs to be defined. dog* pd = static_cast<dog*>(new yellowdog()); // convert pointer/reference from one type // to a related type (down/up cast) /* * 2. dynamic_cast */ dog* pd = new yellowdog(); yellowdog py = dynamic_cast<yellowdog*>(pd); // a. It convert pointer/reference from one type to a related type (down cast) // b. run-time type check. If succeed, py==pd; if fail, py==0; // c. It requires the 2 types to be polymorphic (have virtual function). /* * 3. const_cast */ // only works on pointer/reference const char* str = "Hello, world."; // Only works on same type char* modifiable = const_cast<char*>(str); // cast away constness of the object // being pointed to /* * 4. reinterpret_cast */ long p = 51110980; dog* dd = reinterpret_cast<dog*>(p); // re-interpret the bits of the object pointed to // The ultimate cast that can cast one pointer to any other type of pointer. /* * C-Style Casting: */ short a = 2000; int i = (int)a; // c-like cast notation int j = int(a); // functional notation // A mixture of static_cast, const_cast and reinterpret_cast /* * Generally C++ style of casts are preferred over the C-style, because: * 1. Easier to identify in the code. * 2. Less usage error. C++ style provides: * a. Narrowly specified purpose of each cast, and * b. Run-time type check capability. */ /* * Casting could be risky. * * Example with dynamic_cast: */ class dog { public: virtual ~dog() {} }; class yellowdog : public dog { int age; public: void bark() { cout<< "woof. I am " << age << endl; } }; int main() { dog* pd = new dog(); //... after a long code, we make mistakes. using pd as yellowdog. yellowdog* py = dynamic_cast<yellowdog*>(pd); py->bark(); //the compiler will look up a static function. since bark in derived class doesn't access any member, // it could be treated as static function. so compiler will call yellowdog::bark with a base class pointer, // even it's not a virtual function. cout << "py = " << py << endl; cout << "pd = " << pd << endl; // solution 1: check py if (py) py->bark(); //solution 2(better) : // define a virtual bark() in dog. } OUTPUT: woof. py = 0 pd = 57873400 /* casting could be a handy hack tool */ class dog { public: std::string m_name; dog():m_name("Bob") {} void bark() const { std::cout << "My name is " << m_name << std::endl; } }; // m_name = "Henry"; // const_cast<dog*>(this)->m_name = "Henry"; /* * ========================================= C++ Style Casting ================================ * Generate_Code Generate_data risky data_type * Object Casting: * static_cast yes yes 2 any types * (as long as type * conversion is defined) * Pointer/Reference Casting: * static_cast no no 4 related types * dynamic_cast yes no 3 related types(down-cast) * const_cast no no 1 same type * reinterpret_cast no no 5 any types * * * * * * ========================================= C Style Casting ================================ * Generate_Code Generate_data risky data_type * Object Casting: yes yes 5 any types * (as long as type * conversion is defined) * Pointer/Reference Casting: no no 5 any types * * * Notes can be downloaded at my website: boqian.weebly.com * * Note: * 1. const_cast, dynamic_cast and reinterpret_cast can only work on pointers/references. * 2. static_cast of objects is very different from static_cast of pointers. * 3. reinterpret_cast basically reassigning the type information of the bit pattern. * It should only be used in low-level coding. * 4. dynamic_cast does static_cast plus run-time type check. * 5. dynamic_cast and static_cast for pointers can only work on related type (e.g., * base <-> derived). * */ /* Use polymorphism to minimize castings */ class dog { public: virtual ~dog() {} }; class yellowdog : public dog { public: void bark() { cout<< "Yellow dog rules! " << endl; } }; int main() { dog* pd = get_dog(); if (yellowdog *py = dynamic_cast<yellowdog*>(pd)) { py->bark(); } delete pd; } /* Add virtual bark() in dog */ class dog { public: virtual ~dog() {} virtual void bark() {} }; class yellowdog : public dog { public: void bark() { cout<< "Yellow dog rules! " << endl; } }; int main() { dog* pd = get_dog(); pd->bark(); delete pd; }
[ "zhali@qti.qualcomm.com" ]
zhali@qti.qualcomm.com
f923fbf1e63848e98d700922b9585f6870052ba5
4aae2df13bfd53a8b16aa5f941f2cc8b8ac144b7
/torch/csrc/jit/serialization/python_print.cpp
06c22a90ae36b07c88d07a5f32fb78ac4aa1fe67
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0" ]
permissive
computerguy2030/pytorch-rocm-amd
e9f2718c470b505325d396baf6513e71bcf0a7ca
38da53d721fcb335dedb1b52f14fd89718e90bef
refs/heads/master
2023-04-08T00:55:01.542663
2021-04-16T11:33:39
2021-04-16T11:33:39
334,288,140
3
0
NOASSERTION
2021-04-16T11:27:55
2021-01-29T23:40:06
C++
UTF-8
C++
false
false
53,919
cpp
#include <torch/csrc/jit/serialization/python_print.h> #include <ATen/core/qualified_name.h> #include <c10/util/Exception.h> #include <c10/util/StringUtil.h> #include <torch/csrc/jit/api/module.h> #include <torch/csrc/jit/frontend/error_report.h> #include <torch/csrc/jit/frontend/versioned_symbols.h> #include <torch/csrc/jit/ir/attributes.h> #include <torch/csrc/jit/ir/ir.h> #include <torch/csrc/jit/ir/ir_views.h> #include <torch/csrc/jit/resource_guard.h> #include <algorithm> using c10::QualifiedName; namespace torch { namespace jit { static bool isValidIdentifierChar(char c, size_t pos) { return islower(c) || isupper(c) || c == '_' || (pos > 0 && isdigit(c)); } static bool isValidIdentifier(const std::string& name) { if (name.size() == 0) return false; for (size_t i = 0; i < name.size(); ++i) { if (!isValidIdentifierChar(name[i], i)) return false; } return true; } // some names are valid identifiers but off limits because // they are keywords or namespaces used in the output const static std::unordered_set<std::string> reserved_names = { // identifiers in the environment while parsing "_", // avoid the confusing unnamed _ "as", "aten", "attribute", "CONSTANTS", "fork", "getattr", "inf", "nan", "infj", "nanj", "ops", "__torch__", // the python keywords "and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "False", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda", "None", "nonlocal", "not", "or", "pass", "raise", "return", "True", "try", "with", "while", "with", "yield", "uninitialized", "unchecked_cast", }; // Helper to avoid duplicating class types void PrintDepsTable::add(const c10::NamedTypePtr& type) { // Despite doing the linear search below, we don't want to do // wasteful work and only try to insert each instance once. if (!non_unique_.insert(type).second) { return; } // Need to do actual equality comparison, not a pointer equality. This is // because for some types (e.g. FunctionType), we may have multiple // TypePtr's that represent the same underlying thing. // TODO: this should be really swapped for something more efficient auto it = std::find_if( table_.cbegin(), table_.cend(), [&](const c10::NamedTypePtr& dep) { return *dep == *type; }); if (it == table_.cend()) { table_.push_back(type); } } struct PythonPrintImpl { using SourceRangeStack = std::vector<SourceRange>; SourceRangeStack source_range_stack_ = {SourceRange()}; struct WithSourceRange { explicit WithSourceRange(SourceRangeStack* stack, Node* n) : stack(stack) { TORCH_INTERNAL_ASSERT(stack); if (auto gen_source = n->sourceRange().findSourceRangeThatGenerated()) { stack->push_back(std::move(gen_source.value())); } else { stack->push_back(n->sourceRange()); } } ~WithSourceRange() { stack->pop_back(); } SourceRangeStack* stack; }; class TaggedStringStream { public: TaggedStringStream(const SourceRangeStack* srs) : srs_(srs) {} TaggedStringStream& operator<<(const std::string& s) { // This prevents having redundant entries at the same offset, // which can happen for example in printValueList when begin // and end are the empty string. if (s.size() == 0) { return *this; } if (!ranges_.size() || ranges_.back().range != srs_->back()) { ranges_.emplace_back((size_t)oss_.tellp(), srs_->back()); } oss_ << s; return *this; } TaggedStringStream& operator<<(const TaggedStringStream& rhs) { for (const auto& range : rhs.ranges_) { if (!ranges_.size() || ranges_.back().range != range.range) { ranges_.emplace_back((size_t)oss_.tellp() + range.bytes, range.range); } } oss_ << rhs.oss_.str(); return *this; } // This overload is here to prevent people from shooting themselves in the // foot. I would be highly surprised if someone actually wanted to write out // the address of a TaggedStringStream in the pretty print. TaggedStringStream& operator<<( const std::shared_ptr<TaggedStringStream>& rhs) { (*this) << *rhs; return *this; } template <typename T> TaggedStringStream& operator<<(const T& t) { if (!ranges_.size() || ranges_.back().range != srs_->back()) { ranges_.emplace_back((size_t)oss_.tellp(), srs_->back()); } oss_ << t; return *this; } std::string str() const { return oss_.str(); } const std::vector<TaggedRange>& ranges() const { return ranges_; } private: std::ostringstream oss_; std::vector<TaggedRange> ranges_; const SourceRangeStack* srs_; }; // scanValue, scanNode, scanBlock: // decide if it is safe to omit the output of a temporary variable, // and inline the expression into its use // we only do this if // (1) it is a constant, or // (2) the temporary is unnamed, is single output, is used once, // and would appear in the same order when the expression tree is // reparsed. // The last case can be checked // because when we emit a expresion tree in the parser, // we do a left-to-right postorder traversal of the expression tree (emit // children, then emit op). The reverse of this is a right-to-left preorder // traversal of the tree. By doing a right-to-left preorder traversal of the // inputs of a node, while also scanning the list of emitted nodes backward, // we can see if they line up with what would happen when parsed the node as // an expression. While they line up we collapse them into an inline // expression. // The inductive step is that the right-most input should be produced by the // node immediatly before the current node if it is in tree order. bool canInline(Value* v) { Node* n = v->node(); // there must be only 1 values, otherwise we need an assignment to handle // the multiple outout values if (n->outputs().size() != 1) return false; // if it is used more than once, then we need a variable if (v->uses().size() != 1) return false; auto use = v->uses().at(0); // if it has a name set, then it was written as a variable so preserve that // unless it is being fed directly to the end of the block. // in which case it is not as useful to give it a name just to return it if (v->hasDebugName() && use.user->kind() != prim::Return) return false; // don't try to inline control blocks if (n->blocks().size() != 0) return false; // if it is a loop-carried input, we need a variable // otherwise the condition or trip count may be emitted in the wrong order // w.r.t. to it if (use.user->kind() == prim::Loop && use.offset >= 2) return false; // subgraph may use this more than once, so disable inlining if (use.user->kind() == prim::fork || use.user->kind() == prim::rpc_async || use.user->kind() == prim::rpc_sync || use.user->kind() == prim::rpc_remote) return false; // isinstance appearing in an if expression // causes type refinement to occur, but we have // already handled the refinement and inserted cast // expressions. By not inlining it into the if condition, // we prevent it from happening again. if (v->node()->kind() == prim::isinstance) { return false; } return true; } // block_point is the current node in the reverse linear scan of the emitted // nodes v is the current value in the tree traversal that may match with // block_point's output. Node* scanValue(Node* block_point, Value* v) { Node* n = v->node(); AT_ASSERT(n->kind() == prim::Constant || output_inline_.count(n) == 0); if (n == block_point && canInline(v)) { // the node must be at the expected point of the typical // tree traversal // recursively see if we can inline the inputs to this input block_point = scanNode(block_point); output_inline_.insert(n); } else if (n->kind() == prim::Constant) { // constant nodes can always be inlined, we will de-dup them on parsing // and put them at the top of the function regardless output_inline_.insert(n); } return block_point; } Node* previousNonConstant(Node* n) { do { n = n->prev(); } while (n->kind() == prim::Constant); return n; } Node* scanNode(Node* n) { // don't bother to scan nodes we have already determined to be inline if (output_inline_.count(n)) { return n; } for (auto b : n->blocks()) { scanBlock(b); } Node* block_point = previousNonConstant(n); for (auto it = n->inputs().rbegin(), end = n->inputs().rend(); it != end; ++it) { block_point = scanValue(block_point, *it); } return block_point; } void scanBlock(Block* b) { scanNode(b->return_node()); for (auto node : b->nodes().reverse()) { scanNode(node); } } size_t getOrAddConstant(at::IValue val) { // XXX - N^2 warning. This code does the exact same thing as // ConstantPool, which is also N^2 in the size of the constants, // because it doesn't hash any information about the tensors. // We will probably need to optimize this at some point using hashing. if (val.isTensor()) { auto& t = val.toTensor(); for (size_t i = 0; i < constant_table_.size(); ++i) { if (!constant_table_[i].isTensor()) { continue; } auto& t2 = constant_table_[i].toTensor(); if (t.options().type_equal(t2.options()) && t.equal(t2)) { return i; } } } constant_table_.emplace_back(std::move(val)); return constant_table_.size() - 1; } std::unordered_set<Node*> seen_constants; void buildConstantList(Node* n, std::vector<Node*>& constants) { for (auto input : n->inputs()) { if (input->node()->kind() == prim::Constant && seen_constants.count(input->node()) == 0) { constants.push_back(input->node()); seen_constants.insert(input->node()); } } for (auto b : n->blocks()) { buildConstantList(b, constants); } } void buildConstantList(Block* b, std::vector<Node*>& constants) { for (auto n : b->nodes()) buildConstantList(n, constants); buildConstantList(b->return_node(), constants); } // get a new name unique across calls to debugName() and // anything we have used. std::unordered_map<std::string, size_t> next_id; std::string genNameImpl( const std::string& candidate, std::unordered_set<std::string>& used) { std::string name = candidate; while (used.count(name) || reserved_names.count(name)) { name = candidate + c10::to_string(next_id[name]++); } used.insert(name); return name; } std::string genName(const std::string& candidate) { return genNameImpl(candidate, used_names_); } // unique names might not be valid identifiers, // force them to be by rewriting them static std::string makeValidIdentifier(const std::string& candidate) { std::stringstream ss; if (candidate.size() == 0 || isdigit(candidate[0])) ss << "_"; for (char c : candidate) { if (isupper(c) || islower(c) || isdigit(c) || c == '_') ss << c; else ss << '_'; } return ss.str(); } // if we have to assign 'v' a name, what should it be? // use the debugName if it was set, otherwise generate a name. std::string genUniqueNameFor(Value* v) { return genName( v->hasDebugName() ? makeValidIdentifier(v->debugNameBase()) : "_"); } // map from Value to how it should be printed at each use std::unordered_map<Value*, std::shared_ptr<TaggedStringStream>> expr_table_; std::unordered_map<Value*, std::string> ident_refs_; // NB: we MUST pass around the shared pointers to these streams by value. // There is an interaction in splitLongInlines where the string value for // both the RHS and the LHS of an expression are live at the same time, // however the value for the RHS is overwritten in the table. std::shared_ptr<TaggedStringStream> useOf(Value* v) const { // Ident refs take precedent over expression refs, since presence in // the ident ref table indicates we have already emitted a statement // assigning the given value. if (ident_refs_.count(v)) { auto rv = std::make_shared<TaggedStringStream>(&source_range_stack_); (*rv) << ident_refs_.at(v); return rv; } if (expr_table_.count(v)) { return expr_table_.at(v); } TORCH_INTERNAL_ASSERT( false, "Value was not present in either expressions" " table or ident refs table"); } void assignValue(Value* v, const std::string& s) { ident_refs_[v] = s; } void assignValue(Value* v, std::shared_ptr<TaggedStringStream> s) { expr_table_[v] = std::move(s); } void assignValue(Value* v, Value* w) { assignValue(v, useOf(w)); } void assignValuesToTheirUniqueNames(at::ArrayRef<Value*> values) { for (auto v : values) { assignValue(v, genUniqueNameFor(v)); } } size_t level = 0; // indent to the current indent level TaggedStringStream& indent() { for (size_t i = 0; i < level; ++i) { body_ << " "; } return body_; } ResourceGuard WithIndented() { level++; return ResourceGuard([this] { level--; }); } template <class T0, class T1, class F> void zipWith(at::ArrayRef<T0> list_a, at::ArrayRef<T1> list_b, F action) const { auto it_a = list_a.begin(); auto it_b = list_b.begin(); if (list_a.size() != list_b.size()) { AT_ERROR("Python printer expected 2 lists of same size"); } for (; it_a != list_a.end(); ++it_a, ++it_b) { action(*it_a, *it_b); } } void printValueList( TaggedStringStream& stmt, at::ArrayRef<Value*> list, const char* begin = "", const char* end = "") { stmt << begin; auto delimiter = ""; for (auto* value : list) { stmt << delimiter; stmt << useOf(value); delimiter = ", "; } stmt << end; } void printValueIndex(TaggedStringStream& stmt, at::ArrayRef<Value*> inputs) { const std::string val_name = useOf(inputs[0])->str(); if (isValidIdentifier(val_name)) { stmt << val_name; } else { stmt << "(" << val_name << ")"; } stmt << "["; stmt << useOf(inputs[1]); stmt << "]"; } void printDict( TaggedStringStream& stmt, at::ArrayRef<Value*> key_value_pairs, const char* begin = "{", const char* end = "}") { stmt << begin; auto delimiter = ""; for (size_t i = 0; i < key_value_pairs.size(); i += 2) { stmt << delimiter; auto key = key_value_pairs[i]; auto value = key_value_pairs[i + 1]; stmt << useOf(key) << ": " << useOf(value); delimiter = ", "; } stmt << end; } void printAssignment(at::ArrayRef<Value*> lhs, at::ArrayRef<Value*> rhs) { if (lhs.size() == 0) { return; } indent(); printValueList(body_, lhs); body_ << " = "; printValueList(body_, rhs); body_ << "\n"; } bool requiresAnnotation(Value* lhs, Value* rhs) { return *lhs->type() != *rhs->type(); } void printAnnotatedAssignment( at::ArrayRef<Value*> lhs, at::ArrayRef<Value*> rhs) { for (size_t i = 0; i < lhs.size(); ++i) { indent(); body_ << useOf(lhs[i]); if (requiresAnnotation(lhs[i], rhs[i])) { body_ << ": " << lhs[i]->type()->annotation_str(type_printer_); } body_ << " = " << useOf(rhs[i]) << "\n"; } } void printIf(IfView stmt) { assignValuesToTheirUniqueNames(stmt.outputs()); indent() << "if " << useOf(stmt.cond()) << ":\n"; { auto guard = WithIndented(); // Print node contents printBlock(stmt.thenBlock(), stmt.outputs().size() > 0); printAssignment(stmt.outputs(), stmt.thenOutputs()); } indent() << "else:\n"; { auto guard = WithIndented(); printBlock(stmt.elseBlock(), stmt.outputs().size() > 0); printAssignment(stmt.outputs(), stmt.elseOutputs()); } } void printLoop(LoopView stmt) { // Loop carried dependencies are handled by assigning their initial // values to the node->outputs() before the loop, // and assign node->outputs() to the new values at the end of each trip. auto loop_type = stmt.loopType(); if (loop_type == LoopView::ModifiedLoop) { throw ErrorReport(stmt.node()->sourceRange()) << "loop cannot be printed as python " << "because it has gone through an optimization " << "that combined while and for loops. File a bug"; } bool emit_as_for_loop = loop_type == LoopView::For; assignValuesToTheirUniqueNames(stmt.carriedOutputs()); // Add aliases for loop-carried dependencies zipWith( stmt.bodyCarriedInputs(), // Start at 1 to ignore trip count stmt.carriedOutputs(), [&](Value* block_input, Value* node_output) { assignValue(block_input, node_output); }); // Print initial assignments of loop node outputs = loop node inputs printAnnotatedAssignment(stmt.carriedOutputs(), stmt.carriedInputs()); assignValuesToTheirUniqueNames(stmt.currentTripCount()); // Loop header if (emit_as_for_loop) { indent(); body_ << "for " << useOf(stmt.currentTripCount()) << " in range(" << useOf(stmt.maxTripCount()) << "):\n"; } else { // note: trip_count_in_block is unused because this is a while loop, // so we reuse the Value* as a stand-in for the loop condition printAssignment(stmt.currentTripCount(), stmt.inputCond()); indent(); body_ << "while " << useOf(stmt.currentTripCount()) << ":\n"; } // Loop body { ResourceGuard indent = WithIndented(); // Update block outputs to block inputs for next loop iteration // skip the assignment to the new condition in for loops because // the condition is always True size_t offset = emit_as_for_loop ? 1 : 0; auto body_block = stmt.bodyBlock(); ArrayRef<Value*> loop_carried_block_inputs = body_block->inputs().slice(offset); printBlock(body_block, loop_carried_block_inputs.size() > 0); printAssignment( loop_carried_block_inputs, body_block->outputs().slice(offset)); } } bool isLongLine(const std::string& str) { return str.size() + level * 2 >= 40; } bool isLongInline(Node* node) { return output_inline_.count(node) && isLongLine(useOf(node->output())->str()); } bool isNonConstantInline(Value* input) { return input->node()->kind() != prim::Constant && output_inline_.count(input->node()); } // [reordering of inlines] // We inline anything that is semantically legal to inline, but sometimes // we find that these lines get too long. In that case we break the lines /// and it is important that we un-inline all the inputs preceeding the long /// input: // r = foo(x.add_(b), some_long + expression) // wrong! // _0 = some_long + expression // r = foo(x.add_(b), _0) # wrong! _0 runs before mutating add_ // legal! // _0 = x.add_(b) // _1 = some_long + expression // r = foo(_0, _1) void splitLongInlines(Value* v) { std::vector<Value*> to_split_reversed; Use u = v->uses().at(0); scanLongInlines(u.user, u.offset, to_split_reversed); for (auto it = to_split_reversed.rbegin(), end = to_split_reversed.rend(); it != end; ++it) { printOutputDefinition((*it)->node(), *useOf(*it)); } } void scanLongInlines( Node* user, int64_t offset, std::vector<Value*>& to_split_reversed) { auto it = visited_split_inline_uses_.find(user); bool present = it != visited_split_inline_uses_.end(); for (int64_t i = offset; i >= (present ? it->second + 1 : 0); --i) { Value* prev_arg = user->input(i); if (isNonConstantInline(prev_arg)) { to_split_reversed.push_back(prev_arg); } } visited_split_inline_uses_[user] = offset; if (!present && output_inline_.count(user)) { Use u = user->output()->uses().at(0); scanLongInlines(u.user, int64_t(u.offset) - 1, to_split_reversed); // -1 because the actual use is still being // emitted so it cannot be split } } template <typename T> void printOutputDefinition(Node* node, const T& expr) { assignValuesToTheirUniqueNames(node->outputs()); indent(); // Print outputs if (node->outputs().size() > 0) { printValueList(body_, node->outputs()); body_ << " = "; } body_ << expr << "\n"; } // Recursively check contained types for any class dependencies void registerClassDependencies(const TypePtr& type) { if (const auto classType = type->cast<ClassType>()) { deps_table_.add(classType); } else if (const auto tupleType = type->cast<TupleType>()) { if (tupleType->name()) { deps_table_.add(tupleType); } } else if (const auto interfaceType = type->cast<InterfaceType>()) { deps_table_.add(interfaceType); } else if (const auto enumType = type->cast<EnumType>()) { deps_table_.add(enumType); } for (const auto& containedType : type->containedTypes()) { registerClassDependencies(containedType); } } void scanTypeDependencies(Node* node) { // Check for class dependencies. If this node inputs or outputs a class // type, we need to add it to our table of dependencies. for (const auto input : node->inputs()) { registerClassDependencies(input->type()); } for (const auto output : node->outputs()) { registerClassDependencies(output->type()); } for (const auto& name : node->attributeNames()) { switch (node->kindOf(name)) { case AttributeKind::ty: registerClassDependencies(node->ty(name)); break; case AttributeKind::tys: for (const TypePtr& t : node->tys(name)) { registerClassDependencies(t); } break; default: // noop break; } } } void checkVersion(const Node* const node) { min_version_ = std::max(min_version_, get_min_version_for_kind(node->kind())); } void printNode(Node* node, bool print_const) { WithSourceRange guard(&source_range_stack_, node); scanTypeDependencies(node); checkVersion(node); if (!print_const && node->kind() == prim::Constant) return; switch (node->kind()) { case prim::Return: if (enforce_importable_ && node->inputs().size() != 1) { throw ErrorReport(node->sourceRange()) << "Exportable methods must have a single return value. " << "Normal use of ScriptMethods should enforce this"; } if (node->inputs().size() > 0) { indent(); body_ << "return "; printValueList(body_, node->inputs()); body_ << "\n"; } break; case prim::Loop: printLoop(LoopView(node)); break; case prim::If: printIf(IfView(node)); break; case prim::TupleUnpack: case prim::ListUnpack: assignValuesToTheirUniqueNames(node->outputs()); indent(); // TupleUnpack(unpacked) turns into an assignment op that forces // the unpack to be inserted when parsed back in: // a, b, = unpacked // a, = unpacked # trailing comma forces an unpack to happen if (node->outputs().size() > 0) { printValueList(body_, node->outputs(), "", ", = "); } body_ << useOf(node->input()) << "\n"; break; case prim::SetAttr: { const auto obj = node->inputs().at(0); const auto newVal = node->inputs().at(1); const auto type = obj->type()->expect<ClassType>(); const auto& attrname = node->s(attr::name); indent(); body_ << useOf(obj) << "." << attrname << " = " << useOf(newVal) << "\n"; } break; case prim::fork: { // the subgraph gets emitted as another function auto name = genName("__forked_function"); std::shared_ptr<Graph> graph = node->g(attr::Subgraph); indent(); body_ << "def " << name << "():\n"; for (size_t i = 0; i < node->inputs().size(); ++i) { assignValue(graph->inputs().at(i), node->inputs().at(i)); } printBody(graph->block()); std::stringstream ss; ss << "fork(" << name << ")"; printOutputDefinition(node, ss.str()); } break; case prim::Enter: { const auto in = node->inputs().at(0); const auto out = node->outputs().at(0); indent(); body_ << "with " << useOf(in); if (out->uses().size() > 0) { assignValue(out, genUniqueNameFor(out)); body_ << " as " << useOf(out); } body_ << ":\n"; level++; } break; case prim::Exit: { // If the previous node is a prim::Enter, the with block the generated // this Enter/Exit pair must have been empty. if (node->prev()->kind() == prim::Enter) { indent(); body_ << "pass\n"; } level--; } break; case prim::Closure: { if (enforce_importable_) { throw ErrorReport(node->sourceRange()) << "closures are not exportable"; } assignValuesToTheirUniqueNames(node->outputs()); auto name = useOf(node->output())->str(); std::shared_ptr<Graph> graph = node->g(attr::Subgraph); indent(); body_ << "def " << name << "("; assignValuesToTheirUniqueNames(graph->inputs()); for (size_t i = 0; i < graph->inputs().size(); ++i) { Value* v = graph->inputs().at(i); if (i > 0) { body_ << ", "; } body_ << useOf(v) << ": " << v->type()->annotation_str(type_printer_); } body_ << "):\n"; printBody(graph->block()); } break; case prim::ModuleContainerIndex: { const auto container = node->inputs().at(0); const auto key = node->inputs().at(1); const auto out = node->outputs().at(0); assignValuesToTheirUniqueNames(out); indent(); body_ << useOf(out) << " : " << out->type()->annotation_str() << " = " << useOf(container) << "[" << useOf(key) << "]\n"; } break; default: auto ss = std::make_shared<TaggedStringStream>(&source_range_stack_); printRHS(*ss, node); // we prevent long constants from inlining here. // it is not safe to do the same thing for non-constants here // because of [reordering of inlines] if (output_inline_.count(node) == 0 || (node->kind() == prim::Constant && isLongLine(ss->str()))) { printOutputDefinition(node, *ss); } else { // this node is safe to inline, so assign the output value // to that expression directly assignValue(node->output(), ss); if (isLongLine(ss->str())) { splitLongInlines(node->output()); } } } } static bool containsNonASCIIString(const IValue& val) { bool hasNonASCII = false; auto checkSubvalue = [&hasNonASCII](const IValue& val) { if (val.isString()) { const auto maxASCII = 0x7fu; for (auto& c : val.toStringRef()) { if (c > maxASCII) { hasNonASCII = true; return true; } } } return false; }; val.visit(checkSubvalue); return hasNonASCII; } void printConstant(TaggedStringStream& stmt, const IValue& v) { const auto customFormatter = [&](std::ostream& ss, const IValue& v) { if (v.isTensor() || containsNonASCIIString(v) || v.isObject()) { TORCH_INTERNAL_ASSERT(!v.type()->is_module()); ss << "CONSTANTS.c" << getOrAddConstant(v); return true; } if (v.isTuple() && v.type()->expectRef<TupleType>().schema()) { // print the namedtuple constructor and let rest of tuple printing // continue ss << v.type()->expectRef<TupleType>().annotation_str(type_printer_); } return false; }; std::stringstream ss; v.repr(ss, customFormatter); stmt << ss.str(); } void printOpName(TaggedStringStream& stmt, Symbol kind) { // Special overriding ops set that requires serializing differently to // preserve the original code semantics. // This will be more properly handled when we have namespace semantics // for serializing the ops, and it right now hard coded these ops to // ensure consistency and not breaking BC in the future. const static std::unordered_map<Symbol, std::string> override_symbols = { {aten::backward, "torch.autograd.backward"}, {aten::grad, "torch.autograd.grad"}, }; if (override_symbols.find(kind) != override_symbols.end()) { stmt << override_symbols.at(kind); } else if (kind.is_aten()) { // special case aten -> torch because we want to rename // the aten namespace, but this change will take more time // doing it here ensures we do not have fix up archives later stmt << "torch." << kind.toUnqualString(); } else { stmt << "ops." << kind.ns().toUnqualString() << "." << kind.toUnqualString(); } } // Prints the RHS value of a Node, e.g. `aten.add(x, y)` void printRHS(TaggedStringStream& stmt, Node* node) { switch (node->kind()) { case prim::PythonOp: { auto value = static_cast<const PythonOp*>(node); if (enforce_importable_) { throw ErrorReport(node->sourceRange()) << "Could not export Python function call '" << value->name() << "'. Remove calls to Python functions before export. " << "Did you forget to add @script or @script_method annotation? " << "If this is a nn.ModuleList, add it to __constants__"; } std::stringstream scalars_stream; stmt << "^" << value->name(); value->writeScalars(scalars_stream); stmt << scalars_stream.str(); printValueList(stmt, node->inputs(), "(", ")"); } break; case prim::Uninitialized: { stmt << "uninitialized(" << node->output()->type()->annotation_str(type_printer_) << ")"; } break; case prim::Constant: { if (node->outputs().size() == 1 && node->output()->type()->kind() == TypeKind::FunctionType) { auto fn = node->output()->type()->expect<FunctionType>(); deps_table_.add(fn); stmt << fn->annotation_str(type_printer_); } else if (!node->mustBeNone()) { IValue v = toIValue(node->output()).value(); printConstant(stmt, v); } else { stmt << "None"; } } break; case aten::ScalarImplicit: case aten::FloatImplicit: case aten::IntImplicit: { stmt << "annotate(" << node->output()->type()->annotation_str(type_printer_) << ", " << useOf(node->input()) << ")"; } break; case aten::Int: { printValueList(stmt, node->inputs(), "int(", ")"); } break; case aten::Float: { printValueList(stmt, node->inputs(), "float(", ")"); } break; case aten::Bool: { printValueList(stmt, node->inputs(), "bool(", ")"); } break; case aten::str: { printValueList(stmt, node->inputs(), "str(", ")"); } break; case aten::__getitem__: { printValueIndex(stmt, node->inputs()); } break; case prim::Print: { printValueList(stmt, node->inputs(), "print(", ")"); } break; case aten::sorted: { printValueList(stmt, node->inputs(), "sorted(", ")"); } break; case prim::TupleConstruct: { if (auto qualname = node->output()->type()->expectRef<TupleType>().name()) { stmt << node->output()->type()->annotation_str(type_printer_); } printValueList( stmt, node->inputs(), "(", node->inputs().size() == 1 ? ",)" : ")"); } break; case prim::TupleIndex: { stmt << "(" << useOf(node->inputs().at(0)) << ")[" << useOf(node->inputs().at(1)) << "]"; } break; case prim::TupleSlice: { stmt << "(" << useOf(node->input()) << ")[" << node->i(attr::beg) << ":" << node->i(attr::end) << "]"; } break; case prim::ListConstruct: { ListTypePtr list_type = node->output()->type()->expect<ListType>(); TypePtr elem_type = list_type->getElementType(); // Empty lists must be annotated with their type so the compiler knows // what type is supposed to be inside them if (node->inputs().size() == 0) { stmt << "annotate(" << node->output()->type()->annotation_str(type_printer_) << ", [])"; // If we can't infer the type based on what's inside, explicitly // annotate it to disambiguate. // This happens for List[Tensor] vs. List[Optional[Tensor]] } else if (!elementTypeCanBeInferredFromMembers(elem_type)) { stmt << "annotate(" << node->output()->type()->annotation_str(type_printer_) << ", "; printValueList(stmt, node->inputs(), "[", "]"); stmt << ")"; // Otherwise just print a list } else { printValueList(stmt, node->inputs(), "[", "]"); } } break; case prim::DictConstruct: { auto dict_type = node->output()->type()->expect<DictType>(); // There are cases where we must annotate the dict with an explicit type // to help the compiler out: // - the dict is empty // - the dict has potentially ambiguous element types // (e.g. Tensor vs. Optional[Tensor]) if (node->inputs().size() == 0 || !elementTypeCanBeInferredFromMembers(dict_type->getKeyType()) || !elementTypeCanBeInferredFromMembers(dict_type->getValueType())) { stmt << "annotate(" << node->output()->type()->annotation_str(type_printer_) << ", "; printDict(stmt, node->inputs()); stmt << ")"; // Otherwise just print a dict } else { printDict(stmt, node->inputs()); } } break; case prim::CreateObject: { const auto classType = node->output()->type()->expect<ClassType>(); stmt << classType->annotation_str(type_printer_) << ".__new__(" << classType->annotation_str(type_printer_) << ")"; } break; case prim::GetAttr: { const auto obj = node->inputs().at(0); const auto classType = obj->type()->expect<ClassType>(); const auto& field = node->s(attr::name); if (isValidIdentifier(field)) { stmt << useOf(obj) << "." << field; } else { stmt << "getattr(" << useOf(obj) << ", "; std::stringstream field_stream; c10::printQuotedString(field_stream, field); stmt << field_stream.str() << ")"; } } break; case prim::CallFunction: { stmt << useOf(node->inputs().at(0)) << "("; for (size_t i = 1; i < node->inputs().size(); i++) { stmt << useOf(node->inputs()[i]) << ", "; } stmt << ")"; } break; case prim::CallMethod: { const auto& self = node->inputs().at(0); const auto& methodName = node->s(attr::name); stmt << "(" << useOf(self) << ")" << "." << methodName << "("; for (size_t i = 1; i < node->inputs().size(); i++) { stmt << useOf(node->inputs()[i]) << ", "; } stmt << ")"; if (auto selfClass = self->type()->cast<ClassType>()) { deps_table_.add(selfClass); const Function& method = selfClass->getMethod(node->s(attr::name)); TORCH_INTERNAL_ASSERT( method.qualname() == QualifiedName(selfClass->name()->qualifiedName(), methodName)); } else if (auto selfInterface = self->type()->cast<InterfaceType>()) { deps_table_.add(selfInterface); } else { TORCH_INTERNAL_ASSERT( false, "method call to unhandled type in serialization"); } } break; case aten::_unwrap_optional: { printOpName(stmt, node->kind()); stmt << "("; // we cannot recover the type of unwrap_optional(None), // using normal schema matching, so we route around this by rewriting // the call to unwrap_optional(annotated(Optional[T], None)) if (node->input()->type()->isSubtypeOf(NoneType::get()) || node->input()->mustBeNone()) { auto input_type = OptionalType::create(node->output()->type()); stmt << "annotate(" << input_type->annotation_str(type_printer_) << ", " << useOf(node->input()) << ")"; } else { stmt << useOf(node->input()); } stmt << ")"; } break; // unchecked_unwrap_optional is no longer generated by the compiler, // but may end up here if it was first loaded from a old model and // re-saved. On re-save we upgrade it to an unchecked_cast, which is an // equivalent op case prim::unchecked_unwrap_optional: case prim::unchecked_cast: { stmt << "unchecked_cast(" << node->output()->type()->annotation_str(type_printer_) << ", " << useOf(node->input()) << ")"; } break; case prim::isinstance: { stmt << "isinstance(" << useOf(node->input()) << ", "; const auto& types = node->tys(attr::types); if (types.size() == 1) { stmt << types.at(0)->annotation_str(type_printer_); } else { // check multiple things, e.g. (str, list, int) stmt << "("; bool first = true; for (const TypePtr& typ : types) { if (!first) { stmt << ", "; } stmt << typ->annotation_str(type_printer_); first = false; } stmt << ")"; } stmt << ")"; } break; case prim::tolist: { stmt << "annotate(" << node->output()->type()->annotation_str(type_printer_) << ", "; stmt << useOf(node->input(0)) << ".tolist()" << ")"; } break; case prim::EnumValue: // Note: This CAN NOT be printed as raw operator ops.prim.EnumValue // because its return type depends on type of enum and must be further // resolved, but ops.prim.EnumValue construction does not provide such // functionality. stmt << "(" << useOf(node->input()) << ").value"; break; case prim::EnumName: stmt << "(" << useOf(node->input()) << ").name"; break; default: { printOpName(stmt, node->kind()); const FunctionSchema& schema = node->schema(); stmt << "("; for (size_t i = 0; i < node->inputs().size(); ++i) { if (i > 0) { stmt << ", "; } auto v = useOf(node->inputs().at(i)); // print the kwarg name if it is a kwarg only argument. if (i < schema.arguments().size()) { auto arg = schema.arguments().at(i); if (arg.kwarg_only()) { stmt << arg.name() << "="; } } else { // vararg functions like format can have extra arguments AT_ASSERT(schema.is_vararg()); } stmt << *v; } stmt << ")"; } break; } } TaggedStringStream& printBlock(Block* root, bool block_has_other_statements) { // pythons weird 'pass' syntax creates a bunch of places where we have to // check if this block would be empty. But not everything in a block is a // node. Sometimes if, loop, and return statements will follow this block // and block_has_other_statements == true. if (!block_has_other_statements && root->nodes().begin() == root->nodes().end()) { indent(); body_ << "pass\n"; } for (auto* node : root->nodes()) { printNode(node, /*print_const=*/false); } return body_; } template <typename dtype> IValue createBroadList(dtype value, const int64_t& N) { c10::List<dtype> repeated; repeated.reserve(N); for (int i = 0; i < N; ++i) { repeated.push_back(value); } return repeated; } void printDefaultValue( const Argument& arg, TaggedStringStream& stmt, const IValue& value) { stmt << "="; // handle broadcasting lists if (arg.type()->kind() == ListType::Kind && (value.isInt() || value.isDouble() || value.isBool())) { TORCH_INTERNAL_ASSERT(arg.N(), "expected broadcastinglist"); if (value.isInt()) { printConstant(stmt, createBroadList<int64_t>(value.toInt(), *arg.N())); } else if (value.isBool()) { printConstant(stmt, createBroadList<bool>(value.toBool(), *arg.N())); } else if (value.isDouble()) { printConstant( stmt, createBroadList<double>(value.toDouble(), *arg.N())); } } else { printConstant(stmt, value); } } void printBody(Block* body) { // we always print constants at the top of the function, in the order // in which they are used. std::vector<Node*> constants; buildConstantList(body, constants); // current graph is used to de-dup names within a single graph scanBlock(body); { auto guard = WithIndented(); // Print initial constant table (most are just inlined into their use, // but some like long strings do get emitted) for (Node* n : constants) { printNode(n, /*print_const=*/true); } // Print body printBlock(body, body->return_node()->inputs().size() > 0); printNode(body->return_node(), /*print_const=*/false); } } public: void printFunction( const Function& func, bool print_first_argument_type = true) { TORCH_INTERNAL_ASSERT(func.isGraphFunction()); const FunctionSchema& schema = func.getSchema(); Graph& graph = *func.graph(); used_names_.clear(); // each graph can reuse local names WithSourceRange guard(&source_range_stack_, graph.param_node()); indent(); body_ << "def " << func.name() << "("; auto param_it = graph.inputs().begin(); for (const Argument& arg : schema.arguments()) { registerClassDependencies(arg.type()); std::string arg_name = genName(arg.name()); if (param_it == graph.inputs().begin()) { // the first argument may omit its type when it is implied by context // the flag print_first_argument_type determines when to do this body_ << arg_name; if (print_first_argument_type) { body_ << ": " << arg.type()->annotation_str(type_printer_); } } else { body_ << ",\n " << arg_name << ": " << arg.type()->annotation_str(type_printer_); } if (arg.default_value()) { printDefaultValue(arg, body_, *arg.default_value()); } assignValue(*param_it++, arg_name); } const auto& returnType = schema.returns().at(0).type(); body_ << ") -> " << returnType->annotation_str(type_printer_) << ":\n"; registerClassDependencies(returnType); printBody(graph.block()); } void printMethod(const Function& func) { printFunction(func, /*print_first_argument_type=*/false); } PythonPrintImpl( std::vector<at::IValue>& constant_table, PrintDepsTable& deps_table, c10::TypePrinter type_printer, bool enforce_importable) : body_(&source_range_stack_), constant_table_(constant_table), deps_table_(deps_table), type_printer_(std::move(type_printer)), enforce_importable_(enforce_importable) {} void printClass(const ClassTypePtr& classType) { // If any of the methods are not Graph funtions, this indicates that // this class is a custom-bound C++ class. Skip serialization // of this class, we will depend on the ClassType being defined // in the target process. for (auto& method : classType->methods()) { if (!method->isGraphFunction()) { return; } } bool is_module = classType->is_module(); body_ << "class " << classType->name()->name(); if (is_module) { body_ << "(Module)"; } body_ << ":\n"; { const auto guard = WithIndented(); size_t numAttrs = classType->numAttributes(); // For modules, we need to print special information about the module's // attributes and parameters. if (is_module) { std::vector<std::string> params; std::vector<std::string> buffers; // Populate the __parameters__ field. This tells the importer which // attributes are parameters. for (size_t i = 0; i < numAttrs; i++) { if (classType->is_parameter(i)) { params.push_back(classType->getAttributeName(i)); } if (classType->is_buffer(i)) { buffers.push_back(classType->getAttributeName(i)); } } indent(); body_ << "__parameters__ = ["; for (const auto& param : params) { body_ << "\"" << param << "\", "; } body_ << "]\n"; indent(); body_ << "__buffers__ = ["; for (const auto& buffer : buffers) { body_ << "\"" << buffer << "\", "; } body_ << "]\n"; auto forwardPreHooks = classType->getForwardPreHooks(); if (forwardPreHooks.size() > 0) { indent(); body_ << "__forward_pre_hooks__ = ["; for (const auto& pre_hook : forwardPreHooks) { body_ << "\"" << pre_hook->name() << "\", "; } body_ << "]\n"; } auto forwardHooks = classType->getForwardHooks(); if (forwardHooks.size() > 0) { indent(); body_ << "__forward_hooks__ = ["; for (const auto& hook : forwardHooks) { body_ << "\"" << hook->name() << "\", "; } body_ << "]\n"; } } for (size_t i = 0; i < numAttrs; i++) { const auto& name = classType->getAttributeName(i); const auto& type = classType->getAttribute(i); registerClassDependencies(type); indent(); // Handling for when the attribute name is not a valid Python // identifier. This happens for, e.g. ModuleList. if (!isValidIdentifier(name)) { if (i == 0) { // Initialize the annotations dict if necessary. body_ << "__annotations__ = []\n"; indent(); } // Print out a direct manipulation of the annotations dict, like: // __annotations__["0"] = SomeType body_ << "__annotations__[" << "\"" << name << "\"] = " << type->annotation_str(type_printer_) << "\n"; } else { // Otherwise: just emit a python 3 attribute annotation, like: // foo : SomeType body_ << name << " : " << type->annotation_str(type_printer_) << "\n"; } } size_t numConstants = classType->numConstants(); for (size_t i = 0; i < numConstants; i++) { const auto& name = classType->getConstantName(i); IValue v = classType->getConstant(i); indent(); body_ << name << " : " << "Final[" << v.type()->annotation_str(type_printer_) << "] = "; auto ss = std::make_shared<TaggedStringStream>(&source_range_stack_); printConstant(*ss, v); body_ << ss->str() << "\n"; } // TODO fields for (auto& method : classType->methods()) { printFunction(*method); } std::set<std::string> already_printed; for (auto& hook : classType->getForwardHooks()) { if (already_printed.count(hook->name()) == 0) { already_printed.insert(hook->name()); printFunction(*hook); } } for (auto& pre_hook : classType->getForwardPreHooks()) { if (already_printed.count(pre_hook->name()) == 0) { already_printed.insert(pre_hook->name()); printFunction(*pre_hook); } } } } void printNamedType(const c10::NamedTypePtr& type) { if (auto functionType = type->cast<FunctionType>()) { printFunction(*functionType->function()); } else if (auto classType = type->cast<ClassType>()) { printClass(classType); } else if (auto tupleType = type->cast<TupleType>()) { TORCH_INTERNAL_ASSERT(tupleType->schema()); body_ << "class " << tupleType->name()->name(); body_ << "(NamedTuple):\n"; { const auto guard = WithIndented(); for (const auto& attr : tupleType->schema()->arguments()) { TORCH_INTERNAL_ASSERT(attr.type()); indent(); body_ << attr.name() << " : " << attr.type()->annotation_str(type_printer_) << "\n"; } } } else if (auto interfaceType = type->cast<InterfaceType>()) { body_ << "class " << interfaceType->name()->name(); if (interfaceType->is_module()) { body_ << "(ModuleInterface):\n"; } else { body_ << "(Interface):\n"; } { auto guard = WithIndented(); for (const FunctionSchema& method : interfaceType->methods()) { indent(); body_ << "def " << method.name() << "(self"; TORCH_INTERNAL_ASSERT( method.arguments().size() > 0 && method.arguments().at(0).name() == "self"); for (const Argument& arg : at::ArrayRef<Argument>(method.arguments()).slice(1)) { auto type = arg.type(); registerClassDependencies(type); body_ << ", " << arg.name() << ": " << type->annotation_str(type_printer_); } auto return_type = method.returns().at(0).type(); registerClassDependencies(return_type); body_ << ") -> " << return_type->annotation_str(type_printer_) << ":\n"; indent(); body_ << " pass\n"; } } } else if (auto enumType = type->cast<EnumType>()) { body_ << "class " << enumType->qualifiedClassName().name() << "(Enum):\n"; std::string value_wrapper = ""; if (enumType->getValueType() == StringType::get()) { value_wrapper = "\""; } { auto guard = WithIndented(); for (const auto& name_value : enumType->enumNamesValues()) { indent(); body_ << name_value.first << " = " << value_wrapper << name_value.second << value_wrapper << "\n"; } } } else { TORCH_INTERNAL_ASSERT(false, "Unhandled NamedType"); } } ~PythonPrintImpl() = default; TaggedStringStream body_; // When printing this node, is it safe to write it inline (i.e. without // assigning a temporary variable std::unordered_set<Node*> output_inline_; // see [reordering of inlines] // used to track parts of an inline statement we already scanned // for splitting long lines, so that we do not revisit them causing n^2 // behavior. stores the maximum offset into inputs that has already been // scanned for the node. std::unordered_map<Node*, int64_t> visited_split_inline_uses_; // what valid identifiers are in use for the current function std::unordered_set<std::string> used_names_; // constants are written to this table, and given then named CONSTANTS.cN // where N is the index into this table. std::vector<at::IValue>& constant_table_; // Any NamedTypes (classes, functions, NamedTuples) used are written to this // table. PrintDepsTable& deps_table_; // A function that, given a named type, returns us the correct string to print // for it. c10::TypePrinter type_printer_; // when we print this, should we error if the resulting output would // not be able to be reparsed? bool enforce_importable_; // The least version that supports all printed ops uint64_t min_version_ = 0; }; PythonPrint::PythonPrint( std::vector<at::IValue>& constant_table, PrintDepsTable& deps_table, c10::TypePrinter type_printer, bool enforce_importable) : pImpl(std::make_shared<PythonPrintImpl>( constant_table, deps_table, std::move(type_printer), enforce_importable)) {} void PythonPrint::printNamedType(const c10::NamedTypePtr& type) { pImpl->printNamedType(type); } void PythonPrint::printFunction(const Function& func) { pImpl->printFunction(func); } void PythonPrint::printMethod(const Function& func) { pImpl->printMethod(func); } std::string PythonPrint::str() const { return pImpl->body_.str(); } const SourceRangeRecords& PythonPrint::ranges() const { return pImpl->body_.ranges(); } uint64_t PythonPrint::minVersion() const { return pImpl->min_version_; } PythonPrint::~PythonPrint() = default; } // namespace jit } // namespace torch
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
72c800c9ed87a58f83b614e647fb42f3c55165ec
7c241eb1250ad2e979f75b09eb86a69fa0ba6031
/tags/release_1_12/src/win32com/VPinMAMESplashWnd.cpp
5bed3cbe089815e83d2020502d2da792e7de057a
[]
no_license
mp-lee/pinmame
4e02b72691b6f8843e40ebedc1b7bf3a2049fd98
92f23ffdcb9f0b9c449c0f8ae8bf87f25101a877
refs/heads/master
2021-01-18T08:13:08.609969
2017-12-10T08:57:52
2017-12-10T08:57:52
52,010,521
0
0
null
null
null
null
UTF-8
C++
false
false
4,688
cpp
#include "StdAfx.h" #include "VPinMAMESplashWnd.h" #include "resource.h" #include <atlwin.h> #include <time.h> #define CLOSE_TIMER 1 #define SPLASH_WND_VISIBLE 5000 // ms class CSplashWnd : public CWindowImpl<CSplashWnd> { public: BEGIN_MSG_MAP(CSplashWnd) MESSAGE_HANDLER(WM_CREATE, OnCreate) MESSAGE_HANDLER(WM_LBUTTONDOWN, OnClick) MESSAGE_HANDLER(WM_TIMER, OnClick) MESSAGE_HANDLER(WM_CHAR, OnClick) MESSAGE_HANDLER(WM_PAINT, OnPaint) MESSAGE_HANDLER(WM_DESTROY, OnDestroy) END_MSG_MAP() private: char* m_pszCredits; // use defined credit text, displayed at the bottom of the picture UINT m_uClosedTimer; // if this timer runs out, the window will be closed HBITMAP m_hBitmap; // the bitmap we are displaying BITMAP m_Bitmap; // bitmap info to hBitmap HFONT m_hFont; // font for the credit line COLORREF m_Color; // color for the credit line int m_iCreditStartY; // start of the credit box (Y direction) void DoPaint(HDC hPaintDC=0) { HDC hDC = hPaintDC; if ( !hPaintDC ) hDC = GetDC(); if ( m_hBitmap ) { HDC hMemDC = CreateCompatibleDC(hDC); HBITMAP hOldBitmap = (HBITMAP) SelectObject(hMemDC, m_hBitmap); BitBlt(hDC, 0, 0, m_Bitmap.bmWidth, m_Bitmap.bmHeight, hMemDC, 0, 0, SRCCOPY); SelectObject(hMemDC, hOldBitmap); DeleteDC(hMemDC); } if ( m_pszCredits && *m_pszCredits ) { int OldTextColor = SetTextColor(hDC, m_Color); int OldBkMode = SetBkMode(hDC, TRANSPARENT); HFONT hOldFont = (HFONT) SelectObject(hDC, m_hFont); RECT Rect; GetClientRect(&Rect); if ( Rect.bottom > m_iCreditStartY ) Rect.top = Rect.bottom - m_iCreditStartY; Rect.bottom = Rect.top + 45; Rect.left += 5; Rect.right -= 5; DrawText(hDC, m_pszCredits, -1, &Rect, DT_EDITCONTROL|DT_NOPREFIX|DT_WORDBREAK|DT_CENTER); SelectObject(hDC, hOldFont); SetBkMode(hDC, OldBkMode); SetTextColor(hDC, OldTextColor); } if ( !hPaintDC ) ReleaseDC(hDC); } LRESULT OnCreate(UINT, WPARAM, LPARAM lParam, BOOL&) { m_pszCredits = (char*) ((LPCREATESTRUCT) lParam)->lpCreateParams; srand( (unsigned)time(NULL)); int iSplashScreenNo = int(rand()%4); // choose the right color and font style for the user setable text int iWeight = FW_NORMAL; m_iCreditStartY = 45; switch ( iSplashScreenNo ) { case 1: // Stein's image m_Color = RGB(0,255,0); iWeight = FW_BOLD; m_iCreditStartY = 48; break; case 2: // Forchia's image m_Color = RGB(0,0,0); iWeight = FW_BOLD; break; default: // The original one (0) and Steve's new one (3) m_Color = RGB(255,255,255); break; } m_hBitmap = LoadBitmap(_Module.m_hInst, MAKEINTRESOURCE(IDB_SPLASH)+iSplashScreenNo); if ( m_hBitmap ) { GetObject(m_hBitmap, sizeof m_Bitmap, &m_Bitmap); // resize the window so it fits the bitmap RECT Rect = {0, 0, m_Bitmap.bmWidth, m_Bitmap.bmHeight}; SetWindowPos((HWND) 0, &Rect, SWP_NOMOVE|SWP_NOZORDER); } HDC hDC = GetDC(); m_hFont = CreateFont( -MulDiv(8, GetDeviceCaps(hDC, LOGPIXELSY), 72), 0, 0, 0, iWeight, 0, 0, 0, ANSI_CHARSET, 0, 0, 0, FF_DONTCARE, "Microsoft Sans Serife" ); ReleaseDC(hDC); // center all CenterWindow(); m_uClosedTimer = SetTimer(CLOSE_TIMER, SPLASH_WND_VISIBLE); return 1; } LRESULT OnClick(UINT, WPARAM, LPARAM, BOOL&) { DestroyWindow(); return 1; } LRESULT OnPaint(UINT, WPARAM, LPARAM, BOOL&) { RECT Rect; if ( !GetUpdateRect(&Rect) ) return 1; PAINTSTRUCT PaintStruct; BeginPaint(&PaintStruct); DoPaint(PaintStruct.hdc); EndPaint(&PaintStruct); return 1; }; LRESULT OnDestroy(UINT, WPARAM, LPARAM, BOOL&) { KillTimer(m_uClosedTimer); DeleteObject(m_hFont); return 1; } }; void CreateSplashWnd(void **ppData, char* pszCredits) { if ( !ppData ) return; // create and display dialog on the desktop CSplashWnd* pSplashWnd = new CSplashWnd; pSplashWnd->Create((HWND) 0, CWindow::rcDefault, NULL, WS_VISIBLE|WS_POPUP, NULL, 0U, pszCredits); *ppData = pSplashWnd; /* remove this line if you want to run the game at once */ WaitForSplashWndToClose(ppData); } void DestroySplashWnd(void **ppData) { if ( !ppData ) return; // destroy dialog if it exists CSplashWnd* pSplashWnd = (CSplashWnd*) *ppData; if ( IsWindow(pSplashWnd->m_hWnd) ) DestroyWindow(pSplashWnd->m_hWnd); delete pSplashWnd; *ppData = NULL; } void WaitForSplashWndToClose(void **ppData) { if ( !ppData ) return; // wait for the splash window until it closes CSplashWnd* pSplashWnd = (CSplashWnd*) *ppData; MSG msg; while ( pSplashWnd->IsWindow() ) { GetMessage(&msg,pSplashWnd->m_hWnd,0,0); TranslateMessage(&msg); DispatchMessage(&msg); } }
[ "(no author)@6f51dfdd-75df-4273-8f3b-818b1e6aa8bf" ]
(no author)@6f51dfdd-75df-4273-8f3b-818b1e6aa8bf
9ed3e26c073450b9e8523df0d822a6f6e13baf32
2fbcbd3a83c2f81068cbb67106017a44a29f202f
/MonsterGenerator.cpp
68e98b2daa5396967c9ab1730c1664ed42f24f78
[]
no_license
matthew-fishkin/cpp-practice
e6368187ff20975d5379102840448b700156d29d
207b1c561107127495fb82e144027c2dadad7b60
refs/heads/master
2020-03-26T00:19:50.729846
2018-08-19T19:09:18
2018-08-19T19:09:18
144,315,562
0
0
null
null
null
null
UTF-8
C++
false
false
191
cpp
// // Created by Matthew Fishkin on 8/19/18. // #include "MonsterGenerator.h" Monster MonsterGenerator::generateMonster() { return Monster(Monster::SKELETON, "bones", "*rattle*", 4); }
[ "matt.fishkin@gmail.com" ]
matt.fishkin@gmail.com
62c8650eb0e129f430b0e8f1e522bf873ec606f0
1c9ce29adcb905b1c6990f70e458624a89ff1131
/66. Plus One /solution.cpp
aa9283ed0cbcbc3b67fcff63443ac5267779f528
[ "MIT" ]
permissive
KailinLi/LeetCode-Solutions
90853613d0de566332ad94d96af06024f2772188
bad6aa401b290a203a572362e63e0b1085f7fc36
refs/heads/master
2021-01-23T05:35:05.856028
2018-10-14T09:40:18
2018-10-14T09:40:18
86,318,316
2
0
null
null
null
null
UTF-8
C++
false
false
468
cpp
class Solution { public: vector<int> plusOne(vector<int>& digits) { bool carry = true; for (auto n = digits.rbegin(); n != digits.rend(); n++) { if (carry) { (*n)++; if (*n > 9) { carry = true; *n = 0; } else carry = false; } } if (carry) digits.insert(digits.begin(), 1); return digits; } };
[ "likailinhust@163.com" ]
likailinhust@163.com
803c09125437ed4a74d0f5d83ab22ac5a42e13f5
4d33c090428407d599a4c0a586e0341353bcf8d7
/trunk/tutorial/wtl_02_triangle_form/view.cpp
b091b90ed1d9fce6d635285d4eee3b455548cf91
[]
no_license
yty/bud
f2c46d689be5dfca74e239f90570617b3471ea81
a37348b77fb2722c73d972a77827056b0b2344f6
refs/heads/master
2020-12-11T06:07:55.915476
2012-07-22T21:48:05
2012-07-22T21:48:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,896
cpp
#include "view.h" #include "global.h" LRESULT CView::OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { if (RenderEngineImp::isNull() || NULL == RenderEngineImp::getInstancePtr()->getRenderEngine() || NULL == RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()) { return 0; } if (!_isInitialized()) { _create(); } // RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->clear(0, NULL, Euclid::eClearFlags_Target | Euclid::eClearFlags_ZBuffer, Euclid::Color::Green, 1.0f, 0L); RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->beginScene(); // _renderGeometry(); // RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->endScene(); RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->present(NULL, NULL, NULL); return 0; } void CView::_renderGeometry() { RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->setStreamSource(0, _vb, 0, _material->getStride()); _material->apply(); RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->drawPrimitive(Euclid::ePrimitive_TriangleList, 0, 1); } void CView::_clear() { _material = NULL; _vb = NULL; } bool CView::_create() { // _material = RenderEngineImp::getInstancePtr()->getRenderEngine()->getMaterialManager()->createMaterial(Euclid::eMaterialType_Vertex); // Euclid::sPosition vertices[3]; vertices[0].position = Vec3(-1.0f, 0.0f, 0.0f); vertices[1].position = Vec3(0.0f, 1.0f, 0.0f); vertices[2].position = Vec3(1.0f, 0.0f, 0.0f); _vb = RenderEngineImp::getInstancePtr()->getRenderEngine()->getBufferManager()->createVertexBuffer(3 * _material->getStride(), Euclid::eUsage_WriteOnly, Euclid::ePool_Manager); void* data = _vb->lock(0, 0, Euclid::eLock_Null); memcpy(data, vertices, 3 * _material->getStride()); _vb->unLock(); return true; } bool CView::_isInitialized() { return _material != NULL && _vb != NULL; } LRESULT CView::OnClose( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled ) { // if (_material) { delete _material; _material = 0; } // if (_vb) { _vb->destroy(); delete _vb; _vb = NULL; } RenderEngineImp::getInstancePtr()->destroy(); delete RenderEngineImp::getInstancePtr(); bHandled = false; return 0; } LRESULT CView::OnSize( UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled ) { if (RenderEngineImp::isNull() || NULL == RenderEngineImp::getInstancePtr()->getRenderEngine() || NULL == RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()) { goto out; } // Euclid::sViewPort vp; vp.X = 0; vp.Y = 0; vp.Width = LOWORD(lParam); vp.Height = HIWORD(lParam); vp.MinZ = 0; vp.MaxZ = 1; RenderEngineImp::getInstancePtr()->getRenderEngine()->getRenderSystem()->setViewport(&vp); out: // bHandled = false; return 0; }
[ "297191409@qq.com" ]
297191409@qq.com
03bba477e7ce522ae0a8dcbf511051d5d920c5f0
55b5bb05ea8e287ac072d07f0745a8f88df63410
/boost_1_59_0/libs/asio/test/ssl/stream.cpp
a3d89ca6de788b02bc1d50728d728540d7162d15
[ "MIT", "BSL-1.0" ]
permissive
lbryio/lbrycrd-dependencies
88e187ad0b42acbfc4c13bae84dcab9338b3c830
48c993eb77aed55029ae66bc48d970218a357f9e
refs/heads/master
2020-04-02T04:08:35.350210
2018-02-28T14:42:50
2018-02-28T14:42:50
63,198,671
5
6
MIT
2018-02-28T14:42:50
2016-07-12T23:17:26
HTML
UTF-8
C++
false
false
6,890
cpp
// // stream.cpp // ~~~~~~~~~~ // // Copyright (c) 2003-2015 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // 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) // // Disable autolinking for unit tests. #if !defined(BOOST_ALL_NO_LIB) #define BOOST_ALL_NO_LIB 1 #endif // !defined(BOOST_ALL_NO_LIB) // Test that header file is self-contained. #include <boost/asio/ssl/stream.hpp> #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include "../archetypes/async_result.hpp" #include "../unit_test.hpp" //------------------------------------------------------------------------------ // ssl_stream_compile test // ~~~~~~~~~~~~~~~~~~~~~~~ // The following test checks that all public member functions on the class // ssl::stream::socket compile and link correctly. Runtime failures are ignored. namespace ssl_stream_compile { #if !defined(BOOST_ASIO_ENABLE_OLD_SSL) bool verify_callback(bool, boost::asio::ssl::verify_context&) { return false; } #endif // !defined(BOOST_ASIO_ENABLE_OLD_SSL) void handshake_handler(const boost::system::error_code&) { } void buffered_handshake_handler(const boost::system::error_code&, std::size_t) { } void shutdown_handler(const boost::system::error_code&) { } void write_some_handler(const boost::system::error_code&, std::size_t) { } void read_some_handler(const boost::system::error_code&, std::size_t) { } void test() { using namespace boost::asio; namespace ip = boost::asio::ip; try { io_service ios; char mutable_char_buffer[128] = ""; const char const_char_buffer[128] = ""; boost::asio::ssl::context context(ios, boost::asio::ssl::context::sslv23); archetypes::lazy_handler lazy; boost::system::error_code ec; // ssl::stream constructors. ssl::stream<ip::tcp::socket> stream1(ios, context); ip::tcp::socket socket1(ios, ip::tcp::v4()); ssl::stream<ip::tcp::socket&> stream2(socket1, context); // basic_io_object functions. io_service& ios_ref = stream1.get_io_service(); (void)ios_ref; // ssl::stream functions. #if !defined(BOOST_ASIO_ENABLE_OLD_SSL) SSL* ssl1 = stream1.native_handle(); (void)ssl1; #endif // !defined(BOOST_ASIO_ENABLE_OLD_SSL) SSL* ssl2 = stream1.impl()->ssl; (void)ssl2; ssl::stream<ip::tcp::socket>::lowest_layer_type& lowest_layer = stream1.lowest_layer(); (void)lowest_layer; const ssl::stream<ip::tcp::socket>& stream3 = stream1; const ssl::stream<ip::tcp::socket>::lowest_layer_type& lowest_layer2 = stream3.lowest_layer(); (void)lowest_layer2; #if !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.set_verify_mode(ssl::verify_none); stream1.set_verify_mode(ssl::verify_none, ec); stream1.set_verify_depth(1); stream1.set_verify_depth(1, ec); stream1.set_verify_callback(verify_callback); stream1.set_verify_callback(verify_callback, ec); #endif // !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.handshake(ssl::stream_base::client); stream1.handshake(ssl::stream_base::server); stream1.handshake(ssl::stream_base::client, ec); stream1.handshake(ssl::stream_base::server, ec); #if !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.handshake(ssl::stream_base::client, buffer(mutable_char_buffer)); stream1.handshake(ssl::stream_base::server, buffer(mutable_char_buffer)); stream1.handshake(ssl::stream_base::client, buffer(const_char_buffer)); stream1.handshake(ssl::stream_base::server, buffer(const_char_buffer)); stream1.handshake(ssl::stream_base::client, buffer(mutable_char_buffer), ec); stream1.handshake(ssl::stream_base::server, buffer(mutable_char_buffer), ec); stream1.handshake(ssl::stream_base::client, buffer(const_char_buffer), ec); stream1.handshake(ssl::stream_base::server, buffer(const_char_buffer), ec); #endif // !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.async_handshake(ssl::stream_base::client, handshake_handler); stream1.async_handshake(ssl::stream_base::server, handshake_handler); int i1 = stream1.async_handshake(ssl::stream_base::client, lazy); (void)i1; int i2 = stream1.async_handshake(ssl::stream_base::server, lazy); (void)i2; #if !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.async_handshake(ssl::stream_base::client, buffer(mutable_char_buffer), buffered_handshake_handler); stream1.async_handshake(ssl::stream_base::server, buffer(mutable_char_buffer), buffered_handshake_handler); stream1.async_handshake(ssl::stream_base::client, buffer(const_char_buffer), buffered_handshake_handler); stream1.async_handshake(ssl::stream_base::server, buffer(const_char_buffer), buffered_handshake_handler); int i3 = stream1.async_handshake(ssl::stream_base::client, buffer(mutable_char_buffer), lazy); (void)i3; int i4 = stream1.async_handshake(ssl::stream_base::server, buffer(mutable_char_buffer), lazy); (void)i4; int i5 = stream1.async_handshake(ssl::stream_base::client, buffer(const_char_buffer), lazy); (void)i5; int i6 = stream1.async_handshake(ssl::stream_base::server, buffer(const_char_buffer), lazy); (void)i6; #endif // !defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.shutdown(); stream1.shutdown(ec); stream1.async_shutdown(shutdown_handler); int i7 = stream1.async_shutdown(lazy); (void)i7; stream1.write_some(buffer(mutable_char_buffer)); stream1.write_some(buffer(const_char_buffer)); stream1.write_some(buffer(mutable_char_buffer), ec); stream1.write_some(buffer(const_char_buffer), ec); stream1.async_write_some(buffer(mutable_char_buffer), write_some_handler); stream1.async_write_some(buffer(const_char_buffer), write_some_handler); int i8 = stream1.async_write_some(buffer(mutable_char_buffer), lazy); (void)i8; int i9 = stream1.async_write_some(buffer(const_char_buffer), lazy); (void)i9; stream1.read_some(buffer(mutable_char_buffer)); stream1.read_some(buffer(mutable_char_buffer), ec); stream1.async_read_some(buffer(mutable_char_buffer), read_some_handler); int i10 = stream1.async_read_some(buffer(mutable_char_buffer), lazy); (void)i10; #if defined(BOOST_ASIO_ENABLE_OLD_SSL) stream1.peek(buffer(mutable_char_buffer)); stream1.peek(buffer(mutable_char_buffer), ec); std::size_t in_avail1 = stream1.in_avail(); (void)in_avail1; std::size_t in_avail2 = stream1.in_avail(ec); (void)in_avail2; #endif // defined(BOOST_ASIO_ENABLE_OLD_SSL) } catch (std::exception&) { } } } // namespace ssl_stream_compile //------------------------------------------------------------------------------ BOOST_ASIO_TEST_SUITE ( "ssl/stream", BOOST_ASIO_TEST_CASE(ssl_stream_compile::test) )
[ "jobevers@users.noreply.github.com" ]
jobevers@users.noreply.github.com
d112bab188de9dd700571443cbf87311d22052c4
60dd6073a3284e24092620e430fd05be3157f48e
/tiago_public_ws/devel/include/pal_detection_msgs/RecognizedObject.h
ff9435edd98a3b253c885b1f32024a6d0c30fb58
[]
no_license
SakshayMahna/Programming-Robots-with-ROS
e94d4ec5973f76d49c81406f0de43795bb673c1e
203d97463d07722fbe73bdc007d930b2ae3905f1
refs/heads/master
2020-07-11T07:28:00.547774
2019-10-19T08:05:26
2019-10-19T08:05:26
204,474,383
0
0
null
null
null
null
UTF-8
C++
false
false
8,043
h
// Generated by gencpp from file pal_detection_msgs/RecognizedObject.msg // DO NOT EDIT! #ifndef PAL_DETECTION_MSGS_MESSAGE_RECOGNIZEDOBJECT_H #define PAL_DETECTION_MSGS_MESSAGE_RECOGNIZEDOBJECT_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> #include <sensor_msgs/RegionOfInterest.h> namespace pal_detection_msgs { template <class ContainerAllocator> struct RecognizedObject_ { typedef RecognizedObject_<ContainerAllocator> Type; RecognizedObject_() : object_class() , confidence(0.0) , bounding_box() { } RecognizedObject_(const ContainerAllocator& _alloc) : object_class(_alloc) , confidence(0.0) , bounding_box(_alloc) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _object_class_type; _object_class_type object_class; typedef float _confidence_type; _confidence_type confidence; typedef ::sensor_msgs::RegionOfInterest_<ContainerAllocator> _bounding_box_type; _bounding_box_type bounding_box; typedef boost::shared_ptr< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> const> ConstPtr; }; // struct RecognizedObject_ typedef ::pal_detection_msgs::RecognizedObject_<std::allocator<void> > RecognizedObject; typedef boost::shared_ptr< ::pal_detection_msgs::RecognizedObject > RecognizedObjectPtr; typedef boost::shared_ptr< ::pal_detection_msgs::RecognizedObject const> RecognizedObjectConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> & v) { ros::message_operations::Printer< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace pal_detection_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'sensor_msgs': ['/opt/ros/kinetic/share/sensor_msgs/cmake/../msg'], 'pal_detection_msgs': ['/media/root/BuntuDrive/Programming-Robots-with-ROS/tiago_public_ws/src/pal_msgs/pal_detection_msgs/msg', '/media/root/BuntuDrive/Programming-Robots-with-ROS/tiago_public_ws/devel/share/pal_detection_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > { static const char* value() { return "ac3fbc481abe751cad38199e3707858d"; } static const char* value(const ::pal_detection_msgs::RecognizedObject_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xac3fbc481abe751cULL; static const uint64_t static_value2 = 0xad38199e3707858dULL; }; template<class ContainerAllocator> struct DataType< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > { static const char* value() { return "pal_detection_msgs/RecognizedObject"; } static const char* value(const ::pal_detection_msgs::RecognizedObject_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > { static const char* value() { return "# Contains information about the class of a found object, along with its confidence and ROI of detection\n\ \n\ # class: The respective class type of the found object\n\ string object_class\n\ \n\ # confidence: how sure you are it is that object and not another one.\n\ # It is between 0 and 1 and the closer to one it is the better\n\ float32 confidence\n\ \n\ # bounding_box: The region of the image, where the object is found\n\ sensor_msgs/RegionOfInterest bounding_box\n\ \n\ ================================================================================\n\ MSG: sensor_msgs/RegionOfInterest\n\ # This message is used to specify a region of interest within an image.\n\ #\n\ # When used to specify the ROI setting of the camera when the image was\n\ # taken, the height and width fields should either match the height and\n\ # width fields for the associated image; or height = width = 0\n\ # indicates that the full resolution image was captured.\n\ \n\ uint32 x_offset # Leftmost pixel of the ROI\n\ # (0 if the ROI includes the left edge of the image)\n\ uint32 y_offset # Topmost pixel of the ROI\n\ # (0 if the ROI includes the top edge of the image)\n\ uint32 height # Height of ROI\n\ uint32 width # Width of ROI\n\ \n\ # True if a distinct rectified ROI should be calculated from the \"raw\"\n\ # ROI in this message. Typically this should be False if the full image\n\ # is captured (ROI not used), and True if a subwindow is captured (ROI\n\ # used).\n\ bool do_rectify\n\ "; } static const char* value(const ::pal_detection_msgs::RecognizedObject_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.object_class); stream.next(m.confidence); stream.next(m.bounding_box); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct RecognizedObject_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::pal_detection_msgs::RecognizedObject_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::pal_detection_msgs::RecognizedObject_<ContainerAllocator>& v) { s << indent << "object_class: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.object_class); s << indent << "confidence: "; Printer<float>::stream(s, indent + " ", v.confidence); s << indent << "bounding_box: "; s << std::endl; Printer< ::sensor_msgs::RegionOfInterest_<ContainerAllocator> >::stream(s, indent + " ", v.bounding_box); } }; } // namespace message_operations } // namespace ros #endif // PAL_DETECTION_MSGS_MESSAGE_RECOGNIZEDOBJECT_H
[ "sakshum19@gmail.com" ]
sakshum19@gmail.com
970663ea4b511d7f09024f6f99e9d43f25f88435
579dbb681f772870d692f468322470612fa553aa
/reg-lib/_reg_dti.h
77543da37e65a5c8e2055472ec08a466b4e1ddcf
[]
no_license
chipbuster/niftyreg
eb69441dc3ee76930da08d580f61550fd448271d
d9bd674a1cdae37688444777cc07862dec366228
refs/heads/master
2021-01-11T08:50:14.626799
2016-12-16T20:46:28
2016-12-16T20:46:28
76,684,058
0
0
null
2016-12-16T20:37:50
2016-12-16T20:37:50
null
UTF-8
C++
false
false
3,473
h
/** * @file _reg_ssd.h * @brief File that contains sum squared difference related function * @author Marc Modat * @date 19/05/2009 * * Created by Marc Modat on 19/05/2009. * Copyright (c) 2009, University College London. All rights reserved. * Centre for Medical Image Computing (CMIC) * See the LICENSE.txt file in the nifty_reg root folder * */ #ifndef _REG_DTI_H #define _REG_DTI_H //#include "_reg_measure.h" #include "_reg_ssd.h" // HERE /* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */ /* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */ /// @brief DTI related measure of similarity class class reg_dti : public reg_measure { public: /// @brief reg_dti class constructor reg_dti(); // /// @brief Initialise the reg_dti object void InitialiseMeasure(nifti_image *refImgPtr, nifti_image *floImgPtr, int *maskRefPtr, nifti_image *warFloImgPtr, nifti_image *warFloGraPtr, nifti_image *forVoxBasedGraPtr, int *maskFloPtr = NULL, nifti_image *warRefImgPtr = NULL, nifti_image *warRefGraPtr = NULL, nifti_image *bckVoxBasedGraPtr = NULL); // /// @brief Returns the value virtual double GetSimilarityMeasureValue(); // /// @brief Compute the voxel based gradient for DTI images virtual void GetVoxelBasedSimilarityMeasureGradient(); /// @brief reg_dti class destructor ~reg_dti() {} protected: // Store the indicies of the DT components in the order XX,XY,YY,XZ,YZ,ZZ unsigned int dtIndicies[6]; float currentValue; }; /* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ */ /** @brief Copmutes and returns the SSD between two input image * @param targetImage First input image to use to compute the metric * @param resultImage Second input image to use to compute the metric * @param mask Array that contains a mask to specify which voxel * should be considered. If set to NULL, all voxels are considered * @return Returns an L2 measure of the distance between the anisotropic components of the diffusion tensors */ extern "C++" template <class DTYPE> double reg_getDTIMeasureValue(nifti_image *targetImage, nifti_image *resultImage, int *mask, unsigned int * dtIndicies ); /** @brief Compute a voxel based gradient of the sum squared difference. * @param targetImage First input image to use to compute the metric * @param resultImage Second input image to use to compute the metric * @param resultImageGradient Spatial gradient of the input result image * @param dtiGradientImage Output image that will be updated with the * value of the dti measure gradient * @param maxSD Input scalar that contain the difference value between * the highest and the lowest intensity. * @param mask Array that contains a mask to specify which voxel * should be considered. If set to NULL, all voxels are considered */ extern "C++" template <class DTYPE> void reg_getVoxelBasedDTIMeasureGradient(nifti_image *referenceImage, nifti_image *warpedImage, nifti_image *warpedImageGradient, nifti_image *dtiMeasureGradientImage, int *mask, unsigned int * dtIndicies); #endif
[ "m.modat@ucl.ac.uk" ]
m.modat@ucl.ac.uk
27876d59fd6a36328d414d245be306656de117a6
f0d560c9bb443e24a707347ac498d386d9b274e3
/particlesystem.h
3a8dd7ca6ba9732915b794d7f3567766d1bf60f9
[]
no_license
seamanj/ARAP
e5d7d4166b517fde92965e3a972f12908cbe3e6a
3a5b1b19a912ff9260ef1d88972bedf860566e0f
refs/heads/master
2020-05-02T22:12:34.374982
2019-06-08T13:37:10
2019-06-08T13:37:10
178,244,972
5
1
null
null
null
null
UTF-8
C++
false
false
2,849
h
#ifndef PARTICLESYSTEM_H #define PARTICLESYSTEM_H #include "mypolyhedron.h" #include <QVector> #include <QMap> #include "common.h" #include "renderable.h" #include "particle.h" #include "mesh.h" #include <memory> #include "types.h" #include <CGAL/Polygon_mesh_processing/Weights.h> using std::shared_ptr; template< class HG > class MyPolyhedron; //typedef CGAL::Surface_mesh_deformation<Polyhedron> Surface_mesh_deformation; class ParticleSystem : public Renderable { public: enum Type { Zero, Rigid, Linear, Quadratic }; ParticleSystem(Type type = Rigid); void initFromMesh(shared_ptr<Mesh> spMesh); void initFromPolyhedron(shared_ptr<MyPolyhedron<Polyhedron>> spMyPolyhedron); void setMyPolyhedron(shared_ptr<MyPolyhedron<Polyhedron>>& spMyPolyhedron) { m_spMyPolyhedron = spMyPolyhedron; } virtual void render(); virtual void renderForPicker(); bool hasVBO() const; void buildVBO(); void renderVBO(); void deleteVBO(); inline int getNumTris() const { return m_tris.size(); } inline QList<QList<int>>& getGroups() {return m_groups;} virtual glm::vec3 getCentroid( const glm::mat4 &ctm = glm::mat4(1.f) ); QMap<int, shared_ptr<Particle>>& getParticles(){ return m_particles;} void update(); void updateFromParticles(); void setDeformationMode(int mode) {m_type = Type(mode);} Type& getDeformationMode(){ return m_type;} bool insert_roi_vertex(int i); bool erase_roi_vertex(int i); bool insert_control_vertex(int i); bool erase_control_vertex(int i); void set_target_vertex(int i, Vertex pos); void deform(); protected: QMap<int, shared_ptr<Particle>> m_particles; QVector<Tri> m_tris; GLuint m_glVBO[2]; Color m_color; // Eigen Stuff VectorX m_currentPositions; VectorX m_originalPositions; VectorX m_previousPositions; VectorX m_currentVelocities; VectorX m_previousVelocities; VectorX m_externalForce; SparseMatrix m_massMatrix; SparseMatrix m_invMassMatrix; //Shape matching EigenVector3 m_t0; EigenVector3 m_t; VectorX m_q; VectorX m_qTilda; VectorX m_p; VectorX m_g; EigenMatrix3 m_Aqq; EigenMatrix9x9 m_AqqTilda; EigenMatrix3 m_Apq; EigenMatrix3x9 m_ApqTilda; EigenMatrix3 m_A; EigenMatrix3x9 m_ATilda; EigenMatrix3 m_R; EigenMatrix3x9 m_RTilda; unsigned int m_verticesNum; unsigned int m_triNum; Type m_type; shared_ptr<MyPolyhedron<Polyhedron>> m_spMyPolyhedron; QList<QList<int>> m_groups; int curGroup; friend class Engine; friend class Scene; }; #endif // PARTICLESYSTEM_H
[ "tjiang.work@gmail.com" ]
tjiang.work@gmail.com
121db05264ea4ac1734c9b1e68c3721db0ad3420
33fd5786ddde55a705d74ce2ce909017e2535065
/build/iOS/Release/include/Fuse.Triggers.IScroll-c30a2192.h
f6e58e6b77d0b6b42c2add40da6b43600997b833
[]
no_license
frpaulas/iphodfuse
04cee30add8b50ea134eb5a83e355dce886a5d5a
e8886638c4466b3b0c6299da24156d4ee81c9112
refs/heads/master
2021-01-23T00:48:31.195577
2017-06-01T12:33:13
2017-06-01T12:33:13
92,842,106
3
3
null
2017-05-30T17:43:28
2017-05-30T14:33:26
C++
UTF-8
C++
false
false
1,471
h
// This file was generated based on '../../../../Library/Application Support/Fusetools/Packages/Fuse.Controls.ScrollView/0.47.7/triggers/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Triggers.IScrolledLength.h> #include <Uno.Object.h> namespace g{namespace Fuse{namespace Controls{struct ScrollViewBase;}}} namespace g{namespace Fuse{namespace Triggers{struct IScrolledLengths__ContentSizeLength;}}} namespace g{namespace Uno{struct Float2;}} namespace g{ namespace Fuse{ namespace Triggers{ // private sealed class IScrolledLengths.ContentSizeLength :670 // { struct IScrolledLengths__ContentSizeLength_type : uType { ::g::Fuse::Triggers::IScrolledLength interface0; }; IScrolledLengths__ContentSizeLength_type* IScrolledLengths__ContentSizeLength_typeof(); void IScrolledLengths__ContentSizeLength__ctor__fn(IScrolledLengths__ContentSizeLength* __this); void IScrolledLengths__ContentSizeLength__GetPoints_fn(IScrolledLengths__ContentSizeLength* __this, float* value, ::g::Fuse::Controls::ScrollViewBase* scrollable, ::g::Uno::Float2* __retval); void IScrolledLengths__ContentSizeLength__New1_fn(IScrolledLengths__ContentSizeLength** __retval); struct IScrolledLengths__ContentSizeLength : uObject { void ctor_(); ::g::Uno::Float2 GetPoints(float value, ::g::Fuse::Controls::ScrollViewBase* scrollable); static IScrolledLengths__ContentSizeLength* New1(); }; // } }}} // ::g::Fuse::Triggers
[ "frpaulas@gmail.com" ]
frpaulas@gmail.com
9416de961defd15f4e349b930e7fc9d0cae87066
36655882886da9fa852d1db652a6163299c2ad36
/SpaJam2016/Photon-SDK/iOS/Chat-cpp/inc/Enums/ClientState.h
af416d5d705c8fd98d8fec970f61430ec545ffb6
[]
no_license
HidehikoKondo/FlashMob
37789da1345b9e719c7d39a916013f1beeb9cfa8
b8b803153be9a7a5f0ad163c6d704ff7b17514c4
refs/heads/master
2023-02-15T14:23:31.039876
2017-11-03T08:06:53
2017-11-03T08:06:53
326,894,274
0
0
null
null
null
null
UTF-8
C++
false
false
1,350
h
/* Exit Games Photon Chat - C++ Client Lib * Copyright (C) 2004-2016 by Exit Games GmbH. All rights reserved. * http://www.photonengine.com * mailto:developer@photonengine.com */ #pragma once namespace ExitGames { namespace Chat { /** Possible states for a Client.*/ namespace ClientState { static const int Uninitialized = 0; ///<Peer is created but not used yet. static const int ConnectingToNameServer = 1; ///<Connecting to Name Server (includes connect authenticate and joining the lobby) static const int ConnectedToNameServer = 2; ///<Connected to Name Server. static const int Authenticating = 3; ///<Authenticating. static const int Authenticated = 4; ///<Authenticated. static const int DisconnectingFromNameServer = 5; ///<Transition from Name to Chat Server. static const int ConnectingToFrontEnd = 6; ///<Transition to Chat Server. static const int ConnectedToFrontEnd = 7; ///<Connected to Chat Server. Subscribe to channels and chat here. static const int Disconnecting = 8; ///<The client disconnects (from any server). static const int Disconnected = 9; ///<The client is no longer connected (to any server). Connect to Name Server to go on. } /** @file */ } }
[ "takashi.ohsaka@gmail.com" ]
takashi.ohsaka@gmail.com
cafb7a3a9cd8ee5ed402827765d59c256bef0e9e
72fe18354c126f0b983c5ac425fc06daa1dd79a0
/library.h
4e998cdc9dbcee68d18ec5a32f59c19043cf9640
[]
no_license
Oleksa126/LibraryQt
486baa8bc4e59923c276521e41eb01332df0b3a5
a082455da94e9475b76c9fc6655011b22c6c4fea
refs/heads/master
2021-01-11T01:04:22.377450
2016-11-14T12:46:33
2016-11-14T12:46:33
70,844,578
0
0
null
null
null
null
UTF-8
C++
false
false
1,289
h
#ifndef LIBRARY_H #define LIBRARY_H #include <QString> #include <QFile> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QJsonValue> #include <QTextStream> #include "iostream" #include "reader.h" #include "reading.h" #include "book.h" using namespace std; class Library { public: vector <Book> ListBook; vector <Reader> ListReader; void findBookById(int bookId)const{ for(int i =0; i<ListBook.size(); i++){ if(ListBook[i].getID() == bookId){ cout<<ListBook[i]; } } } void addBook(Book book){ListBook.push_back(book);} void addReader(Reader reader){ListReader.push_back(reader);} void searchByGenre(QString genre); void searchByAuthor(QString author); void loadBooksFromJsonFile(); Book readBook(const QJsonObject &json){ return Book(json["Title"].toString(),json["Genre"].toString(),json["First Name"].toString(),json["Last Name"].toString(), json["ID"].toInt());} void saveBookToJsonString(QJsonArray &json)const; void saveBookToJsonFile(); void saveReaderToJsonString(QJsonArray &json)const; void saveReaderToJsonFile(); void loadReadersFromJsonFile(); Reader readReader(const QJsonObject &json); }; #endif // LIBRARIAN_H
[ "Олександр Барадач" ]
Олександр Барадач
75e9c06828b5ac4b66e1c55b99ed9302948394cf
9d364070c646239b2efad7abbab58f4ad602ef7b
/platform/external/chromium_org/chrome/browser/sync/glue/non_frontend_data_type_controller_mock.h
d27d7f1fb3c80e3fb70e2c861589db1d5bbc68d3
[ "BSD-3-Clause" ]
permissive
denix123/a32_ul
4ffe304b13c1266b6c7409d790979eb8e3b0379c
b2fd25640704f37d5248da9cc147ed267d4771c2
refs/heads/master
2021-01-17T20:21:17.196296
2016-08-16T04:30:53
2016-08-16T04:30:53
65,786,970
0
2
null
2020-03-06T22:00:52
2016-08-16T04:15:54
null
UTF-8
C++
false
false
2,683
h
// 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. #ifndef CHROME_BROWSER_SYNC_GLUE_NON_FRONTEND_DATA_TYPE_CONTROLLER_MOCK_H__ #define CHROME_BROWSER_SYNC_GLUE_NON_FRONTEND_DATA_TYPE_CONTROLLER_MOCK_H__ #include "chrome/browser/sync/glue/non_frontend_data_type_controller.h" #include "sync/api/sync_error.h" #include "testing/gmock/include/gmock/gmock.h" namespace browser_sync { class NonFrontendDataTypeControllerMock : public NonFrontendDataTypeController { public: NonFrontendDataTypeControllerMock(); MOCK_METHOD1(StartAssociating, void(const StartCallback& start_callback)); MOCK_METHOD1(LoadModels, void(const ModelLoadCallback& model_load_callback)); MOCK_METHOD0(OnModelLoaded, void()); MOCK_METHOD0(Stop, void()); MOCK_METHOD0(enabled, bool()); MOCK_CONST_METHOD0(type, syncer::ModelType()); MOCK_CONST_METHOD0(name, std::string()); MOCK_CONST_METHOD0(model_safe_group, syncer::ModelSafeGroup()); MOCK_CONST_METHOD0(state, State()); MOCK_METHOD2(OnUnrecoverableError, void(const tracked_objects::Location&, const std::string&)); MOCK_METHOD0(StartModels, bool()); MOCK_METHOD2(PostTaskOnBackendThread, bool(const tracked_objects::Location&, const base::Closure&)); MOCK_METHOD0(StartAssociation, void()); MOCK_METHOD0(CreateSyncComponents, ProfileSyncComponentsFactory::SyncComponents()); MOCK_METHOD3(StartDone, void(DataTypeController::ConfigureResult result, const syncer::SyncMergeResult& local_merge_result, const syncer::SyncMergeResult& syncer_merge_result)); MOCK_METHOD4(StartDoneImpl, void(DataTypeController::ConfigureResult result, DataTypeController::State new_state, const syncer::SyncMergeResult& local_merge_result, const syncer::SyncMergeResult& syncer_merge_result)); MOCK_METHOD1(DisconnectProcessor, void(sync_driver::ChangeProcessor*)); MOCK_METHOD2(OnUnrecoverableErrorImpl, void(const tracked_objects::Location&, const std::string&)); MOCK_METHOD2(RecordUnrecoverableError, void(const tracked_objects::Location&, const std::string&)); MOCK_METHOD1(RecordAssociationTime, void(base::TimeDelta time)); MOCK_METHOD1(RecordStartFailure, void(ConfigureResult result)); protected: virtual ~NonFrontendDataTypeControllerMock(); }; } #endif
[ "allegrant@mail.ru" ]
allegrant@mail.ru
b0f9e2b6fb97bbdadcac87ec8d0fea34c12cbf50
4389afd3c1cfdfb36af578ebd8e099aee51f5b41
/Source/PlantThatWheat/Private/PStarting/CObjectiveZonePStarting.cpp
bad7120fc59c547cac186c4143ea8297a48d23e3
[]
no_license
Hengle/Plant-That-Wheat
b0ab254442a3c80021519f17b8d586af4d91b3ff
9dba0c868b4fcfb49710e1f6bfb3cf06b748d30b
refs/heads/master
2023-03-27T01:48:27.770579
2020-05-26T15:58:20
2020-05-26T15:58:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,575
cpp
#include "CObjectiveZonePStarting.h" #include "PlantThatWheat.h" #include "CPlayerState.h" //#include "CLevelManagerPStarting.h" #include "CEvents_PStarting.h" #include "CLevelWidget_PStarting.h" #include "CMoveableActor.h" ACObjectiveZonePStarting::ACObjectiveZonePStarting() { OB_CollectGears = Objective{EObjectiveType::OT_Gears, false }; } void ACObjectiveZonePStarting::BeginPlay() { Level = Cast<ACLevel_PStarting>(GetWorld()->GetLevelScriptActor()); } void ACObjectiveZonePStarting::OnOverlapMoveable(ACMoveableActor * Moveable) { if (!OB_CollectGears.bIsComplete && Moveable->bCanAffectObjective) { NumGearsCollected++; Moveable->bCanAffectObjective = false; /*if (LevelWidget) { LevelWidget->UpdateGearCount(NumGearsCollected); }*/ // Call binded event here. /*if (LevelWidget) { LevelWidget->UpdateGearCount(NumGearsCollected); }*/ if (Level) { Level->OnCollectGear.Broadcast(); } if (NumGearsCollected >= ACEvents_PStarting::NUM_GEARS) { //LevelWidget->OnCollectAllGears(); CompleteObjective(OB_CollectGears); } if (Moveable) { Moveable->OnObjectiveOverlap(); } } } void ACObjectiveZonePStarting::OnOverlapCharacter(ACCharacterBase * Character) { } void ACObjectiveZonePStarting::OnObjectiveComplete(EPlanet CurPlanet, uint8 Objective) { // Tell the GameMode that an objective has been completed Super::OnObjectiveComplete(CurPlanet, Objective); } void ACObjectiveZonePStarting::CompleteObjective(Objective& Obj) { Obj.bIsComplete = true; OnObjectiveComplete(EPlanet::P_Starting, (uint8)(Obj.Type)); }
[ "kevin.c.vanhorn@gmail.com" ]
kevin.c.vanhorn@gmail.com
8c5f7457289ce7d638e595baf5815175b0c7791a
b7ba4574e66b09c09b1ebd2bfe9d3d77aaf51399
/matrix.h
ed807ad9891302993e95e98c632ac8e0de3950e2
[]
no_license
MouseGray/SimplexLib
798294d650ed8967d2127bc010d04d74b25135dc
5cb27063fa65ae23ddfccc2bf96148f829208bf9
refs/heads/master
2023-03-28T16:06:02.664753
2021-03-30T14:39:15
2021-03-30T14:39:15
353,034,210
0
0
null
null
null
null
UTF-8
C++
false
false
2,044
h
#ifndef MATRIX_H #define MATRIX_H #include <basis.h> #include <num.h> #define byRows for(int r = 0; r < m_rows; r++) #define byColumns for(int c = 0; c < m_columns; c++) #define byRows_(mat) for(int r = 0; r < mat.m_rows; r++) #define byColumns_(mat) for(int c = 0; c < mat.m_columns; c++) // ------------------- // | a11 ... a1m | // | ... ... ... | // | an1 ... anm | // ------------------- class SIMPLEXLIB_EXPORT Matrix { public: Matrix(); Matrix(short rows, short columns); Matrix(const Matrix &matrix); virtual ~Matrix(); virtual Matrix &initialize(short rows, short columns); Matrix &operator=(const Matrix &matrix); num& cell(const short row, const short column); num& cell(const short row, const short column) const; inline int rows() const { return m_rows; } inline int columns() const { return m_columns; } virtual void swapRows(const short first, const short second); virtual void swapColumns(const short first, const short second); virtual void multiplyRowBy(const short row, const num value); virtual void multiplyRowByWithout(const short row, const short column, const num value); virtual void multiplyColumnByWithout(const short column, const short row, const num value); virtual void divideRowBy(const short row, const num value); virtual void rowDifference(const short dist, const short src, const num coef); virtual void rowDifferenceWithout(const short dist, const short src, const short column, const num coef); int absMaxPosColumn(const short start, const short column); num sumColumn(const short column); virtual void removeRow(const short row); virtual void removeColumn(const short column); bool isNotPositiveColumn(const short column); static void MatrixCopy(Matrix &dist, const Matrix &src); static void MatrixNull(Matrix &dist); private: void init(); void free(); num** m_body = nullptr; protected: short m_rows = 0; short m_columns = 0; }; #endif // MATRIX_H
[ "swat.officer@yandex.ru" ]
swat.officer@yandex.ru
4a314232df24381ef949da173ec5d1f60e28bfe7
d5267ce6c82d0ee041fcef12988c63f882729beb
/语言/C++/CCpp/cpp/add-sub/sub.cpp
3faf14cf9aa6ff9c777ae21b41378df2298d2aa9
[ "MIT" ]
permissive
nashaofu/talk-is-cheap-show-me-the-code
2ce2beb63830a8ddeb122423a55e0cf51f32891b
b7ccc0c819df7a7dc95f9b1609755d76e8bdd9f1
refs/heads/master
2022-03-14T15:23:21.662982
2022-03-04T13:30:59
2022-03-04T13:30:59
135,306,614
11
2
null
null
null
null
UTF-8
C++
false
false
61
cpp
#include "sub.h" int sub(int a, int b) { return a - b; }
[ "diaocheng@outlook.com" ]
diaocheng@outlook.com
4881d594bc7eb2235578dfc45867712edbc5e72b
1e1821bfad90f14c380a3c2375ef68a4837429ad
/Site Hardware/_Asset/Library/ArduinoJson/src/ArduinoJson/Serialization/Writers/StaticStringWriter.hpp
1abb8eeeb62d719d928cb42d6650652cc2283ef2
[ "MIT" ]
permissive
Azzziel/Lulus-Online
1e6197341b3bbda1cbb0cb0a8e0b1eb00676bd3f
1964b834690f584d13484241a5a2391a50c924c4
refs/heads/master
2023-01-13T14:46:21.086453
2020-06-22T15:29:42
2020-06-22T15:29:42
247,638,404
0
1
MIT
2023-01-05T18:27:14
2020-03-16T07:32:53
C++
UTF-8
C++
false
false
767
hpp
// ArduinoJson - arduinojson.org // Copyright Benoit Blanchon 2014-2020 // MIT License #pragma once #include <ArduinoJson/Namespace.hpp> namespace ARDUINOJSON_NAMESPACE { // A Print implementation that allows to write in a char[] class StaticStringWriter { public: StaticStringWriter(char *buf, size_t size) : end(buf + size - 1), p(buf) { *p = '\0'; } size_t write(uint8_t c) { if (p >= end) return 0; *p++ = static_cast<char>(c); *p = '\0'; return 1; } size_t write(const uint8_t *s, size_t n) { char *begin = p; while (p < end && n > 0) { *p++ = static_cast<char>(*s++); n--; } *p = '\0'; return size_t(p - begin); } private: char *end; char *p; }; } // namespace ARDUINOJSON_NAMESPACE
[ "azriel.hutagalung@gmail.com" ]
azriel.hutagalung@gmail.com
f8a4638a34c7f0a174434b4b7015a076e3093d4a
33f5492bd183d3efbdf8bd31b4bf7d946a79c097
/wepetMeter/WiFiHTTPFunction.ino
478821b7bfada162b83c27121e5cf46c857ae882
[]
no_license
JungHanter/wepet_arduino
3fc586e903e05e0d6ebffdc8643164c019739310
0c83a1f24852ec3b6c91cc8ff1bc199da5fe2ade
refs/heads/master
2020-05-26T09:47:41.168098
2013-06-14T17:13:23
2013-06-14T17:13:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,340
ino
void disconnectServer() { if (!client.connected()) { client.flush(); client.stop(); } } boolean connectWiFi(boolean bFirst) { while ( wifiStatus != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: wifiStatus = WiFi.begin(ssid, pass); // wait 10 seconds for connection: delay(10000); } printWifiStatus(); // disconnectServer(); return true; } boolean httpRequest_sendData(const char* data, int dataSize) { // if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting...SendData..."); client.println("POST /hw/meter/step/ HTTP/1.1"); client.println("Host: 54.249.149.48"); client.println("User-Agent: WepetMeter"); client.println("Connection: close"); client.print("Content-Length: "); client.println(dataSize); client.println(); client.print(data); // note the time that the connection was made: lastConnectionTime = millis(); return true; } else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println("disconnecting."); client.stop(); return false; } } boolean httpRequest_getTime() { if (client.connect(server, 80)) { Serial.println("connecting...GetTime..."); client.println("POST /hw/time/now/ HTTP/1.1"); client.println("Host: 54.249.149.48"); client.println("User-Agent: WepetMeter"); client.println("Connection: close"); client.println(); // note the time that the connection was made: lastConnectionTime = millis(); return true; } else { // if you couldn't make a connection: Serial.println("connection failed"); Serial.println("disconnecting."); client.stop(); return false; } } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }
[ "hanterkr@gmail.com" ]
hanterkr@gmail.com
7620e16fed2fea937095bf42550971dc4e8f04c6
866c535388481d6f2b34f6aae745849bc462cf5a
/Tnode.h
4b37a0d2c1835a3982d3b703df965449c3a52054
[]
no_license
aliir74/DSfinal
95d0469cc25a7ef2db27dad6ff68b025f03573db
76f5de93d02ff17bd59060a501ab36fc8810302b
refs/heads/master
2021-01-22T03:57:33.139773
2017-06-12T09:20:04
2017-06-12T09:20:04
81,478,872
1
0
null
null
null
null
UTF-8
C++
false
false
377
h
#ifndef tnode_H #define tnode_H #include <iostream> #include "huffmantree.h" using namespace std; class Tnode{ public: Tnode *right; Tnode *left; string sdata; int countofdata; string code; Tnode(){ right = 0; left = 0; sdata = ""; code = ""; } }; #endif
[ "aliirani74@gmail.com" ]
aliirani74@gmail.com
91968c56392bae1742931fa9dd1370725722c89a
1446a45de06399c141ad722b70f8a4e2f88f01c8
/boost_1_34_1/boost_1_34_1/libs/xpressive/test/test10u.cpp
fe107eecfd90a60c0acc93b430b1d0f91f2c6023
[ "LicenseRef-scancode-unknown-license-reference", "BSL-1.0" ]
permissive
Thrinaria/Codebase
270d2b837242e113d733a7e6405b5294faede534
85e541a9d1e57f7bf30b5114e5e0a2063275a75d
refs/heads/master
2021-01-01T20:34:47.359877
2015-01-30T06:04:42
2015-01-30T06:04:42
29,504,087
3
4
null
2015-01-25T01:55:41
2015-01-20T00:41:11
C++
UTF-8
C++
false
false
800
cpp
/////////////////////////////////////////////////////////////////////////////// // test10.cpp // // Copyright 2004 Eric Niebler. 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 "./test10.hpp" /////////////////////////////////////////////////////////////////////////////// // test_main // read the tests from the input file and execute them int test_main( int, char*[] ) { #ifndef BOOST_XPRESSIVE_NO_WREGEX typedef std::wstring::const_iterator iterator_type; boost::iterator_range<test_case<iterator_type> const *> rng = get_test_cases<iterator_type>(); std::for_each(rng.begin(), rng.end(), test_runner<iterator_type>()); #endif return 0; }
[ "thrin_d@live.nl" ]
thrin_d@live.nl
8862e0ddce919cd5fd007adee60b9ec4e398f918
80296ed1826f6d59a7030d46dae57a65a70f789e
/1lab/0.4_does_it_fit/simple.cxxtest.cpp
95de835d34dc552c1f5ab923efd97ed1408541d3
[]
no_license
ZetaTwo/dd2387-laborationer
79860fe7c44a3db987db21b3667ab888077ffbd8
fd07bde9b864f00ecd07e2a2dbbac3db8c19cd85
refs/heads/master
2020-12-24T17:44:05.681762
2015-04-17T00:03:46
2015-04-17T00:03:46
21,952,837
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
cpp
#include <cxxtest/TestSuite.h> #include "count_if_followed_by.h" class MyTestSuite : public CxxTest::TestSuite { public: void test1 () { char const data[6] = {'G','G','X','G','X','G'}; int const test_len = 4; int const result = count_if_followed_by (data, test_len, 'X', 'G'); // SYNOPSIS: // result should be 1 since the length specified is 4, // and only one pair of [X, G] is present in that range! TS_ASSERT_EQUALS(result, 1); } void test_that_it_does_not_look_outside_the_specified_range() { char const data[6] = {'G','G','X','G','X','G'}; int const result = count_if_followed_by (data, 4, 'G', 'X'); TS_ASSERT_EQUALS(result, 1); } void test_that_it_does_not_crash_when_prefix_is_at_the_end() { char const data[6] = {'G','G','X','G','X','G'}; int const result = count_if_followed_by (data, 6, 'G', 'X'); TS_ASSERT_EQUALS(result, 2); } void test_that_it_does_not_count_suffix_when_not_preceded_by_prefix() { char const data[6] = {'G','A','X','G','X','G'}; int const result = count_if_followed_by (data, 6, 'G', 'X'); TS_ASSERT_EQUALS(result, 1); } };
[ "lundberg.emil@gmail.com" ]
lundberg.emil@gmail.com
a69fa7022a304360be7276055a74f9bdc655feb9
86a9081a05b837ad0f0feaf6e003a1cbb276993f
/cg_exercises-cg_exercise_04/04_bvh_v5/cg_exercise_04/cglib/lib/glm/glm/detail/type_vec4.hpp
efa028a3d0a2203f1f0ed08e12248c0fcf69da2c
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-happy-bunny", "LicenseRef-scancode-unknown-license-reference" ]
permissive
flex3r/cg_exercises
e2defd27427c251d5f0f567a8d192af8d87bca3c
7c4b699a8211ba66710ac2137f0d460933069331
refs/heads/master
2020-12-11T14:06:15.052585
2018-02-11T13:58:23
2018-02-11T13:58:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,341
hpp
/// @ref core /// @file glm/detail/type_vec4.hpp #pragma once #include "type_vec.hpp" #if GLM_SWIZZLE == GLM_SWIZZLE_ENABLED # if GLM_HAS_UNRESTRICTED_UNIONS # include "_swizzle.hpp" # else # include "_swizzle_func.hpp" # endif #endif //GLM_SWIZZLE #include <cstddef> namespace glm { template <typename T, precision P = defaultp> struct tvec4 { // -- Implementation detail -- typedef T value_type; typedef tvec4<T, P> type; typedef tvec4<bool, P> bool_type; // -- Data -- # if GLM_HAS_ONLY_XYZW T x, y, z, w; # elif GLM_HAS_ALIGNED_TYPE # if GLM_COMPILER & GLM_COMPILER_GCC # pragma GCC diagnostic push # pragma GCC diagnostic ignored "-Wpedantic" # endif # if GLM_COMPILER & GLM_COMPILER_CLANG # pragma clang diagnostic push # pragma clang diagnostic ignored "-Wgnu-anonymous-struct" # pragma clang diagnostic ignored "-Wnested-anon-types" # endif union { struct { T x, y, z, w;}; struct { T r, g, b, a; }; struct { T s, t, p, q; }; typename detail::storage<T, sizeof(T) * 4, detail::is_aligned<P>::value>::type data; # if GLM_SWIZZLE == GLM_SWIZZLE_ENABLED _GLM_SWIZZLE4_2_MEMBERS(T, P, glm::tvec2, x, y, z, w) _GLM_SWIZZLE4_2_MEMBERS(T, P, glm::tvec2, r, g, b, a) _GLM_SWIZZLE4_2_MEMBERS(T, P, glm::tvec2, s, t, p, q) _GLM_SWIZZLE4_3_MEMBERS(T, P, glm::tvec3, x, y, z, w) _GLM_SWIZZLE4_3_MEMBERS(T, P, glm::tvec3, r, g, b, a) _GLM_SWIZZLE4_3_MEMBERS(T, P, glm::tvec3, s, t, p, q) _GLM_SWIZZLE4_4_MEMBERS(T, P, glm::tvec4, x, y, z, w) _GLM_SWIZZLE4_4_MEMBERS(T, P, glm::tvec4, r, g, b, a) _GLM_SWIZZLE4_4_MEMBERS(T, P, glm::tvec4, s, t, p, q) # endif//GLM_SWIZZLE }; # if GLM_COMPILER & GLM_COMPILER_CLANG # pragma clang diagnostic pop # endif # if GLM_COMPILER & GLM_COMPILER_GCC # pragma GCC diagnostic pop # endif # else union { T x, r, s; }; union { T y, g, t; }; union { T z, b, p; }; union { T w, a, q; }; # if GLM_SWIZZLE == GLM_SWIZZLE_ENABLED GLM_SWIZZLE_GEN_VEC_FROM_VEC4(T, P, tvec4, tvec2, tvec3, tvec4) # endif//GLM_SWIZZLE # endif // -- Component accesses -- /// Return the count of components of the vector typedef length_t length_type; GLM_FUNC_DECL static length_type length(){return 4;} GLM_FUNC_DECL T & operator[](length_type i); GLM_FUNC_DECL T const & operator[](length_type i) const; // -- Implicit basic constructors -- GLM_FUNC_DECL GLM_CONSTEXPR_SIMD tvec4() GLM_DEFAULT_CTOR; GLM_FUNC_DECL GLM_CONSTEXPR_SIMD tvec4(tvec4<T, P> const& v) GLM_DEFAULT; template <precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_SIMD tvec4(tvec4<T, Q> const& v); // -- Explicit basic constructors -- GLM_FUNC_DECL GLM_CONSTEXPR_SIMD explicit tvec4(ctor); GLM_FUNC_DECL GLM_CONSTEXPR_SIMD explicit tvec4(T scalar); GLM_FUNC_DECL GLM_CONSTEXPR_SIMD tvec4(T a, T b, T c, T d); // -- Conversion scalar constructors -- /// Explicit converions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, typename D> GLM_FUNC_DECL GLM_CONSTEXPR_SIMD tvec4(A a, B b, C c, D d); template <typename A, typename B, typename C, typename D> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec1<A, P> const& a, tvec1<B, P> const& b, tvec1<C, P> const& c, tvec1<D, P> const& d); // -- Conversion vector constructors -- /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec2<A, Q> const & a, B b, C c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec2<A, Q> const & a, tvec1<B, Q> const & b, tvec1<C, Q> const & c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(A a, tvec2<B, Q> const & b, C c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec1<A, Q> const & a, tvec2<B, Q> const & b, tvec1<C, Q> const & c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(A a, B b, tvec2<C, Q> const & c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, typename C, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec1<A, Q> const & a, tvec1<B, Q> const & b, tvec2<C, Q> const & c); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec3<A, Q> const & a, B b); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec3<A, Q> const & a, tvec1<B, Q> const & b); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(A a, tvec3<B, Q> const & b); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec1<A, Q> const & a, tvec3<B, Q> const & b); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename A, typename B, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR tvec4(tvec2<A, Q> const & a, tvec2<B, Q> const & b); /// Explicit conversions (From section 5.4.1 Conversion and scalar constructors of GLSL 1.30.08 specification) template <typename U, precision Q> GLM_FUNC_DECL GLM_CONSTEXPR_CTOR GLM_EXPLICIT tvec4(tvec4<U, Q> const& v); // -- Swizzle constructors -- # if GLM_HAS_UNRESTRICTED_UNIONS && (GLM_SWIZZLE == GLM_SWIZZLE_ENABLED) template <int E0, int E1, int E2, int E3> GLM_FUNC_DECL tvec4(detail::_swizzle<4, T, P, glm::tvec4, E0, E1, E2, E3> const & that) { *this = that(); } template <int E0, int E1, int F0, int F1> GLM_FUNC_DECL tvec4(detail::_swizzle<2, T, P, glm::tvec2, E0, E1, -1, -2> const & v, detail::_swizzle<2, T, P, glm::tvec2, F0, F1, -1, -2> const & u) { *this = tvec4<T, P>(v(), u()); } template <int E0, int E1> GLM_FUNC_DECL tvec4(T const & x, T const & y, detail::_swizzle<2, T, P, glm::tvec2, E0, E1, -1, -2> const & v) { *this = tvec4<T, P>(x, y, v()); } template <int E0, int E1> GLM_FUNC_DECL tvec4(T const & x, detail::_swizzle<2, T, P, glm::tvec2, E0, E1, -1, -2> const & v, T const & w) { *this = tvec4<T, P>(x, v(), w); } template <int E0, int E1> GLM_FUNC_DECL tvec4(detail::_swizzle<2, T, P, glm::tvec2, E0, E1, -1, -2> const & v, T const & z, T const & w) { *this = tvec4<T, P>(v(), z, w); } template <int E0, int E1, int E2> GLM_FUNC_DECL tvec4(detail::_swizzle<3, T, P, glm::tvec3, E0, E1, E2, -1> const & v, T const & w) { *this = tvec4<T, P>(v(), w); } template <int E0, int E1, int E2> GLM_FUNC_DECL tvec4(T const & x, detail::_swizzle<3, T, P, glm::tvec3, E0, E1, E2, -1> const & v) { *this = tvec4<T, P>(x, v()); } # endif// GLM_HAS_UNRESTRICTED_UNIONS && (GLM_SWIZZLE == GLM_SWIZZLE_ENABLED) // -- Unary arithmetic operators -- GLM_FUNC_DECL tvec4<T, P> & operator=(tvec4<T, P> const & v) GLM_DEFAULT; template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator+=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator+=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator+=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator-=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator-=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator-=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator*=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator*=(tvec1<U, P> const& v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator*=(tvec4<U, P> const& v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator/=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator/=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator/=(tvec4<U, P> const & v); // -- Increment and decrement operators -- GLM_FUNC_DECL tvec4<T, P> & operator++(); GLM_FUNC_DECL tvec4<T, P> & operator--(); GLM_FUNC_DECL tvec4<T, P> operator++(int); GLM_FUNC_DECL tvec4<T, P> operator--(int); // -- Unary bit operators -- template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator%=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator%=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator%=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator&=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator&=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator&=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator|=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator|=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator|=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator^=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator^=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator^=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator<<=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator<<=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator<<=(tvec4<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator>>=(U scalar); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator>>=(tvec1<U, P> const & v); template <typename U> GLM_FUNC_DECL tvec4<T, P> & operator>>=(tvec4<U, P> const & v); }; // -- Unary operators -- template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(tvec4<T, P> const & v); // -- Binary operators -- template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(tvec4<T, P> const & v1, tvec1<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(tvec1<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator+(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(tvec4<T, P> const & v1, tvec1<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(tvec1<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator-(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator*(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator*(tvec4<T, P> const & v1, tvec1<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator*(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator*(tvec1<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator*(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator/(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator/(tvec4<T, P> const & v1, tvec1<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator/(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator/(tvec1<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator/(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator%(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator%(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator%(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator%(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator%(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator&(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator&(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator&(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator&(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator&(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator|(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator|(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator|(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator|(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator|(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator^(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator^(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator^(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator^(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator^(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator<<(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator<<(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator<<(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator<<(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator<<(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator>>(tvec4<T, P> const & v, T scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator>>(tvec4<T, P> const & v, tvec1<T, P> const & scalar); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator>>(T scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator>>(tvec1<T, P> const & scalar, tvec4<T, P> const & v); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator>>(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL tvec4<T, P> operator~(tvec4<T, P> const & v); // -- Boolean operators -- template <typename T, precision P> GLM_FUNC_DECL bool operator==(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <typename T, precision P> GLM_FUNC_DECL bool operator!=(tvec4<T, P> const & v1, tvec4<T, P> const & v2); template <precision P> GLM_FUNC_DECL tvec4<bool, P> operator&&(tvec4<bool, P> const & v1, tvec4<bool, P> const & v2); template <precision P> GLM_FUNC_DECL tvec4<bool, P> operator||(tvec4<bool, P> const & v1, tvec4<bool, P> const & v2); }//namespace glm #ifndef GLM_EXTERNAL_TEMPLATE #include "type_vec4.inl" #endif//GLM_EXTERNAL_TEMPLATE // CG_REVISION 923b9bac8f5225422060a543872d939f9f9f68dd
[ "n1085633848@outlook.com" ]
n1085633848@outlook.com
117dba44f67fa539b18edabf2efb1d58a1688138
82795a583b692be0968e6d7a3e5c28d64c6936bb
/src/rpcrawtransaction.cpp
5326745709a949f437a3e681d809a388f09bf8c4
[ "MIT" ]
permissive
KIDCoin4200/KIDC
0ca772254ae99249abd2df344da78edde765cc23
4e308bf83ca5df9afb8db6eae67d2e196aa9334d
refs/heads/main
2023-06-06T05:50:02.804412
2021-06-26T12:02:17
2021-06-26T12:02:17
380,417,184
0
0
null
null
null
null
UTF-8
C++
false
false
19,225
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <boost/assign/list_of.hpp> #include "base58.h" #include "bitcoinrpc.h" #include "db.h" #include "init.h" #include "main.h" #include "net.h" #include "wallet.h" using namespace std; using namespace boost; using namespace boost::assign; using namespace json_spirit; void ScriptPubKeyToJSON(const CScript& scriptPubKey, Object& out) { txnouttype type; vector<CTxDestination> addresses; int nRequired; out.push_back(Pair("asm", scriptPubKey.ToString())); out.push_back(Pair("hex", HexStr(scriptPubKey.begin(), scriptPubKey.end()))); if (!ExtractDestinations(scriptPubKey, type, addresses, nRequired)) { out.push_back(Pair("type", GetTxnOutputType(TX_NONSTANDARD))); return; } out.push_back(Pair("reqSigs", nRequired)); out.push_back(Pair("type", GetTxnOutputType(type))); Array a; BOOST_FOREACH(const CTxDestination& addr, addresses) a.push_back(CBitcoinAddress(addr).ToString()); out.push_back(Pair("addresses", a)); } void TxToJSON(const CTransaction& tx, const uint256 hashBlock, Object& entry) { entry.push_back(Pair("txid", tx.GetHash().GetHex())); entry.push_back(Pair("version", tx.nVersion)); entry.push_back(Pair("time", (boost::int64_t)tx.nTime)); entry.push_back(Pair("locktime", (boost::int64_t)tx.nLockTime)); Array vin; BOOST_FOREACH(const CTxIn& txin, tx.vin) { Object in; if (tx.IsCoinBase()) in.push_back(Pair("coinbase", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); else { in.push_back(Pair("txid", txin.prevout.hash.GetHex())); in.push_back(Pair("vout", (boost::int64_t)txin.prevout.n)); Object o; o.push_back(Pair("asm", txin.scriptSig.ToString())); o.push_back(Pair("hex", HexStr(txin.scriptSig.begin(), txin.scriptSig.end()))); in.push_back(Pair("scriptSig", o)); } in.push_back(Pair("sequence", (boost::int64_t)txin.nSequence)); vin.push_back(in); } entry.push_back(Pair("vin", vin)); Array vout; for (unsigned int i = 0; i < tx.vout.size(); i++) { const CTxOut& txout = tx.vout[i]; Object out; out.push_back(Pair("value", ValueFromAmount(txout.nValue))); out.push_back(Pair("n", (boost::int64_t)i)); Object o; ScriptPubKeyToJSON(txout.scriptPubKey, o); out.push_back(Pair("scriptPubKey", o)); vout.push_back(out); } entry.push_back(Pair("vout", vout)); if (hashBlock != 0) { entry.push_back(Pair("blockhash", hashBlock.GetHex())); map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) { entry.push_back(Pair("confirmations", 1 + nBestHeight - pindex->nHeight)); entry.push_back(Pair("time", (boost::int64_t)pindex->nTime)); entry.push_back(Pair("blocktime", (boost::int64_t)pindex->nTime)); } else entry.push_back(Pair("confirmations", 0)); } } } Value getrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getrawtransaction <txid> [verbose=0]\n" "If verbose=0, returns a string that is\n" "serialized, hex-encoded data for <txid>.\n" "If verbose is non-zero, returns an Object\n" "with information about <txid>."); uint256 hash; hash.SetHex(params[0].get_str()); bool fVerbose = false; if (params.size() > 1) fVerbose = (params[1].get_int() != 0); CTransaction tx; uint256 hashBlock = 0; if (!GetTransaction(hash, tx, hashBlock)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "No information available about transaction"); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; string strHex = HexStr(ssTx.begin(), ssTx.end()); if (!fVerbose) return strHex; Object result; result.push_back(Pair("hex", strHex)); TxToJSON(tx, hashBlock, result); return result; } Value listunspent(const Array& params, bool fHelp) { if (fHelp || params.size() > 3) throw runtime_error( "listunspent [minconf=1] [maxconf=9999999] [\"address\",...]\n" "Returns array of unspent transaction outputs\n" "with between minconf and maxconf (inclusive) confirmations.\n" "Optionally filtered to only include txouts paid to specified addresses.\n" "Results are an array of Objects, each of which has:\n" "{txid, vout, scriptPubKey, amount, confirmations}"); RPCTypeCheck(params, list_of(int_type)(int_type)(array_type)); int nMinDepth = 1; if (params.size() > 0) nMinDepth = params[0].get_int(); int nMaxDepth = 9999999; if (params.size() > 1) nMaxDepth = params[1].get_int(); set<CBitcoinAddress> setAddress; if (params.size() > 2) { Array inputs = params[2].get_array(); BOOST_FOREACH(Value& input, inputs) { CBitcoinAddress address(input.get_str()); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid SUCoin address: ")+input.get_str()); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str()); setAddress.insert(address); } } Array results; vector<COutput> vecOutputs; pwalletMain->AvailableCoins(vecOutputs, false); BOOST_FOREACH(const COutput& out, vecOutputs) { if (out.nDepth < nMinDepth || out.nDepth > nMaxDepth) continue; if(setAddress.size()) { CTxDestination address; if(!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; if (!setAddress.count(address)) continue; } int64 nValue = out.tx->vout[out.i].nValue; const CScript& pk = out.tx->vout[out.i].scriptPubKey; Object entry; entry.push_back(Pair("txid", out.tx->GetHash().GetHex())); entry.push_back(Pair("vout", out.i)); entry.push_back(Pair("scriptPubKey", HexStr(pk.begin(), pk.end()))); entry.push_back(Pair("amount",ValueFromAmount(nValue))); entry.push_back(Pair("confirmations",out.nDepth)); results.push_back(entry); } return results; } Value createrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "createrawtransaction [{\"txid\":txid,\"vout\":n},...] {address:amount,...}\n" "Create a transaction spending given inputs\n" "(array of objects containing transaction id and output number),\n" "sending to given address(es).\n" "Returns hex-encoded raw transaction.\n" "Note that the transaction's inputs are not signed, and\n" "it is not stored in the wallet or transmitted to the network."); RPCTypeCheck(params, list_of(array_type)(obj_type)); Array inputs = params[0].get_array(); Object sendTo = params[1].get_obj(); CTransaction rawTx; BOOST_FOREACH(Value& input, inputs) { const Object& o = input.get_obj(); const Value& txid_v = find_value(o, "txid"); if (txid_v.type() != str_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key"); string txid = txid_v.get_str(); if (!IsHex(txid)) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid"); const Value& vout_v = find_value(o, "vout"); if (vout_v.type() != int_type) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key"); int nOutput = vout_v.get_int(); if (nOutput < 0) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive"); CTxIn in(COutPoint(uint256(txid), nOutput)); rawTx.vin.push_back(in); } set<CBitcoinAddress> setAddress; BOOST_FOREACH(const Pair& s, sendTo) { CBitcoinAddress address(s.name_); if (!address.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid SUCoin address: ")+s.name_); if (setAddress.count(address)) throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_); setAddress.insert(address); CScript scriptPubKey; scriptPubKey.SetDestination(address.Get()); int64 nAmount = AmountFromValue(s.value_); CTxOut out(nAmount, scriptPubKey); rawTx.vout.push_back(out); } CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << rawTx; return HexStr(ss.begin(), ss.end()); } Value decoderawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "decoderawtransaction <hex string>\n" "Return a JSON object representing the serialized, hex-encoded transaction."); RPCTypeCheck(params, list_of(str_type)); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } Object result; TxToJSON(tx, 0, result); return result; } Value signrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 4) throw runtime_error( "signrawtransaction <hex string> [{\"txid\":txid,\"vout\":n,\"scriptPubKey\":hex},...] [<privatekey1>,...] [sighashtype=\"ALL\"]\n" "Sign inputs for raw transaction (serialized, hex-encoded).\n" "Second optional argument (may be null) is an array of previous transaction outputs that\n" "this transaction depends on but may not yet be in the blockchain.\n" "Third optional argument (may be null) is an array of base58-encoded private\n" "keys that, if given, will be the only keys used to sign the transaction.\n" "Fourth optional argument is a string that is one of six values; ALL, NONE, SINGLE or\n" "ALL|ANYONECANPAY, NONE|ANYONECANPAY, SINGLE|ANYONECANPAY.\n" "Returns json object with keys:\n" " hex : raw transaction with signature(s) (hex-encoded string)\n" " complete : 1 if transaction has a complete set of signature (0 if not)" + HelpRequiringPassphrase()); RPCTypeCheck(params, list_of(str_type)(array_type)(array_type)(str_type), true); vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); vector<CTransaction> txVariants; while (!ssData.empty()) { try { CTransaction tx; ssData >> tx; txVariants.push_back(tx); } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } } if (txVariants.empty()) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Missing transaction"); // mergedTx will end up with all the signatures; it // starts as a clone of the rawtx: CTransaction mergedTx(txVariants[0]); bool fComplete = true; // Fetch previous transactions (inputs): map<COutPoint, CScript> mapPrevOut; for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTransaction tempTx; MapPrevTx mapPrevTx; CTxDB txdb("r"); map<uint256, CTxIndex> unused; bool fInvalid; // FetchInputs aborts on failure, so we go one at a time. tempTx.vin.push_back(mergedTx.vin[i]); tempTx.FetchInputs(txdb, unused, false, false, mapPrevTx, fInvalid); // Copy results into mapPrevOut: BOOST_FOREACH(const CTxIn& txin, tempTx.vin) { const uint256& prevHash = txin.prevout.hash; if (mapPrevTx.count(prevHash) && mapPrevTx[prevHash].second.vout.size()>txin.prevout.n) mapPrevOut[txin.prevout] = mapPrevTx[prevHash].second.vout[txin.prevout.n].scriptPubKey; } } // Add previous txouts given in the RPC call: if (params.size() > 1 && params[1].type() != null_type) { Array prevTxs = params[1].get_array(); BOOST_FOREACH(Value& p, prevTxs) { if (p.type() != obj_type) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "expected object with {\"txid'\",\"vout\",\"scriptPubKey\"}"); Object prevOut = p.get_obj(); RPCTypeCheck(prevOut, map_list_of("txid", str_type)("vout", int_type)("scriptPubKey", str_type)); string txidHex = find_value(prevOut, "txid").get_str(); if (!IsHex(txidHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "txid must be hexadecimal"); uint256 txid; txid.SetHex(txidHex); int nOut = find_value(prevOut, "vout").get_int(); if (nOut < 0) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "vout must be positive"); string pkHex = find_value(prevOut, "scriptPubKey").get_str(); if (!IsHex(pkHex)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "scriptPubKey must be hexadecimal"); vector<unsigned char> pkData(ParseHex(pkHex)); CScript scriptPubKey(pkData.begin(), pkData.end()); COutPoint outpoint(txid, nOut); if (mapPrevOut.count(outpoint)) { // Complain if scriptPubKey doesn't match if (mapPrevOut[outpoint] != scriptPubKey) { string err("Previous output scriptPubKey mismatch:\n"); err = err + mapPrevOut[outpoint].ToString() + "\nvs:\n"+ scriptPubKey.ToString(); throw JSONRPCError(RPC_DESERIALIZATION_ERROR, err); } } else mapPrevOut[outpoint] = scriptPubKey; } } bool fGivenKeys = false; CBasicKeyStore tempKeystore; if (params.size() > 2 && params[2].type() != null_type) { fGivenKeys = true; Array keys = params[2].get_array(); BOOST_FOREACH(Value k, keys) { CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(k.get_str()); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY,"Invalid private key"); CKey key; bool fCompressed; CSecret secret = vchSecret.GetSecret(fCompressed); key.SetSecret(secret, fCompressed); tempKeystore.AddKey(key); } } else EnsureWalletIsUnlocked(); const CKeyStore& keystore = (fGivenKeys ? tempKeystore : *pwalletMain); int nHashType = SIGHASH_ALL; if (params.size() > 3 && params[3].type() != null_type) { static map<string, int> mapSigHashValues = boost::assign::map_list_of (string("ALL"), int(SIGHASH_ALL)) (string("ALL|ANYONECANPAY"), int(SIGHASH_ALL|SIGHASH_ANYONECANPAY)) (string("NONE"), int(SIGHASH_NONE)) (string("NONE|ANYONECANPAY"), int(SIGHASH_NONE|SIGHASH_ANYONECANPAY)) (string("SINGLE"), int(SIGHASH_SINGLE)) (string("SINGLE|ANYONECANPAY"), int(SIGHASH_SINGLE|SIGHASH_ANYONECANPAY)) ; string strHashType = params[3].get_str(); if (mapSigHashValues.count(strHashType)) nHashType = mapSigHashValues[strHashType]; else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid sighash param"); } bool fHashSingle = ((nHashType & ~SIGHASH_ANYONECANPAY) == SIGHASH_SINGLE); // Sign what we can: for (unsigned int i = 0; i < mergedTx.vin.size(); i++) { CTxIn& txin = mergedTx.vin[i]; if (mapPrevOut.count(txin.prevout) == 0) { fComplete = false; continue; } const CScript& prevPubKey = mapPrevOut[txin.prevout]; txin.scriptSig.clear(); // Only sign SIGHASH_SINGLE if there's a corresponding output: if (!fHashSingle || (i < mergedTx.vout.size())) SignSignature(keystore, prevPubKey, mergedTx, i, nHashType); // ... and merge in other signatures: BOOST_FOREACH(const CTransaction& txv, txVariants) { txin.scriptSig = CombineSignatures(prevPubKey, mergedTx, i, txin.scriptSig, txv.vin[i].scriptSig); } if (!VerifyScript(txin.scriptSig, prevPubKey, mergedTx, i, true, 0)) fComplete = false; } Object result; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << mergedTx; result.push_back(Pair("hex", HexStr(ssTx.begin(), ssTx.end()))); result.push_back(Pair("complete", fComplete)); return result; } Value sendrawtransaction(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 1) throw runtime_error( "sendrawtransaction <hex string>\n" "Submits raw transaction (serialized, hex-encoded) to local node and network."); RPCTypeCheck(params, list_of(str_type)); // parse hex string from parameter vector<unsigned char> txData(ParseHex(params[0].get_str())); CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; // deserialize binary data stream try { ssData >> tx; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed"); } uint256 hashTx = tx.GetHash(); // See if the transaction is already in a block // or in the memory pool: CTransaction existingTx; uint256 hashBlock = 0; if (GetTransaction(hashTx, existingTx, hashBlock)) { if (hashBlock != 0) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("transaction already in block ")+hashBlock.GetHex()); // Not in block, but already in the memory pool; will drop // through to re-relay it. } else { // push to local node CTxDB txdb("r"); if (!tx.AcceptToMemoryPool(txdb)) throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX rejected"); SyncWithWallets(tx, NULL, true); } RelayMessage(CInv(MSG_TX, hashTx), tx); return hashTx.GetHex(); }
[ "noreply@github.com" ]
noreply@github.com
d3741b3e6c6a55d03aeb9ea288e8c69d56ce99b6
53949cff58d8c0ba1144b710f82f807f2f94e233
/bagua-caffe/tools/convert_annoset.cpp
32ca2588cba59d0e00dce0872d3858985c734f23
[ "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
overmad/Inference-Library-for-JavaScript
d197e016b790860d38b24fd9122d5a50aa965cce
50686f240cb308d2dab9d30739fb953ce21aaff6
refs/heads/master
2020-12-04T00:16:23.574074
2018-10-08T15:01:34
2018-10-08T15:01:34
231,534,913
1
0
BSD-2-Clause
2020-01-03T07:21:15
2020-01-03T07:21:14
null
UTF-8
C++
false
false
7,311
cpp
// This program converts a set of images and annotations to a lmdb/leveldb by // storing them as AnnotatedDatum proto buffers. // Usage: // convert_annoset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME // // where ROOTFOLDER is the root folder that holds all the images and // annotations, and LISTFILE should be a list of files as well as their labels // or label files. // For classification task, the file should be in the format as // imgfolder1/img1.JPEG 7 // .... // For detection task, the file should be in the format as // imgfolder1/img1.JPEG annofolder1/anno1.xml // .... #include <algorithm> #include <fstream> // NOLINT(readability/streams) #include <map> #include <string> #include <utility> #include <vector> #include "boost/scoped_ptr.hpp" #include "boost/variant.hpp" #include "gflags/gflags.h" #include "glog/logging.h" #include "caffe/proto/caffe.pb.h" #include "caffe/util/db.hpp" #include "caffe/util/format.hpp" #include "caffe/util/io.hpp" #include "caffe/util/rng.hpp" using namespace caffe; // NOLINT(build/namespaces) using std::pair; using boost::scoped_ptr; DEFINE_bool(gray, false, "When this option is on, treat images as grayscale ones"); DEFINE_bool(shuffle, false, "Randomly shuffle the order of images and their labels"); DEFINE_string(backend, "lmdb", "The backend {lmdb, leveldb} for storing the result"); DEFINE_string(anno_type, "classification", "The type of annotation {classification, detection}."); DEFINE_string(label_type, "xml", "The type of annotation file format."); DEFINE_string(label_map_file, "", "A file with LabelMap protobuf message."); DEFINE_bool(check_label, false, "When this option is on, check that there is no duplicated name/label."); DEFINE_int32(min_dim, 0, "Minimum dimension images are resized to (keep same aspect ratio)"); DEFINE_int32(max_dim, 0, "Maximum dimension images are resized to (keep same aspect ratio)"); DEFINE_int32(resize_width, 0, "Width images are resized to"); DEFINE_int32(resize_height, 0, "Height images are resized to"); DEFINE_bool(check_size, false, "When this option is on, check that all the datum have the same size"); DEFINE_bool(encoded, false, "When this option is on, the encoded image will be save in datum"); DEFINE_string(encode_type, "", "Optional: What type should we encode the image as ('png','jpg',...)."); int main(int argc, char** argv) { #ifdef USE_OPENCV ::google::InitGoogleLogging(argv[0]); // Print output to stderr (while still logging) FLAGS_alsologtostderr = 1; #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif gflags::SetUsageMessage("Convert a set of images and annotations to the " "leveldb/lmdb format used as input for Caffe.\n" "Usage:\n" " convert_annoset [FLAGS] ROOTFOLDER/ LISTFILE DB_NAME\n"); gflags::ParseCommandLineFlags(&argc, &argv, true); if (argc < 4) { gflags::ShowUsageWithFlagsRestrict(argv[0], "tools/convert_annoset"); return 1; } const bool is_color = !FLAGS_gray; const bool check_size = FLAGS_check_size; const bool encoded = FLAGS_encoded; const string encode_type = FLAGS_encode_type; const string anno_type = FLAGS_anno_type; AnnotatedDatum_AnnotationType type; const string label_type = FLAGS_label_type; const string label_map_file = FLAGS_label_map_file; const bool check_label = FLAGS_check_label; std::map<std::string, int> name_to_label; std::ifstream infile(argv[2]); std::vector<std::pair<std::string, boost::variant<int, std::string> > > lines; std::string filename; int label; std::string labelname; if (anno_type == "classification") { while (infile >> filename >> label) { lines.push_back(std::make_pair(filename, label)); } } else if (anno_type == "detection") { type = AnnotatedDatum_AnnotationType_BBOX; LabelMap label_map; CHECK(ReadProtoFromTextFile(label_map_file, &label_map)) << "Failed to read label map file."; CHECK(MapNameToLabel(label_map, check_label, &name_to_label)) << "Failed to convert name to label."; while (infile >> filename >> labelname) { lines.push_back(std::make_pair(filename, labelname)); } } if (FLAGS_shuffle) { // randomly shuffle data LOG(INFO) << "Shuffling data"; shuffle(lines.begin(), lines.end()); } LOG(INFO) << "A total of " << lines.size() << " images."; if (encode_type.size() && !encoded) LOG(INFO) << "encode_type specified, assuming encoded=true."; int min_dim = std::max<int>(0, FLAGS_min_dim); int max_dim = std::max<int>(0, FLAGS_max_dim); int resize_height = std::max<int>(0, FLAGS_resize_height); int resize_width = std::max<int>(0, FLAGS_resize_width); // Create new DB scoped_ptr<db::DB> db(db::GetDB(FLAGS_backend)); db->Open(argv[3], db::NEW); scoped_ptr<db::Transaction> txn(db->NewTransaction()); // Storing to db std::string root_folder(argv[1]); AnnotatedDatum anno_datum; Datum* datum = anno_datum.mutable_datum(); int count = 0; int data_size = 0; bool data_size_initialized = false; for (int line_id = 0; line_id < lines.size(); ++line_id) { bool status = true; std::string enc = encode_type; if (encoded && !enc.size()) { // Guess the encoding type from the file name string fn = lines[line_id].first; size_t p = fn.rfind('.'); if ( p == fn.npos ) LOG(WARNING) << "Failed to guess the encoding of '" << fn << "'"; enc = fn.substr(p); std::transform(enc.begin(), enc.end(), enc.begin(), ::tolower); } filename = root_folder + lines[line_id].first; if (anno_type == "classification") { label = boost::get<int>(lines[line_id].second); status = ReadImageToDatum(filename, label, resize_height, resize_width, min_dim, max_dim, is_color, enc, datum); } else if (anno_type == "detection") { labelname = root_folder + boost::get<std::string>(lines[line_id].second); status = ReadRichImageToAnnotatedDatum(filename, labelname, resize_height, resize_width, min_dim, max_dim, is_color, enc, type, label_type, name_to_label, &anno_datum); anno_datum.set_type(AnnotatedDatum_AnnotationType_BBOX); } if (status == false) { LOG(WARNING) << "Failed to read " << lines[line_id].first; continue; } if (check_size) { if (!data_size_initialized) { data_size = datum->channels() * datum->height() * datum->width(); data_size_initialized = true; } else { const std::string& data = datum->data(); CHECK_EQ(data.size(), data_size) << "Incorrect data field size " << data.size(); } } // sequential string key_str = caffe::format_int(line_id, 8) + "_" + lines[line_id].first; // Put in db string out; CHECK(anno_datum.SerializeToString(&out)); txn->Put(key_str, out); if (++count % 1000 == 0) { // Commit db txn->Commit(); txn.reset(db->NewTransaction()); LOG(INFO) << "Processed " << count << " files."; } } // write the last batch if (count % 1000 != 0) { txn->Commit(); LOG(INFO) << "Processed " << count << " files."; } #else LOG(FATAL) << "This tool requires OpenCV; compile with USE_OPENCV."; #endif // USE_OPENCV return 0; }
[ "kanghua.yu@intel.com" ]
kanghua.yu@intel.com
86d2a1f62467f920ca6712fe2987884bf967be00
5fab8a83f52d9803dca75f9a7ee97d35e1f44239
/src/external/bgfx/3rdparty/ocornut-imgui/imgui.cpp
e62a3d62c843ff3ffb86d759a2579fe9c40555ac
[ "MIT" ]
permissive
yy-yyaa/ProDBG
a147ed1e408adbb44e172ee511ead8ac82689090
b9a0b0119cbc9ed8f3e4f28251408fe3a4a8accd
refs/heads/master
2021-01-18T04:58:54.420460
2015-06-21T09:05:57
2015-06-21T09:05:57
37,754,085
0
0
null
2015-06-20T01:51:52
2015-06-20T01:51:52
null
UTF-8
C++
false
false
485,129
cpp
// ImGui library v1.39 WIP // See ImGui::ShowTestWindow() for sample code. // Read 'Programmer guide' below for notes on how to setup ImGui in your codebase. // Get latest version at https://github.com/ocornut/imgui // Developed by Omar Cornut and ImGui contributors. /* Index - MISSION STATEMENT - END-USER GUIDE - PROGRAMMER GUIDE (read me!) - API BREAKING CHANGES (read me when you update!) - FREQUENTLY ASKED QUESTIONS (FAQ), TIPS - Can I have multiple widgets with the same label? (Yes) - How do I update to a newer version of ImGui? - Why is my text output blurry? - How can I load a different font than the default? - How can I load multiple fonts? - How can I display and input Chinese, Japanese, Korean characters? - ISSUES & TODO-LIST - CODE - SAMPLE CODE - FONT DATA MISSION STATEMENT ================= - easy to use to create code-driven and data-driven tools - easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools - easy to hack and improve - minimize screen real-estate usage - minimize setup and maintenance - minimize state storage on user side - portable, minimize dependencies, run on target (consoles, phones, etc.) - efficient runtime (NB- we do allocate when "growing" content - creating a window / opening a tree node for the first time, etc. - but a typical frame won't allocate anything) - read about immediate-mode gui principles @ http://mollyrocket.com/861, http://mollyrocket.com/forums/index.html Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes: - doesn't look fancy, doesn't animate - limited layout features, intricate layouts are typically crafted in code - occasionally uses statically sized buffers for string manipulations - won't crash, but some very long pieces of text may be clipped. functions like ImGui::TextUnformatted() don't have such restriction. END-USER GUIDE ============== - double-click title bar to collapse window - click upper right corner to close a window, available when 'bool* p_opened' is passed to ImGui::Begin() - click and drag on lower right corner to resize window - click and drag on any empty space to move window - double-click/double-tap on lower right corner grip to auto-fit to content - TAB/SHIFT+TAB to cycle through keyboard editable fields - use mouse wheel to scroll - use CTRL+mouse wheel to zoom window contents (if IO.FontAllowScaling is true) - CTRL+Click on a slider to input value as text - text editor: - Hold SHIFT or use mouse to select text. - CTRL+Left/Right to word jump - CTRL+Shift+Left/Right to select words - CTRL+A our Double-Click to select all - CTRL+X,CTRL+C,CTRL+V to use OS clipboard - CTRL+Z,CTRL+Y to undo/redo - ESCAPE to revert text to its original value - You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!) PROGRAMMER GUIDE ================ - read the FAQ below this section! - your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention on your side, no state duplication, less sync, less bugs. - call and read ImGui::ShowTestWindow() for sample code demonstrating most features. - see examples/ folder for standalone sample applications. e.g. examples/opengl_example/ - customization: PushStyleColor()/PushStyleVar() or the style editor to tweak the look of the interface (e.g. if you want a more compact UI or a different color scheme). - getting started: - initialisation: call ImGui::GetIO() to retrieve the ImGuiIO structure and fill the 'Settings' data. - every frame: 1/ in your mainloop or right after you got your keyboard/mouse info, call ImGui::GetIO() and fill the 'Input' data, then call ImGui::NewFrame(). 2/ use any ImGui function you want between NewFrame() and Render() 3/ ImGui::Render() to render all the accumulated command-lists. it will call your RenderDrawListFn handler that you set in the IO structure. - all rendering information are stored into command-lists until ImGui::Render() is called. - ImGui never touches or know about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you must provide. - effectively it means you can create widgets at any time in your code, regardless of "update" vs "render" considerations. - refer to the examples applications in the examples/ folder for instruction on how to setup your code. - a typical application skeleton may be: // Application init ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = 1920.0f; io.DisplaySize.y = 1280.0f; io.DeltaTime = 1.0f/60.0f; io.IniFilename = "imgui.ini"; // TODO: Fill others settings of the io structure // Load texture unsigned char* pixels; int width, height, bytes_per_pixels; io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height, &bytes_per_pixels); // TODO: copy texture to graphics memory. // TODO: store your texture pointer/identifier in 'io.Fonts->TexID' // Application main loop while (true) { // 1) get low-level input // e.g. on Win32, GetKeyboardState(), or poll your events, etc. // 2) TODO: fill all fields of IO structure and call NewFrame ImGuiIO& io = ImGui::GetIO(); io.MousePos = mouse_pos; io.MouseDown[0] = mouse_button_0; io.KeysDown[i] = ... ImGui::NewFrame(); // 3) most of your application code here - you can use any of ImGui::* functions at any point in the frame ImGui::Begin("My window"); ImGui::Text("Hello, world."); ImGui::End(); GameUpdate(); GameRender(); // 4) render & swap video buffers ImGui::Render(); // swap video buffer, etc. } - after calling ImGui::NewFrame() you can read back 'io.WantCaptureMouse' and 'io.WantCaptureKeyboard' to tell if ImGui wants to use your inputs. if it does you can discard/hide the inputs from the rest of your application. API BREAKING CHANGES ==================== Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix. Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code. - 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function (will obsolete). - 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API - 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive. - 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead. - 2015/03/17 (1.36) - renamed GetItemRectMin()/GetItemRectMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function (will obsolete). - 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing - 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function (will obsolete). - 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth - 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function (will obsolete). - 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once. - 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now. - 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior - 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing() - 2015/02/01 (1.31) - removed IO.MemReallocFn (unused) - 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions. - 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader. (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels. this sequence: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); // <Copy to GPU> became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); // <Copy to GPU> io.Fonts->TexID = (your_texture_identifier); you now have much more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs. it is now recommended your sample the font texture with bilinear interpolation. (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID. (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix) (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets - 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver) - 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph) - 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility - 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered() - 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly) - 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity) - 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale() - 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn - 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically) - 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite - 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes FREQUENTLY ASKED QUESTIONS (FAQ), TIPS ====================================== Q: Can I have multiple widgets with the same label? A: Yes. A primer on the use of labels/IDs in ImGui.. - Interactive widgets require state to be carried over multiple frames (most typically ImGui often needs to remember what is the "active" widget). to do so they need an unique ID. unique ID are typically derived from a string label, an integer index or a pointer. Button("OK"); // Label = "OK", ID = hash of "OK" Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel" - Elements that are not clickable, such as Text() items don't need an ID. - ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK" in two different windows or in two different locations of a tree. - if you have a same ID twice in the same location, you'll have a conflict: Button("OK"); Button("OK"); // ID collision! Both buttons will be treated as the same. Fear not! this is easy to solve and there are many ways to solve it! - when passing a label you can optionally specify extra unique ID information within string itself. This helps solving the simpler collision cases. use "##" to pass a complement to the ID that won't be visible to the end-user: Button("Play##0"); // Label = "Play", ID = hash of "Play##0" Button("Play##1"); // Label = "Play", ID = hash of "Play##1" (different from above) - occasionally (rarely) you might want change a label while preserving a constant ID. This allows you to animate labels. use "###" to pass a label that isn't part of ID: Button("Hello###ID"; // Label = "Hello", ID = hash of "ID" Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above) - use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window. this is the most convenient way of distinguish ID if you are iterating and creating many UI elements. you can push a pointer, a string or an integer value. remember that ID are formed from the addition of everything in the ID stack! for (int i = 0; i < 100; i++) { PushID(i); Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj); Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique) PopID(); } for (int i = 0; i < 100; i++) { MyObject* obj = Objects[i]; PushID(obj->Name); Button("Click"); // Label = "Click", ID = hash of string + "label" (unique) PopID(); } - more example showing that you can stack multiple prefixes into the ID stack: Button("Click"); // Label = "Click", ID = hash of "Click" PushID("node"); Button("Click"); // Label = "Click", ID = hash of "node" + "Click" PushID(my_ptr); Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click" PopID(); PopID(); - tree nodes implicitly creates a scope for you by calling PushID(). Button("Click"); // Label = "Click", ID = hash of "Click" if (TreeNode("node")) { Button("Click"); // Label = "Click", ID = hash of "node" + "Click" TreePop(); } - when working with trees, ID are used to preserve the opened/closed state of each tree node. depending on your use cases you may want to use strings, indices or pointers as ID. e.g. when displaying a single object that may change over time (1-1 relationship), using a static string as ID will preserve your node open/closed state when the targeted object change. e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently. experiment and see what makes more sense! Q: How do I update to a newer version of ImGui? A: Overwrite the following files: imgui.cpp imgui.h stb_rect_pack.h stb_textedit.h stb_truetype.h Check the "API BREAKING CHANGES" sections for a list of occasional API breaking changes. Q: Why is my text output blurry? A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f) Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13) A: Use the font atlas to load the TTF file you want: io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() Q: How can I load multiple fonts? A: Use the font atlas to pack them into a single texture: ImFont* font0 = io.Fonts->AddFontDefault(); ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels); ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels); io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() // the first loaded font gets used by default // use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime Q: How can I render and input Chinese, Japanese, Korean characters? A: When loading a font, pass custom Unicode ranges to specify the glyphs to load. ImGui will support UTF-8 encoding across the board. Character input depends on you passing the right character code to io.AddInputCharacter(). The example applications do that. io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, io.Fonts->GetGlyphRangesJapanese()); // Load Japanese characters io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() io.ImeWindowHandle = MY_HWND; // To input using Microsoft IME, give ImGui the hwnd of your application - tip: the construct 'IMGUI_ONCE_UPON_A_FRAME { ... }' will run the block of code only once a frame. You can use it to quickly add custom UI in the middle of a deep nested inner loop in your code. - tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug" - tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window. - tip: you can call Render() multiple times (e.g for VR renders). - tip: call and read the ShowTestWindow() code for more example of how to use ImGui! ISSUES & TODO-LIST ================== - misc: merge or clarify ImVec4 vs ImRect? - window: add horizontal scroll - window: fix resize grip rendering scaling along with Rounding style setting - window: autofit feedback loop when user relies on any dynamic layout (window width multiplier, column). maybe just clearly drop manual autofit? - window: add a way for very transient windows (non-saved, temporary overlay over hundreds of objects) to "clean" up from the global window list. - window: allow resizing of child windows (possibly given min/max for each axis?) - window: background options for child windows, border option (disable rounding) - window: resizing from any sides? + mouse cursor directives for app. - widgets: display mode: widget-label, label-widget (aligned on column or using fixed size), label-newline-tab-widget etc. - widgets: clean up widgets internal toward exposing everything. - main: considering adding EndFrame()/Init(). some constructs are awkward in the implementation because of the lack of them. - main: IsItemHovered() make it more consistent for various type of widgets, widgets with multiple components, etc. also effectively IsHovered() region sometimes differs from hot region, e.g tree nodes - main: IsItemHovered() info stored in a stack? so that 'if TreeNode() { Text; TreePop; } if IsHovered' return the hover state of the TreeNode? !- input number: large int not reliably supported because of int<>float conversions. - input number: optional range min/max for Input*() functions - input number: holding [-]/[+] buttons could increase the step speed non-linearly (or user-controlled) - input number: use mouse wheel to step up/down - input number: non-decimal input. - text: proper alignment options - layout: horizontal layout helper (github issue #97) - layout: more generic alignment state (left/right/centered) for single items? - layout: clean up the InputFloatN/SliderFloatN/ColorEdit4 layout code. item width should include frame padding. - columns: separator function or parameter that works within the column (currently Separator() bypass all columns) (github issue #125) - columns: declare column set (each column: fixed size, %, fill, distribute default size among fills) (github issue #125) - columns: columns header to act as button (~sort op) and allow resize/reorder (github issue #125) - columns: user specify columns size (github issue #125) - popup: border options. richer api like BeginChild() perhaps? (github issue #197) - combo: turn child handling code into pop up helper - combo: contents should extends to fit label if combo widget is small - listbox: multiple selection - listbox: user may want to initial scroll to focus on the one selected value? ! menubar, menus (github issue #126) - tabs - gauge: various forms of gauge/loading bars widgets - color: better color editor. - plot: make it easier for user to draw extra stuff into the graph (e.g: draw basis, highlight certain points, 2d plots, multiple plots) - plot: "smooth" automatic scale over time, user give an input 0.0(full user scale) 1.0(full derived from value) - plot: add a helper e.g. Plot(char* label, float value, float time_span=2.0f) that stores values and Plot them for you - probably another function name. and/or automatically allow to plot ANY displayed value (more reliance on stable ID) - file selection widget -> build the tool in our codebase to improve model-dialog idioms - slider: allow using the [-]/[+] buttons used by InputFloat()/InputInt() - slider: initial absolute click is imprecise. change to relative movement slider (same as scrollbar). - slider: add dragging-based widgets to edit values with mouse (on 2 axises), saving screen real-estate. - text edit: clean up the mess caused by converting UTF-8 <> wchar. the code is rather inefficient right now. - text edit: centered text for slider as input text so it matches typical positioning. - text edit: flag to disable live update of the user buffer. - text edit: field resize behavior - field could stretch when being edited? hover tooltip shows more text? - text edit: add multi-line text edit - tree: add treenode/treepush int variants? because (void*) cast from int warns on some platforms/settings - settings: write more decent code to allow saving/loading new fields - settings: api for per-tool simple persistent data (bool,int,float,columns sizes,etc.) in .ini file ! style: store rounded corners in texture to use 1 quad per corner (filled and wireframe). so rounding have minor cost. - style: checkbox: padding for "active" color should be a multiplier of the - style: colorbox not always square? - text: simple markup language for color change? - log: LogButtons() options for specifying depth and/or hiding depth slider - log: have more control over the log scope (e.g. stop logging when leaving current tree node scope) - log: be able to log anything (e.g. right-click on a window/tree-node, shows context menu? log into tty/file/clipboard) - log: let user copy any window content to clipboard easily (CTRL+C on windows? while moving it? context menu?). code is commented because it fails with multiple Begin/End pairs. - filters: set a current filter that tree node can automatically query to hide themselves - filters: handle wildcards (with implicit leading/trailing *), regexps - shortcuts: add a shortcut api, e.g. parse "&Save" and/or "Save (CTRL+S)", pass in to widgets or provide simple ways to use (button=activate, input=focus) ! keyboard: tooltip & combo boxes are messing up / not honoring keyboard tabbing - keyboard: full keyboard navigation and focus. - input: rework IO to be able to pass actual events to fix temporal aliasing issues. - input: support track pad style scrolling & slider edit. - tooltip: move to fit within screen (e.g. when mouse cursor is right of the screen). - portability: big-endian test/support (github issue #81) - misc: mark printf compiler attributes on relevant functions - misc: provide a way to compile out the entire implementation while providing a dummy API (e.g. #define IMGUI_DUMMY_IMPL) - misc: double-clicking on title bar to minimize isn't consistent, perhaps move to single-click on left-most collapse icon? - style editor: have a more global HSV setter (e.g. alter hue on all elements). consider replacing active/hovered by offset in HSV space? - style editor: color child window height expressed in multiple of line height. - optimization/render: use indexed rendering to reduce vertex data cost (e.g. for remote/networked imgui) - optimization/render: merge command-lists with same clip-rect into one even if they aren't sequential? (as long as in-between clip rectangle don't overlap)? - optimization: turn some the various stack vectors into statically-sized arrays - optimization: better clipping for multi-component widgets */ #if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS #endif #include "imgui.h" #include <ctype.h> // toupper, isprint #include <math.h> // sqrtf, fabsf, fmodf, powf, cosf, sinf, floorf, ceilf #include <stdint.h> // intptr_t #include <stdio.h> // vsnprintf, sscanf #include <new> // new (ptr) #ifdef _MSC_VER #pragma warning (disable: 4505) // unreferenced local function has been removed (stb stuff) #pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen #endif // Clang warnings with -Weverything #ifdef __clang__ #pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse. #pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants ok. #pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code. #pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals. #pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it. #pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness // #pragma clang diagnostic ignored "-Wmissing-noreturn" // warning : function xx could be declared with attribute 'noreturn' warning // GetDefaultFontData() asserts which some implementation makes it never return. #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used #endif //------------------------------------------------------------------------- // STB libraries implementation //------------------------------------------------------------------------- struct ImGuiTextEditState; //#define IMGUI_STB_NAMESPACE ImStb //#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION //#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION #ifdef IMGUI_STB_NAMESPACE namespace IMGUI_STB_NAMESPACE { #endif #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wmissing-prototypes" #endif #define STBRP_ASSERT(x) IM_ASSERT(x) #ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION #define STBRP_STATIC #define STB_RECT_PACK_IMPLEMENTATION #endif #include "stb_rect_pack.h" #define STBTT_malloc(x,u) ((void)(u), ImGui::MemAlloc(x)) #define STBTT_free(x,u) ((void)(u), ImGui::MemFree(x)) #define STBTT_assert(x) IM_ASSERT(x) #ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION #define STBTT_STATIC #define STB_TRUETYPE_IMPLEMENTATION #else #define STBTT_DEF extern #endif #include "stb_truetype.h" #undef STB_TEXTEDIT_STRING #undef STB_TEXTEDIT_CHARTYPE #define STB_TEXTEDIT_STRING ImGuiTextEditState #define STB_TEXTEDIT_CHARTYPE ImWchar #include "stb_textedit.h" #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef IMGUI_STB_NAMESPACE } // namespace ImStb using namespace IMGUI_STB_NAMESPACE; #endif //------------------------------------------------------------------------- // Forward Declarations //------------------------------------------------------------------------- struct ImRect; struct ImGuiColMod; struct ImGuiStyleMod; struct ImGuiDrawContext; struct ImGuiTextEditState; struct ImGuiIniData; struct ImGuiState; struct ImGuiWindow; static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat = false, bool pressed_on_click = false); static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end = NULL); static void RenderText(ImVec2 pos, const char* text, const char* text_end = NULL, bool hide_text_after_hash = true); static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width); static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& clip_max); static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border = true, float rounding = 0.0f); static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale = 1.0f, bool shadow = false); static void SetFont(ImFont* font); static bool ItemAdd(const ImRect& bb, const ImGuiID* id); static void ItemSize(ImVec2 size, float text_offset_y = 0.0f); static void ItemSize(const ImRect& bb, float text_offset_y = 0.0f); static void PushColumnClipRect(int column_index = -1); static bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged); static bool IsMouseHoveringRect(const ImRect& bb); static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true); static void Scrollbar(ImGuiWindow* window); static bool CloseWindowButton(bool* p_opened = NULL); static void FocusWindow(ImGuiWindow* window); static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs); // Helpers: String static int ImStricmp(const char* str1, const char* str2); static int ImStrnicmp(const char* str1, const char* str2, int count); static char* ImStrdup(const char *str); static size_t ImStrlenW(const ImWchar* str); static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end); static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...); static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args); // Helpers: Misc static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed); static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes = 0); static inline int ImUpperPowerOfTwo(int v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } static inline bool ImCharIsSpace(int c) { return c == ' ' || c == '\t' || c == 0x3000; } // Helpers: UTF-8 <> wchar static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int in_char); // return output UTF-8 bytes count static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end); // return output UTF-8 bytes count static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end); // return input UTF-8 bytes count static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_remaining = NULL); // return input UTF-8 bytes count static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end); // return number of UTF-8 code-points (NOT bytes count) static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end); // return number of bytes to express string as UTF-8 code-points //----------------------------------------------------------------------------- // Platform dependent default implementations //----------------------------------------------------------------------------- static const char* GetClipboardTextFn_DefaultImpl(); static void SetClipboardTextFn_DefaultImpl(const char* text); static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y); //----------------------------------------------------------------------------- // User facing structures //----------------------------------------------------------------------------- ImGuiStyle::ImGuiStyle() { Alpha = 1.0f; // Global alpha applies to everything in ImGui WindowPadding = ImVec2(8,8); // Padding within a window WindowMinSize = ImVec2(32,32); // Minimum window size WindowRounding = 9.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows ChildWindowRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular windows FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets) FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets). ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label) TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much! AutoFitPadding = ImVec2(8,8); // Extra space after auto-fit (double-clicking on resize grip) WindowFillAlphaDefault = 0.70f; // Default alpha of window background, if not specified in ImGui::Begin() IndentSpacing = 22.0f; // Horizontal spacing when e.g. entering a tree node ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns ScrollbarWidth = 16.0f; // Width of the vertical scrollbar GrabMinSize = 10.0f; // Minimum width/height of a slider or scrollbar grab DisplaySafeAreaPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area. If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding Colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f); Colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f); Colors[ImGuiCol_ChildWindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); Colors[ImGuiCol_Border] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.60f); Colors[ImGuiCol_FrameBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.30f); // Background of checkbox, radio button, plot, slider, text input Colors[ImGuiCol_FrameBgHovered] = ImVec4(0.90f, 0.80f, 0.80f, 0.40f); Colors[ImGuiCol_FrameBgActive] = ImVec4(0.90f, 0.65f, 0.65f, 0.45f); Colors[ImGuiCol_TitleBg] = ImVec4(0.50f, 0.50f, 1.00f, 0.45f); Colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f); Colors[ImGuiCol_ScrollbarBg] = ImVec4(0.40f, 0.40f, 0.80f, 0.15f); Colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.40f, 0.40f, 0.80f, 0.30f); Colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.40f, 0.40f, 0.80f, 0.40f); Colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 0.40f); Colors[ImGuiCol_ComboBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.99f); Colors[ImGuiCol_CheckMark] = ImVec4(0.90f, 0.90f, 0.90f, 0.50f); Colors[ImGuiCol_SliderGrab] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_SliderGrabActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Button] = ImVec4(0.67f, 0.40f, 0.40f, 0.60f); Colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.40f, 0.40f, 1.00f); Colors[ImGuiCol_ButtonActive] = ImVec4(0.80f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_Header] = ImVec4(0.40f, 0.40f, 0.90f, 0.45f); Colors[ImGuiCol_HeaderHovered] = ImVec4(0.45f, 0.45f, 0.90f, 0.80f); Colors[ImGuiCol_HeaderActive] = ImVec4(0.53f, 0.53f, 0.87f, 0.80f); Colors[ImGuiCol_Column] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); Colors[ImGuiCol_ColumnHovered] = ImVec4(0.70f, 0.60f, 0.60f, 1.00f); Colors[ImGuiCol_ColumnActive] = ImVec4(0.90f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.30f); Colors[ImGuiCol_ResizeGripHovered] = ImVec4(1.00f, 1.00f, 1.00f, 0.60f); Colors[ImGuiCol_ResizeGripActive] = ImVec4(1.00f, 1.00f, 1.00f, 0.90f); Colors[ImGuiCol_CloseButton] = ImVec4(0.50f, 0.50f, 0.90f, 0.50f); Colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.70f, 0.70f, 0.90f, 0.60f); Colors[ImGuiCol_CloseButtonActive] = ImVec4(0.70f, 0.70f, 0.70f, 1.00f); Colors[ImGuiCol_PlotLines] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); Colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); Colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); Colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f); Colors[ImGuiCol_TooltipBg] = ImVec4(0.05f, 0.05f, 0.10f, 0.90f); } // Statically allocated font atlas. This is merely a maneuver to keep ImFontAtlas definition at the bottom of the .h file (otherwise it'd be inside ImGuiIO) // Also we wouldn't be able to new() one at this point, before users may define IO.MemAllocFn. static ImFontAtlas GDefaultFontAtlas; ImGuiIO::ImGuiIO() { // Most fields are initialized with zero memset(this, 0, sizeof(*this)); DisplaySize = ImVec2(-1.0f, -1.0f); DeltaTime = 1.0f/60.0f; IniSavingRate = 5.0f; IniFilename = "imgui.ini"; LogFilename = "imgui_log.txt"; Fonts = &GDefaultFontAtlas; FontGlobalScale = 1.0f; MousePos = ImVec2(-1,-1); MousePosPrev = ImVec2(-1,-1); MouseDoubleClickTime = 0.30f; MouseDoubleClickMaxDist = 6.0f; MouseDragThreshold = 6.0f; UserData = NULL; // User functions RenderDrawListsFn = NULL; MemAllocFn = malloc; MemFreeFn = free; GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations SetClipboardTextFn = SetClipboardTextFn_DefaultImpl; ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl; } // Pass in translated ASCII characters for text input. // - with glfw you can get those from the callback set in glfwSetCharCallback() // - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message void ImGuiIO::AddInputCharacter(ImWchar c) { const size_t n = ImStrlenW(InputCharacters); if (n + 1 < sizeof(InputCharacters) / sizeof(InputCharacters[0])) { InputCharacters[n] = c; InputCharacters[n+1] = 0; } } //----------------------------------------------------------------------------- // Helpers //----------------------------------------------------------------------------- #define IM_ARRAYSIZE(_ARR) ((int)(sizeof(_ARR)/sizeof(*_ARR))) #undef PI const float PI = 3.14159265358979323846f; #ifdef INT_MAX #define IM_INT_MIN INT_MIN #define IM_INT_MAX INT_MAX #else #define IM_INT_MIN (-2147483647-1) #define IM_INT_MAX (2147483647) #endif // Play it nice with Windows users. Notepad in 2015 still doesn't display text data with Unix-style \n. #ifdef _MSC_VER #define STR_NEWLINE "\r\n" #else #define STR_NEWLINE "\n" #endif // Math bits // We are keeping those static in the .cpp file so as not to leak them outside, in the case the user has implicit cast operators between ImVec2 and its own types. static inline ImVec2 operator*(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x*rhs, lhs.y*rhs); } //static inline ImVec2 operator/(const ImVec2& lhs, const float rhs) { return ImVec2(lhs.x/rhs, lhs.y/rhs); } static inline ImVec2 operator+(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x+rhs.x, lhs.y+rhs.y); } static inline ImVec2 operator-(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(lhs.x-rhs.x, lhs.y-rhs.y); } static inline ImVec2 operator*(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x*rhs.x, lhs.y*rhs.y); } static inline ImVec2 operator/(const ImVec2& lhs, const ImVec2 rhs) { return ImVec2(lhs.x/rhs.x, lhs.y/rhs.y); } static inline ImVec2& operator+=(ImVec2& lhs, const ImVec2& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } static inline ImVec2& operator-=(ImVec2& lhs, const ImVec2& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } static inline ImVec2& operator*=(ImVec2& lhs, const float rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } //static inline ImVec2& operator/=(ImVec2& lhs, const float rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } static inline int ImMin(int lhs, int rhs) { return lhs < rhs ? lhs : rhs; } static inline int ImMax(int lhs, int rhs) { return lhs >= rhs ? lhs : rhs; } static inline float ImMin(float lhs, float rhs) { return lhs < rhs ? lhs : rhs; } static inline float ImMax(float lhs, float rhs) { return lhs >= rhs ? lhs : rhs; } static inline ImVec2 ImMin(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMin(lhs.x,rhs.x), ImMin(lhs.y,rhs.y)); } static inline ImVec2 ImMax(const ImVec2& lhs, const ImVec2& rhs) { return ImVec2(ImMax(lhs.x,rhs.x), ImMax(lhs.y,rhs.y)); } static inline int ImClamp(int v, int mn, int mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } static inline float ImClamp(float v, float mn, float mx) { return (v < mn) ? mn : (v > mx) ? mx : v; } static inline ImVec2 ImClamp(const ImVec2& f, const ImVec2& mn, ImVec2 mx) { return ImVec2(ImClamp(f.x,mn.x,mx.x), ImClamp(f.y,mn.y,mx.y)); } static inline float ImSaturate(float f) { return (f < 0.0f) ? 0.0f : (f > 1.0f) ? 1.0f : f; } static inline float ImLerp(float a, float b, float t) { return a + (b - a) * t; } static inline ImVec2 ImLerp(const ImVec2& a, const ImVec2& b, const ImVec2& t) { return ImVec2(a.x + (b.x - a.x) * t.x, a.y + (b.y - a.y) * t.y); } static inline float ImLengthSqr(const ImVec2& lhs) { return lhs.x*lhs.x + lhs.y*lhs.y; } static int ImStricmp(const char* str1, const char* str2) { int d; while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; } return d; } static int ImStrnicmp(const char* str1, const char* str2, int count) { int d = 0; while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; } return d; } static char* ImStrdup(const char *str) { char *buff = (char*)ImGui::MemAlloc(strlen(str) + 1); IM_ASSERT(buff); strcpy(buff, str); return buff; } static size_t ImStrlenW(const ImWchar* str) { size_t n = 0; while (*str++) n++; return n; } static const char* ImStristr(const char* haystack, const char* needle, const char* needle_end) { if (!needle_end) needle_end = needle + strlen(needle); const char un0 = (char)toupper(*needle); while (*haystack) { if (toupper(*haystack) == un0) { const char* b = needle + 1; for (const char* a = haystack + 1; b < needle_end; a++, b++) if (toupper(*a) != toupper(*b)) break; if (b == needle_end) return haystack; } haystack++; } return NULL; } // Pass data_size==0 for zero-terminated string // Try to replace with FNV1a hash? static ImU32 ImHash(const void* data, size_t data_size, ImU32 seed = 0) { static ImU32 crc32_lut[256] = { 0 }; if (!crc32_lut[1]) { const ImU32 polynomial = 0xEDB88320; for (ImU32 i = 0; i < 256; i++) { ImU32 crc = i; for (ImU32 j = 0; j < 8; j++) crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial); crc32_lut[i] = crc; } } seed = ~seed; ImU32 crc = seed; const unsigned char* current = (const unsigned char*)data; if (data_size > 0) { // Known size while (data_size--) crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++]; } else { // Zero-terminated string while (unsigned char c = *current++) { // We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed. // Because this syntax is rarely used we are optimizing for the common case. // - If we reach ### in the string we discard the hash so far and reset to the seed. // - We don't do 'current += 2; continue;' after handling ### to keep the code smaller. if (c == '#' && current[0] == '#' && current[1] == '#') crc = seed; crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c]; } } return ~crc; } static size_t ImFormatString(char* buf, size_t buf_size, const char* fmt, ...) { va_list args; va_start(args, fmt); int w = vsnprintf(buf, buf_size, fmt, args); va_end(args); buf[buf_size-1] = 0; return (w == -1) ? buf_size : (size_t)w; } static size_t ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args) { int w = vsnprintf(buf, buf_size, fmt, args); buf[buf_size-1] = 0; return (w == -1) ? buf_size : (size_t)w; } ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in) { ImU32 out = ((ImU32)(ImSaturate(in.x)*255.f)); out |= ((ImU32)(ImSaturate(in.y)*255.f) << 8); out |= ((ImU32)(ImSaturate(in.z)*255.f) << 16); out |= ((ImU32)(ImSaturate(in.w)*255.f) << 24); return out; } // Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592 // Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v) { float K = 0.f; if (g < b) { const float tmp = g; g = b; b = tmp; K = -1.f; } if (r < g) { const float tmp = r; r = g; g = tmp; K = -2.f / 6.f - K; } const float chroma = r - (g < b ? g : b); out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f)); out_s = chroma / (r + 1e-20f); out_v = r; } // Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593 // also http://en.wikipedia.org/wiki/HSL_and_HSV void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b) { if (s == 0.0f) { // gray out_r = out_g = out_b = v; return; } h = fmodf(h, 1.0f) / (60.0f/360.0f); int i = (int)h; float f = h - (float)i; float p = v * (1.0f - s); float q = v * (1.0f - s * f); float t = v * (1.0f - s * (1.0f - f)); switch (i) { case 0: out_r = v; out_g = t; out_b = p; break; case 1: out_r = q; out_g = v; out_b = p; break; case 2: out_r = p; out_g = v; out_b = t; break; case 3: out_r = p; out_g = q; out_b = v; break; case 4: out_r = t; out_g = p; out_b = v; break; case 5: default: out_r = v; out_g = p; out_b = q; break; } } // Load file content into memory // Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree() static bool ImLoadFileToMemory(const char* filename, const char* file_open_mode, void** out_file_data, size_t* out_file_size, size_t padding_bytes) { IM_ASSERT(filename && file_open_mode && out_file_data && out_file_size); *out_file_data = NULL; *out_file_size = 0; FILE* f; if ((f = fopen(filename, file_open_mode)) == NULL) return false; long file_size_signed; if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET)) { fclose(f); return false; } size_t file_size = (size_t)file_size_signed; void* file_data = ImGui::MemAlloc(file_size + padding_bytes); if (file_data == NULL) { fclose(f); return false; } if (fread(file_data, 1, file_size, f) != file_size) { fclose(f); ImGui::MemFree(file_data); return false; } if (padding_bytes > 0) memset((void *)(((char*)file_data) + file_size), 0, padding_bytes); fclose(f); *out_file_data = file_data; *out_file_size = file_size; return true; } //----------------------------------------------------------------------------- struct ImGuiColMod // Color modifier, backup of modified data so we can restore it { ImGuiCol Col; ImVec4 PreviousValue; }; struct ImGuiStyleMod // Style modifier, backup of modified data so we can restore it { ImGuiStyleVar Var; ImVec2 PreviousValue; }; struct ImRect // 2D axis aligned bounding-box { ImVec2 Min; ImVec2 Max; ImRect() { Min = ImVec2(FLT_MAX,FLT_MAX); Max = ImVec2(-FLT_MAX,-FLT_MAX); } ImRect(const ImVec2& min, const ImVec2& max) { Min = min; Max = max; } ImRect(const ImVec4& v) { Min.x = v.x; Min.y = v.y; Max.x = v.z; Max.y = v.w; } ImRect(float x1, float y1, float x2, float y2) { Min.x = x1; Min.y = y1; Max.x = x2; Max.y = y2; } ImVec2 GetCenter() const { return Min + (Max-Min)*0.5f; } ImVec2 GetSize() const { return Max-Min; } float GetWidth() const { return (Max-Min).x; } float GetHeight() const { return (Max-Min).y; } ImVec2 GetTL() const { return Min; } ImVec2 GetTR() const { return ImVec2(Max.x,Min.y); } ImVec2 GetBL() const { return ImVec2(Min.x,Max.y); } ImVec2 GetBR() const { return Max; } bool Contains(const ImVec2& p) const { return p.x >= Min.x && p.y >= Min.y && p.x < Max.x && p.y < Max.y; } bool Contains(const ImRect& r) const { return r.Min.x >= Min.x && r.Min.y >= Min.y && r.Max.x < Max.x && r.Max.y < Max.y; } bool Overlaps(const ImRect& r) const { return r.Min.y < Max.y && r.Max.y > Min.y && r.Min.x < Max.x && r.Max.x > Min.x; } void Add(const ImVec2& rhs) { Min.x = ImMin(Min.x, rhs.x); Min.y = ImMin(Min.y, rhs.y); Max.x = ImMax(Max.x, rhs.x); Max.y = ImMax(Max.x, rhs.x); } void Add(const ImRect& rhs) { Min.x = ImMin(Min.x, rhs.Min.x); Min.y = ImMin(Min.y, rhs.Min.y); Max.x = ImMax(Max.x, rhs.Max.x); Max.y = ImMax(Max.y, rhs.Max.y); } void Expand(const float amount) { Min.x -= amount; Min.y -= amount; Max.x += amount; Max.y += amount; } void Expand(const ImVec2& amount) { Min -= amount; Max += amount; } void Clip(const ImRect& clip) { Min.x = ImMax(Min.x, clip.Min.x); Min.y = ImMax(Min.y, clip.Min.y); Max.x = ImMin(Max.x, clip.Max.x); Max.y = ImMin(Max.y, clip.Max.y); } ImVec2 GetClosestPoint(ImVec2 p, bool on_edge) const { if (!on_edge && Contains(p)) return p; if (p.x > Max.x) p.x = Max.x; else if (p.x < Min.x) p.x = Min.x; if (p.y > Max.y) p.y = Max.y; else if (p.y < Min.y) p.y = Min.y; return p; } }; typedef ImRect ImGuiAabb; // FIXME-OBSOLETE struct ImGuiGroupData { ImVec2 BackupCursorPos; ImVec2 BackupCursorMaxPos; float BackupColumnsStartX; float BackupCurrentLineHeight; float BackupCurrentLineTextBaseOffset; float BackupLogLinePosY; }; // Temporary per-window data, reset at the beginning of the frame struct ImGuiDrawContext { ImVec2 CursorPos; ImVec2 CursorPosPrevLine; ImVec2 CursorStartPos; ImVec2 CursorMaxPos; // Implicitly calculate the size of our contents, always extending. Saved into window->SizeContents at the end of the frame float CurrentLineHeight; float CurrentLineTextBaseOffset; float PrevLineHeight; float PrevLineTextBaseOffset; float LogLinePosY; int TreeDepth; ImGuiID LastItemID; ImRect LastItemRect; bool LastItemHoveredAndUsable; bool LastItemHoveredRect; ImVector<ImGuiWindow*> ChildWindows; ImVector<bool> AllowKeyboardFocus; ImVector<float> ItemWidth; // 0.0: default, >0.0: width in pixels, <0.0: align xx pixels to the right of window ImVector<float> TextWrapPos; ImVector<ImGuiGroupData> GroupStack; ImGuiColorEditMode ColorEditMode; ImGuiStorage* StateStorage; float ColumnsStartX; // Indentation / start position from left of window (increased by TreePush/TreePop, etc.) float ColumnsOffsetX; // Offset to the current column (if ColumnsCurrent > 0). FIXME: This and the above should be a stack to allow use cases like Tree->Column->Tree. Need revamp columns API. int ColumnsCurrent; int ColumnsCount; ImVec2 ColumnsStartPos; float ColumnsCellMinY; float ColumnsCellMaxY; bool ColumnsShowBorders; ImGuiID ColumnsSetID; ImVector<float> ColumnsOffsetsT; // Columns offset normalized 0.0 (far left) -> 1.0 (far right) ImGuiDrawContext() { CursorPos = CursorPosPrevLine = CursorStartPos = CursorMaxPos = ImVec2(0.0f, 0.0f); CurrentLineHeight = PrevLineHeight = 0.0f; CurrentLineTextBaseOffset = PrevLineTextBaseOffset = 0.0f; LogLinePosY = -1.0f; TreeDepth = 0; LastItemID = 0; LastItemRect = ImRect(0.0f,0.0f,0.0f,0.0f); LastItemHoveredAndUsable = LastItemHoveredRect = false; ColorEditMode = ImGuiColorEditMode_RGB; StateStorage = NULL; ColumnsStartX = 0.0f; ColumnsOffsetX = 0.0f; ColumnsCurrent = 0; ColumnsCount = 1; ColumnsStartPos = ImVec2(0.0f, 0.0f); ColumnsCellMinY = ColumnsCellMaxY = 0.0f; ColumnsShowBorders = true; ColumnsSetID = 0; } }; // Internal state of the currently focused/edited text input box struct ImGuiTextEditState { ImGuiID Id; // widget id owning the text state ImWchar Text[1024]; // edit buffer, we need to persist but can't guarantee the persistence of the user-provided buffer. so we copy into own buffer. char InitialText[1024*3+1]; // backup of end-user buffer at the time of focus (in UTF-8, unaltered) size_t CurLenA, CurLenW; // we need to maintain our buffer length in both UTF-8 and wchar format. size_t BufSizeA; // end-user buffer size, <= 1024 (or increase above) float Width; // widget width float ScrollX; STB_TexteditState StbState; float CursorAnim; ImVec2 InputCursorScreenPos; // Cursor position in screen space to be used by IME callback. bool SelectedAllMouseLock; ImFont* Font; float FontSize; ImGuiTextEditState() { memset(this, 0, sizeof(*this)); } void CursorAnimReset() { CursorAnim = -0.30f; } // After a user-input the cursor stays on for a while without blinking bool CursorIsVisible() const { return CursorAnim <= 0.0f || fmodf(CursorAnim, 1.20f) <= 0.80f; } // Blinking bool HasSelection() const { return StbState.select_start != StbState.select_end; } void SelectAll() { StbState.select_start = 0; StbState.select_end = (int)ImStrlenW(Text); StbState.cursor = StbState.select_end; StbState.has_preferred_x = false; } void OnKeyPressed(int key); void UpdateScrollOffset(); ImVec2 CalcDisplayOffsetFromCharIdx(int i) const; // Static functions because they are used to render non-focused instances of a text input box static const char* GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size = NULL); static const ImWchar* GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size = NULL); static void RenderTextScrolledClipped(ImFont* font, float font_size, const char* text, ImVec2 pos_base, float width, float scroll_x); }; // Data saved in imgui.ini file struct ImGuiIniData { char* Name; ImGuiID ID; ImVec2 Pos; ImVec2 Size; bool Collapsed; ImGuiIniData() { memset(this, 0, sizeof(*this)); } ~ImGuiIniData() { if (Name) { ImGui::MemFree(Name); Name = NULL; } } }; struct ImGuiMouseCursorData { ImGuiMouseCursor Type; ImVec2 Offset; ImVec2 Size; ImVec2 TexUvMin[2]; ImVec2 TexUvMax[2]; }; // Main state for ImGui struct ImGuiState { bool Initialized; ImGuiIO IO; ImGuiStyle Style; ImFont* Font; // (Shortcut) == FontStack.empty() ? IO.Font : FontStack.back() float FontSize; // (Shortcut) == FontBaseSize * g.CurrentWindow->FontWindowScale == window->FontSize() float FontBaseSize; // (Shortcut) == IO.FontGlobalScale * Font->Scale * Font->FontSize. Size of characters. ImVec2 FontTexUvWhitePixel; // (Shortcut) == Font->TexUvForWhite float Time; int FrameCount; int FrameCountRendered; ImVector<ImGuiWindow*> Windows; ImVector<ImGuiWindow*> WindowsSortBuffer; ImGuiWindow* CurrentWindow; // Being drawn into ImVector<ImGuiWindow*> CurrentWindowStack; ImGuiWindow* FocusedWindow; // Will catch keyboard inputs ImGuiWindow* HoveredWindow; // Will catch mouse inputs ImGuiWindow* HoveredRootWindow; // Will catch mouse inputs (for focus/move only) ImGuiID HoveredId; // Hovered widget ImGuiID ActiveId; // Active widget ImGuiID ActiveIdPreviousFrame; bool ActiveIdIsAlive; bool ActiveIdIsJustActivated; // Set when bool ActiveIdIsFocusedOnly; // Set only by active widget. Denote focus but no active interaction. ImGuiWindow* MovedWindow; // Track the child window we clicked on to move a window. Only valid if ActiveID is the "#MOVE" identifier of a window. float SettingsDirtyTimer; ImVector<ImGuiIniData*> Settings; int DisableHideTextAfterDoubleHash; ImVector<ImGuiColMod> ColorModifiers; ImVector<ImGuiStyleMod> StyleModifiers; ImVector<ImFont*> FontStack; ImVec2 SetNextWindowPosVal; ImGuiSetCond SetNextWindowPosCond; ImVec2 SetNextWindowSizeVal; ImGuiSetCond SetNextWindowSizeCond; bool SetNextWindowCollapsedVal; ImGuiSetCond SetNextWindowCollapsedCond; bool SetNextWindowFocus; bool SetNextTreeNodeOpenedVal; ImGuiSetCond SetNextTreeNodeOpenedCond; // Render ImVector<ImDrawList*> RenderDrawLists[3]; // Mouse cursor ImGuiMouseCursor MouseCursor; ImDrawList MouseCursorDrawList; // Optional software render of mouse cursors, if io.MouseDrawCursor is set ImGuiMouseCursorData MouseCursorData[ImGuiMouseCursor_Count_]; // Widget state ImGuiTextEditState InputTextState; ImGuiID ScalarAsInputTextId; // Temporary text input when CTRL+clicking on a slider, etc. ImGuiStorage ColorEditModeStorage; // for user selection ImGuiID ActiveComboID; ImVec2 ActiveClickDeltaToCenter; float DragCurrentValue; // current dragged value, always float, not rounded by end-user precision settings ImVec2 DragLastMouseDelta; float DragSpeedDefaultRatio; // if speed == 0.0f, uses (max-min) * DragSpeedDefaultRatio float DragSpeedScaleSlow; float DragSpeedScaleFast; float ScrollbarClickDeltaToGrabCenter; // distance between mouse and center of grab box, normalized in parent space char Tooltip[1024]; char* PrivateClipboard; // if no custom clipboard handler is defined // Logging bool LogEnabled; FILE* LogFile; ImGuiTextBuffer* LogClipboard; // pointer so our GImGui static constructor doesn't call heap allocators. int LogStartDepth; int LogAutoExpandMaxDepth; // Misc float FramerateSecPerFrame[120]; // calculate estimate of framerate for user int FramerateSecPerFrameIdx; float FramerateSecPerFrameAccum; char TempBuffer[1024*3+1]; // temporary text buffer ImGuiState() { Initialized = false; Font = NULL; FontBaseSize = FontSize = 0.0f; FontTexUvWhitePixel = ImVec2(0.0f, 0.0f); Time = 0.0f; FrameCount = 0; FrameCountRendered = -1; CurrentWindow = NULL; FocusedWindow = NULL; HoveredWindow = NULL; HoveredRootWindow = NULL; HoveredId = 0; ActiveId = 0; ActiveIdPreviousFrame = 0; ActiveIdIsAlive = false; ActiveIdIsJustActivated = false; ActiveIdIsFocusedOnly = false; MovedWindow = NULL; SettingsDirtyTimer = 0.0f; DisableHideTextAfterDoubleHash = 0; SetNextWindowPosVal = ImVec2(0.0f, 0.0f); SetNextWindowPosCond = 0; SetNextWindowSizeVal = ImVec2(0.0f, 0.0f); SetNextWindowSizeCond = 0; SetNextWindowCollapsedVal = false; SetNextWindowCollapsedCond = 0; SetNextWindowFocus = false; SetNextTreeNodeOpenedVal = false; SetNextTreeNodeOpenedCond = 0; ScalarAsInputTextId = 0; ActiveComboID = 0; ActiveClickDeltaToCenter = ImVec2(0.0f, 0.0f); DragCurrentValue = 0.0f; DragLastMouseDelta = ImVec2(0.0f, 0.0f); DragSpeedDefaultRatio = 0.01f; DragSpeedScaleSlow = 0.01f; DragSpeedScaleFast = 10.0f; ScrollbarClickDeltaToGrabCenter = 0.0f; memset(Tooltip, 0, sizeof(Tooltip)); PrivateClipboard = NULL; MouseCursor = ImGuiMouseCursor_Arrow; LogEnabled = false; LogFile = NULL; LogClipboard = NULL; LogStartDepth = 0; LogAutoExpandMaxDepth = 2; memset(FramerateSecPerFrame, 0, sizeof(FramerateSecPerFrame)); FramerateSecPerFrameIdx = 0; FramerateSecPerFrameAccum = 0.0f; } }; static ImGuiState GImDefaultState; // Internal state storage static ImGuiState* GImGui = &GImDefaultState; // We access everything through this pointer. NB: this pointer is always assumed to be != NULL struct ImGuiWindow { char* Name; ImGuiID ID; ImGuiWindowFlags Flags; ImVec2 PosFloat; ImVec2 Pos; // Position rounded-up to nearest pixel ImVec2 Size; // Current size (==SizeFull or collapsed title bar size) ImVec2 SizeFull; // Size when non collapsed ImVec2 SizeContents; // Size of contents (== extents reach of the drawing cursor) from previous frame ImGuiID MoveID; // == window->GetID("#MOVE") float ScrollY; float NextScrollY; bool ScrollbarY; bool Visible; // Set to true on Begin() bool WasVisible; bool Accessed; // Set to true when any widget access the current window bool Collapsed; // Set when collapsing window to become only title-bar bool SkipItems; // == Visible && !Collapsed int AutoFitFrames; bool AutoFitOnlyGrows; int SetWindowPosAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowPos() call will succeed with this particular flag. int SetWindowSizeAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowSize() call will succeed with this particular flag. int SetWindowCollapsedAllowFlags; // bit ImGuiSetCond_*** specify if SetWindowCollapsed() call will succeed with this particular flag. ImGuiDrawContext DC; // Temporary per-window data, reset at the beginning of the frame ImVector<ImGuiID> IDStack; // ID stack. ID are hashes seeded with the value at the top of the stack ImVector<ImVec4> ClipRectStack; // Scissoring / clipping rectangle. x1, y1, x2, y2. ImRect ClippedRect; // = ClipRectStack.front() after setup in Begin() int LastFrameDrawn; float ItemWidthDefault; ImGuiStorage StateStorage; float FontWindowScale; // Scale multiplier per-window ImDrawList* DrawList; ImGuiWindow* RootWindow; // Focus int FocusIdxAllCounter; // Start at -1 and increase as assigned via FocusItemRegister() int FocusIdxTabCounter; // (same, but only count widgets which you can Tab through) int FocusIdxAllRequestCurrent; // Item being requested for focus int FocusIdxTabRequestCurrent; // Tab-able item being requested for focus int FocusIdxAllRequestNext; // Item being requested for focus, for next update (relies on layout to be stable between the frame pressing TAB and the next frame) int FocusIdxTabRequestNext; // " public: ImGuiWindow(const char* name); ~ImGuiWindow(); ImGuiID GetID(const char* str, const char* str_end = NULL); ImGuiID GetID(const void* ptr); bool FocusItemRegister(bool is_active, bool tab_stop = true); // Return true if focus is requested void FocusItemUnregister(); ImRect Rect() const { return ImRect(Pos, Pos+Size); } float CalcFontSize() const { return GImGui->FontBaseSize * FontWindowScale; } float TitleBarHeight() const { return (Flags & ImGuiWindowFlags_NoTitleBar) ? 0 : CalcFontSize() + GImGui->Style.FramePadding.y * 2.0f; } ImRect TitleBarRect() const { return ImRect(Pos, Pos + ImVec2(SizeFull.x, TitleBarHeight())); } ImVec2 WindowPadding() const { return ((Flags & ImGuiWindowFlags_ChildWindow) && !(Flags & ImGuiWindowFlags_ShowBorders) && !(Flags & ImGuiWindowFlags_ComboBox)) ? ImVec2(0,0) : GImGui->Style.WindowPadding; } ImU32 Color(ImGuiCol idx, float a=1.f) const { ImVec4 c = GImGui->Style.Colors[idx]; c.w *= GImGui->Style.Alpha * a; return ImGui::ColorConvertFloat4ToU32(c); } ImU32 Color(const ImVec4& col) const { ImVec4 c = col; c.w *= GImGui->Style.Alpha; return ImGui::ColorConvertFloat4ToU32(c); } }; static inline ImGuiWindow* GetCurrentWindow() { // If this ever crash it probably means that ImGui::NewFrame() hasn't been called. We should always have a CurrentWindow in the stack (there is an implicit "Debug" window) ImGuiState& g = *GImGui; g.CurrentWindow->Accessed = true; return g.CurrentWindow; } static inline void SetCurrentWindow(ImGuiWindow* window) { ImGuiState& g = *GImGui; g.CurrentWindow = window; if (window) g.FontSize = window->CalcFontSize(); } static inline ImGuiWindow* GetParentWindow() { ImGuiState& g = *GImGui; IM_ASSERT(g.CurrentWindowStack.size() >= 2); return g.CurrentWindowStack[g.CurrentWindowStack.size() - 2]; } static void SetActiveId(ImGuiID id) { ImGuiState& g = *GImGui; g.ActiveId = id; g.ActiveIdIsFocusedOnly = false; g.ActiveIdIsJustActivated = true; } static void RegisterAliveId(ImGuiID id) { ImGuiState& g = *GImGui; if (g.ActiveId == id) g.ActiveIdIsAlive = true; } //----------------------------------------------------------------------------- // Helper: Key->value storage void ImGuiStorage::Clear() { Data.clear(); } // std::lower_bound but without the bullshit static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImU32 key) { ImVector<ImGuiStorage::Pair>::iterator first = data.begin(); ImVector<ImGuiStorage::Pair>::iterator last = data.end(); int count = (int)(last - first); while (count > 0) { int count2 = count / 2; ImVector<ImGuiStorage::Pair>::iterator mid = first + count2; if (mid->key < key) { first = ++mid; count -= count2 + 1; } else { count = count2; } } return first; } int ImGuiStorage::GetInt(ImU32 key, int default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_i; } float ImGuiStorage::GetFloat(ImU32 key, float default_val) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return default_val; return it->val_f; } void* ImGuiStorage::GetVoidPtr(ImGuiID key) const { ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key); if (it == Data.end() || it->key != key) return NULL; return it->val_p; } // References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer. int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_i; } float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_f; } void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) it = Data.insert(it, Pair(key, default_val)); return &it->val_p; } // FIXME-OPT: Wasting CPU because all SetInt() are preceeded by GetInt() calls so we should have the result from lower_bound already in place. // However we only use SetInt() on explicit user action (so that's maximum once a frame) so the optimisation isn't much needed. void ImGuiStorage::SetInt(ImU32 key, int val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_i = val; } void ImGuiStorage::SetFloat(ImU32 key, float val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_f = val; } void ImGuiStorage::SetVoidPtr(ImU32 key, void* val) { ImVector<Pair>::iterator it = LowerBound(Data, key); if (it == Data.end() || it->key != key) { Data.insert(it, Pair(key, val)); return; } it->val_p = val; } void ImGuiStorage::SetAllInt(int v) { for (size_t i = 0; i < Data.size(); i++) Data[i].val_i = v; } //----------------------------------------------------------------------------- // Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]" ImGuiTextFilter::ImGuiTextFilter(const char* default_filter) { if (default_filter) { ImFormatString(InputBuf, IM_ARRAYSIZE(InputBuf), "%s", default_filter); Build(); } else { InputBuf[0] = 0; CountGrep = 0; } } void ImGuiTextFilter::Draw(const char* label, float width) { if (width > 0.0f) ImGui::PushItemWidth(width); ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf)); if (width > 0.0f) ImGui::PopItemWidth(); Build(); } void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out) { out.resize(0); const char* wb = b; const char* we = wb; while (we < e) { if (*we == separator) { out.push_back(TextRange(wb, we)); wb = we + 1; } we++; } if (wb != we) out.push_back(TextRange(wb, we)); } void ImGuiTextFilter::Build() { Filters.resize(0); TextRange input_range(InputBuf, InputBuf+strlen(InputBuf)); input_range.split(',', Filters); CountGrep = 0; for (size_t i = 0; i != Filters.size(); i++) { Filters[i].trim_blanks(); if (Filters[i].empty()) continue; if (Filters[i].front() != '-') CountGrep += 1; } } bool ImGuiTextFilter::PassFilter(const char* val) const { if (Filters.empty()) return true; if (val == NULL) val = ""; for (size_t i = 0; i != Filters.size(); i++) { const TextRange& f = Filters[i]; if (f.empty()) continue; if (f.front() == '-') { // Subtract if (ImStristr(val, f.begin()+1, f.end()) != NULL) return false; } else { // Grep if (ImStristr(val, f.begin(), f.end()) != NULL) return true; } } // Implicit * grep if (CountGrep == 0) return true; return false; } //----------------------------------------------------------------------------- // On some platform vsnprintf() takes va_list by reference and modifies it. // va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it. #ifndef va_copy #define va_copy(dest, src) (dest = src) #endif // Helper: Text buffer for logging/accumulating text void ImGuiTextBuffer::appendv(const char* fmt, va_list args) { va_list args_copy; va_copy(args_copy, args); int len = vsnprintf(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass. if (len <= 0) return; const size_t write_off = Buf.size(); const size_t needed_sz = write_off + (size_t)len; if (write_off + (size_t)len >= Buf.capacity()) { const size_t double_capacity = Buf.capacity() * 2; Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity); } Buf.resize(needed_sz); ImFormatStringV(&Buf[write_off] - 1, (size_t)len+1, fmt, args_copy); } void ImGuiTextBuffer::append(const char* fmt, ...) { va_list args; va_start(args, fmt); appendv(fmt, args); va_end(args); } //----------------------------------------------------------------------------- ImGuiWindow::ImGuiWindow(const char* name) { Name = ImStrdup(name); ID = ImHash(name, 0); IDStack.push_back(ID); MoveID = GetID("#MOVE"); Flags = 0; PosFloat = Pos = ImVec2(0.0f, 0.0f); Size = SizeFull = ImVec2(0.0f, 0.0f); SizeContents = ImVec2(0.0f, 0.0f); ScrollY = 0.0f; NextScrollY = 0.0f; ScrollbarY = false; Visible = WasVisible = false; Accessed = false; Collapsed = false; SkipItems = false; AutoFitFrames = -1; AutoFitOnlyGrows = false; SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiSetCond_Always | ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver; LastFrameDrawn = -1; ItemWidthDefault = 0.0f; FontWindowScale = 1.0f; DrawList = (ImDrawList*)ImGui::MemAlloc(sizeof(ImDrawList)); new(DrawList) ImDrawList(); RootWindow = NULL; FocusIdxAllCounter = FocusIdxTabCounter = -1; FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = IM_INT_MAX; FocusIdxAllRequestNext = FocusIdxTabRequestNext = IM_INT_MAX; } ImGuiWindow::~ImGuiWindow() { DrawList->~ImDrawList(); ImGui::MemFree(DrawList); DrawList = NULL; ImGui::MemFree(Name); Name = NULL; } ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end) { ImGuiID seed = IDStack.back(); const ImGuiID id = ImHash(str, str_end ? str_end - str : 0, seed); RegisterAliveId(id); return id; } ImGuiID ImGuiWindow::GetID(const void* ptr) { ImGuiID seed = IDStack.back(); const ImGuiID id = ImHash(&ptr, sizeof(void*), seed); RegisterAliveId(id); return id; } bool ImGuiWindow::FocusItemRegister(bool is_active, bool tab_stop) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const bool allow_keyboard_focus = window->DC.AllowKeyboardFocus.back(); FocusIdxAllCounter++; if (allow_keyboard_focus) FocusIdxTabCounter++; // Process keyboard input at this point: TAB, Shift-TAB switch focus // We can always TAB out of a widget that doesn't allow tabbing in. if (tab_stop && FocusIdxAllRequestNext == IM_INT_MAX && FocusIdxTabRequestNext == IM_INT_MAX && is_active && IsKeyPressedMap(ImGuiKey_Tab)) { // Modulo on index will be applied at the end of frame once we've got the total counter of items. FocusIdxTabRequestNext = FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); } if (FocusIdxAllCounter == FocusIdxAllRequestCurrent) return true; if (allow_keyboard_focus) if (FocusIdxTabCounter == FocusIdxTabRequestCurrent) return true; return false; } void ImGuiWindow::FocusItemUnregister() { FocusIdxAllCounter--; FocusIdxTabCounter--; } static inline void AddDrawListToRenderList(ImVector<ImDrawList*>& out_render_list, ImDrawList* draw_list) { if (!draw_list->commands.empty() && !draw_list->vtx_buffer.empty()) { if (draw_list->commands.back().vtx_count == 0) draw_list->commands.pop_back(); out_render_list.push_back(draw_list); GImGui->IO.MetricsRenderVertices += (int)draw_list->vtx_buffer.size(); } } static void AddWindowToRenderList(ImVector<ImDrawList*>& out_render_list, ImGuiWindow* window) { AddDrawListToRenderList(out_render_list, window->DrawList); for (size_t i = 0; i < window->DC.ChildWindows.size(); i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Visible) // clipped children may have been marked not Visible AddWindowToRenderList(out_render_list, child); } } //----------------------------------------------------------------------------- void* ImGui::MemAlloc(size_t sz) { return GImGui->IO.MemAllocFn(sz); } void ImGui::MemFree(void* ptr) { return GImGui->IO.MemFreeFn(ptr); } static ImGuiIniData* FindWindowSettings(const char* name) { ImGuiState& g = *GImGui; ImGuiID id = ImHash(name, 0); for (size_t i = 0; i != g.Settings.size(); i++) { ImGuiIniData* ini = g.Settings[i]; if (ini->ID == id) return ini; } return NULL; } static ImGuiIniData* AddWindowSettings(const char* name) { ImGuiIniData* ini = (ImGuiIniData*)ImGui::MemAlloc(sizeof(ImGuiIniData)); new(ini) ImGuiIniData(); ini->Name = ImStrdup(name); ini->ID = ImHash(name, 0); ini->Collapsed = false; ini->Pos = ImVec2(FLT_MAX,FLT_MAX); ini->Size = ImVec2(0,0); GImGui->Settings.push_back(ini); return ini; } // Zero-tolerance, poor-man .ini parsing // FIXME: Write something less rubbish static void LoadSettings() { ImGuiState& g = *GImGui; const char* filename = g.IO.IniFilename; if (!filename) return; char* file_data; size_t file_size; if (!ImLoadFileToMemory(filename, "rb", (void**)&file_data, &file_size, 1)) return; ImGuiIniData* settings = NULL; const char* buf_end = file_data + file_size; for (const char* line_start = file_data; line_start < buf_end; ) { const char* line_end = line_start; while (line_end < buf_end && *line_end != '\n' && *line_end != '\r') line_end++; if (line_start[0] == '[' && line_end > line_start && line_end[-1] == ']') { char name[64]; ImFormatString(name, IM_ARRAYSIZE(name), "%.*s", line_end-line_start-2, line_start+1); settings = FindWindowSettings(name); if (!settings) settings = AddWindowSettings(name); } else if (settings) { float x, y; int i; if (sscanf(line_start, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y); else if (sscanf(line_start, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), g.Style.WindowMinSize); else if (sscanf(line_start, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0); } line_start = line_end+1; } ImGui::MemFree(file_data); } static void SaveSettings() { ImGuiState& g = *GImGui; const char* filename = g.IO.IniFilename; if (!filename) return; // Gather data from windows that were active during this session for (size_t i = 0; i != g.Windows.size(); i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_NoSavedSettings) continue; ImGuiIniData* settings = FindWindowSettings(window->Name); settings->Pos = window->Pos; settings->Size = window->SizeFull; settings->Collapsed = window->Collapsed; } // Write .ini file // If a window wasn't opened in this session we preserve its settings FILE* f = fopen(filename, "wt"); if (!f) return; for (size_t i = 0; i != g.Settings.size(); i++) { const ImGuiIniData* settings = g.Settings[i]; if (settings->Pos.x == FLT_MAX) continue; const char* name = settings->Name; if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID() name = p; fprintf(f, "[%s]\n", name); fprintf(f, "Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y); fprintf(f, "Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y); fprintf(f, "Collapsed=%d\n", settings->Collapsed); fprintf(f, "\n"); } fclose(f); } static void MarkSettingsDirty() { ImGuiState& g = *GImGui; if (g.SettingsDirtyTimer <= 0.0f) g.SettingsDirtyTimer = g.IO.IniSavingRate; } const char* ImGui::GetVersion() { return IMGUI_VERSION; } // Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself // Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module void* ImGui::GetInternalState() { return GImGui; } size_t ImGui::GetInternalStateSize() { return sizeof(ImGuiState); } void ImGui::SetInternalState(void* state, bool construct) { if (construct) new (state) ImGuiState(); GImGui = (ImGuiState*)state; } ImGuiIO& ImGui::GetIO() { return GImGui->IO; } ImGuiStyle& ImGui::GetStyle() { return GImGui->Style; } void ImGui::NewFrame() { ImGuiState& g = *GImGui; // Check user data IM_ASSERT(g.IO.DeltaTime > 0.0f); IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f); IM_ASSERT(g.IO.RenderDrawListsFn != NULL); // Must be implemented IM_ASSERT(g.IO.Fonts->Fonts.size() > 0); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ? if (!g.Initialized) { // Initialize on first frame g.LogClipboard = (ImGuiTextBuffer*)ImGui::MemAlloc(sizeof(ImGuiTextBuffer)); new(g.LogClipboard) ImGuiTextBuffer(); IM_ASSERT(g.Settings.empty()); LoadSettings(); g.Initialized = true; } SetFont(g.IO.Fonts->Fonts[0]); g.Time += g.IO.DeltaTime; g.FrameCount += 1; g.Tooltip[0] = '\0'; // Update inputs state if (g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) g.IO.MousePos = ImVec2(-9999.0f, -9999.0f); if ((g.IO.MousePos.x < 0 && g.IO.MousePos.y < 0) || (g.IO.MousePosPrev.x < 0 && g.IO.MousePosPrev.y < 0)) // if mouse just appeared or disappeared (negative coordinate) we cancel out movement in MouseDelta g.IO.MouseDelta = ImVec2(0.0f, 0.0f); else g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev; g.IO.MousePosPrev = g.IO.MousePos; for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { g.IO.MouseDownTime[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownTime[i] < 0.0f ? 0.0f : g.IO.MouseDownTime[i] + g.IO.DeltaTime) : -1.0f; g.IO.MouseClicked[i] = (g.IO.MouseDownTime[i] == 0.0f); g.IO.MouseDoubleClicked[i] = false; if (g.IO.MouseClicked[i]) { if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime) { if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist) g.IO.MouseDoubleClicked[i] = true; g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click } else { g.IO.MouseClickedTime[i] = g.Time; } g.IO.MouseClickedPos[i] = g.IO.MousePos; g.IO.MouseDragMaxDistanceSqr[i] = 0.0f; } else if (g.IO.MouseDown[i]) { g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i])); } } for (size_t i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++) g.IO.KeysDownTime[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownTime[i] < 0.0f ? 0.0f : g.IO.KeysDownTime[i] + g.IO.DeltaTime) : -1.0f; // Calculate frame-rate for the user, as a purely luxurious feature g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx]; g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime; g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame); g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame)); // Clear reference to active widget if the widget isn't alive anymore g.HoveredId = 0; if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0) SetActiveId(0); g.ActiveIdPreviousFrame = g.ActiveId; g.ActiveIdIsAlive = false; g.ActiveIdIsJustActivated = false; if (!g.ActiveId) g.MovedWindow = NULL; // Delay saving settings so we don't spam disk too much if (g.SettingsDirtyTimer > 0.0f) { g.SettingsDirtyTimer -= g.IO.DeltaTime; if (g.SettingsDirtyTimer <= 0.0f) SaveSettings(); } // Find the window we are hovering. Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow g.HoveredWindow = FindHoveredWindow(g.IO.MousePos, false); if (g.HoveredWindow && (g.HoveredWindow->Flags & ImGuiWindowFlags_ChildWindow)) g.HoveredRootWindow = g.HoveredWindow->RootWindow; else g.HoveredRootWindow = FindHoveredWindow(g.IO.MousePos, true); // Are we using inputs? Tell user so they can capture/discard the inputs away from the rest of their application. // When clicking outside of a window we assume the click is owned by the application and won't request capture. int mouse_earliest_button_down = -1; for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++) { if (g.IO.MouseClicked[i]) g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL); if (g.IO.MouseDown[i]) if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[mouse_earliest_button_down] > g.IO.MouseClickedTime[i]) mouse_earliest_button_down = i; } bool mouse_owned_by_application = mouse_earliest_button_down != -1 && !g.IO.MouseDownOwned[mouse_earliest_button_down]; g.IO.WantCaptureMouse = (!mouse_owned_by_application && g.HoveredWindow != NULL) || (g.ActiveId != 0); g.IO.WantCaptureKeyboard = (g.ActiveId != 0); g.MouseCursor = ImGuiMouseCursor_Arrow; // If mouse was first clicked outside of ImGui bounds we also cancel out hovering. if (mouse_owned_by_application) g.HoveredWindow = g.HoveredRootWindow = NULL; // Scale & Scrolling if (g.HoveredWindow && g.IO.MouseWheel != 0.0f) { ImGuiWindow* window = g.HoveredWindow; if (g.IO.KeyCtrl) { if (g.IO.FontAllowUserScaling) { // Zoom / Scale window float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f); float scale = new_font_scale / window->FontWindowScale; window->FontWindowScale = new_font_scale; const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size; window->Pos += offset; window->PosFloat += offset; window->Size *= scale; window->SizeFull *= scale; } } else { // Scroll if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse)) { const int scroll_lines = (window->Flags & ImGuiWindowFlags_ComboBox) ? 3 : 5; window->NextScrollY -= g.IO.MouseWheel * window->CalcFontSize() * scroll_lines; } } } // Pressing TAB activate widget focus // NB: Don't discard FocusedWindow if it isn't active, so that a window that go on/off programatically won't lose its keyboard focus. if (g.ActiveId == 0 && g.FocusedWindow != NULL && g.FocusedWindow->Visible && IsKeyPressedMap(ImGuiKey_Tab, false)) { g.FocusedWindow->FocusIdxTabRequestNext = 0; } // Mark all windows as not visible for (size_t i = 0; i != g.Windows.size(); i++) { ImGuiWindow* window = g.Windows[i]; window->WasVisible = window->Visible; window->Visible = false; window->Accessed = false; } // No window should be open at the beginning of the frame. // But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear. g.CurrentWindowStack.resize(0); // Create implicit window - we will only render it if the user has added something to it. ImGui::SetNextWindowSize(ImVec2(400,400), ImGuiSetCond_FirstUseEver); ImGui::Begin("Debug"); } // NB: behavior of ImGui after Shutdown() is not tested/guaranteed at the moment. This function is merely here to free heap allocations. void ImGui::Shutdown() { ImGuiState& g = *GImGui; if (!g.Initialized) return; SaveSettings(); for (size_t i = 0; i < g.Windows.size(); i++) { g.Windows[i]->~ImGuiWindow(); ImGui::MemFree(g.Windows[i]); } g.Windows.clear(); g.WindowsSortBuffer.clear(); g.CurrentWindowStack.clear(); g.FocusedWindow = NULL; g.HoveredWindow = NULL; g.HoveredRootWindow = NULL; for (size_t i = 0; i < g.Settings.size(); i++) { g.Settings[i]->~ImGuiIniData(); ImGui::MemFree(g.Settings[i]); } g.Settings.clear(); g.ColorModifiers.clear(); g.StyleModifiers.clear(); g.FontStack.clear(); for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].clear(); g.MouseCursorDrawList.ClearFreeMemory(); g.ColorEditModeStorage.Clear(); if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } if (g.LogFile && g.LogFile != stdout) { fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard) { g.LogClipboard->~ImGuiTextBuffer(); ImGui::MemFree(g.LogClipboard); } g.IO.Fonts->Clear(); g.Initialized = false; } // FIXME: Add a more explicit sort order in the window structure. static int ChildWindowComparer(const void* lhs, const void* rhs) { const ImGuiWindow* a = *(const ImGuiWindow**)lhs; const ImGuiWindow* b = *(const ImGuiWindow**)rhs; if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup)) return d; if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip)) return d; if (int d = (a->Flags & ImGuiWindowFlags_ComboBox) - (b->Flags & ImGuiWindowFlags_ComboBox)) return d; return 0; } static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>& out_sorted_windows, ImGuiWindow* window) { out_sorted_windows.push_back(window); if (window->Visible) { const size_t count = window->DC.ChildWindows.size(); if (count > 1) qsort(window->DC.ChildWindows.begin(), count, sizeof(ImGuiWindow*), ChildWindowComparer); for (size_t i = 0; i < count; i++) { ImGuiWindow* child = window->DC.ChildWindows[i]; if (child->Visible) AddWindowToSortedBuffer(out_sorted_windows, child); } } } static void PushClipRect(const ImVec4& clip_rect, bool clipped = true) { ImGuiWindow* window = GetCurrentWindow(); ImVec4 cr = clip_rect; if (clipped && !window->ClipRectStack.empty()) { // Clip with existing clip rect const ImVec4 cur_cr = window->ClipRectStack.back(); cr = ImVec4(ImMax(cr.x, cur_cr.x), ImMax(cr.y, cur_cr.y), ImMin(cr.z, cur_cr.z), ImMin(cr.w, cur_cr.w)); } cr.z = ImMax(cr.x, cr.z); cr.w = ImMax(cr.y, cr.w); IM_ASSERT(cr.x <= cr.z && cr.y <= cr.w); window->ClipRectStack.push_back(cr); window->DrawList->PushClipRect(cr); } static void PopClipRect() { ImGuiWindow* window = GetCurrentWindow(); window->ClipRectStack.pop_back(); window->DrawList->PopClipRect(); } void ImGui::Render() { ImGuiState& g = *GImGui; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() const bool first_render_of_the_frame = (g.FrameCountRendered != g.FrameCount); g.FrameCountRendered = g.FrameCount; if (first_render_of_the_frame) { // Hide implicit window if it hasn't been used IM_ASSERT(g.CurrentWindowStack.size() == 1); // Mismatched Begin/End if (g.CurrentWindow && !g.CurrentWindow->Accessed) g.CurrentWindow->Visible = false; ImGui::End(); if (g.ActiveId == 0 && g.HoveredId == 0 && g.IO.MouseClicked[0]) { if (g.HoveredRootWindow != NULL) { // Select window for move/focus when we're done with all our widgets (we use the root window ID here) IM_ASSERT(g.MovedWindow == NULL); g.MovedWindow = g.HoveredWindow; SetActiveId(g.HoveredRootWindow->MoveID); } else if (g.FocusedWindow != NULL) { // Clicking on void disable focus FocusWindow(NULL); } } // Sort the window list so that all child windows are after their parent // We cannot do that on FocusWindow() because childs may not exist yet g.WindowsSortBuffer.resize(0); g.WindowsSortBuffer.reserve(g.Windows.size()); for (size_t i = 0; i != g.Windows.size(); i++) { ImGuiWindow* window = g.Windows[i]; if (window->Flags & ImGuiWindowFlags_ChildWindow) // if a child is visible its parent will add it if (window->Visible) continue; AddWindowToSortedBuffer(g.WindowsSortBuffer, window); } IM_ASSERT(g.Windows.size() == g.WindowsSortBuffer.size()); // we done something wrong g.Windows.swap(g.WindowsSortBuffer); // Clear data for next frame g.IO.MouseWheel = 0.0f; memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } // Skip render altogether if alpha is 0.0 // Note that vertex buffers have been created, so it is best practice that you don't call Begin/End in the first place. if (g.Style.Alpha > 0.0f) { // Render tooltip if (g.Tooltip[0]) { // Use a dummy window to render the tooltip ImGui::BeginTooltip(); ImGui::TextUnformatted(g.Tooltip); ImGui::EndTooltip(); } // Gather windows to render g.IO.MetricsRenderVertices = 0; for (size_t i = 0; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) g.RenderDrawLists[i].resize(0); for (size_t i = 0; i != g.Windows.size(); i++) { ImGuiWindow* window = g.Windows[i]; if (window->Visible && (window->Flags & (ImGuiWindowFlags_ChildWindow)) == 0) { // FIXME: Generalize this with a proper layering system so we can stack. if (window->Flags & ImGuiWindowFlags_Popup) AddWindowToRenderList(g.RenderDrawLists[1], window); else if (window->Flags & ImGuiWindowFlags_Tooltip) AddWindowToRenderList(g.RenderDrawLists[2], window); else AddWindowToRenderList(g.RenderDrawLists[0], window); } } // Flatten layers size_t n = g.RenderDrawLists[0].size(); size_t flattened_size = n; for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) flattened_size += g.RenderDrawLists[i].size(); g.RenderDrawLists[0].resize(flattened_size); for (size_t i = 1; i < IM_ARRAYSIZE(g.RenderDrawLists); i++) { ImVector<ImDrawList*>& layer = g.RenderDrawLists[i]; if (!layer.empty()) { memcpy(&g.RenderDrawLists[0][n], &layer[0], layer.size() * sizeof(ImDrawList*)); n += layer.size(); } } if (g.IO.MouseDrawCursor) { const ImGuiMouseCursorData& cursor_data = g.MouseCursorData[g.MouseCursor]; const ImVec2 pos = g.IO.MousePos - cursor_data.Offset; const ImVec2 size = cursor_data.Size; const ImTextureID tex_id = g.IO.Fonts->TexID; g.MouseCursorDrawList.Clear(); g.MouseCursorDrawList.PushTextureID(tex_id); g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(1,0), pos+ImVec2(1,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow g.MouseCursorDrawList.AddImage(tex_id, pos+ImVec2(2,0), pos+ImVec2(2,0) + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0x30000000); // Shadow g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[1], cursor_data.TexUvMax[1], 0xFF000000); // Black border g.MouseCursorDrawList.AddImage(tex_id, pos, pos + size, cursor_data.TexUvMin[0], cursor_data.TexUvMax[0], 0xFFFFFFFF); // White fill g.MouseCursorDrawList.PopTextureID(); AddDrawListToRenderList(g.RenderDrawLists[0], &g.MouseCursorDrawList); } // Render if (!g.RenderDrawLists[0].empty()) g.IO.RenderDrawListsFn(&g.RenderDrawLists[0][0], (int)g.RenderDrawLists[0].size()); } } // Find the optional ## from which we stop displaying text. static const char* FindTextDisplayEnd(const char* text, const char* text_end = NULL) { const char* text_display_end = text; if (!text_end) text_end = (const char*)-1; ImGuiState& g = *GImGui; if (g.DisableHideTextAfterDoubleHash > 0) { while (text_display_end < text_end && *text_display_end != '\0') text_display_end++; } else { while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#')) text_display_end++; } return text_display_end; } // Pass text data straight to log (without being displayed) void ImGui::LogText(const char* fmt, ...) { ImGuiState& g = *GImGui; if (!g.LogEnabled) return; va_list args; va_start(args, fmt); if (g.LogFile) { vfprintf(g.LogFile, fmt, args); } else { g.LogClipboard->appendv(fmt, args); } va_end(args); } // Internal version that takes a position to decide on newline placement and pad items according to their depth. // We split text into individual lines to add current tree level padding static void LogText(const ImVec2& ref_pos, const char* text, const char* text_end) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) text_end = FindTextDisplayEnd(text, text_end); const bool log_new_line = ref_pos.y > window->DC.LogLinePosY+1; window->DC.LogLinePosY = ref_pos.y; const char* text_remaining = text; if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth g.LogStartDepth = window->DC.TreeDepth; const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth); for (;;) { // Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry. const char* line_end = text_remaining; while (line_end < text_end) if (*line_end == '\n') break; else line_end++; if (line_end >= text_end) line_end = NULL; const bool is_first_line = (text == text_remaining); bool is_last_line = false; if (line_end == NULL) { is_last_line = true; line_end = text_end; } if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0)) { const int char_count = (int)(line_end - text_remaining); if (log_new_line || !is_first_line) ImGui::LogText(STR_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining); else ImGui::LogText(" %.*s", char_count, text_remaining); } if (is_last_line) break; text_remaining = line_end + 1; } } static float CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x) { if (wrap_pos_x < 0.0f) return 0.0f; ImGuiWindow* window = GetCurrentWindow(); if (wrap_pos_x == 0.0f) wrap_pos_x = ImGui::GetContentRegionMax().x; if (wrap_pos_x > 0.0f) wrap_pos_x += window->Pos.x; // wrap_pos_x is provided is window local space const float wrap_width = wrap_pos_x > 0.0f ? ImMax(wrap_pos_x - pos.x, 0.00001f) : 0.0f; return wrap_width; } // Internal ImGui functions to render text // RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText() static void RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end; if (hide_text_after_hash) { text_display_end = FindTextDisplayEnd(text, text_end); } else { if (!text_end) text_end = text + strlen(text); // FIXME-OPT text_display_end = text_end; } const int text_len = (int)(text_display_end - text); if (text_len > 0) { // Render window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end); // Log as text if (g.LogEnabled) LogText(pos, text, text_display_end); } } static void RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!text_end) text_end = text + strlen(text); // FIXME-OPT const int text_len = (int)(text_end - text); if (text_len > 0) { // Render window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_end, wrap_width); // Log as text if (g.LogEnabled) LogText(pos, text, text_end); } } static void RenderTextClipped(ImVec2 pos, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& clip_max) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Hide anything after a '##' string const char* text_display_end = FindTextDisplayEnd(text, text_end); const int text_len = (int)(text_display_end - text); if (text_len > 0) { const ImVec2 text_size = text_size_if_known ? *text_size_if_known : ImGui::CalcTextSize(text, text_display_end, false, 0.0f); // Perform CPU side clipping for single clipped element to avoid using scissor state const bool need_clipping = (pos.x + text_size.x >= clip_max.x) || (pos.y + text_size.y >= clip_max.y); // Render window->DrawList->AddText(g.Font, g.FontSize, pos, window->Color(ImGuiCol_Text), text, text_display_end, 0.0f, need_clipping ? &clip_max : NULL); // Log as text if (g.LogEnabled) LogText(pos, text, text_display_end); } } // Render a rectangle shaped with optional rounding and borders static void RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding) { ImGuiWindow* window = GetCurrentWindow(); window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding); if (border && (window->Flags & ImGuiWindowFlags_ShowBorders)) { // FIXME: This is the best I've found that works on multiple renderer/back ends. Bit dodgy. window->DrawList->AddRect(p_min+ImVec2(1.5f,1.5f), p_max+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), rounding); window->DrawList->AddRect(p_min+ImVec2(0.5f,0.5f), p_max+ImVec2(0,0), window->Color(ImGuiCol_Border), rounding); } } // Render a triangle to denote expanded/collapsed state static void RenderCollapseTriangle(ImVec2 p_min, bool opened, float scale, bool shadow) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const float h = g.FontSize * 1.00f; const float r = h * 0.40f * scale; ImVec2 center = p_min + ImVec2(h*0.50f, h*0.50f*scale); ImVec2 a, b, c; if (opened) { center.y -= r*0.25f; a = center + ImVec2(0,1)*r; b = center + ImVec2(-0.866f,-0.5f)*r; c = center + ImVec2(0.866f,-0.5f)*r; } else { a = center + ImVec2(1,0)*r; b = center + ImVec2(-0.500f,0.866f)*r; c = center + ImVec2(-0.500f,-0.866f)*r; } if (shadow && (window->Flags & ImGuiWindowFlags_ShowBorders) != 0) window->DrawList->AddTriangleFilled(a+ImVec2(2,2), b+ImVec2(2,2), c+ImVec2(2,2), window->Color(ImGuiCol_BorderShadow)); window->DrawList->AddTriangleFilled(a, b, c, window->Color(ImGuiCol_Text)); } // Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker. // CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize) ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width) { ImGuiState& g = *GImGui; const char* text_display_end; if (hide_text_after_double_hash) text_display_end = FindTextDisplayEnd(text, text_end); // Hide anything after a '##' string else text_display_end = text_end; ImFont* font = g.Font; const float font_size = g.FontSize; ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL); // Cancel out character spacing for the last character of a line (it is baked into glyph->XAdvance field) const float font_scale = font_size / font->FontSize; const float character_spacing_x = 1.0f * font_scale; if (text_size.x > 0.0f) text_size.x -= character_spacing_x; return text_size; } // Helper to calculate coarse clipping of large list of evenly sized items. // If you are displaying thousands of items and you have a random access to the list, you can perform clipping yourself to save on CPU. // { // float item_height = ImGui::GetTextLineHeightWithSpacing(); // int display_start, display_end; // ImGui::CalcListClipping(count, item_height, &display_start, &display_end); // calculate how many to clip/display // ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * item_height); // advance cursor // for (int i = display_start; i < display_end; i++) // display only visible items // // TODO: display visible item // ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (count - display_end) * item_height); // advance cursor // } void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (g.LogEnabled) { // If logging is active, do not perform any clipping *out_items_display_start = 0; *out_items_display_end = items_count; return; } const ImVec2 pos = window->DC.CursorPos; const ImVec4 clip_rect = window->ClipRectStack.back(); const float clip_y1 = clip_rect.y; const float clip_y2 = clip_rect.w; int start = (int)((clip_y1 - pos.y) / items_height); int end = (int)((clip_y2 - pos.y) / items_height); start = ImClamp(start, 0, items_count); end = ImClamp(end + 1, start, items_count); *out_items_display_start = start; *out_items_display_end = end; } // Find window given position, search front-to-back static ImGuiWindow* FindHoveredWindow(ImVec2 pos, bool excluding_childs) { ImGuiState& g = *GImGui; for (int i = (int)g.Windows.size()-1; i >= 0; i--) { ImGuiWindow* window = g.Windows[(size_t)i]; if (!window->Visible) continue; if (excluding_childs && (window->Flags & ImGuiWindowFlags_ChildWindow) != 0) continue; // Using the clipped AABB so a child window will typically be clipped by its parent. ImRect bb(window->ClippedRect.Min - g.Style.TouchExtraPadding, window->ClippedRect.Max + g.Style.TouchExtraPadding); if (bb.Contains(pos)) return window; } return NULL; } // Test if mouse cursor is hovering given rectangle // NB- Rectangle is clipped by our current clip setting // NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding) static bool IsMouseHoveringRect(const ImRect& rect) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); // Clip ImRect rect_clipped = rect; if (!window->ClipRectStack.empty()) { const ImVec4 clip_rect = window->ClipRectStack.back(); rect_clipped.Clip(ImRect(ImVec2(clip_rect.x, clip_rect.y), ImVec2(clip_rect.z, clip_rect.w))); } // Expand for touch input const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding); return rect_for_touch.Contains(g.IO.MousePos); } bool ImGui::IsMouseHoveringRect(const ImVec2& rect_min, const ImVec2& rect_max) { return IsMouseHoveringRect(ImRect(rect_min, rect_max)); } bool ImGui::IsMouseHoveringWindow() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); return g.HoveredWindow == window; } bool ImGui::IsMouseHoveringAnyWindow() { ImGuiState& g = *GImGui; return g.HoveredWindow != NULL; } bool ImGui::IsPosHoveringAnyWindow(const ImVec2& pos) { return FindHoveredWindow(pos, false) != NULL; } static bool IsKeyPressedMap(ImGuiKey key, bool repeat) { ImGuiState& g = *GImGui; const int key_index = g.IO.KeyMap[key]; return ImGui::IsKeyPressed(key_index, repeat); } bool ImGui::IsKeyPressed(int key_index, bool repeat) { ImGuiState& g = *GImGui; IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown)); const float t = g.IO.KeysDownTime[key_index]; if (t == 0.0f) return true; // FIXME: Repeat rate should be provided elsewhere? const float KEY_REPEAT_DELAY = 0.250f; const float KEY_REPEAT_RATE = 0.020f; if (repeat && t > KEY_REPEAT_DELAY) if ((fmodf(t - KEY_REPEAT_DELAY, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f) != (fmodf(t - KEY_REPEAT_DELAY - g.IO.DeltaTime, KEY_REPEAT_RATE) > KEY_REPEAT_RATE*0.5f)) return true; return false; } bool ImGui::IsMouseClicked(int button, bool repeat) { ImGuiState& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); const float t = g.IO.MouseDownTime[button]; if (t == 0.0f) return true; // FIXME: Repeat rate should be provided elsewhere? const float MOUSE_REPEAT_DELAY = 0.250f; const float MOUSE_REPEAT_RATE = 0.020f; if (repeat && t > MOUSE_REPEAT_DELAY) if ((fmodf(t - MOUSE_REPEAT_DELAY, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f) != (fmodf(t - MOUSE_REPEAT_DELAY - g.IO.DeltaTime, MOUSE_REPEAT_RATE) > MOUSE_REPEAT_RATE*0.5f)) return true; return false; } bool ImGui::IsMouseDoubleClicked(int button) { ImGuiState& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); return g.IO.MouseDoubleClicked[button]; } bool ImGui::IsMouseDragging(int button, float lock_threshold) { ImGuiState& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold; } ImVec2 ImGui::GetMousePos() { return GImGui->IO.MousePos; } ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold) { ImGuiState& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); if (lock_threshold < 0.0f) lock_threshold = g.IO.MouseDragThreshold; if (g.IO.MouseDown[button]) if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold) return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment). return ImVec2(0.0f, 0.0f); } void ImGui::ResetMouseDragDelta(int button) { ImGuiState& g = *GImGui; IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown)); // NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr g.IO.MouseClickedPos[button] = g.IO.MousePos; } ImGuiMouseCursor ImGui::GetMouseCursor() { return GImGui->MouseCursor; } void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type) { GImGui->MouseCursor = cursor_type; } bool ImGui::IsItemHovered() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemHoveredAndUsable; } bool ImGui::IsItemHoveredRect() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemHoveredRect; } bool ImGui::IsItemActive() { ImGuiState& g = *GImGui; if (g.ActiveId) { ImGuiWindow* window = GetCurrentWindow(); return g.ActiveId == window->DC.LastItemID; } return false; } bool ImGui::IsAnyItemActive() { ImGuiState& g = *GImGui; return g.ActiveId != 0; } bool ImGui::IsItemVisible() { ImGuiWindow* window = GetCurrentWindow(); ImRect r(window->ClipRectStack.back()); return r.Overlaps(window->DC.LastItemRect); } ImVec2 ImGui::GetItemRectMin() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemRect.Min; } ImVec2 ImGui::GetItemRectMax() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemRect.Max; } ImVec2 ImGui::GetItemRectSize() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.LastItemRect.GetSize(); } ImVec2 ImGui::CalcItemRectClosestPoint(const ImVec2& pos, bool on_edge, float outward) { ImGuiWindow* window = GetCurrentWindow(); ImRect rect = window->DC.LastItemRect; rect.Expand(outward); return rect.GetClosestPoint(pos, on_edge); } // Tooltip is stored and turned into a BeginTooltip()/EndTooltip() sequence at the end of the frame. Each call override previous value. void ImGui::SetTooltipV(const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImFormatStringV(g.Tooltip, IM_ARRAYSIZE(g.Tooltip), fmt, args); } void ImGui::SetTooltip(const char* fmt, ...) { va_list args; va_start(args, fmt); SetTooltipV(fmt, args); va_end(args); } float ImGui::GetTime() { return GImGui->Time; } int ImGui::GetFrameCount() { return GImGui->FrameCount; } void ImGui::BeginTooltip() { ImGuiState& g = *GImGui; ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("##Tooltip", NULL, ImVec2(0,0), g.Style.Colors[ImGuiCol_TooltipBg].w, flags); } void ImGui::EndTooltip() { IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Tooltip); ImGui::End(); } void ImGui::BeginPopup(bool* p_opened) { IM_ASSERT(p_opened != NULL); // Must provide a bool at the moment ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); ImGuiWindowFlags flags = ImGuiWindowFlags_Popup|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize; ImGui::Begin("##Popup", p_opened, flags); } void ImGui::EndPopup() { IM_ASSERT(GetCurrentWindow()->Flags & ImGuiWindowFlags_Popup); ImGui::End(); ImGui::PopStyleVar(); } bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow; const ImVec2 content_max = window->Pos + ImGui::GetContentRegionMax(); const ImVec2 cursor_pos = window->Pos + ImGui::GetCursorPos(); ImVec2 size = size_arg; if (size.x <= 0.0f) { if (size.x == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitX; size.x = ImMax(content_max.x - cursor_pos.x, g.Style.WindowMinSize.x) - fabsf(size.x); } if (size.y <= 0.0f) { if (size.y == 0.0f) flags |= ImGuiWindowFlags_ChildWindowAutoFitY; size.y = ImMax(content_max.y - cursor_pos.y, g.Style.WindowMinSize.y) - fabsf(size.y); } if (border) flags |= ImGuiWindowFlags_ShowBorders; flags |= extra_flags; char title[256]; ImFormatString(title, IM_ARRAYSIZE(title), "%s.%s", window->Name, str_id); const float alpha = 1.0f; bool ret = ImGui::Begin(title, NULL, size, alpha, flags); if (!(window->Flags & ImGuiWindowFlags_ShowBorders)) g.CurrentWindow->Flags &= ~ImGuiWindowFlags_ShowBorders; return ret; } bool ImGui::BeginChild(ImGuiID id, const ImVec2& size, bool border, ImGuiWindowFlags extra_flags) { char str_id[32]; ImFormatString(str_id, IM_ARRAYSIZE(str_id), "child_%x", id); bool ret = ImGui::BeginChild(str_id, size, border, extra_flags); return ret; } void ImGui::EndChild() { ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); if (window->Flags & ImGuiWindowFlags_ComboBox) { ImGui::End(); } else { // When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting. ImGuiState& g = *GImGui; ImVec2 sz = ImGui::GetWindowSize(); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitX) sz.x = ImMax(g.Style.WindowMinSize.x, sz.x - g.Style.AutoFitPadding.x); if (window->Flags & ImGuiWindowFlags_ChildWindowAutoFitY) sz.y = ImMax(g.Style.WindowMinSize.y, sz.y - g.Style.AutoFitPadding.y); ImGui::End(); window = GetCurrentWindow(); ImRect bb(window->DC.CursorPos, window->DC.CursorPos + sz); ItemSize(sz); ItemAdd(bb, NULL); } } // Helper to create a child window / scrolling region that looks like a normal widget frame. void ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size) { ImGuiState& g = *GImGui; const ImGuiStyle& style = g.Style; ImGui::PushStyleColor(ImGuiCol_ChildWindowBg, style.Colors[ImGuiCol_FrameBg]); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, style.FrameRounding); ImGui::BeginChild(id, size); } void ImGui::EndChildFrame() { ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::PopStyleColor(); } static ImGuiWindow* FindWindowByName(const char* name) { // FIXME-OPT: Store sorted hashes -> pointers. ImGuiState& g = *GImGui; ImGuiID id = ImHash(name, 0); for (size_t i = 0; i < g.Windows.size(); i++) if (g.Windows[i]->ID == id) return g.Windows[i]; return NULL; } static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags) { ImGuiState& g = *GImGui; // Create window the first time ImGuiWindow* window = (ImGuiWindow*)ImGui::MemAlloc(sizeof(ImGuiWindow)); new(window) ImGuiWindow(name); window->Flags = flags; if (flags & ImGuiWindowFlags_NoSavedSettings) { // User can disable loading and saving of settings. Tooltip and child windows also don't store settings. window->Size = window->SizeFull = size; } else { // Retrieve settings from .ini file // Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window. window->PosFloat = ImVec2(60, 60); window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); ImGuiIniData* settings = FindWindowSettings(name); if (!settings) { settings = AddWindowSettings(name); } else { window->SetWindowPosAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowSizeAllowFlags &= ~ImGuiSetCond_FirstUseEver; window->SetWindowCollapsedAllowFlags &= ~ImGuiSetCond_FirstUseEver; } if (settings->Pos.x != FLT_MAX) { window->PosFloat = settings->Pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->Collapsed = settings->Collapsed; } if (ImLengthSqr(settings->Size) > 0.00001f && !(flags & ImGuiWindowFlags_NoResize)) size = settings->Size; window->Size = window->SizeFull = size; } if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { window->AutoFitFrames = 2; window->AutoFitOnlyGrows = false; } else if (ImLengthSqr(window->Size) < 0.00001f) { window->AutoFitFrames = 2; window->AutoFitOnlyGrows = true; } g.Windows.push_back(window); return window; } // Push a new ImGui window to add widgets to. // - 'size' for a regular window denote the initial size for first-time creation (no saved data) and isn't that useful. Use SetNextWindowSize() prior to calling Begin() for more flexible window manipulation. // - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair. // - Begin/End can be called multiple times during the frame with the same window name to append content. // - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file). // You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file. // - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned. // - Passing 'bool* p_opened' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed. // - Passing non-zero 'size' is roughly equivalent to calling SetNextWindowSize(size, ImGuiSetCond_FirstUseEver) prior to calling Begin(). bool ImGui::Begin(const char* name, bool* p_opened, ImGuiWindowFlags flags) { return ImGui::Begin(name, p_opened, ImVec2(0.f, 0.f), -1.0f, flags); } bool ImGui::Begin(const char* name, bool* p_opened, const ImVec2& size_on_first_use, float bg_alpha, ImGuiWindowFlags flags) { ImGuiState& g = *GImGui; const ImGuiStyle& style = g.Style; IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame() IM_ASSERT(name != NULL); // Must pass a name // Find or create bool window_is_new = false; ImGuiWindow* window = FindWindowByName(name); if (!window) { window = CreateNewWindow(name, size_on_first_use, flags); window_is_new = true; } window->Flags = (ImGuiWindowFlags)flags; // Add to stack g.CurrentWindowStack.push_back(window); SetCurrentWindow(window); // Process SetNextWindow***() calls bool window_pos_set_by_api = false; if (g.SetNextWindowPosCond) { const ImVec2 backup_cursor_pos = window->DC.CursorPos; // FIXME: not sure of the exact reason of this anymore :( need to look into that. ImGui::SetWindowPos(g.SetNextWindowPosVal, g.SetNextWindowPosCond); window->DC.CursorPos = backup_cursor_pos; window_pos_set_by_api = true; g.SetNextWindowPosCond = 0; } if (g.SetNextWindowSizeCond) { ImGui::SetWindowSize(g.SetNextWindowSizeVal, g.SetNextWindowSizeCond); g.SetNextWindowSizeCond = 0; } if (g.SetNextWindowCollapsedCond) { ImGui::SetWindowCollapsed(g.SetNextWindowCollapsedVal, g.SetNextWindowCollapsedCond); g.SetNextWindowCollapsedCond = 0; } if (g.SetNextWindowFocus) { ImGui::SetWindowFocus(); g.SetNextWindowFocus = false; } // Find parent ImGuiWindow* parent_window = (flags & ImGuiWindowFlags_ChildWindow) != 0 ? g.CurrentWindowStack[g.CurrentWindowStack.size()-2] : NULL; // Update known root window (if we are a child window, otherwise window == window->RootWindow) size_t root_idx = g.CurrentWindowStack.size() - 1; while (root_idx > 0) { if ((g.CurrentWindowStack[root_idx]->Flags & ImGuiWindowFlags_ChildWindow) == 0) break; root_idx--; } window->RootWindow = g.CurrentWindowStack[root_idx]; // Default alpha if (bg_alpha < 0.0f) bg_alpha = style.WindowFillAlphaDefault; // When reusing window again multiple times a frame, just append content (don't need to setup again) const int current_frame = ImGui::GetFrameCount(); const bool first_begin_of_the_frame = (window->LastFrameDrawn != current_frame); if (first_begin_of_the_frame) { window->DrawList->Clear(); window->Visible = true; // New windows appears in front if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip)) { if (window->LastFrameDrawn < current_frame - 1) { FocusWindow(window); // Popup position themselves when they first appear if (flags & ImGuiWindowFlags_Popup) { if (!window_pos_set_by_api) window->PosFloat = g.IO.MousePos; } } } window->LastFrameDrawn = current_frame; window->ClipRectStack.resize(0); // Reset contents size for auto-fitting window->SizeContents = window_is_new ? ImVec2(0.0f, 0.0f) : window->DC.CursorMaxPos - window->Pos; window->SizeContents.y += window->ScrollY; if (flags & ImGuiWindowFlags_ChildWindow) { parent_window->DC.ChildWindows.push_back(window); window->Pos = window->PosFloat = parent_window->DC.CursorPos; window->SizeFull = size_on_first_use; } } // Setup texture window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID); // Setup outer clipping rectangle if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_ComboBox)) PushClipRect(parent_window->ClipRectStack.back()); else if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) PushClipRect(ImVec4(g.IO.DisplayVisibleMin.x, g.IO.DisplayVisibleMin.y, g.IO.DisplayVisibleMax.x, g.IO.DisplayVisibleMax.y)); else PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); // Setup and draw window if (first_begin_of_the_frame) { // Reset ID stack window->IDStack.resize(1); // Move window (at the beginning of the frame to avoid input lag or sheering). Only valid for root windows. RegisterAliveId(window->MoveID); if (g.ActiveId == window->MoveID) { if (g.IO.MouseDown[0]) { if (!(window->Flags & ImGuiWindowFlags_NoMove)) { window->PosFloat += g.IO.MouseDelta; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); } IM_ASSERT(g.MovedWindow != NULL); FocusWindow(g.MovedWindow); } else { SetActiveId(0); g.MovedWindow = NULL; // Not strictly necessary but doing it for sanity. } } // Tooltips always follows mouse if (!window_pos_set_by_api && (window->Flags & ImGuiWindowFlags_Tooltip) != 0) { window->PosFloat = g.IO.MousePos + ImVec2(32,16) - style.FramePadding*2; } // Clamp into view if (!(window->Flags & ImGuiWindowFlags_ChildWindow) && !(window->Flags & ImGuiWindowFlags_Tooltip)) { if (window->AutoFitFrames <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing. { ImVec2 clip_min = style.DisplaySafeAreaPadding; ImVec2 clip_max = g.IO.DisplaySize - style.DisplaySafeAreaPadding; window->PosFloat = ImMax(window->PosFloat + window->Size, clip_min) - window->Size; window->PosFloat = ImMin(window->PosFloat, clip_max); } window->SizeFull = ImMax(window->SizeFull, style.WindowMinSize); } window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); // Default item width. Make it proportional to window size if window manually resizes if (window->Size.x > 0.0f && !(window->Flags & ImGuiWindowFlags_Tooltip) && !(window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f); else window->ItemWidthDefault = 200.0f; // Prepare for focus requests if (window->FocusIdxAllRequestNext == IM_INT_MAX || window->FocusIdxAllCounter == -1) window->FocusIdxAllRequestCurrent = IM_INT_MAX; else window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1); if (window->FocusIdxTabRequestNext == IM_INT_MAX || window->FocusIdxTabCounter == -1) window->FocusIdxTabRequestCurrent = IM_INT_MAX; else window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1); window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1; window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = IM_INT_MAX; ImRect title_bar_rect = window->TitleBarRect(); // Apply and ImClamp scrolling window->ScrollY = window->NextScrollY; window->ScrollY = ImMax(window->ScrollY, 0.0f); if (!window->Collapsed && !window->SkipItems) window->ScrollY = ImMin(window->ScrollY, ImMax(0.0f, window->SizeContents.y - window->SizeFull.y)); window->NextScrollY = window->ScrollY; // At this point we don't have a clipping rectangle setup yet, so we can test and draw in title bar // Collapse window by double-clicking on title bar if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) { if (!(window->Flags & ImGuiWindowFlags_NoCollapse) && g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect) && g.IO.MouseDoubleClicked[0]) { window->Collapsed = !window->Collapsed; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); FocusWindow(window); } } else { window->Collapsed = false; } // Calculate auto-fit size ImVec2 size_auto_fit; if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) { // Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose. size_auto_fit = window->SizeContents + style.WindowPadding - ImVec2(0.0f, style.ItemSpacing.y); } else { size_auto_fit = ImClamp(window->SizeContents + style.AutoFitPadding, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - style.AutoFitPadding)); if (size_auto_fit.y < window->SizeContents.y + style.AutoFitPadding.y) size_auto_fit.x += style.ScrollbarWidth; } const float window_rounding = (window->Flags & ImGuiWindowFlags_ChildWindow) ? style.ChildWindowRounding : style.WindowRounding; if (window->Collapsed) { // We still process initial auto-fit on collapsed windows to get a window width // But otherwise we don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed. if (window->AutoFitFrames > 0) { window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; title_bar_rect = window->TitleBarRect(); } // Draw title bar only window->Size = title_bar_rect.GetSize(); window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBgCollapsed), window_rounding); if (window->Flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddRect(title_bar_rect.GetTL()+ImVec2(1,1), title_bar_rect.GetBR()+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); window->DrawList->AddRect(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border), window_rounding); } } else { ImU32 resize_col = 0; if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) { window->Size = window->SizeFull = size_auto_fit; } else { if ((window->Flags & ImGuiWindowFlags_AlwaysAutoResize) != 0) { // Don't continuously mark settings as dirty, the size of the window doesn't need to be stored. window->SizeFull = size_auto_fit; } else if (window->AutoFitFrames > 0) { // Auto-fit only grows during the first few frames window->SizeFull = window->AutoFitOnlyGrows ? ImMax(window->SizeFull, size_auto_fit) : size_auto_fit; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); } else if (!(window->Flags & ImGuiWindowFlags_NoResize)) { // Manual resize grip const ImRect resize_rect(window->Rect().GetBR()-ImVec2(14,14), window->Rect().GetBR()); const ImGuiID resize_id = window->GetID("#RESIZE"); bool hovered, held; ButtonBehavior(resize_rect, resize_id, &hovered, &held, true); resize_col = window->Color(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeNWSE; if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0]) { // Manual auto-fit when double-clicking window->SizeFull = size_auto_fit; if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); SetActiveId(0); } else if (held) { // Resize window->SizeFull = ImMax(window->SizeFull + g.IO.MouseDelta, style.WindowMinSize); if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings)) MarkSettingsDirty(); } } // Update rectangle immediately so that rendering right below us isn't one frame late window->Size = window->SizeFull; title_bar_rect = window->TitleBarRect(); } // Scrollbar window->ScrollbarY = (window->SizeContents.y > window->Size.y) && !(window->Flags & ImGuiWindowFlags_NoScrollbar); // Window background if (bg_alpha > 0.0f) { if ((window->Flags & ImGuiWindowFlags_ComboBox) != 0) window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_ComboBg, bg_alpha), window_rounding); else if ((window->Flags & ImGuiWindowFlags_Tooltip) != 0) window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_TooltipBg, bg_alpha), window_rounding); else if ((window->Flags & ImGuiWindowFlags_ChildWindow) != 0) window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size-ImVec2(window->ScrollbarY?style.ScrollbarWidth:0.0f,0.0f), window->Color(ImGuiCol_ChildWindowBg, bg_alpha), window_rounding, window->ScrollbarY ? (1|8) : (0xF)); else window->DrawList->AddRectFilled(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_WindowBg, bg_alpha), window_rounding); } // Title bar if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddRectFilled(title_bar_rect.GetTL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_TitleBg), window_rounding, 1|2); // Borders if (window->Flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddRect(window->Pos+ImVec2(1,1), window->Pos+window->Size+ImVec2(1,1), window->Color(ImGuiCol_BorderShadow), window_rounding); window->DrawList->AddRect(window->Pos, window->Pos+window->Size, window->Color(ImGuiCol_Border), window_rounding); if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) window->DrawList->AddLine(title_bar_rect.GetBL(), title_bar_rect.GetBR(), window->Color(ImGuiCol_Border)); } // Scrollbar if (window->ScrollbarY) Scrollbar(window); // Render resize grip // (after the input handling so we don't have a frame of latency) if (!(window->Flags & ImGuiWindowFlags_NoResize)) { const float r = window_rounding; const ImVec2 br = window->Rect().GetBR(); if (r == 0.0f) { window->DrawList->AddTriangleFilled(br, br-ImVec2(0,14), br-ImVec2(14,0), resize_col); } else { // FIXME: We should draw 4 triangles and decide on a size that's not dependent on the rounding size (previously used 18) window->DrawList->AddArcFast(br - ImVec2(r,r), r, resize_col, 6, 9, true); window->DrawList->AddTriangleFilled(br+ImVec2(0,-2*r),br+ImVec2(0,-r),br+ImVec2(-r,-r), resize_col); window->DrawList->AddTriangleFilled(br+ImVec2(-r,-r), br+ImVec2(-r,0),br+ImVec2(-2*r,0), resize_col); } } } // Setup drawing context window->DC.ColumnsStartX = window->WindowPadding().x; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.ColumnsStartX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->WindowPadding().y) - ImVec2(0.0f, window->ScrollY); window->DC.CursorPos = window->DC.CursorStartPos; window->DC.CursorPosPrevLine = window->DC.CursorPos; window->DC.CursorMaxPos = window->DC.CursorStartPos; window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; window->DC.ChildWindows.resize(0); window->DC.ItemWidth.resize(0); window->DC.ItemWidth.push_back(window->ItemWidthDefault); window->DC.AllowKeyboardFocus.resize(0); window->DC.AllowKeyboardFocus.push_back(true); window->DC.TextWrapPos.resize(0); window->DC.TextWrapPos.push_back(-1.0f); // disabled window->DC.ColorEditMode = ImGuiColorEditMode_UserSelect; window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = 1; window->DC.ColumnsStartPos = window->DC.CursorPos; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.ColumnsStartPos.y; window->DC.TreeDepth = 0; window->DC.StateStorage = &window->StateStorage; window->DC.GroupStack.resize(0); if (window->AutoFitFrames > 0) window->AutoFitFrames--; // Title bar if (!(window->Flags & ImGuiWindowFlags_NoTitleBar)) { if (p_opened != NULL) CloseWindowButton(p_opened); ImVec2 text_min = window->Pos + style.FramePadding; if (!(window->Flags & ImGuiWindowFlags_NoCollapse)) { RenderCollapseTriangle(window->Pos + style.FramePadding, !window->Collapsed, 1.0f, true); text_min.x += g.FontSize + style.ItemInnerSpacing.x; } const ImVec2 text_size = CalcTextSize(name, NULL, true); const ImVec2 text_max = window->Pos + ImVec2(window->Size.x - (p_opened ? (title_bar_rect.GetHeight()-3) : style.FramePadding.x), style.FramePadding.y*2 + text_size.y); RenderTextClipped(text_min, name, NULL, &text_size, text_max); } if (window->Flags & ImGuiWindowFlags_Popup) { if (p_opened) { if (g.IO.MouseClicked[0] && (!g.HoveredWindow || g.HoveredWindow->RootWindow != window)) *p_opened = false; else if (!g.FocusedWindow) *p_opened = false; else if (g.FocusedWindow->RootWindow != window)// && !(g.FocusedWindow->RootWindow->Flags & ImGuiWindowFlags_Tooltip)) *p_opened = false; } } // Save clipped aabb so we can access it in constant-time in FindHoveredWindow() window->ClippedRect = window->Rect(); window->ClippedRect.Clip(window->ClipRectStack.front()); // Pressing CTRL+C while holding on a window copy its content to the clipboard // This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope. // Maybe we can support CTRL+C on every element? /* if (g.ActiveId == move_id) if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C)) ImGui::LogToClipboard(); */ } // Inner clipping rectangle // We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame // Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior. const ImRect title_bar_rect = window->TitleBarRect(); ImVec4 clip_rect(title_bar_rect.Min.x+0.5f+window->WindowPadding().x*0.5f, title_bar_rect.Max.y+0.5f, window->Rect().Max.x+0.5f-window->WindowPadding().x*0.5f, window->Rect().Max.y-1.5f); if (window->ScrollbarY) clip_rect.z -= style.ScrollbarWidth; PushClipRect(clip_rect); // Clear 'accessed' flag last thing if (first_begin_of_the_frame) window->Accessed = false; // Child window can be out of sight and have "negative" clip windows. // Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar). if (flags & ImGuiWindowFlags_ChildWindow) { IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0); window->Collapsed = parent_window && parent_window->Collapsed; const ImVec4 clip_rect_t = window->ClipRectStack.back(); window->Collapsed |= (clip_rect_t.x >= clip_rect_t.z || clip_rect_t.y >= clip_rect_t.w); // We also hide the window from rendering because we've already added its border to the command list. // (we could perform the check earlier in the function but it is simpler at this point) if (window->Collapsed) window->Visible = false; } if (style.Alpha <= 0.0f) window->Visible = false; // Return false if we don't intend to display anything to allow user to perform an early out optimization window->SkipItems = (window->Collapsed || !window->Visible) && window->AutoFitFrames <= 0; return !window->SkipItems; } void ImGui::End() { ImGuiState& g = *GImGui; ImGuiWindow* window = g.CurrentWindow; ImGui::Columns(1, "#CloseColumns"); PopClipRect(); // inner window clip rectangle PopClipRect(); // outer window clip rectangle window->DrawList->PopTextureID(); // Stop logging if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging ImGui::LogFinish(); // Pop // NB: we don't clear 'window->RootWindow'. The pointer is allowed to live until the next call to Begin(). g.CurrentWindowStack.pop_back(); SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back()); } // Vertical scrollbar // The entire piece of code below is rather confusing because: // - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab) // - We store values as ratio and in a form that allows the window content to change while we are holding on a scrollbar static void Scrollbar(ImGuiWindow* window) { ImGuiState& g = *GImGui; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#SCROLLY"); // Render background ImRect bb(window->Rect().Max.x - style.ScrollbarWidth, window->Pos.y + window->TitleBarHeight()+1, window->Rect().Max.x, window->Rect().Max.y-1); window->DrawList->AddRectFilled(bb.Min, bb.Max, window->Color(ImGuiCol_ScrollbarBg)); bb.Expand(-3.0f); const float scrollbar_height = bb.GetHeight(); // The grabable box size generally represent the amount visible (vs the total scrollable amount) // But we maintain a minimum size in pixel to allow for the user to still aim inside. const float grab_h_pixels = ImMin(ImMax(scrollbar_height * ImSaturate(window->Size.y / ImMax(window->SizeContents.y, window->Size.y)), style.GrabMinSize), scrollbar_height); const float grab_h_norm = grab_h_pixels / scrollbar_height; // Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar(). bool held = false; bool hovered = false; const bool previously_held = (g.ActiveId == id); ButtonBehavior(bb, id, &hovered, &held, true); const float scroll_max = ImMax(1.0f, window->SizeContents.y - window->Size.y); float scroll_ratio = ImSaturate(window->ScrollY / scroll_max); float grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; if (held) { const float clicked_y_norm = ImSaturate((g.IO.MousePos.y - bb.Min.y) / scrollbar_height); // Click position in scrollbar space (0.0f->1.0f) g.HoveredId = id; bool seek_absolute = false; if (!previously_held) { // On initial click calculate the distance between mouse and the center of the grab if (clicked_y_norm >= grab_y_norm && clicked_y_norm <= grab_y_norm + grab_h_norm) { g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; } else { seek_absolute = true; g.ScrollbarClickDeltaToGrabCenter = 0; } } // Apply scroll const float scroll_y_norm = ImSaturate((clicked_y_norm - g.ScrollbarClickDeltaToGrabCenter - grab_h_norm*0.5f) / (1.0f - grab_h_norm)); window->ScrollY = (float)(int)(0.5f + scroll_y_norm * (window->SizeContents.y - window->Size.y)); window->NextScrollY = window->ScrollY; // Update values for rendering scroll_ratio = ImSaturate(window->ScrollY / scroll_max); grab_y_norm = scroll_ratio * (scrollbar_height - grab_h_pixels) / scrollbar_height; // Update distance to grab now that we have seeked and saturated if (seek_absolute) g.ScrollbarClickDeltaToGrabCenter = clicked_y_norm - grab_y_norm - grab_h_norm*0.5f; } // Render const ImU32 grab_col = window->Color(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab); window->DrawList->AddRectFilled(ImVec2(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm)), ImVec2(bb.Max.x, ImLerp(bb.Min.y, bb.Max.y, grab_y_norm) + grab_h_pixels), grab_col); } // Moving window to front of display (which happens to be back of our sorted list) static void FocusWindow(ImGuiWindow* window) { ImGuiState& g = *GImGui; // Always mark the window we passed as focused. This is used for keyboard interactions such as tabbing. g.FocusedWindow = window; // Passing NULL allow to disable keyboard focus if (!window) return; // And move its root window to the top of the pile if (window->RootWindow) window = window->RootWindow; if (g.Windows.back() == window) return; for (size_t i = 0; i < g.Windows.size(); i++) if (g.Windows[i] == window) { g.Windows.erase(g.Windows.begin() + i); break; } g.Windows.push_back(window); } void ImGui::PushItemWidth(float item_width) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth.push_back(item_width == 0.0f ? window->ItemWidthDefault : item_width); } void ImGui::PopItemWidth() { ImGuiWindow* window = GetCurrentWindow(); window->DC.ItemWidth.pop_back(); } float ImGui::CalcItemWidth() { ImGuiWindow* window = GetCurrentWindow(); float w = window->DC.ItemWidth.back(); if (w < 0.0f) { // Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well. ImGuiState& g = *GImGui; w = -w; float width_to_right_edge = window->Pos.x + ImGui::GetContentRegionMax().x - window->DC.CursorPos.x; w = ImMax(1.0f, width_to_right_edge - w - g.Style.FramePadding.x * 2.0f); } w = (float)(int)w; return w; } static void SetFont(ImFont* font) { ImGuiState& g = *GImGui; IM_ASSERT(font && font->IsLoaded()); IM_ASSERT(font->Scale > 0.0f); g.Font = font; g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale; g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f; g.FontTexUvWhitePixel = g.Font->ContainerAtlas->TexUvWhitePixel; } void ImGui::PushFont(ImFont* font) { ImGuiState& g = *GImGui; if (!font) font = g.IO.Fonts->Fonts[0]; SetFont(font); g.FontStack.push_back(font); g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID); } void ImGui::PopFont() { ImGuiState& g = *GImGui; g.CurrentWindow->DrawList->PopTextureID(); g.FontStack.pop_back(); SetFont(g.FontStack.empty() ? g.IO.Fonts->Fonts[0] : g.FontStack.back()); } void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus) { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocus.push_back(allow_keyboard_focus); } void ImGui::PopAllowKeyboardFocus() { ImGuiWindow* window = GetCurrentWindow(); window->DC.AllowKeyboardFocus.pop_back(); } void ImGui::PushTextWrapPos(float wrap_x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos.push_back(wrap_x); } void ImGui::PopTextWrapPos() { ImGuiWindow* window = GetCurrentWindow(); window->DC.TextWrapPos.pop_back(); } void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col) { ImGuiState& g = *GImGui; ImGuiColMod backup; backup.Col = idx; backup.PreviousValue = g.Style.Colors[idx]; g.ColorModifiers.push_back(backup); g.Style.Colors[idx] = col; } void ImGui::PopStyleColor(int count) { ImGuiState& g = *GImGui; while (count > 0) { ImGuiColMod& backup = g.ColorModifiers.back(); g.Style.Colors[backup.Col] = backup.PreviousValue; g.ColorModifiers.pop_back(); count--; } } static float* GetStyleVarFloatAddr(ImGuiStyleVar idx) { ImGuiState& g = *GImGui; switch (idx) { case ImGuiStyleVar_Alpha: return &g.Style.Alpha; case ImGuiStyleVar_WindowRounding: return &g.Style.WindowRounding; case ImGuiStyleVar_ChildWindowRounding: return &g.Style.ChildWindowRounding; case ImGuiStyleVar_FrameRounding: return &g.Style.FrameRounding; case ImGuiStyleVar_IndentSpacing: return &g.Style.IndentSpacing; case ImGuiStyleVar_GrabMinSize: return &g.Style.GrabMinSize; } return NULL; } static ImVec2* GetStyleVarVec2Addr(ImGuiStyleVar idx) { ImGuiState& g = *GImGui; switch (idx) { case ImGuiStyleVar_WindowPadding: return &g.Style.WindowPadding; case ImGuiStyleVar_FramePadding: return &g.Style.FramePadding; case ImGuiStyleVar_ItemSpacing: return &g.Style.ItemSpacing; case ImGuiStyleVar_ItemInnerSpacing: return &g.Style.ItemInnerSpacing; } return NULL; } void ImGui::PushStyleVar(ImGuiStyleVar idx, float val) { ImGuiState& g = *GImGui; float* pvar = GetStyleVarFloatAddr(idx); IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a float. ImGuiStyleMod backup; backup.Var = idx; backup.PreviousValue = ImVec2(*pvar, 0.0f); g.StyleModifiers.push_back(backup); *pvar = val; } void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val) { ImGuiState& g = *GImGui; ImVec2* pvar = GetStyleVarVec2Addr(idx); IM_ASSERT(pvar != NULL); // Called function with wrong-type? Variable is not a ImVec2. ImGuiStyleMod backup; backup.Var = idx; backup.PreviousValue = *pvar; g.StyleModifiers.push_back(backup); *pvar = val; } void ImGui::PopStyleVar(int count) { ImGuiState& g = *GImGui; while (count > 0) { ImGuiStyleMod& backup = g.StyleModifiers.back(); if (float* pvar_f = GetStyleVarFloatAddr(backup.Var)) *pvar_f = backup.PreviousValue.x; else if (ImVec2* pvar_v = GetStyleVarVec2Addr(backup.Var)) *pvar_v = backup.PreviousValue; g.StyleModifiers.pop_back(); count--; } } const char* ImGui::GetStyleColName(ImGuiCol idx) { // Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1"; switch (idx) { case ImGuiCol_Text: return "Text"; case ImGuiCol_WindowBg: return "WindowBg"; case ImGuiCol_ChildWindowBg: return "ChildWindowBg"; case ImGuiCol_Border: return "Border"; case ImGuiCol_BorderShadow: return "BorderShadow"; case ImGuiCol_FrameBg: return "FrameBg"; case ImGuiCol_FrameBgHovered: return "FrameBgHovered"; case ImGuiCol_FrameBgActive: return "FrameBgActive"; case ImGuiCol_TitleBg: return "TitleBg"; case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed"; case ImGuiCol_ScrollbarBg: return "ScrollbarBg"; case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab"; case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered"; case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive"; case ImGuiCol_ComboBg: return "ComboBg"; case ImGuiCol_CheckMark: return "CheckMark"; case ImGuiCol_SliderGrab: return "SliderGrab"; case ImGuiCol_SliderGrabActive: return "SliderGrabActive"; case ImGuiCol_Button: return "Button"; case ImGuiCol_ButtonHovered: return "ButtonHovered"; case ImGuiCol_ButtonActive: return "ButtonActive"; case ImGuiCol_Header: return "Header"; case ImGuiCol_HeaderHovered: return "HeaderHovered"; case ImGuiCol_HeaderActive: return "HeaderActive"; case ImGuiCol_Column: return "Column"; case ImGuiCol_ColumnHovered: return "ColumnHovered"; case ImGuiCol_ColumnActive: return "ColumnActive"; case ImGuiCol_ResizeGrip: return "ResizeGrip"; case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered"; case ImGuiCol_ResizeGripActive: return "ResizeGripActive"; case ImGuiCol_CloseButton: return "CloseButton"; case ImGuiCol_CloseButtonHovered: return "CloseButtonHovered"; case ImGuiCol_CloseButtonActive: return "CloseButtonActive"; case ImGuiCol_PlotLines: return "PlotLines"; case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered"; case ImGuiCol_PlotHistogram: return "PlotHistogram"; case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered"; case ImGuiCol_TextSelectedBg: return "TextSelectedBg"; case ImGuiCol_TooltipBg: return "TooltipBg"; } IM_ASSERT(0); return "Unknown"; } bool ImGui::IsWindowFocused() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); return g.FocusedWindow == window; } bool ImGui::IsRootWindowFocused() { ImGuiState& g = *GImGui; ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; return g.FocusedWindow == root_window; } bool ImGui::IsRootWindowOrAnyChildFocused() { ImGuiState& g = *GImGui; ImGuiWindow* root_window = GetCurrentWindow()->RootWindow; return g.FocusedWindow && g.FocusedWindow->RootWindow == root_window; } float ImGui::GetWindowWidth() { ImGuiWindow* window = GetCurrentWindow(); return window->Size.x; } ImVec2 ImGui::GetWindowPos() { ImGuiWindow* window = GetCurrentWindow(); return window->Pos; } static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowPosAllowFlags & cond) == 0) return; window->SetWindowPosAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); // Set const ImVec2 old_pos = window->Pos; window->PosFloat = pos; window->Pos = ImVec2((float)(int)window->PosFloat.x, (float)(int)window->PosFloat.y); window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected. } void ImGui::SetWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiWindow* window = GetCurrentWindow(); SetWindowPos(window, pos, cond); } void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowPos(window, pos, cond); } ImVec2 ImGui::GetWindowSize() { ImGuiWindow* window = GetCurrentWindow(); return window->Size; } static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowSizeAllowFlags & cond) == 0) return; window->SetWindowSizeAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); // Set if (ImLengthSqr(size) > 0.00001f) { window->SizeFull = size; window->AutoFitFrames = 0; } else { // Autofit window->AutoFitFrames = 2; window->AutoFitOnlyGrows = false; } } void ImGui::SetWindowSize(const ImVec2& size, ImGuiSetCond cond) { ImGuiWindow* window = GetCurrentWindow(); SetWindowSize(window, size, cond); } void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowSize(window, size, cond); } static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiSetCond cond) { // Test condition (NB: bit 0 is always true) and clear flags for next time if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0) return; window->SetWindowCollapsedAllowFlags &= ~(ImGuiSetCond_Once | ImGuiSetCond_FirstUseEver); // Set window->Collapsed = collapsed; } void ImGui::SetWindowCollapsed(bool collapsed, ImGuiSetCond cond) { ImGuiWindow* window = GetCurrentWindow(); SetWindowCollapsed(window, collapsed, cond); } bool ImGui::GetWindowCollapsed() { ImGuiWindow* window = GetCurrentWindow(); return window->Collapsed; } void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiSetCond cond) { ImGuiWindow* window = FindWindowByName(name); if (window) SetWindowCollapsed(window, collapsed, cond); } void ImGui::SetWindowFocus() { ImGuiWindow* window = GetCurrentWindow(); FocusWindow(window); } void ImGui::SetWindowFocus(const char* name) { if (name) { ImGuiWindow* window = FindWindowByName(name); if (window) FocusWindow(window); } else { FocusWindow(NULL); } } void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiSetCond cond) { ImGuiState& g = *GImGui; g.SetNextWindowPosVal = pos; g.SetNextWindowPosCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiSetCond cond) { ImGuiState& g = *GImGui; g.SetNextWindowSizeVal = size; g.SetNextWindowSizeCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiSetCond cond) { ImGuiState& g = *GImGui; g.SetNextWindowCollapsedVal = collapsed; g.SetNextWindowCollapsedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::SetNextWindowFocus() { ImGuiState& g = *GImGui; g.SetNextWindowFocus = true; } ImVec2 ImGui::GetContentRegionMax() { ImGuiWindow* window = GetCurrentWindow(); ImVec2 window_padding = window->WindowPadding(); ImVec2 mx = window->Size - window_padding; if (window->DC.ColumnsCount != 1) { mx.x = ImGui::GetColumnOffset(window->DC.ColumnsCurrent + 1); mx.x -= window_padding.x; } else { if (window->ScrollbarY) mx.x -= GImGui->Style.ScrollbarWidth; } return mx; } ImVec2 ImGui::GetWindowContentRegionMin() { ImGuiWindow* window = GetCurrentWindow(); return ImVec2(0, window->TitleBarHeight()) + window->WindowPadding(); } ImVec2 ImGui::GetWindowContentRegionMax() { ImGuiWindow* window = GetCurrentWindow(); ImVec2 m = window->Size - window->WindowPadding(); if (window->ScrollbarY) m.x -= GImGui->Style.ScrollbarWidth; return m; } float ImGui::GetTextLineHeight() { ImGuiState& g = *GImGui; return g.FontSize; } float ImGui::GetTextLineHeightWithSpacing() { ImGuiState& g = *GImGui; return g.FontSize + g.Style.ItemSpacing.y; } ImDrawList* ImGui::GetWindowDrawList() { ImGuiWindow* window = GetCurrentWindow(); return window->DrawList; } ImFont* ImGui::GetWindowFont() { ImGuiState& g = *GImGui; return g.Font; } float ImGui::GetWindowFontSize() { ImGuiState& g = *GImGui; return g.FontSize; } void ImGui::SetWindowFontScale(float scale) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->FontWindowScale = scale; g.FontSize = window->CalcFontSize(); } // NB: internally we store CursorPos in absolute screen coordinates because it is more convenient. // Conversion happens as we pass the value to user, but it makes our naming convention dodgy. May want to rename 'DC.CursorPos'. ImVec2 ImGui::GetCursorPos() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.CursorPos - window->Pos; } float ImGui::GetCursorPosX() { return ImGui::GetCursorPos().x; } float ImGui::GetCursorPosY() { return ImGui::GetCursorPos().y; } void ImGui::SetCursorPos(const ImVec2& pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = window->Pos + pos; window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos); } void ImGui::SetCursorPosX(float x) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.x = window->Pos.x + x; window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x); } void ImGui::SetCursorPosY(float y) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos.y = window->Pos.y + y; window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); } ImVec2 ImGui::GetCursorScreenPos() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.CursorPos; } void ImGui::SetCursorScreenPos(const ImVec2& screen_pos) { ImGuiWindow* window = GetCurrentWindow(); window->DC.CursorPos = screen_pos; } float ImGui::GetScrollPosY() { ImGuiWindow* window = GetCurrentWindow(); return window->ScrollY; } float ImGui::GetScrollMaxY() { ImGuiWindow* window = GetCurrentWindow(); return window->SizeContents.y - window->SizeFull.y; } void ImGui::SetScrollPosHere() { ImGuiWindow* window = GetCurrentWindow(); window->NextScrollY = (window->DC.CursorPos.y + window->ScrollY) - (window->Pos.y + window->SizeFull.y * 0.5f) - (window->TitleBarHeight() + window->WindowPadding().y); } void ImGui::SetKeyboardFocusHere(int offset) { ImGuiWindow* window = GetCurrentWindow(); window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset; window->FocusIdxTabRequestNext = IM_INT_MAX; } void ImGui::SetStateStorage(ImGuiStorage* tree) { ImGuiWindow* window = GetCurrentWindow(); window->DC.StateStorage = tree ? tree : &window->StateStorage; } ImGuiStorage* ImGui::GetStateStorage() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.StateStorage; } void ImGui::TextV(const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); TextUnformatted(g.TempBuffer, text_end); } void ImGui::Text(const char* fmt, ...) { va_list args; va_start(args, fmt); TextV(fmt, args); va_end(args); } void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args) { ImGui::PushStyleColor(ImGuiCol_Text, col); TextV(fmt, args); ImGui::PopStyleColor(); } void ImGui::TextColored(const ImVec4& col, const char* fmt, ...) { va_list args; va_start(args, fmt); TextColoredV(col, fmt, args); va_end(args); } void ImGui::TextWrappedV(const char* fmt, va_list args) { ImGui::PushTextWrapPos(0.0f); TextV(fmt, args); ImGui::PopTextWrapPos(); } void ImGui::TextWrapped(const char* fmt, ...) { va_list args; va_start(args, fmt); TextWrappedV(fmt, args); va_end(args); } void ImGui::TextUnformatted(const char* text, const char* text_end) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; IM_ASSERT(text != NULL); const char* text_begin = text; if (text_end == NULL) text_end = text + strlen(text); // FIXME-OPT const float wrap_pos_x = window->DC.TextWrapPos.back(); const bool wrap_enabled = wrap_pos_x >= 0.0f; if (text_end - text > 2000 && !wrap_enabled) { // Long text! // Perform manual coarse clipping to optimize for long multi-line text // From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled. // We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line. const char* line = text; const float line_height = ImGui::GetTextLineHeight(); const ImVec2 text_pos = window->DC.CursorPos + ImVec2(0.0f, window->DC.CurrentLineTextBaseOffset); const ImVec4 clip_rect = window->ClipRectStack.back(); ImVec2 text_size(0,0); if (text_pos.y <= clip_rect.w) { ImVec2 pos = text_pos; // Lines to skip (can't skip when logging text) if (!g.LogEnabled) { int lines_skippable = (int)((clip_rect.y - text_pos.y) / line_height) - 1; if (lines_skippable > 0) { int lines_skipped = 0; while (line < text_end && lines_skipped <= lines_skippable) { const char* line_end = strchr(line, '\n'); line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } } // Lines to render if (line < text_end) { ImRect line_rect(pos, pos + ImVec2(ImGui::GetWindowWidth(), line_height)); while (line < text_end) { const char* line_end = strchr(line, '\n'); if (IsClippedEx(line_rect, NULL, false)) break; const ImVec2 line_size = CalcTextSize(line, line_end, false); text_size.x = ImMax(text_size.x, line_size.x); RenderText(pos, line, line_end, false); if (!line_end) line_end = text_end; line = line_end + 1; line_rect.Min.y += line_height; line_rect.Max.y += line_height; pos.y += line_height; } // Count remaining lines int lines_skipped = 0; while (line < text_end) { const char* line_end = strchr(line, '\n'); if (!line_end) line_end = text_end; line = line_end + 1; lines_skipped++; } pos.y += lines_skipped * line_height; } text_size.y += (pos - text_pos).y; } ImRect bb(text_pos, text_pos + text_size); ItemSize(bb); ItemAdd(bb, NULL); } else { const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f; const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width); // Account of baseline offset ImVec2 text_pos = window->DC.CursorPos; text_pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb(text_pos, text_pos + text_size); ItemSize(bb.GetSize()); if (!ItemAdd(bb, NULL)) return; // Render (we don't hide text after ## in this end-user function) RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width); } } void ImGui::AlignFirstTextHeightToWidgets() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Declare a dummy item size to that upcoming items that are smaller will center-align on the newly expanded line height. ItemSize(ImVec2(0, g.FontSize + g.Style.FramePadding.y*2), g.Style.FramePadding.y); ImGui::SameLine(0, 0); } // Add a label+text combo aligned to other label+value widgets void ImGui::LabelTextV(const char* label, const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImGuiStyle& style = g.Style; const float w = ImGui::CalcItemWidth(); const char* value_text_begin = &g.TempBuffer[0]; const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2, label_size.y + style.FramePadding.y*2)); const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + style.FramePadding.x*2 + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Render RenderTextClipped(ImVec2(value_bb.Min.x, value_bb.Min.y + style.FramePadding.y), value_text_begin, value_text_end, NULL, value_bb.Max); RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label); } void ImGui::LabelText(const char* label, const char* fmt, ...) { va_list args; va_start(args, fmt); LabelTextV(label, fmt, args); va_end(args); } static inline bool IsWindowContentHoverable(ImGuiWindow* window) { ImGuiState& g = *GImGui; // An active popup disable hovering on other windows (apart from its own children) if (ImGuiWindow* focused_window = g.FocusedWindow) if (ImGuiWindow* focused_root_window = focused_window->RootWindow) if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) != 0 && focused_root_window->WasVisible && focused_root_window != window->RootWindow) return false; return true; } static bool IsHovered(const ImRect& bb, ImGuiID id) { ImGuiState& g = *GImGui; if (g.HoveredId == 0) { ImGuiWindow* window = GetCurrentWindow(); if (g.HoveredRootWindow == window->RootWindow) if ((g.ActiveId == 0 || g.ActiveId == id || g.ActiveIdIsFocusedOnly) && IsMouseHoveringRect(bb)) if (IsWindowContentHoverable(g.HoveredRootWindow)) return true; } return false; } static bool ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, bool allow_key_modifiers, bool repeat, bool pressed_on_click) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const bool hovered = IsHovered(bb, id); bool pressed = false; if (hovered) { g.HoveredId = id; if (allow_key_modifiers || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt)) { if (g.IO.MouseClicked[0]) { if (pressed_on_click) { pressed = true; SetActiveId(0); } else { SetActiveId(id); } FocusWindow(window); } else if (repeat && g.ActiveId && ImGui::IsMouseClicked(0, true)) { pressed = true; } } } bool held = false; if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { held = true; } else { if (hovered) pressed = true; SetActiveId(0); } } if (out_hovered) *out_hovered = hovered; if (out_held) *out_held = held; return pressed; } bool ImGui::Button(const char* label, const ImVec2& size_arg, bool repeat_when_held) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : (label_size.x + style.FramePadding.x*2), size_arg.y != 0.0f ? size_arg.y : (label_size.y + style.FramePadding.y*2)); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true, repeat_when_held); // Render const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); const ImVec2 off = ImVec2(ImMax(0.0f, size.x - label_size.x) * 0.5f, ImMax(0.0f, size.y - label_size.y) * 0.5f); // Center (only applies if we explicitly gave a size bigger than the text size, which isn't the common path) RenderTextClipped(bb.Min + off, label, NULL, &label_size, bb.Max); // Render clip (only applies if we explicitly gave a size smaller than the text size, which isn't the commmon path) return pressed; } // Small buttons fits within text without additional spacing. bool ImGui::SmallButton(const char* label) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); ImVec2 text_pos = window->DC.CursorPos; text_pos.y += window->DC.CurrentLineTextBaseOffset; ImRect bb(text_pos, text_pos + label_size + ImVec2(style.FramePadding.x*2,0)); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); // Render const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); RenderFrame(bb.Min, bb.Max, col); RenderText(bb.Min + ImVec2(style.FramePadding.x,0), label); return pressed; } // Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack. // Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id) bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiID id = window->GetID(str_id); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); return pressed; } // Upper-right button to close a window. static bool CloseWindowButton(bool* p_opened) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiID id = window->GetID("#CLOSE"); const float size = window->TitleBarHeight() - 4.0f; const ImRect bb(window->Rect().GetTR() + ImVec2(-3.0f-size,2.0f), window->Rect().GetTR() + ImVec2(-3.0f,2.0f+size)); bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); // Render const ImU32 col = window->Color((held && hovered) ? ImGuiCol_CloseButtonActive : hovered ? ImGuiCol_CloseButtonHovered : ImGuiCol_CloseButton); const ImVec2 center = bb.GetCenter(); window->DrawList->AddCircleFilled(center, ImMax(2.0f,size*0.5f), col, 16); const float cross_extent = (size * 0.5f * 0.7071f) - 1.0f; if (hovered) { window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), window->Color(ImGuiCol_Text)); window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), window->Color(ImGuiCol_Text)); } if (p_opened != NULL && pressed) *p_opened = !*p_opened; return pressed; } void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); if (border_col.w > 0.0f) bb.Max += ImVec2(2,2); ItemSize(bb); if (!ItemAdd(bb, NULL)) return; if (border_col.w > 0.0f) { window->DrawList->AddRect(bb.Min, bb.Max, window->Color(border_col), 0.0f); window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, window->Color(tint_col)); } else { window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, window->Color(tint_col)); } } // frame_padding < 0: uses FramePadding from style (default) // frame_padding = 0: no framing // frame_padding > 0: set framing size // The color used are the button colors. bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; // Default to using texture ID as ID. User can still push string/integer prefixes. // We could hash the size/uv to create a unique ID but that would prevent the user from animating buttons. ImGui::PushID((void *)user_texture_id); const ImGuiID id = window->GetID("#image"); ImGui::PopID(); const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2); const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size); ItemSize(bb); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); // Render const ImU32 col = window->Color((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); if (padding.x > 0.0f || padding.y > 0.0f) RenderFrame(bb.Min, bb.Max, col); if (bg_col.w > 0.0f) window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, window->Color(bg_col)); window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, window->Color(tint_col)); return pressed; } // Start logging ImGui output to TTY void ImGui::LogToTTY(int max_depth) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (g.LogEnabled) return; g.LogEnabled = true; g.LogFile = stdout; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to given file void ImGui::LogToFile(int max_depth, const char* filename) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (g.LogEnabled) return; if (!filename) { filename = g.IO.LogFilename; if (!filename) return; } g.LogFile = fopen(filename, "ab"); if (!g.LogFile) { IM_ASSERT(g.LogFile != NULL); // Consider this an error return; } g.LogEnabled = true; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } // Start logging ImGui output to clipboard void ImGui::LogToClipboard(int max_depth) { ImGuiWindow* window = GetCurrentWindow(); ImGuiState& g = *GImGui; if (g.LogEnabled) return; g.LogEnabled = true; g.LogFile = NULL; g.LogStartDepth = window->DC.TreeDepth; if (max_depth >= 0) g.LogAutoExpandMaxDepth = max_depth; } void ImGui::LogFinish() { ImGuiState& g = *GImGui; if (!g.LogEnabled) return; ImGui::LogText(STR_NEWLINE); g.LogEnabled = false; if (g.LogFile != NULL) { if (g.LogFile == stdout) fflush(g.LogFile); else fclose(g.LogFile); g.LogFile = NULL; } if (g.LogClipboard->size() > 1) { if (g.IO.SetClipboardTextFn) g.IO.SetClipboardTextFn(g.LogClipboard->begin()); g.LogClipboard->clear(); } } // Helper to display logging buttons void ImGui::LogButtons() { ImGuiState& g = *GImGui; ImGui::PushID("LogButtons"); const bool log_to_tty = ImGui::Button("Log To TTY"); ImGui::SameLine(); const bool log_to_file = ImGui::Button("Log To File"); ImGui::SameLine(); const bool log_to_clipboard = ImGui::Button("Log To Clipboard"); ImGui::SameLine(); ImGui::PushItemWidth(80.0f); ImGui::PushAllowKeyboardFocus(false); ImGui::SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL); ImGui::PopAllowKeyboardFocus(); ImGui::PopItemWidth(); ImGui::PopID(); // Start logging at the end of the function so that the buttons don't appear in the log if (log_to_tty) LogToTTY(g.LogAutoExpandMaxDepth); if (log_to_file) LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename); if (log_to_clipboard) LogToClipboard(g.LogAutoExpandMaxDepth); } bool ImGui::CollapsingHeader(const char* label, const char* str_id, bool display_frame, bool default_open) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; IM_ASSERT(str_id != NULL || label != NULL); if (str_id == NULL) str_id = label; if (label == NULL) label = str_id; const ImGuiID id = window->GetID(str_id); // We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions) ImGuiStorage* storage = window->DC.StateStorage; bool opened; if (g.SetNextTreeNodeOpenedCond != 0) { if (g.SetNextTreeNodeOpenedCond & ImGuiSetCond_Always) { opened = g.SetNextTreeNodeOpenedVal; storage->SetInt(id, opened); } else { // We treat ImGuiSetCondition_Once and ImGuiSetCondition_FirstUseEver the same because tree node state are not saved persistently. const int stored_value = storage->GetInt(id, -1); if (stored_value == -1) { opened = g.SetNextTreeNodeOpenedVal; storage->SetInt(id, opened); } else { opened = stored_value != 0; } } g.SetNextTreeNodeOpenedCond = 0; } else { opened = storage->GetInt(id, default_open) != 0; } // Framed header expand a little outside the default padding const ImVec2 window_padding = window->WindowPadding(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 pos_min = window->DC.CursorPos; const ImVec2 pos_max = window->Pos + GetContentRegionMax(); ImRect bb = ImRect(pos_min, ImVec2(pos_max.x, pos_min.y + label_size.y)); if (display_frame) { bb.Min.x -= window_padding.x*0.5f - 1; bb.Max.x += window_padding.x*0.5f - 1; bb.Max.y += style.FramePadding.y * 2; } // FIXME: we don't provide our width so that it doesn't get feed back into AutoFit. Should manage that better so we can still hover without extending ContentsSize const ImRect text_bb(bb.Min, bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2*2,0) + label_size); ItemSize(ImVec2(text_bb.GetSize().x, bb.GetSize().y), display_frame ? style.FramePadding.y : 0.0f); // When logging is enabled, if automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior). // NB- If we are above max depth we still allow manually opened nodes to be logged. if (g.LogEnabled && !display_frame && window->DC.TreeDepth < g.LogAutoExpandMaxDepth) opened = true; if (!ItemAdd(bb, &id)) return opened; bool hovered, held; bool pressed = ButtonBehavior(display_frame ? bb : text_bb, id, &hovered, &held, false); if (pressed) { opened = !opened; storage->SetInt(id, opened); } // Render const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); if (display_frame) { // Framed type RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderCollapseTriangle(bb.Min + style.FramePadding, opened, 1.0f, true); if (g.LogEnabled) { // NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here. const char log_prefix[] = "\n##"; LogText(bb.Min + style.FramePadding, log_prefix, log_prefix+3); } RenderText(bb.Min + style.FramePadding + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); if (g.LogEnabled) { const char log_suffix[] = "##"; LogText(bb.Min + style.FramePadding, log_suffix, log_suffix+2); } } else { // Unframed typed for tree nodes if ((held && hovered) || hovered) RenderFrame(bb.Min, bb.Max, col, false); RenderCollapseTriangle(bb.Min + ImVec2(style.FramePadding.x, g.FontSize*0.15f), opened, 0.70f, false); if (g.LogEnabled) LogText(bb.Min, ">"); RenderText(bb.Min + ImVec2(g.FontSize + style.FramePadding.x*2,0), label); } return opened; } void ImGui::Bullet() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImGuiStyle& style = g.Style; const float line_height = g.FontSize; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height, line_height)); ItemSize(bb); if (!ItemAdd(bb, NULL)) return; // Render const float bullet_size = line_height*0.15f; window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); // Stay on same line ImGui::SameLine(0, -1); } // Text with a little bullet aligned to the typical tree node. void ImGui::BulletTextV(const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const char* text_begin = g.TempBuffer; const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); const ImGuiStyle& style = g.Style; const float line_height = g.FontSize; const ImVec2 label_size = CalcTextSize(text_begin, text_end, true); const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(line_height + (label_size.x > 0.0f ? (style.FramePadding.x*2) : 0.0f),0) + label_size); // Empty text doesn't add padding ItemSize(bb); if (!ItemAdd(bb, NULL)) return; // Render const float bullet_size = line_height*0.15f; window->DrawList->AddCircleFilled(bb.Min + ImVec2(style.FramePadding.x + line_height*0.5f, line_height*0.5f), bullet_size, window->Color(ImGuiCol_Text)); RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2,0), text_begin, text_end); } void ImGui::BulletText(const char* fmt, ...) { va_list args; va_start(args, fmt); BulletTextV(fmt, args); va_end(args); } // If returning 'true' the node is open and the user is responsible for calling TreePop bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); if (!str_id || !str_id[0]) str_id = fmt; ImGui::PushID(str_id); const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); ImGui::PopID(); if (opened) ImGui::TreePush(str_id); return opened; } bool ImGui::TreeNode(const char* str_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool s = TreeNodeV(str_id, fmt, args); va_end(args); return s; } // If returning 'true' the node is open and the user is responsible for calling TreePop bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args); if (!ptr_id) ptr_id = fmt; ImGui::PushID(ptr_id); const bool opened = ImGui::CollapsingHeader(g.TempBuffer, "", false); ImGui::PopID(); if (opened) ImGui::TreePush(ptr_id); return opened; } bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...) { va_list args; va_start(args, fmt); bool s = TreeNodeV(ptr_id, fmt, args); va_end(args); return s; } bool ImGui::TreeNode(const char* str_label_id) { return TreeNode(str_label_id, "%s", str_label_id); } void ImGui::SetNextTreeNodeOpened(bool opened, ImGuiSetCond cond) { ImGuiState& g = *GImGui; g.SetNextTreeNodeOpenedVal = opened; g.SetNextTreeNodeOpenedCond = cond ? cond : ImGuiSetCond_Always; } void ImGui::PushID(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id)); } void ImGui::PushID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(str_id_begin, str_id_end)); } void ImGui::PushID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PushID(const int int_id) { const void* ptr_id = (void*)(intptr_t)int_id; ImGuiWindow* window = GetCurrentWindow(); window->IDStack.push_back(window->GetID(ptr_id)); } void ImGui::PopID() { ImGuiWindow* window = GetCurrentWindow(); window->IDStack.pop_back(); } ImGuiID ImGui::GetID(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); return window->GetID(str_id); } ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end) { ImGuiWindow* window = GetCurrentWindow(); return window->GetID(str_id_begin, str_id_end); } ImGuiID ImGui::GetID(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); return window->GetID(ptr_id); } // User can input math operators (e.g. +100) to edit a numerical values. // NB: only call right after InputText because we are using its InitialValue storage static void ApplyNumericalTextInput(const char* buf, float *v) { while (ImCharIsSpace(*buf)) buf++; // We don't support '-' op because it would conflict with inputing negative value. // Instead you can use +-100 to subtract from an existing value char op = buf[0]; if (op == '+' || op == '*' || op == '/') { buf++; while (ImCharIsSpace(*buf)) buf++; } else { op = 0; } if (!buf[0]) return; float ref_v = *v; if (op) if (sscanf(GImGui->InputTextState.InitialText, "%f", &ref_v) < 1) return; float op_v = 0.0f; if (sscanf(buf, "%f", &op_v) < 1) return; if (op == '+') *v = ref_v + op_v; else if (op == '*') *v = ref_v * op_v; else if (op == '/') { if (op_v == 0.0f) return; *v = ref_v / op_v; } else *v = op_v; } // Create text input in place of a slider (when CTRL+Clicking on slider) static bool SliderFloatAsInputText(const char* label, float* v, ImGuiID id, int decimal_precision) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); char text_buf[64]; ImFormatString(text_buf, IM_ARRAYSIZE(text_buf), "%.*f", decimal_precision, *v); SetActiveId(g.ScalarAsInputTextId); g.HoveredId = 0; // Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen) window->FocusItemUnregister(); bool value_changed = ImGui::InputText(label, text_buf, IM_ARRAYSIZE(text_buf), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll); if (g.ScalarAsInputTextId == 0) { // First frame IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible) g.ScalarAsInputTextId = g.ActiveId; g.HoveredId = id; } else if (g.ActiveId != g.ScalarAsInputTextId) { // Release g.ScalarAsInputTextId = 0; } if (value_changed) { ApplyNumericalTextInput(text_buf, v); } return value_changed; } // Parse display precision back from the display format string static inline void ParseFormat(const char* fmt, int& decimal_precision) { while ((fmt = strchr(fmt, '%')) != NULL) { fmt++; if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%" while (*fmt >= '0' && *fmt <= '9') fmt++; if (*fmt == '.') { decimal_precision = atoi(fmt + 1); if (decimal_precision < 0 || decimal_precision > 10) decimal_precision = 3; } break; } } static inline float RoundScalar(float value, int decimal_precision) { // Round past decimal precision // 0: 1, 1: 0.1, 2: 0.01, etc. // So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0 // FIXME: Investigate better rounding methods const float min_step = 1.0f / powf(10.0f, (float)decimal_precision); const float remainder = fmodf(value, min_step); if (remainder <= min_step*0.5f) value -= remainder; else value += (min_step - remainder); return value; } static bool SliderScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, bool horizontal) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); const bool is_non_linear = fabsf(power - 1.0f) > 0.0001f; const float padding = horizontal ? style.FramePadding.x : style.FramePadding.y; const float slider_sz = horizontal ? (frame_bb.GetWidth() - padding * 2.0f) : (frame_bb.GetHeight() - padding * 2.0f); float grab_sz; if (decimal_precision > 0) grab_sz = ImMin(style.GrabMinSize, slider_sz); else grab_sz = ImMin(ImMax(1.0f * (slider_sz / (v_max-v_min+1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit const float slider_usable_sz = slider_sz - grab_sz; const float slider_usable_pos_min = (horizontal ? frame_bb.Min.x : frame_bb.Min.y) + padding + grab_sz*0.5f; const float slider_usable_pos_max = (horizontal ? frame_bb.Max.x : frame_bb.Max.y) - padding - grab_sz*0.5f; bool value_changed = false; // For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f float linear_zero_pos = 0.0f; // 0.0->1.0f if (v_min * v_max < 0.0f) { // Different sign const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power); const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power); linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0); } else { // Same sign linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f; } // Process clicking on the slider if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { const float mouse_abs_pos = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y; float normalized_pos = ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f); if (!horizontal) normalized_pos = 1.0f - normalized_pos; float new_value; if (is_non_linear) { // Account for logarithmic scale on both sides of the zero if (normalized_pos < linear_zero_pos) { // Negative: rescale to the negative range before powering float a = 1.0f - (normalized_pos / linear_zero_pos); a = powf(a, power); new_value = ImLerp(ImMin(v_max,0.0f), v_min, a); } else { // Positive: rescale to the positive range before powering float a; if (fabsf(linear_zero_pos - 1.0f) > 1.e-6) a = (normalized_pos - linear_zero_pos) / (1.0f - linear_zero_pos); else a = normalized_pos; a = powf(a, power); new_value = ImLerp(ImMax(v_min,0.0f), v_max, a); } } else { // Linear slider new_value = ImLerp(v_min, v_max, normalized_pos); } // Round past decimal precision new_value = RoundScalar(new_value, decimal_precision); if (*v != new_value) { *v = new_value; value_changed = true; } } else { SetActiveId(0); } } // Calculate slider grab positioning float grab_t; if (is_non_linear) { float v_clamped = ImClamp(*v, v_min, v_max); if (v_clamped < 0.0f) { const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min); grab_t = (1.0f - powf(f, 1.0f/power)) * linear_zero_pos; } else { const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min)); grab_t = linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos); } } else { // Linear slider grab_t = (ImClamp(*v, v_min, v_max) - v_min) / (v_max - v_min); } // Draw if (!horizontal) grab_t = 1.0f - grab_t; const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t); ImRect grab_bb; if (horizontal) grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + 2.0f), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - 2.0f)); else grab_bb = ImRect(ImVec2(frame_bb.Min.x + 2.0f, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - 2.0f, grab_pos + grab_sz*0.5f)); window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, window->Color(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab)); return value_changed; } // Use power!=1.0 for logarithmic sliders. // Adjust display_format to decorate the value with a prefix or a suffix. // "%.3f" 1.234 // "%5.2f secs" 01.23 secs // "Gold: %.0f" Gold: 1 bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = ImGui::CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) g.HoveredId = id; if (!display_format) display_format = "%.3f"; int decimal_precision = 3; ParseFormat(display_format, decimal_precision); // Tabbing or CTRL-clicking on Slider turns it into an input box bool start_text_input = false; const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); if (tab_focus_requested || (hovered && g.IO.MouseClicked[0])) { SetActiveId(id); FocusWindow(window); const bool is_ctrl_down = g.IO.KeyCtrl; if (tab_focus_requested || is_ctrl_down) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return SliderFloatAsInputText(label, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual slider behavior + render grab const bool value_changed = SliderScalarBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, true); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, frame_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); ItemSize(bb, style.FramePadding.y); if (!ItemAdd(frame_bb, &id)) return false; const bool hovered = IsHovered(frame_bb, id); if (hovered) g.HoveredId = id; if (!display_format) display_format = "%.3f"; int decimal_precision = 3; ParseFormat(display_format, decimal_precision); if (hovered && g.IO.MouseClicked[0]) { SetActiveId(id); FocusWindow(window); } // Actual slider behavior + render grab bool value_changed = SliderScalarBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, false); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. // For the vertical slider we allow centered text to overlap the frame padding char value_buf[64]; char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x, frame_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); return value_changed; } bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max) { float v_deg = (*v_rad) * 360.0f / (2*PI); bool value_changed = ImGui::SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f); *v_rad = v_deg * (2*PI) / 360.0f; return value_changed; } bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = ImGui::SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = ImGui::VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f); *v = (int)v_f; return value_changed; } // Add multiple sliders on 1 line for compact edition of multiple components static bool SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::SliderFloat("##v", &v[i], v_min, v_max, display_format, power); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 2, v_min, v_max, display_format, power); } bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 3, v_min, v_max, display_format, power); } bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power) { return SliderFloatN(label, v, 4, v_min, v_max, display_format, power); } static bool SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::SliderInt("##v", &v[i], v_min, v_max, display_format); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 2, v_min, v_max, display_format); } bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 3, v_min, v_max, display_format); } bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format) { return SliderIntN(label, v, 4, v_min, v_max, display_format); } // FIXME-WIP: Work in progress. May change API / behavior. static bool DragScalarBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = g.Style; // Draw frame const ImU32 frame_col = window->Color(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg); RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding); bool value_changed = false; // Process clicking on the drag if (g.ActiveId == id) { if (g.IO.MouseDown[0]) { if (g.ActiveIdIsJustActivated) { // Lock current value on click g.DragCurrentValue = *v; g.DragLastMouseDelta = ImVec2(0.f, 0.f); } const ImVec2 mouse_drag_delta = ImGui::GetMouseDragDelta(0, 1.0f); if (fabsf(mouse_drag_delta.x - g.DragLastMouseDelta.x) > 0.0f) { float speed = v_speed; if (speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX) speed = (v_max - v_min) * g.DragSpeedDefaultRatio; if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f) speed = speed * g.DragSpeedScaleFast; if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f) speed = speed * g.DragSpeedScaleSlow; float v_cur = g.DragCurrentValue; float delta = (mouse_drag_delta.x - g.DragLastMouseDelta.x) * speed; if (fabsf(power - 1.0f) > 0.001f) { // Logarithmic curve on both side of 0.0 float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur; float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f; float v1 = powf(v0_abs, 1.0f / power) + (delta * v0_sign); float v1_abs = v1 >= 0.0f ? v1 : -v1; float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign } else { v_cur += delta; } g.DragLastMouseDelta.x = mouse_drag_delta.x; // Clamp if (v_min < v_max) v_cur = ImClamp(v_cur, v_min, v_max); g.DragCurrentValue = v_cur; // Round to user desired precision, then apply v_cur = RoundScalar(v_cur, decimal_precision); if (*v != v_cur) { *v = v_cur; value_changed = true; } } } else { SetActiveId(0); } } return value_changed; } bool ImGui::DragFloat(const char* label, float *v, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = ImGui::CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); // NB- we don't call ItemSize() yet because we may turn into a text edit box below if (!ItemAdd(total_bb, &id)) { ItemSize(total_bb, style.FramePadding.y); return false; } const bool hovered = IsHovered(frame_bb, id); if (hovered) g.HoveredId = id; if (!display_format) display_format = "%.3f"; int decimal_precision = 3; ParseFormat(display_format, decimal_precision); // Tabbing or CTRL-clicking on Drag turns it into an input box bool start_text_input = false; const bool tab_focus_requested = window->FocusItemRegister(g.ActiveId == id); if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] | g.IO.MouseDoubleClicked[0]))) { SetActiveId(id); FocusWindow(window); if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0]) { start_text_input = true; g.ScalarAsInputTextId = 0; } } if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id)) return SliderFloatAsInputText(label, v, id, decimal_precision); ItemSize(total_bb, style.FramePadding.y); // Actual drag behavior const bool value_changed = DragScalarBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power); // Display value using user-provided display format so user can add prefix/suffix/decorations to the value. char value_buf[64]; const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v); const ImVec2 value_text_size = CalcTextSize(value_buf, value_buf_end, true); RenderTextClipped(ImVec2(ImMax(frame_bb.Min.x + style.FramePadding.x, inner_bb.GetCenter().x - value_text_size.x*0.5f), frame_bb.Min.y + style.FramePadding.y), value_buf, value_buf_end, &value_text_size, frame_bb.Max); if (label_size.x > 0.0f) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); return value_changed; } static bool DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat3(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power); } bool ImGui::DragFloat4(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power) { return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power); } // NB: v_speed is float to allow adjusting the drag speed with more precision bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format) { if (!display_format) display_format = "%.0f"; float v_f = (float)*v; bool value_changed = ImGui::DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format); *v = (int)v_f; return value_changed; } static bool DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x)*(components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::DragInt("##v", &v[i], v_speed, v_min, v_max, display_format); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format); } bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format) { return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format); } enum ImGuiPlotType { ImGuiPlotType_Lines, ImGuiPlotType_Histogram }; static void Plot(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; const ImGuiStyle& style = g.Style; const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); if (graph_size.x == 0.0f) graph_size.x = ImGui::CalcItemWidth() + (style.FramePadding.x * 2); if (graph_size.y == 0.0f) graph_size.y = label_size.y + (style.FramePadding.y * 2); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y)); const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, NULL)) return; // Determine scale from values if not specified if (scale_min == FLT_MAX || scale_max == FLT_MAX) { float v_min = FLT_MAX; float v_max = -FLT_MAX; for (int i = 0; i < values_count; i++) { const float v = values_getter(data, i); v_min = ImMin(v_min, v); v_max = ImMax(v_max, v); } if (scale_min == FLT_MAX) scale_min = v_min; if (scale_max == FLT_MAX) scale_max = v_max; } RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); int res_w = ImMin((int)graph_size.x, values_count); if (plot_type == ImGuiPlotType_Lines) res_w -= 1; // Tooltip on hover int v_hovered = -1; if (IsMouseHoveringRect(inner_bb)) { const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f); const int v_idx = (int)(t * (values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0))); IM_ASSERT(v_idx >= 0 && v_idx < values_count); const float v0 = values_getter(data, (v_idx + values_offset) % values_count); const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count); if (plot_type == ImGuiPlotType_Lines) ImGui::SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1); else if (plot_type == ImGuiPlotType_Histogram) ImGui::SetTooltip("%d: %8.4g", v_idx, v0); v_hovered = v_idx; } const float t_step = 1.0f / (float)res_w; float v0 = values_getter(data, (0 + values_offset) % values_count); float t0 = 0.0f; ImVec2 p0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) / (scale_max - scale_min)) ); const ImU32 col_base = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram); const ImU32 col_hovered = window->Color((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered); for (int n = 0; n < res_w; n++) { const float t1 = t0 + t_step; const int v_idx = (int)(t0 * values_count); IM_ASSERT(v_idx >= 0 && v_idx < values_count); const float v1 = values_getter(data, (v_idx + values_offset + 1) % values_count); const ImVec2 p1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) / (scale_max - scale_min)) ); // NB- Draw calls are merged together by the DrawList system. if (plot_type == ImGuiPlotType_Lines) window->DrawList->AddLine(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, p1), v_hovered == v_idx ? col_hovered : col_base); else if (plot_type == ImGuiPlotType_Histogram) window->DrawList->AddRectFilled(ImLerp(inner_bb.Min, inner_bb.Max, p0), ImLerp(inner_bb.Min, inner_bb.Max, ImVec2(p1.x, 1.0f))+ImVec2(-1,0), v_hovered == v_idx ? col_hovered : col_base); t0 = t1; p0 = p1; } // Text overlay if (overlay_text) RenderText(ImVec2(inner_bb.GetCenter().x - ImGui::CalcTextSize(overlay_text, NULL, true).x*0.5f, frame_bb.Min.y + style.FramePadding.y), overlay_text); RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label); } struct ImGuiPlotArrayGetterData { const float* Values; size_t Stride; ImGuiPlotArrayGetterData(const float* values, size_t stride) { Values = values; Stride = stride; } }; static float Plot_ArrayGetter(void* data, int idx) { ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data; const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride); return v; } void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) { ImGuiPlotArrayGetterData data(values, stride); Plot(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { Plot(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, size_t stride) { ImGuiPlotArrayGetterData data(values, stride); Plot(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size) { Plot(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size); } bool ImGui::Checkbox(const char* label, bool* v) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, (int)style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max)); } if (!ItemAdd(total_bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); if (pressed) *v = !(*v); RenderFrame(check_bb.Min, check_bb.Max, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding); if (*v) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; window->DrawList->AddRectFilled(check_bb.Min+ImVec2(pad,pad), check_bb.Max-ImVec2(pad,pad), window->Color(ImGuiCol_CheckMark), style.FrameRounding); } if (g.LogEnabled) LogText(text_bb.GetTL(), *v ? "[x]" : "[ ]"); RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value) { bool v = (*flags & flags_value) ? true : false; bool pressed = ImGui::Checkbox(label, &v); if (v) *flags |= flags_value; else *flags &= ~flags_value; return pressed; } bool ImGui::RadioButton(const char* label, bool active) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1)); ItemSize(check_bb, style.FramePadding.y); ImRect total_bb = check_bb; if (label_size.x > 0) SameLine(0, (int)style.ItemInnerSpacing.x); const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size); if (label_size.x > 0) { ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y); total_bb.Add(text_bb); } if (!ItemAdd(total_bb, &id)) return false; ImVec2 center = check_bb.GetCenter(); center.x = (float)(int)center.x + 0.5f; center.y = (float)(int)center.y + 0.5f; const float radius = check_bb.GetHeight() * 0.5f; bool hovered, held; bool pressed = ButtonBehavior(total_bb, id, &hovered, &held, true); window->DrawList->AddCircleFilled(center, radius, window->Color((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16); if (active) { const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight()); const float pad = check_sz < 8.0f ? 1.0f : check_sz < 13.0f ? 2.0f : 3.0f; window->DrawList->AddCircleFilled(center, radius-pad, window->Color(ImGuiCol_CheckMark), 16); } if (window->Flags & ImGuiWindowFlags_ShowBorders) { window->DrawList->AddCircle(center+ImVec2(1,1), radius, window->Color(ImGuiCol_BorderShadow), 16); window->DrawList->AddCircle(center, radius, window->Color(ImGuiCol_Border), 16); } if (g.LogEnabled) LogText(text_bb.GetTL(), active ? "(x)" : "( )"); RenderText(text_bb.GetTL(), label); return pressed; } bool ImGui::RadioButton(const char* label, int* v, int v_button) { const bool pressed = ImGui::RadioButton(label, *v == v_button); if (pressed) { *v = v_button; } return pressed; } // Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar) static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return (int)ImStrlenW(obj->Text); } static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; } static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { (void)line_start_idx; return obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, &obj->Text[char_idx], &obj->Text[char_idx]+1, NULL).x; } static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; } static ImWchar STB_TEXTEDIT_NEWLINE = '\n'; static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx) { const ImWchar* text_remaining = NULL; const ImVec2 size = obj->Font->CalcTextSizeW(obj->FontSize, FLT_MAX, obj->Text + line_start_idx, NULL, &text_remaining); r->x0 = 0.0f; r->x1 = size.x; r->baseline_y_delta = size.y; r->ymin = 0.0f; r->ymax = size.y; r->num_chars = (int)(text_remaining - (obj->Text + line_start_idx)); } static bool is_separator(unsigned int c) { return c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; } #define STB_TEXTEDIT_IS_SPACE(CH) ( ImCharIsSpace((unsigned int)CH) || is_separator((unsigned int)CH) ) static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n) { ImWchar* dst = obj->Text + pos; // We maintain our buffer length in both UTF-8 and wchar formats obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n); obj->CurLenW -= n; // Offset remaining text const ImWchar* src = obj->Text + pos + n; while (ImWchar c = *src++) *dst++ = c; *dst = '\0'; } static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len) { const size_t text_len = obj->CurLenW; if ((size_t)new_text_len + text_len + 1 > IM_ARRAYSIZE(obj->Text)) return false; const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len); if ((size_t)new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA) return false; if (pos != (int)text_len) memmove(obj->Text + (size_t)pos + new_text_len, obj->Text + (size_t)pos, (text_len - (size_t)pos) * sizeof(ImWchar)); memcpy(obj->Text + (size_t)pos, new_text, (size_t)new_text_len * sizeof(ImWchar)); obj->CurLenW += new_text_len; obj->CurLenA += new_text_len_utf8; obj->Text[obj->CurLenW] = '\0'; return true; } // We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols) #define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left #define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right #define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up #define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down #define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line #define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line #define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text #define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text #define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor #define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor #define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo #define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo #define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word #define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word #define STB_TEXTEDIT_K_SHIFT 0x20000 #ifdef IMGUI_STB_NAMESPACE namespace IMGUI_STB_NAMESPACE { #endif #define STB_TEXTEDIT_IMPLEMENTATION #include "stb_textedit.h" #ifdef IMGUI_STB_NAMESPACE } #endif void ImGuiTextEditState::OnKeyPressed(int key) { stb_textedit_key(this, &StbState, key); CursorAnimReset(); } void ImGuiTextEditState::UpdateScrollOffset() { // Scroll in chunks of quarter width const float scroll_x_increment = Width * 0.25f; const float cursor_offset_x = Font->CalcTextSizeW(FontSize, FLT_MAX, Text, Text+StbState.cursor, NULL).x; // If widget became bigger than text (because of a resize), reset horizontal scrolling if (ScrollX > 0.0f) { const float text_width = cursor_offset_x + Font->CalcTextSizeW(FontSize, FLT_MAX, Text+StbState.cursor, NULL, NULL).x; if (text_width < Width) { ScrollX = 0.0f; return; } } if (cursor_offset_x < ScrollX) ScrollX = ImMax(0.0f, cursor_offset_x - scroll_x_increment); else if (cursor_offset_x - Width >= ScrollX) ScrollX = cursor_offset_x - Width + scroll_x_increment; } ImVec2 ImGuiTextEditState::CalcDisplayOffsetFromCharIdx(int i) const { const ImWchar* text_start = GetTextPointerClippedW(Font, FontSize, Text, ScrollX, NULL); const ImWchar* text_end = (Text+i >= text_start) ? Text+i : text_start; // Clip if requested character is outside of display IM_ASSERT(text_end >= text_start); const ImVec2 offset = Font->CalcTextSizeW(FontSize, Width+1, text_start, text_end, NULL); return offset; } // [Static] const char* ImGuiTextEditState::GetTextPointerClippedA(ImFont* font, float font_size, const char* text, float width, ImVec2* out_text_size) { if (width <= 0.0f) return text; const char* text_clipped_end = NULL; const ImVec2 text_size = font->CalcTextSizeA(font_size, width, 0.0f, text, NULL, &text_clipped_end); if (out_text_size) *out_text_size = text_size; return text_clipped_end; } // [Static] const ImWchar* ImGuiTextEditState::GetTextPointerClippedW(ImFont* font, float font_size, const ImWchar* text, float width, ImVec2* out_text_size) { if (width <= 0.0f) return text; const ImWchar* text_clipped_end = NULL; const ImVec2 text_size = font->CalcTextSizeW(font_size, width, text, NULL, &text_clipped_end); if (out_text_size) *out_text_size = text_size; return text_clipped_end; } // [Static] void ImGuiTextEditState::RenderTextScrolledClipped(ImFont* font, float font_size, const char* buf, ImVec2 pos, float width, float scroll_x) { ImGuiWindow* window = GetCurrentWindow(); const ImU32 font_color = window->Color(ImGuiCol_Text); //window->DrawList->AddLine(pos, pos+ImVec2(width,0), 0xFF00FFFF); // Determine start and end of visible string // FIXME-OPT: This is pretty slow for what it does. const char* text_start = scroll_x <= 0.0f ? buf : GetTextPointerClippedA(font, font_size, buf, scroll_x, NULL); const char* text_end = GetTextPointerClippedA(font, font_size, text_start, width + 1, NULL); // +1 to allow character spacing to fit outside the allowed width window->DrawList->AddText(font, font_size, pos, font_color, text_start, text_end); // Log as text if (GImGui->LogEnabled) LogText(pos, buf, NULL); } bool ImGui::InputFloat(const char* label, float *v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w = ImGui::CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); ImGui::BeginGroup(); ImGui::PushID(label); const ImVec2 button_sz = ImVec2(g.FontSize, g.FontSize) + style.FramePadding * 2; if (step > 0.0f) ImGui::PushItemWidth(ImMax(1.0f, w - (button_sz.x + style.ItemInnerSpacing.x)*2)); char buf[64]; if (decimal_precision < 0) ImFormatString(buf, IM_ARRAYSIZE(buf), "%f", *v); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits? else ImFormatString(buf, IM_ARRAYSIZE(buf), "%.*f", decimal_precision, *v); bool value_changed = false; const ImGuiInputTextFlags flags = extra_flags | (ImGuiInputTextFlags_CharsDecimal|ImGuiInputTextFlags_AutoSelectAll); if (ImGui::InputText("", buf, IM_ARRAYSIZE(buf), flags)) { ApplyNumericalTextInput(buf, v); value_changed = true; } // Step buttons if (step > 0.0f) { ImGui::PopItemWidth(); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); if (ImGui::Button("-", button_sz, true)) { *v -= g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; value_changed = true; } ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); if (ImGui::Button("+", button_sz, true)) { *v += g.IO.KeyCtrl && step_fast > 0.0f ? step_fast : step; value_changed = true; } } ImGui::PopID(); if (label_size.x > 0) { ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label); ItemSize(label_size, style.FramePadding.y); } ImGui::EndGroup(); return value_changed; } bool ImGui::InputInt(const char* label, int *v, int step, int step_fast, ImGuiInputTextFlags extra_flags) { float f = (float)*v; const bool value_changed = ImGui::InputFloat(label, &f, (float)step, (float)step_fast, 0, extra_flags); if (value_changed) *v = (int)f; return value_changed; } // Public API to manipulate UTF-8 text // We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar) void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count) { char* dst = Buf + pos; const char* src = Buf + pos + bytes_count; while (char c = *src++) *dst++ = c; *dst = '\0'; BufDirty = true; if (CursorPos + bytes_count >= pos) CursorPos -= bytes_count; else if (CursorPos >= pos) CursorPos = pos; SelectionStart = SelectionEnd = CursorPos; } void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end) { const size_t text_len = strlen(Buf); if (!new_text_end) new_text_end = new_text + strlen(new_text); const size_t new_text_len = (size_t)(new_text_end - new_text); if (new_text_len + text_len + 1 >= BufSize) return; size_t upos = (size_t)pos; if (text_len != upos) memmove(Buf + upos + new_text_len, Buf + upos, text_len - upos); memcpy(Buf + upos, new_text, new_text_len * sizeof(char)); Buf[text_len + new_text_len] = '\0'; BufDirty = true; if (CursorPos >= pos) CursorPos += (int)new_text_len; SelectionStart = SelectionEnd = CursorPos; } // Return false to discard a character. static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { unsigned int c = *p_char; if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF))) return false; if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys. return false; if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank)) { if (flags & ImGuiInputTextFlags_CharsDecimal) if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/')) return false; if (flags & ImGuiInputTextFlags_CharsHexadecimal) if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F')) return false; if (flags & ImGuiInputTextFlags_CharsUppercase) if (c >= 'a' && c <= 'z') *p_char = (c += (unsigned int)('A'-'a')); if (flags & ImGuiInputTextFlags_CharsNoBlank) if (ImCharIsSpace(c)) return false; } if (flags & ImGuiInputTextFlags_CallbackCharFilter) { ImGuiTextEditCallbackData callback_data; memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData)); callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter; callback_data.EventChar = (ImWchar)c; callback_data.Flags = flags; callback_data.UserData = user_data; if (callback(&callback_data) != 0) return false; *p_char = callback_data.EventChar; if (!callback_data.EventChar) return false; } return true; } // Edit a string of text bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiIO& io = g.IO; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = ImGui::CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; // NB: we are only allowed to access 'edit_state' if we are the active widget. ImGuiTextEditState& edit_state = g.InputTextState; const bool is_ctrl_down = io.KeyCtrl; const bool is_shift_down = io.KeyShift; const bool focus_requested = window->FocusItemRegister(g.ActiveId == id, (flags & ImGuiInputTextFlags_CallbackCompletion) == 0); // Using completion callback disable keyboard tabbing const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent); const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code; const bool hovered = IsHovered(frame_bb, id); if (hovered) { g.HoveredId = id; g.MouseCursor = ImGuiMouseCursor_TextInput; } const bool user_clicked = hovered && io.MouseClicked[0]; bool select_all = (g.ActiveId != id) && (flags & ImGuiInputTextFlags_AutoSelectAll) != 0; if (focus_requested || user_clicked) { if (g.ActiveId != id) { // Start edition // Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar) // From the moment we focused we are ignoring the content of 'buf' ImFormatString(edit_state.InitialText, IM_ARRAYSIZE(edit_state.InitialText), "%s", buf); const char* buf_end = NULL; edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), buf, NULL, &buf_end); edit_state.CurLenA = buf_end - buf; // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8. edit_state.Width = w + style.FramePadding.x; edit_state.InputCursorScreenPos = ImVec2(-1.f,-1.f); edit_state.CursorAnimReset(); if (edit_state.Id != id) { edit_state.Id = id; edit_state.ScrollX = 0.0f; stb_textedit_initialize_state(&edit_state.StbState, true); if (focus_requested_by_code) select_all = true; } else { // Recycle existing cursor/selection/undo stack but clamp position // Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler. edit_state.StbState.cursor = ImMin(edit_state.StbState.cursor, (int)edit_state.CurLenW); edit_state.StbState.select_start = ImMin(edit_state.StbState.select_start, (int)edit_state.CurLenW); edit_state.StbState.select_end = ImMin(edit_state.StbState.select_end, (int)edit_state.CurLenW); } if (focus_requested_by_tab || (user_clicked && is_ctrl_down)) select_all = true; } SetActiveId(id); FocusWindow(window); } else if (io.MouseClicked[0]) { // Release focus when we click outside if (g.ActiveId == id) { SetActiveId(0); } } // Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget. // Down the line we should have a cleaner concept of focused vs active in the library. if (g.ActiveId == id) g.ActiveIdIsFocusedOnly = !io.MouseDown[0]; bool value_changed = false; bool cancel_edit = false; bool enter_pressed = false; if (g.ActiveId == id) //if (edit_state.Id == id) // Works, but double-click to select-all sets cursors to end which in turn tends to scroll toward the right when shrinking widget. { // Update some data if we are active or last active edit_state.Width = w + style.FramePadding.x; edit_state.BufSizeA = buf_size; edit_state.Font = g.Font; edit_state.FontSize = g.FontSize; edit_state.UpdateScrollOffset(); } if (g.ActiveId == id) { // Edit in progress const float mx = g.IO.MousePos.x - frame_bb.Min.x - style.FramePadding.x; const float my = g.FontSize*0.5f; // Flatten mouse because we are doing a single-line edit if (select_all || (hovered && io.MouseDoubleClicked[0])) { edit_state.SelectAll(); edit_state.SelectedAllMouseLock = true; } else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock) { stb_textedit_click(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); edit_state.CursorAnimReset(); } else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock) { stb_textedit_drag(&edit_state, &edit_state.StbState, mx + edit_state.ScrollX, my); edit_state.CursorAnimReset(); } if (edit_state.SelectedAllMouseLock && !io.MouseDown[0]) edit_state.SelectedAllMouseLock = false; if (g.IO.InputCharacters[0]) { // Process text input (before we check for Return because using some IME will effectively send a Return?) for (int n = 0; n < IM_ARRAYSIZE(g.IO.InputCharacters) && g.IO.InputCharacters[n]; n++) { unsigned int c = (unsigned int)g.IO.InputCharacters[n]; if (c) { // Insert character if they pass filtering if (!InputTextFilterCharacter(&c, flags, callback, user_data)) continue; edit_state.OnKeyPressed((int)c); } } // Consume characters memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters)); } const int k_mask = (is_shift_down ? STB_TEXTEDIT_K_SHIFT : 0); if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDLEFT | k_mask : STB_TEXTEDIT_K_LEFT | k_mask); } else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_WORDRIGHT | k_mask : STB_TEXTEDIT_K_RIGHT | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); } else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(is_ctrl_down ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Delete)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Backspace)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask); } else if (IsKeyPressedMap(ImGuiKey_Enter)) { SetActiveId(0); enter_pressed = true; } else if (IsKeyPressedMap(ImGuiKey_Escape)) { SetActiveId(0); cancel_edit = true; } else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Z)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); } else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_Y)) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); } else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); } else if (is_ctrl_down && (IsKeyPressedMap(ImGuiKey_X) || IsKeyPressedMap(ImGuiKey_C))) { // Cut, Copy const bool cut = IsKeyPressedMap(ImGuiKey_X); if (cut && !edit_state.HasSelection()) edit_state.SelectAll(); if (g.IO.SetClipboardTextFn) { const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0; const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : (int)edit_state.CurLenW; ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text+ib, edit_state.Text+ie); g.IO.SetClipboardTextFn(g.TempBuffer); } if (cut) stb_textedit_cut(&edit_state, &edit_state.StbState); } else if (is_ctrl_down && IsKeyPressedMap(ImGuiKey_V)) { // Paste if (g.IO.GetClipboardTextFn) { if (const char* clipboard = g.IO.GetClipboardTextFn()) { // Remove new-line from pasted buffer const size_t clipboard_len = strlen(clipboard); ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar)); int clipboard_filtered_len = 0; for (const char* s = clipboard; *s; ) { unsigned int c; s += ImTextCharFromUtf8(&c, s, NULL); if (c == 0) break; if (c >= 0x10000) continue; if (!InputTextFilterCharacter(&c, flags, callback, user_data)) continue; clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c; } clipboard_filtered[clipboard_filtered_len] = 0; if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len); ImGui::MemFree(clipboard_filtered); } } } edit_state.CursorAnim += g.IO.DeltaTime; edit_state.UpdateScrollOffset(); if (cancel_edit) { // Restore initial value ImFormatString(buf, buf_size, "%s", edit_state.InitialText); value_changed = true; } else { // Apply new value immediately - copy modified buffer back // Note that as soon as we can focus into the input box, the in-widget value gets priority over any underlying modification of the input buffer // FIXME: We actually always render 'buf' in RenderTextScrolledClipped // FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks ImTextStrToUtf8(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), edit_state.Text, NULL); // User callback if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0) { IM_ASSERT(callback != NULL); // The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment. ImGuiInputTextFlags event_flag = 0; ImGuiKey event_key = ImGuiKey_COUNT; if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab)) { event_flag = ImGuiInputTextFlags_CallbackCompletion; event_key = ImGuiKey_Tab; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_UpArrow; } else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow)) { event_flag = ImGuiInputTextFlags_CallbackHistory; event_key = ImGuiKey_DownArrow; } if (event_key != ImGuiKey_COUNT || (flags & ImGuiInputTextFlags_CallbackAlways) != 0) { ImGuiTextEditCallbackData callback_data; callback_data.EventFlag = event_flag; callback_data.EventKey = event_key; callback_data.Buf = g.TempBuffer; callback_data.BufSize = edit_state.BufSizeA; callback_data.BufDirty = false; callback_data.Flags = flags; callback_data.UserData = user_data; // We have to convert from position from wchar to UTF-8 positions const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.cursor); const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_start); const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(edit_state.Text, edit_state.Text + edit_state.StbState.select_end); // Call user code callback(&callback_data); // Read back what user may have modified IM_ASSERT(callback_data.Buf == g.TempBuffer); // Invalid to modify those fields IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA); IM_ASSERT(callback_data.Flags == flags); if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos); if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart); if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd); if (callback_data.BufDirty) { ImTextStrFromUtf8(edit_state.Text, IM_ARRAYSIZE(edit_state.Text), g.TempBuffer, NULL); edit_state.CursorAnimReset(); } } } if (strcmp(g.TempBuffer, buf) != 0) { ImFormatString(buf, buf_size, "%s", g.TempBuffer); value_changed = true; } } } RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); const ImVec2 font_off_up = ImVec2(0.0f, g.FontSize+1.0f); // FIXME: those offsets are part of the style or font API const ImVec2 font_off_dn = ImVec2(0.0f, 2.0f); if (g.ActiveId == id) { // Draw selection const int select_begin_idx = edit_state.StbState.select_start; const int select_end_idx = edit_state.StbState.select_end; if (select_begin_idx != select_end_idx) { const ImVec2 select_begin_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMin(select_begin_idx,select_end_idx)); const ImVec2 select_end_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(ImMax(select_begin_idx,select_end_idx)); window->DrawList->AddRectFilled(select_begin_pos - font_off_up, select_end_pos + font_off_dn, window->Color(ImGuiCol_TextSelectedBg)); } } //const float render_scroll_x = (g.ActiveId == id) ? edit_state.ScrollX : 0.0f; const float render_scroll_x = (edit_state.Id == id) ? edit_state.ScrollX : 0.0f; ImGuiTextEditState::RenderTextScrolledClipped(g.Font, g.FontSize, buf, frame_bb.Min + style.FramePadding, w + style.FramePadding.x, render_scroll_x); if (g.ActiveId == id) { const ImVec2 cursor_pos = frame_bb.Min + style.FramePadding + edit_state.CalcDisplayOffsetFromCharIdx(edit_state.StbState.cursor); // Draw blinking cursor if (g.InputTextState.CursorIsVisible()) window->DrawList->AddRect(cursor_pos - font_off_up + ImVec2(0,2), cursor_pos + font_off_dn - ImVec2(0,3), window->Color(ImGuiCol_Text)); // Notify OS of text input position for advanced IME if (io.ImeSetInputScreenPosFn && ImLengthSqr(edit_state.InputCursorScreenPos - cursor_pos) > 0.0001f) io.ImeSetInputScreenPosFn((int)cursor_pos.x - 1, (int)(cursor_pos.y - g.FontSize)); // -1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety. edit_state.InputCursorScreenPos = cursor_pos; } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0) return enter_pressed; else return value_changed; } static bool InputFloatN(const char* label, float* v, int components, int decimal_precision) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::InputFloat("##v", &v[i], 0, 0, decimal_precision); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, style.FramePadding.y); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision) { return InputFloatN(label, v, 2, decimal_precision); } bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision) { return InputFloatN(label, v, 3, decimal_precision); } bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision) { return InputFloatN(label, v, 4, decimal_precision); } static bool InputIntN(const char* label, int* v, int components) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const float w_full = ImGui::CalcItemWidth(); const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); ImGui::PushItemWidth(w_item_one); for (int i = 0; i < components; i++) { ImGui::PushID(i); if (i + 1 == components) { ImGui::PopItemWidth(); ImGui::PushItemWidth(w_item_last); } value_changed |= ImGui::InputInt("##v", &v[i], 0, 0); ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); ImGui::PopID(); } ImGui::PopItemWidth(); ImGui::PopID(); window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, style.FramePadding.y); ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); ImGui::EndGroup(); return value_changed; } bool ImGui::InputInt2(const char* label, int v[2]) { return InputIntN(label, v, 2); } bool ImGui::InputInt3(const char* label, int v[3]) { return InputIntN(label, v, 3); } bool ImGui::InputInt4(const char* label, int v[4]) { return InputIntN(label, v, 4); } static bool Items_ArrayGetter(void* data, int idx, const char** out_text) { const char** items = (const char**)data; if (out_text) *out_text = items[idx]; return true; } static bool Items_SingleStringGetter(void* data, int idx, const char** out_text) { // FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited. const char* items_separated_by_zeros = (const char*)data; int items_count = 0; const char* p = items_separated_by_zeros; while (*p) { if (idx == items_count) break; p += strlen(p) + 1; items_count++; } if (!*p) return false; if (out_text) *out_text = p; return true; } // Combo box helper allowing to pass an array of strings. bool ImGui::Combo(const char* label, int* current_item, const char** items, int items_count, int height_in_items) { const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items); return value_changed; } // Combo box helper allowing to pass all items in a single string. bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items) { int items_count = 0; const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this while (*p) { p += strlen(p) + 1; items_count++; } bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items); return value_changed; } // Combo box function. bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w = ImGui::CalcItemWidth(); const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y) + style.FramePadding*2.0f); const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(style.ItemInnerSpacing.x + label_size.x,0)); ItemSize(total_bb, style.FramePadding.y); if (!ItemAdd(total_bb, &id)) return false; const float arrow_size = (g.FontSize + style.FramePadding.x * 2.0f); const bool hovered = IsHovered(frame_bb, id); bool value_changed = false; const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f)); RenderFrame(frame_bb.Min, frame_bb.Max, window->Color(ImGuiCol_FrameBg), true, style.FrameRounding); RenderFrame(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y), frame_bb.Max, window->Color(hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button), true, style.FrameRounding); // FIXME-ROUNDING RenderCollapseTriangle(ImVec2(frame_bb.Max.x-arrow_size, frame_bb.Min.y) + style.FramePadding, true); if (*current_item >= 0 && *current_item < items_count) { const char* item_text; if (items_getter(data, *current_item, &item_text)) RenderTextClipped(frame_bb.Min + style.FramePadding, item_text, NULL, NULL, value_bb.Max); } if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); ImGui::PushID((int)id); bool menu_toggled = false; if (hovered) { g.HoveredId = id; if (g.IO.MouseClicked[0]) { menu_toggled = true; g.ActiveComboID = (g.ActiveComboID == id) ? 0 : id; if (g.ActiveComboID) FocusWindow(window); } } if (g.ActiveComboID == id) { // Size default to hold ~7 items if (height_in_items < 0) height_in_items = 7; const ImVec2 backup_pos = ImGui::GetCursorPos(); const float popup_off_x = 0.0f;//style.ItemInnerSpacing.x; const float popup_height = (label_size.y + style.ItemSpacing.y) * ImMin(items_count, height_in_items) + (style.FramePadding.y * 3); const ImRect popup_rect(ImVec2(frame_bb.Min.x+popup_off_x, frame_bb.Max.y), ImVec2(frame_bb.Max.x+popup_off_x, frame_bb.Max.y + popup_height)); ImGui::SetCursorPos(popup_rect.Min - window->Pos); const ImGuiWindowFlags flags = ImGuiWindowFlags_ComboBox | ((window->Flags & ImGuiWindowFlags_ShowBorders) ? ImGuiWindowFlags_ShowBorders : 0); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding); ImGui::BeginChild("#ComboBox", popup_rect.GetSize(), false, flags); ImGui::Spacing(); bool combo_item_active = false; combo_item_active |= (g.ActiveId == GetCurrentWindow()->GetID("#SCROLLY")); // Display items for (int i = 0; i < items_count; i++) { ImGui::PushID((void*)(intptr_t)i); const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; if (ImGui::Selectable(item_text, item_selected)) { SetActiveId(0); g.ActiveComboID = 0; value_changed = true; *current_item = i; } if (item_selected && menu_toggled) ImGui::SetScrollPosHere(); combo_item_active |= ImGui::IsItemActive(); ImGui::PopID(); } ImGui::EndChild(); ImGui::PopStyleVar(); ImGui::SetCursorPos(backup_pos); if (!combo_item_active && g.ActiveId != 0) g.ActiveComboID = 0; } ImGui::PopID(); return value_changed; } // Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image. // But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID. bool ImGui::Selectable(const char* label, bool selected, const ImVec2& size_arg) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const ImVec2 label_size = CalcTextSize(label, NULL, true); const float w = ImMax(label_size.x, window->Pos.x + ImGui::GetContentRegionMax().x - style.AutoFitPadding.x - window->DC.CursorPos.x); const ImVec2 size(size_arg.x != 0.0f ? size_arg.x : w, size_arg.y != 0.0f ? size_arg.y : label_size.y); ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size); ItemSize(bb); if (size_arg.x == 0.0f) bb.Max.x += style.AutoFitPadding.x; // Selectables are meant to be tightly packed together. So for both rendering and collision we extend to compensate for spacing. ImRect bb_with_spacing = bb; const float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f); const float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f); const float spacing_R = style.ItemSpacing.x - spacing_L; const float spacing_D = style.ItemSpacing.y - spacing_U; bb_with_spacing.Min.x -= spacing_L; bb_with_spacing.Min.y -= spacing_U; bb_with_spacing.Max.x += spacing_R; bb_with_spacing.Max.y += spacing_D; if (!ItemAdd(bb_with_spacing, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, true, false, false); // Render if (hovered || selected) { const ImU32 col = window->Color((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header); RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, style.FrameRounding); } //const ImVec2 off = ImVec2(ImMax(0.0f, size.x - text_size.x) * 0.5f, ImMax(0.0f, size.y - text_size.y) * 0.5f); RenderTextClipped(bb.Min, label, NULL, &label_size, bb_with_spacing.Max); return pressed; } bool ImGui::Selectable(const char* label, bool* p_selected, const ImVec2& size_arg) { if (ImGui::Selectable(label, *p_selected, size_arg)) { *p_selected = !*p_selected; return true; } return false; } // Helper to calculate the size of a listbox and display a label on the right. // Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty" bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg) { ImGuiWindow* window = GetCurrentWindow(); const ImGuiStyle& style = ImGui::GetStyle(); const ImGuiID id = ImGui::GetID(label); const ImVec2 label_size = ImGui::CalcTextSize(label, NULL, true); // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. ImVec2 size; size.x = (size_arg.x != 0.0f) ? (size_arg.x) : ImGui::CalcItemWidth() + style.FramePadding.x * 2.0f; size.y = (size_arg.y != 0.0f) ? (size_arg.y) : ImGui::GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y; const ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y)); const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size); const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f)); window->DC.LastItemRect = bb; ImGui::BeginGroup(); if (label_size.x > 0) RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label); ImGui::BeginChildFrame(id, frame_bb.GetSize()); return true; } bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items) { // Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar. // However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size. // I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution. if (height_in_items < 0) height_in_items = ImMin(items_count, 7); float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f); // We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild(). ImVec2 size; size.x = 0.0f; size.y = ImGui::GetTextLineHeightWithSpacing() * height_in_items_f + ImGui::GetStyle().ItemSpacing.y; return ImGui::ListBoxHeader(label, size); } void ImGui::ListBoxFooter() { ImGuiWindow* parent_window = GetParentWindow(); const ImRect bb = parent_window->DC.LastItemRect; const ImGuiStyle& style = ImGui::GetStyle(); ImGui::EndChildFrame(); // Redeclare item size so that it includes the label (we have stored the full size in LastItemRect) // We call SameLine() to restore DC.CurrentLine* data ImGui::SameLine(); parent_window->DC.CursorPos = bb.Min; ItemSize(bb, style.FramePadding.y); ImGui::EndGroup(); } bool ImGui::ListBox(const char* label, int* current_item, const char** items, int items_count, int height_items) { const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items); return value_changed; } bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items) { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; if (!ImGui::ListBoxHeader(label, items_count, height_in_items)) return false; bool value_changed = false; for (int i = 0; i < items_count; i++) { const bool item_selected = (i == *current_item); const char* item_text; if (!items_getter(data, i, &item_text)) item_text = "*Unknown item*"; ImGui::PushID(i); if (ImGui::Selectable(item_text, item_selected)) { *current_item = i; value_changed = true; } ImGui::PopID(); } ImGui::ListBoxFooter(); return value_changed; } // A little colored square. Return true when clicked. bool ImGui::ColorButton(const ImVec4& col, bool small_height, bool outline_border) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID("#colorbutton"); const float square_size = g.FontSize; const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(square_size + style.FramePadding.x*2, square_size + (small_height ? 0 : style.FramePadding.y*2))); ItemSize(bb, small_height ? 0.0f : style.FramePadding.y); if (!ItemAdd(bb, &id)) return false; bool hovered, held; bool pressed = ButtonBehavior(bb, id, &hovered, &held, true); RenderFrame(bb.Min, bb.Max, window->Color(col), outline_border, style.FrameRounding); if (hovered) { int ix = (int)(col.x * 255.0f + 0.5f); int iy = (int)(col.y * 255.0f + 0.5f); int iz = (int)(col.z * 255.0f + 0.5f); int iw = (int)(col.w * 255.0f + 0.5f); ImGui::SetTooltip("Color:\n(%.2f,%.2f,%.2f,%.2f)\n#%02X%02X%02X%02X", col.x, col.y, col.z, col.w, ix, iy, iz, iw); } return pressed; } bool ImGui::ColorEdit3(const char* label, float col[3]) { float col4[4]; col4[0] = col[0]; col4[1] = col[1]; col4[2] = col[2]; col4[3] = 1.0f; const bool value_changed = ImGui::ColorEdit4(label, col4, false); col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2]; return value_changed; } // Edit colors components (each component in 0.0f..1.0f range // Use CTRL-Click to input value and TAB to go to next item. bool ImGui::ColorEdit4(const char* label, float col[4], bool alpha) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return false; const ImGuiStyle& style = g.Style; const ImGuiID id = window->GetID(label); const float w_full = ImGui::CalcItemWidth(); const float square_sz = (g.FontSize + style.FramePadding.x * 2.0f); ImGuiColorEditMode edit_mode = window->DC.ColorEditMode; if (edit_mode == ImGuiColorEditMode_UserSelect || edit_mode == ImGuiColorEditMode_UserSelectShowButton) edit_mode = g.ColorEditModeStorage.GetInt(id, 0) % 3; float f[4] = { col[0], col[1], col[2], col[3] }; if (edit_mode == ImGuiColorEditMode_HSV) ImGui::ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]); int i[4] = { (int)(f[0] * 255.0f + 0.5f), (int)(f[1] * 255.0f + 0.5f), (int)(f[2] * 255.0f + 0.5f), (int)(f[3] * 255.0f + 0.5f) }; int components = alpha ? 4 : 3; bool value_changed = false; ImGui::BeginGroup(); ImGui::PushID(label); const bool hsv = (edit_mode == 1); switch (edit_mode) { case ImGuiColorEditMode_RGB: case ImGuiColorEditMode_HSV: { // RGB/HSV 0..255 Sliders const float w_items_all = w_full - (square_sz + style.ItemInnerSpacing.x); const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1)) / (float)components)); const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.FramePadding.x*2.0f + style.ItemInnerSpacing.x) * (components-1))); const bool hide_prefix = (w_item_one <= CalcTextSize("M:999").x); const char* ids[4] = { "##X", "##Y", "##Z", "##W" }; const char* fmt_table[3][4] = { { "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, { "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, { "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } }; const char** fmt = hide_prefix ? fmt_table[0] : hsv ? fmt_table[2] : fmt_table[1]; ImGui::PushItemWidth(w_item_one); for (int n = 0; n < components; n++) { if (n > 0) ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); if (n + 1 == components) ImGui::PushItemWidth(w_item_last); value_changed |= ImGui::DragInt(ids[n], &i[n], 1.0f, 0, 255, fmt[n]); } ImGui::PopItemWidth(); ImGui::PopItemWidth(); } break; case ImGuiColorEditMode_HEX: { // RGB Hexadecimal Input const float w_slider_all = w_full - square_sz; char buf[64]; if (alpha) ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", i[0], i[1], i[2], i[3]); else ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", i[0], i[1], i[2]); ImGui::PushItemWidth(w_slider_all - style.ItemInnerSpacing.x); value_changed |= ImGui::InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); ImGui::PopItemWidth(); char* p = buf; while (*p == '#' || ImCharIsSpace(*p)) p++; // Treat at unsigned (%X is unsigned) i[0] = i[1] = i[2] = i[3] = 0; if (alpha) sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); else sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]); } break; } ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); const ImVec4 col_display(col[0], col[1], col[2], 1.0f); if (ImGui::ColorButton(col_display)) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! if (window->DC.ColorEditMode == ImGuiColorEditMode_UserSelectShowButton) { ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); const char* button_titles[3] = { "RGB", "HSV", "HEX" }; if (ImGui::Button(button_titles[edit_mode])) g.ColorEditModeStorage.SetInt(id, (edit_mode + 1) % 3); // Don't set local copy of 'edit_mode' right away! ImGui::SameLine(); } else { ImGui::SameLine(0, (int)style.ItemInnerSpacing.x); } ImGui::TextUnformatted(label, FindTextDisplayEnd(label)); // Convert back for (int n = 0; n < 4; n++) f[n] = i[n] / 255.0f; if (edit_mode == 1) ImGui::ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]); if (value_changed) { col[0] = f[0]; col[1] = f[1]; col[2] = f[2]; if (alpha) col[3] = f[3]; } ImGui::PopID(); ImGui::EndGroup(); return value_changed; } void ImGui::ColorEditMode(ImGuiColorEditMode mode) { ImGuiWindow* window = GetCurrentWindow(); window->DC.ColorEditMode = mode; } // Horizontal separating line. void ImGui::Separator() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.ColumnsCount > 1) PopClipRect(); const ImRect bb(ImVec2(window->Pos.x, window->DC.CursorPos.y), ImVec2(window->Pos.x + window->Size.x, window->DC.CursorPos.y)); ItemSize(ImVec2(0.0f, bb.GetSize().y)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit if (!ItemAdd(bb, NULL)) { if (window->DC.ColumnsCount > 1) PushColumnClipRect(); return; } window->DrawList->AddLine(bb.Min, bb.Max, window->Color(ImGuiCol_Border)); ImGuiState& g = *GImGui; if (g.LogEnabled) ImGui::LogText(STR_NEWLINE "--------------------------------"); if (window->DC.ColumnsCount > 1) { PushColumnClipRect(); window->DC.ColumnsCellMinY = window->DC.CursorPos.y; } } // A little vertical spacing. void ImGui::Spacing() { ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; ItemSize(ImVec2(0,0)); } // Advance cursor given item size. static void ItemSize(ImVec2 size, float text_offset_y) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; // Always align ourselves on pixel boundaries const float line_height = ImMax(window->DC.CurrentLineHeight, size.y); const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y); window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y); window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y)); window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x); window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y); //window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, 0xFF0000FF, 4); // Debug window->DC.PrevLineHeight = line_height; window->DC.PrevLineTextBaseOffset = text_base_offset; window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f; } static inline void ItemSize(const ImRect& bb, float text_offset_y) { ItemSize(bb.GetSize(), text_offset_y); } static bool IsClippedEx(const ImRect& bb, const ImGuiID* id, bool clip_even_when_logged) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (!bb.Overlaps(ImRect(window->ClipRectStack.back()))) { if (!id || *id != GImGui->ActiveId) if (clip_even_when_logged || !g.LogEnabled) return true; } return false; } bool ImGui::IsRectClipped(const ImVec2& size) { ImGuiWindow* window = GetCurrentWindow(); return IsClippedEx(ImRect(window->DC.CursorPos, window->DC.CursorPos + size), NULL, true); } static bool ItemAdd(const ImRect& bb, const ImGuiID* id) { ImGuiWindow* window = GetCurrentWindow(); window->DC.LastItemID = id ? *id : 0; window->DC.LastItemRect = bb; if (IsClippedEx(bb, id, false)) { window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; return false; } // This is a sensible default, but widgets are free to override it after calling ItemAdd() ImGuiState& g = *GImGui; if (IsMouseHoveringRect(bb)) { // Matching the behavior of IsHovered() but ignore if ActiveId==window->MoveID (we clicked on the window background) // So that clicking on items with no active id such as Text() still returns true with IsItemHovered() window->DC.LastItemHoveredRect = true; window->DC.LastItemHoveredAndUsable = false; if (g.HoveredRootWindow == window->RootWindow) if (g.ActiveId == 0 || (id && g.ActiveId == *id) || g.ActiveIdIsFocusedOnly || (g.ActiveId == window->MoveID)) if (IsWindowContentHoverable(window)) window->DC.LastItemHoveredAndUsable = true; } else { window->DC.LastItemHoveredAndUsable = window->DC.LastItemHoveredRect = false; } return true; } void ImGui::BeginGroup() { ImGuiWindow* window = GetCurrentWindow(); window->DC.GroupStack.resize(window->DC.GroupStack.size() + 1); ImGuiGroupData& group_data = window->DC.GroupStack.back(); group_data.BackupCursorPos = window->DC.CursorPos; group_data.BackupCursorMaxPos = window->DC.CursorMaxPos; group_data.BackupColumnsStartX = window->DC.ColumnsStartX; group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight; group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset; group_data.BackupLogLinePosY = window->DC.LogLinePosY; window->DC.ColumnsStartX = window->DC.CursorPos.x - window->Pos.x; window->DC.CursorMaxPos = window->DC.CursorPos; window->DC.CurrentLineHeight = 0.0f; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; } void ImGui::EndGroup() { ImGuiWindow* window = GetCurrentWindow(); ImGuiStyle& style = ImGui::GetStyle(); IM_ASSERT(!window->DC.GroupStack.empty()); ImGuiGroupData& group_data = window->DC.GroupStack.back(); ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos); group_bb.Max.y -= style.ItemSpacing.y; // Cancel out last vertical spacing because we are adding one ourselves. group_bb.Max = ImMax(group_bb.Min, group_bb.Max); window->DC.CursorPos = group_data.BackupCursorPos; window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos); window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight; window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset; // FIXME: Ideally we'll grab the base offset from the first line of the group. window->DC.ColumnsStartX = group_data.BackupColumnsStartX; window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset); ItemAdd(group_bb, NULL); window->DC.GroupStack.pop_back(); //window->DrawList->AddRect(group_bb.Min, group_bb.Max, 0xFFFF00FF); // Debug } // Gets back to previous line and continue with horizontal layout // column_x == 0 : follow on previous item // columm_x != 0 : align to specified column // spacing_w < 0 : use default spacing if column_x==0, no spacing if column_x!=0 // spacing_w >= 0 : enforce spacing void ImGui::SameLine(int column_x, int spacing_w) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; float x, y; if (column_x != 0) { if (spacing_w < 0) spacing_w = 0; x = window->Pos.x + (float)column_x + (float)spacing_w; y = window->DC.CursorPosPrevLine.y; } else { if (spacing_w < 0) spacing_w = (int)g.Style.ItemSpacing.x; x = window->DC.CursorPosPrevLine.x + (float)spacing_w; y = window->DC.CursorPosPrevLine.y; } window->DC.CurrentLineHeight = window->DC.PrevLineHeight; window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset; window->DC.CursorPos = ImVec2(x, y); } void ImGui::NextColumn() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->SkipItems) return; if (window->DC.ColumnsCount > 1) { ImGui::PopItemWidth(); PopClipRect(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); if (++window->DC.ColumnsCurrent < window->DC.ColumnsCount) { window->DC.ColumnsOffsetX = ImGui::GetColumnOffset(window->DC.ColumnsCurrent) - window->DC.ColumnsStartX + g.Style.ItemSpacing.x; } else { window->DC.ColumnsCurrent = 0; window->DC.ColumnsOffsetX = 0.0f; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY; } window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); window->DC.CursorPos.y = window->DC.ColumnsCellMinY; window->DC.CurrentLineHeight = 0.0f; window->DC.CurrentLineTextBaseOffset = 0.0f; PushColumnClipRect(); ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); // FIXME } } int ImGui::GetColumnIndex() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.ColumnsCurrent; } int ImGui::GetColumnsCount() { ImGuiWindow* window = GetCurrentWindow(); return window->DC.ColumnsCount; } static float GetDraggedColumnOffset(int column_index) { // Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing // window creates a feedback loop because we store normalized positions/ So while dragging we enforce absolute positioning ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); IM_ASSERT(g.ActiveId == window->DC.ColumnsSetID + ImGuiID(column_index)); float x = g.IO.MousePos.x + g.ActiveClickDeltaToCenter.x; x -= window->Pos.x; x = ImClamp(x, ImGui::GetColumnOffset(column_index-1)+g.Style.ColumnsMinSpacing, ImGui::GetColumnOffset(column_index+1)-g.Style.ColumnsMinSpacing); return x; } float ImGui::GetColumnOffset(int column_index) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; if (g.ActiveId) { const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); if (g.ActiveId == column_id) return GetDraggedColumnOffset(column_index); } // Read from cache IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); const float t = window->DC.ColumnsOffsetsT[column_index]; const float min_x = window->DC.ColumnsStartX; const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; const float offset = min_x + t * (max_x - min_x); return offset; } void ImGui::SetColumnOffset(int column_index, float offset) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; IM_ASSERT(column_index < (int)window->DC.ColumnsOffsetsT.size()); const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); const float min_x = window->DC.ColumnsStartX; const float max_x = window->Size.x - (g.Style.ScrollbarWidth);// - window->WindowPadding().x; const float t = (offset - min_x) / (max_x - min_x); window->DC.StateStorage->SetFloat(column_id, t); window->DC.ColumnsOffsetsT[column_index] = t; } float ImGui::GetColumnWidth(int column_index) { ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; const float w = GetColumnOffset(column_index+1) - GetColumnOffset(column_index); return w; } static void PushColumnClipRect(int column_index) { ImGuiWindow* window = GetCurrentWindow(); if (column_index < 0) column_index = window->DC.ColumnsCurrent; const float x1 = window->Pos.x + ImGui::GetColumnOffset(column_index) - 1; const float x2 = window->Pos.x + ImGui::GetColumnOffset(column_index+1) - 1; PushClipRect(ImVec4(x1,-FLT_MAX,x2,+FLT_MAX)); } void ImGui::Columns(int columns_count, const char* id, bool border) { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); if (window->DC.ColumnsCount != 1) { if (window->DC.ColumnsCurrent != 0) ItemSize(ImVec2(0,0)); // Advance to column 0 ImGui::PopItemWidth(); PopClipRect(); window->DC.ColumnsCellMaxY = ImMax(window->DC.ColumnsCellMaxY, window->DC.CursorPos.y); window->DC.CursorPos.y = window->DC.ColumnsCellMaxY; } // Draw columns borders and handle resize at the time of "closing" a columns set if (window->DC.ColumnsCount != columns_count && window->DC.ColumnsCount != 1 && window->DC.ColumnsShowBorders && !window->SkipItems) { const float y1 = window->DC.ColumnsStartPos.y; const float y2 = window->DC.CursorPos.y; for (int i = 1; i < window->DC.ColumnsCount; i++) { float x = window->Pos.x + GetColumnOffset(i); const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(i); const ImRect column_rect(ImVec2(x-4,y1),ImVec2(x+4,y2)); if (IsClippedEx(column_rect, &column_id, false)) continue; bool hovered, held; ButtonBehavior(column_rect, column_id, &hovered, &held, true); if (hovered || held) g.MouseCursor = ImGuiMouseCursor_ResizeEW; // Draw before resize so our items positioning are in sync with the line being drawn const ImU32 col = window->Color(held ? ImGuiCol_ColumnActive : hovered ? ImGuiCol_ColumnHovered : ImGuiCol_Column); const float xi = (float)(int)x; window->DrawList->AddLine(ImVec2(xi, y1), ImVec2(xi, y2), col); if (held) { if (g.ActiveIdIsJustActivated) g.ActiveClickDeltaToCenter.x = x - g.IO.MousePos.x; x = GetDraggedColumnOffset(i); SetColumnOffset(i, x); } } } // Set state for first column window->DC.ColumnsSetID = window->GetID(id ? id : ""); window->DC.ColumnsCurrent = 0; window->DC.ColumnsCount = columns_count; window->DC.ColumnsShowBorders = border; window->DC.ColumnsStartPos = window->DC.CursorPos; window->DC.ColumnsCellMinY = window->DC.ColumnsCellMaxY = window->DC.CursorPos.y; window->DC.ColumnsOffsetX = 0.0f; window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX); if (window->DC.ColumnsCount != 1) { // Cache column offsets window->DC.ColumnsOffsetsT.resize((size_t)columns_count + 1); for (int column_index = 0; column_index < columns_count + 1; column_index++) { const ImGuiID column_id = window->DC.ColumnsSetID + ImGuiID(column_index); RegisterAliveId(column_id); const float default_t = column_index / (float)window->DC.ColumnsCount; const float t = window->DC.StateStorage->GetFloat(column_id, default_t); // Cheaply store our floating point value inside the integer (could store an union into the map?) window->DC.ColumnsOffsetsT[column_index] = t; } PushColumnClipRect(); ImGui::PushItemWidth(ImGui::GetColumnWidth() * 0.65f); } else { window->DC.ColumnsOffsetsT.resize(2); window->DC.ColumnsOffsetsT[0] = 0.0f; window->DC.ColumnsOffsetsT[1] = 1.0f; } } inline void ImGui::Indent() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.ColumnsStartX += g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; } inline void ImGui::Unindent() { ImGuiState& g = *GImGui; ImGuiWindow* window = GetCurrentWindow(); window->DC.ColumnsStartX -= g.Style.IndentSpacing; window->DC.CursorPos.x = window->Pos.x + window->DC.ColumnsStartX + window->DC.ColumnsOffsetX; } void ImGui::TreePush(const char* str_id) { ImGuiWindow* window = GetCurrentWindow(); ImGui::Indent(); window->DC.TreeDepth++; PushID(str_id ? str_id : "#TreePush"); } void ImGui::TreePush(const void* ptr_id) { ImGuiWindow* window = GetCurrentWindow(); ImGui::Indent(); window->DC.TreeDepth++; PushID(ptr_id ? ptr_id : (const void*)"#TreePush"); } void ImGui::TreePop() { ImGuiWindow* window = GetCurrentWindow(); ImGui::Unindent(); window->DC.TreeDepth--; PopID(); } void ImGui::Value(const char* prefix, bool b) { ImGui::Text("%s: %s", prefix, (b ? "true" : "false")); } void ImGui::Value(const char* prefix, int v) { ImGui::Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, unsigned int v) { ImGui::Text("%s: %d", prefix, v); } void ImGui::Value(const char* prefix, float v, const char* float_format) { if (float_format) { char fmt[64]; ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format); ImGui::Text(fmt, prefix, v); } else { ImGui::Text("%s: %.3f", prefix, v); } } void ImGui::Color(const char* prefix, const ImVec4& v) { ImGui::Text("%s: (%.2f,%.2f,%.2f,%.2f)", prefix, v.x, v.y, v.z, v.w); ImGui::SameLine(); ImGui::ColorButton(v, true); } void ImGui::Color(const char* prefix, unsigned int v) { ImGui::Text("%s: %08X", prefix, v); ImGui::SameLine(); ImVec4 col; col.x = (float)((v >> 0) & 0xFF) / 255.0f; col.y = (float)((v >> 8) & 0xFF) / 255.0f; col.z = (float)((v >> 16) & 0xFF) / 255.0f; col.w = (float)((v >> 24) & 0xFF) / 255.0f; ImGui::ColorButton(col, true); } //----------------------------------------------------------------------------- // ImDrawList //----------------------------------------------------------------------------- static ImVec4 GNullClipRect(-9999.0f,-9999.0f, +9999.0f, +9999.0f); void ImDrawList::Clear() { commands.resize(0); vtx_buffer.resize(0); vtx_write = NULL; clip_rect_stack.resize(0); texture_id_stack.resize(0); } void ImDrawList::ClearFreeMemory() { commands.clear(); vtx_buffer.clear(); vtx_write = NULL; clip_rect_stack.clear(); texture_id_stack.clear(); } void ImDrawList::AddDrawCmd() { ImDrawCmd draw_cmd; draw_cmd.vtx_count = 0; draw_cmd.clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); draw_cmd.texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); draw_cmd.user_callback = NULL; draw_cmd.user_callback_data = NULL; IM_ASSERT(draw_cmd.clip_rect.x <= draw_cmd.clip_rect.z && draw_cmd.clip_rect.y <= draw_cmd.clip_rect.w); commands.push_back(draw_cmd); } void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data) { ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); if (!current_cmd || current_cmd->vtx_count != 0 || current_cmd->user_callback != NULL) { AddDrawCmd(); current_cmd = &commands.back(); } current_cmd->user_callback = callback; current_cmd->user_callback_data = callback_data; // Force a new command after us // We function this way so that the most common calls (AddLine, AddRect..) always have a command to add to without doing any check. AddDrawCmd(); } void ImDrawList::UpdateClipRect() { ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); if (!current_cmd || (current_cmd->vtx_count != 0) || current_cmd->user_callback != NULL) { AddDrawCmd(); } else { current_cmd->clip_rect = clip_rect_stack.empty() ? GNullClipRect : clip_rect_stack.back(); } } // Scissoring. The values in clip_rect are x1, y1, x2, y2. void ImDrawList::PushClipRect(const ImVec4& clip_rect) { clip_rect_stack.push_back(clip_rect); UpdateClipRect(); } void ImDrawList::PushClipRectFullScreen() { PushClipRect(GNullClipRect); // This would be more correct but we're not supposed to access ImGuiState from here? //ImGuiState& g = *GImGui; //if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y) // PushClipRect(ImVec4(g.IO.DisplayVisibleMin.x, g.IO.DisplayVisibleMin.y, g.IO.DisplayVisibleMax.x, g.IO.DisplayVisibleMax.y)); //else // PushClipRect(ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y)); } void ImDrawList::PopClipRect() { IM_ASSERT(clip_rect_stack.size() > 0); clip_rect_stack.pop_back(); UpdateClipRect(); } void ImDrawList::UpdateTextureID() { ImDrawCmd* current_cmd = commands.empty() ? NULL : &commands.back(); const ImTextureID texture_id = texture_id_stack.empty() ? NULL : texture_id_stack.back(); if (!current_cmd || (current_cmd->vtx_count != 0 && current_cmd->texture_id != texture_id) || current_cmd->user_callback != NULL) { AddDrawCmd(); } else { current_cmd->texture_id = texture_id; } } void ImDrawList::PushTextureID(const ImTextureID& texture_id) { texture_id_stack.push_back(texture_id); UpdateTextureID(); } void ImDrawList::PopTextureID() { IM_ASSERT(texture_id_stack.size() > 0); texture_id_stack.pop_back(); UpdateTextureID(); } void ImDrawList::PrimReserve(unsigned int vtx_count) { ImDrawCmd& draw_cmd = commands.back(); draw_cmd.vtx_count += vtx_count; size_t vtx_buffer_size = vtx_buffer.size(); vtx_buffer.resize(vtx_buffer_size + vtx_count); vtx_write = &vtx_buffer[vtx_buffer_size]; } void ImDrawList::PrimTriangle(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) { const ImVec2 uv = GImGui->FontTexUvWhitePixel; vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; vtx_write += 3; } void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col) { const ImVec2 uv = GImGui->FontTexUvWhitePixel; const ImVec2 b(c.x, a.y); const ImVec2 d(a.x, c.y); vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; vtx_write[3].pos = a; vtx_write[3].uv = uv; vtx_write[3].col = col; vtx_write[4].pos = c; vtx_write[4].uv = uv; vtx_write[4].col = col; vtx_write[5].pos = d; vtx_write[5].uv = uv; vtx_write[5].col = col; vtx_write += 6; } void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col) { const ImVec2 b(c.x, a.y); const ImVec2 d(a.x, c.y); const ImVec2 uv_b(uv_c.x, uv_a.y); const ImVec2 uv_d(uv_a.x, uv_c.y); vtx_write[0].pos = a; vtx_write[0].uv = uv_a; vtx_write[0].col = col; vtx_write[1].pos = b; vtx_write[1].uv = uv_b; vtx_write[1].col = col; vtx_write[2].pos = c; vtx_write[2].uv = uv_c; vtx_write[2].col = col; vtx_write[3].pos = a; vtx_write[3].uv = uv_a; vtx_write[3].col = col; vtx_write[4].pos = c; vtx_write[4].uv = uv_c; vtx_write[4].col = col; vtx_write[5].pos = d; vtx_write[5].uv = uv_d; vtx_write[5].col = col; vtx_write += 6; } void ImDrawList::PrimQuad(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, ImU32 col) { const ImVec2 uv = GImGui->FontTexUvWhitePixel; vtx_write[0].pos = a; vtx_write[0].uv = uv; vtx_write[0].col = col; vtx_write[1].pos = b; vtx_write[1].uv = uv; vtx_write[1].col = col; vtx_write[2].pos = c; vtx_write[2].uv = uv; vtx_write[2].col = col; vtx_write[3].pos = a; vtx_write[3].uv = uv; vtx_write[3].col = col; vtx_write[4].pos = c; vtx_write[4].uv = uv; vtx_write[4].col = col; vtx_write[5].pos = d; vtx_write[5].uv = uv; vtx_write[5].col = col; vtx_write += 6; } // FIXME-OPT: In many instances the caller could provide a normal. void ImDrawList::PrimLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) { const float inv_length = 1.0f / sqrtf(ImLengthSqr(b - a)); const float dx = (b.x - a.x) * (thickness * 0.5f * inv_length); // line direction, halved const float dy = (b.y - a.y) * (thickness * 0.5f * inv_length); // line direction, halved const ImVec2 pa(a.x + dy, a.y - dx); const ImVec2 pb(b.x + dy, b.y - dx); const ImVec2 pc(b.x - dy, b.y + dx); const ImVec2 pd(a.x - dy, a.y + dx); PrimQuad(pa, pb, pc, pd, col); } void ImDrawList::AddLine(const ImVec2& a, const ImVec2& b, ImU32 col, float thickness) { if ((col >> 24) == 0) return; PrimReserve(6); PrimLine(a, b, col, thickness); } void ImDrawList::AddArcFast(const ImVec2& center, float radius, ImU32 col, int a_min, int a_max, bool filled, const ImVec2& third_point_offset) { if ((col >> 24) == 0) return; const int SAMPLES = 12; static ImVec2 circle_vtx[SAMPLES]; static bool circle_vtx_builds = false; if (!circle_vtx_builds) { for (int i = 0; i < SAMPLES; i++) { const float a = ((float)i / (float)SAMPLES) * 2*PI; circle_vtx[i].x = cosf(a + PI); circle_vtx[i].y = sinf(a + PI); } circle_vtx_builds = true; } const ImVec2 uv = GImGui->FontTexUvWhitePixel; if (filled) { PrimReserve((unsigned int)(a_max-a_min) * 3); for (int a0 = a_min; a0 < a_max; a0++) { int a1 = (a0 + 1 == SAMPLES) ? 0 : a0 + 1; PrimVtx(center + circle_vtx[a0] * radius, uv, col); PrimVtx(center + circle_vtx[a1] * radius, uv, col); PrimVtx(center + third_point_offset, uv, col); } } else { PrimReserve((unsigned int)(a_max-a_min) * 6); for (int a0 = a_min; a0 < a_max; a0++) { int a1 = (a0 + 1 == SAMPLES) ? 0 : a0 + 1; PrimLine(center + circle_vtx[a0] * radius, center + circle_vtx[a1] * radius, col); } } } void ImDrawList::AddRect(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) { if ((col >> 24) == 0) return; float r = rounding; r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); if (r == 0.0f || rounding_corners == 0) { PrimReserve(4*6); PrimLine(ImVec2(a.x,a.y), ImVec2(b.x,a.y), col); PrimLine(ImVec2(b.x,a.y), ImVec2(b.x,b.y), col); PrimLine(ImVec2(b.x,b.y), ImVec2(a.x,b.y), col); PrimLine(ImVec2(a.x,b.y), ImVec2(a.x,a.y), col); } else { PrimReserve(4*6); PrimLine(ImVec2(a.x + ((rounding_corners & 1)?r:0), a.y), ImVec2(b.x - ((rounding_corners & 2)?r:0), a.y), col); PrimLine(ImVec2(b.x, a.y + ((rounding_corners & 2)?r:0)), ImVec2(b.x, b.y - ((rounding_corners & 4)?r:0)), col); PrimLine(ImVec2(b.x - ((rounding_corners & 4)?r:0), b.y), ImVec2(a.x + ((rounding_corners & 8)?r:0), b.y), col); PrimLine(ImVec2(a.x, b.y - ((rounding_corners & 8)?r:0)), ImVec2(a.x, a.y + ((rounding_corners & 1)?r:0)), col); if (rounding_corners & 1) AddArcFast(ImVec2(a.x+r,a.y+r), r, col, 0, 3); if (rounding_corners & 2) AddArcFast(ImVec2(b.x-r,a.y+r), r, col, 3, 6); if (rounding_corners & 4) AddArcFast(ImVec2(b.x-r,b.y-r), r, col, 6, 9); if (rounding_corners & 8) AddArcFast(ImVec2(a.x+r,b.y-r), r, col, 9, 12); } } void ImDrawList::AddRectFilled(const ImVec2& a, const ImVec2& b, ImU32 col, float rounding, int rounding_corners) { if ((col >> 24) == 0) return; float r = rounding; r = ImMin(r, fabsf(b.x-a.x) * ( ((rounding_corners&(1|2))==(1|2)) || ((rounding_corners&(4|8))==(4|8)) ? 0.5f : 1.0f )); r = ImMin(r, fabsf(b.y-a.y) * ( ((rounding_corners&(1|8))==(1|8)) || ((rounding_corners&(2|4))==(2|4)) ? 0.5f : 1.0f )); if (r == 0.0f || rounding_corners == 0) { // Use triangle so we can merge more draw calls together (at the cost of extra vertices) PrimReserve(6); PrimRect(a, b, col); } else { PrimReserve(6+6*2); PrimRect(ImVec2(a.x+r,a.y), ImVec2(b.x-r,b.y), col); float top_y = (rounding_corners & 1) ? a.y+r : a.y; float bot_y = (rounding_corners & 8) ? b.y-r : b.y; PrimRect(ImVec2(a.x,top_y), ImVec2(a.x+r,bot_y), col); top_y = (rounding_corners & 2) ? a.y+r : a.y; bot_y = (rounding_corners & 4) ? b.y-r : b.y; PrimRect(ImVec2(b.x-r,top_y), ImVec2(b.x,bot_y), col); if (rounding_corners & 1) AddArcFast(ImVec2(a.x+r,a.y+r), r, col, 0, 3, true); if (rounding_corners & 2) AddArcFast(ImVec2(b.x-r,a.y+r), r, col, 3, 6, true); if (rounding_corners & 4) AddArcFast(ImVec2(b.x-r,b.y-r), r, col, 6, 9, true); if (rounding_corners & 8) AddArcFast(ImVec2(a.x+r,b.y-r), r, col, 9, 12, true); } } void ImDrawList::AddTriangleFilled(const ImVec2& a, const ImVec2& b, const ImVec2& c, ImU32 col) { if ((col >> 24) == 0) return; PrimReserve(3); PrimTriangle(a, b, c, col); } void ImDrawList::AddCircle(const ImVec2& centre, float radius, ImU32 col, int num_segments) { if ((col >> 24) == 0) return; PrimReserve((unsigned int)num_segments*6); const float a_step = 2*PI/(float)num_segments; float a0 = 0.0f; for (int i = 0; i < num_segments; i++) { const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; PrimLine(centre + ImVec2(cosf(a0), sinf(a0))*radius, centre + ImVec2(cosf(a1), sinf(a1))*radius, col); a0 = a1; } } void ImDrawList::AddCircleFilled(const ImVec2& centre, float radius, ImU32 col, int num_segments) { if ((col >> 24) == 0) return; const ImVec2 uv = GImGui->FontTexUvWhitePixel; PrimReserve((unsigned int)num_segments*3); const float a_step = 2*PI/(float)num_segments; float a0 = 0.0f; for (int i = 0; i < num_segments; i++) { const float a1 = (i + 1) == num_segments ? 0.0f : a0 + a_step; PrimVtx(centre + ImVec2(cosf(a0), sinf(a0))*radius, uv, col); PrimVtx(centre + ImVec2(cosf(a1), sinf(a1))*radius, uv, col); PrimVtx(centre, uv, col); a0 = a1; } } void ImDrawList::AddText(const ImFont* font, float font_size, const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end, float wrap_width, const ImVec2* cpu_clip_max) { if ((col >> 24) == 0) return; if (text_end == NULL) text_end = text_begin + strlen(text_begin); if (text_begin == text_end) return; IM_ASSERT(font->ContainerAtlas->TexID == texture_id_stack.back()); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font. // reserve vertices for worse case const unsigned int char_count = (unsigned int)(text_end - text_begin); const unsigned int vtx_count_max = char_count * 6; const size_t vtx_begin = vtx_buffer.size(); PrimReserve(vtx_count_max); font->RenderText(font_size, pos, col, clip_rect_stack.back(), text_begin, text_end, this, wrap_width, cpu_clip_max); // give back unused vertices vtx_buffer.resize((size_t)(vtx_write - &vtx_buffer.front())); const size_t vtx_count = vtx_buffer.size() - vtx_begin; commands.back().vtx_count -= (unsigned int)(vtx_count_max - vtx_count); vtx_write -= (vtx_count_max - vtx_count); } void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& a, const ImVec2& b, const ImVec2& uv0, const ImVec2& uv1, ImU32 col) { if ((col >> 24) == 0) return; // FIXME-OPT: This is wasting draw calls. const bool push_texture_id = texture_id_stack.empty() || user_texture_id != texture_id_stack.back(); if (push_texture_id) PushTextureID(user_texture_id); PrimReserve(6); PrimRectUV(a, b, uv0, uv1, col); if (push_texture_id) PopTextureID(); } //----------------------------------------------------------------------------- // ImFontAtlias //----------------------------------------------------------------------------- struct ImFontAtlas::ImFontAtlasData { // Input ImFont* OutFont; // Load into this font void* TTFData; // TTF data, we own the memory size_t TTFDataSize; // TTF data size, in bytes float SizePixels; // Desired output size, in pixels const ImWchar* GlyphRanges; // List of Unicode range (2 value per range, values are inclusive, zero-terminated list) int FontNo; // Index of font within .TTF file (0) // Temporary Build Data stbtt_fontinfo FontInfo; stbrp_rect* Rects; stbtt_pack_range* Ranges; int RangesCount; }; ImFontAtlas::ImFontAtlas() { TexID = NULL; TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; TexWidth = TexHeight = 0; TexUvWhitePixel = ImVec2(0, 0); } ImFontAtlas::~ImFontAtlas() { Clear(); } void ImFontAtlas::ClearInputData() { for (size_t i = 0; i < InputData.size(); i++) { if (InputData[i]->TTFData) ImGui::MemFree(InputData[i]->TTFData); ImGui::MemFree(InputData[i]); } InputData.clear(); } void ImFontAtlas::ClearTexData() { if (TexPixelsAlpha8) ImGui::MemFree(TexPixelsAlpha8); if (TexPixelsRGBA32) ImGui::MemFree(TexPixelsRGBA32); TexPixelsAlpha8 = NULL; TexPixelsRGBA32 = NULL; } void ImFontAtlas::Clear() { ClearInputData(); ClearTexData(); for (size_t i = 0; i < Fonts.size(); i++) { Fonts[i]->~ImFont(); ImGui::MemFree(Fonts[i]); } Fonts.clear(); } void ImGui::GetDefaultFontData(const void** fnt_data, unsigned int* fnt_size, const void** png_data, unsigned int* png_size) { printf("GetDefaultFontData() is obsoleted in ImGui 1.30.\n"); printf("Please use ImGui::GetIO().Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8() functions to retrieve uncompressed texture data.\n"); if (fnt_data) *fnt_data = NULL; if (fnt_size) *fnt_size = 0; if (png_data) *png_data = NULL; if (png_size) *png_size = 0; IM_ASSERT(false); } void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Lazily build if (TexPixelsAlpha8 == NULL) { if (InputData.empty()) AddFontDefault(); Build(); } *out_pixels = TexPixelsAlpha8; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 1; } void ImFontAtlas::GetTexDataAsRGBA32(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel) { // Lazily convert to RGBA32 format // Although it is likely to be the most commonly used format, our font rendering is 8 bpp if (!TexPixelsRGBA32) { unsigned char* pixels; GetTexDataAsAlpha8(&pixels, NULL, NULL); TexPixelsRGBA32 = (unsigned int*)ImGui::MemAlloc((size_t)(TexWidth * TexHeight * 4)); const unsigned char* src = pixels; unsigned int* dst = TexPixelsRGBA32; for (int n = TexWidth * TexHeight; n > 0; n--) *dst++ = ((unsigned int)(*src++) << 24) | 0x00FFFFFF; } *out_pixels = (unsigned char*)TexPixelsRGBA32; if (out_width) *out_width = TexWidth; if (out_height) *out_height = TexHeight; if (out_bytes_per_pixel) *out_bytes_per_pixel = 4; } static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size); static unsigned int stb_decompress_length(unsigned char *input); static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length); // Load embedded ProggyClean.ttf at size 13 ImFont* ImFontAtlas::AddFontDefault() { unsigned int ttf_compressed_size; const void* ttf_compressed; GetDefaultCompressedFontDataTTF(&ttf_compressed, &ttf_compressed_size); ImFont* font = AddFontFromMemoryCompressedTTF(ttf_compressed, ttf_compressed_size, 13.0f, GetGlyphRangesDefault(), 0); font->DisplayOffset.y += 1; return font; } ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImWchar* glyph_ranges, int font_no) { void* data = NULL; size_t data_size = 0; if (!ImLoadFileToMemory(filename, "rb", (void**)&data, &data_size)) { IM_ASSERT(0); // Could not load file. return NULL; } ImFont* font = AddFontFromMemoryTTF(data, (unsigned int)data_size, size_pixels, glyph_ranges, font_no); return font; } // NB: ownership of 'data' is given to ImFontAtlas which will clear it. ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* in_ttf_data, unsigned int in_ttf_data_size, float size_pixels, const ImWchar* glyph_ranges, int font_no) { // Create new font ImFont* font = (ImFont*)ImGui::MemAlloc(sizeof(ImFont)); new (font) ImFont(); Fonts.push_back(font); // Add to build list ImFontAtlasData* data = (ImFontAtlasData*)ImGui::MemAlloc(sizeof(ImFontAtlasData)); memset(data, 0, sizeof(ImFontAtlasData)); data->OutFont = font; data->TTFData = in_ttf_data; data->TTFDataSize = in_ttf_data_size; data->SizePixels = size_pixels; data->GlyphRanges = glyph_ranges; data->FontNo = font_no; InputData.push_back(data); // Invalidate texture ClearTexData(); return font; } ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* in_compressed_ttf_data, unsigned int in_compressed_ttf_data_size, float size_pixels, const ImWchar* glyph_ranges, int font_no) { // Decompress const size_t buf_decompressed_size = stb_decompress_length((unsigned char*)in_compressed_ttf_data); unsigned char* buf_decompressed = (unsigned char *)ImGui::MemAlloc(buf_decompressed_size); stb_decompress(buf_decompressed, (unsigned char*)in_compressed_ttf_data, in_compressed_ttf_data_size); // Add ImFont* font = AddFontFromMemoryTTF(buf_decompressed, (unsigned int)buf_decompressed_size, size_pixels, glyph_ranges, font_no); return font; } bool ImFontAtlas::Build() { IM_ASSERT(InputData.size() > 0); TexID = NULL; TexWidth = TexHeight = 0; TexUvWhitePixel = ImVec2(0, 0); ClearTexData(); // Initialize font information early (so we can error without any cleanup) + count glyphs int total_glyph_count = 0; int total_glyph_range_count = 0; for (size_t input_i = 0; input_i < InputData.size(); input_i++) { ImFontAtlasData& data = *InputData[input_i]; IM_ASSERT(data.OutFont && !data.OutFont->IsLoaded()); const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)data.TTFData, data.FontNo); IM_ASSERT(font_offset >= 0); if (!stbtt_InitFont(&data.FontInfo, (unsigned char*)data.TTFData, font_offset)) return false; if (!data.GlyphRanges) data.GlyphRanges = GetGlyphRangesDefault(); for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) { total_glyph_count += (in_range[1] - in_range[0]) + 1; total_glyph_range_count++; } } // Start packing TexWidth = (total_glyph_count > 1000) ? 1024 : 512; // Width doesn't actually matters. TexHeight = 0; const int max_tex_height = 1024*32; stbtt_pack_context spc; int ret = stbtt_PackBegin(&spc, NULL, TexWidth, max_tex_height, 0, 1, NULL); IM_ASSERT(ret); stbtt_PackSetOversampling(&spc, 1, 1); // Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values). ImVector<stbrp_rect> extra_rects; RenderCustomTexData(0, &extra_rects); stbrp_pack_rects((stbrp_context*)spc.pack_info, &extra_rects[0], (int)extra_rects.size()); for (size_t i = 0; i < extra_rects.size(); i++) if (extra_rects[i].was_packed) TexHeight = ImMax(TexHeight, extra_rects[i].y + extra_rects[i].h); // Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0) int buf_packedchars_n = 0, buf_rects_n = 0, buf_ranges_n = 0; stbtt_packedchar* buf_packedchars = (stbtt_packedchar*)ImGui::MemAlloc(total_glyph_count * sizeof(stbtt_packedchar)); stbrp_rect* buf_rects = (stbrp_rect*)ImGui::MemAlloc(total_glyph_count * sizeof(stbrp_rect)); stbtt_pack_range* buf_ranges = (stbtt_pack_range*)ImGui::MemAlloc(total_glyph_range_count * sizeof(stbtt_pack_range)); memset(buf_packedchars, 0, total_glyph_count * sizeof(stbtt_packedchar)); memset(buf_rects, 0, total_glyph_count * sizeof(stbrp_rect)); // Unnecessary but let's clear this for the sake of sanity. memset(buf_ranges, 0, total_glyph_range_count * sizeof(stbtt_pack_range)); // First font pass: pack all glyphs (no rendering at this point, we are working with glyph sizes only) for (size_t input_i = 0; input_i < InputData.size(); input_i++) { ImFontAtlasData& data = *InputData[input_i]; // Setup ranges int glyph_count = 0; int glyph_ranges_count = 0; for (const ImWchar* in_range = data.GlyphRanges; in_range[0] && in_range[1]; in_range += 2) { glyph_count += (in_range[1] - in_range[0]) + 1; glyph_ranges_count++; } data.Ranges = buf_ranges + buf_ranges_n; data.RangesCount = glyph_ranges_count; buf_ranges_n += glyph_ranges_count; for (int i = 0; i < glyph_ranges_count; i++) { const ImWchar* in_range = &data.GlyphRanges[i * 2]; stbtt_pack_range& range = data.Ranges[i]; range.font_size = data.SizePixels; range.first_unicode_char_in_range = in_range[0]; range.num_chars_in_range = (in_range[1] - in_range[0]) + 1; range.chardata_for_range = buf_packedchars + buf_packedchars_n; buf_packedchars_n += range.num_chars_in_range; } // Pack data.Rects = buf_rects + buf_rects_n; buf_rects_n += glyph_count; const int n = stbtt_PackFontRangesGatherRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); stbrp_pack_rects((stbrp_context*)spc.pack_info, data.Rects, n); // Extend texture height for (int i = 0; i < n; i++) if (data.Rects[i].was_packed) TexHeight = ImMax(TexHeight, data.Rects[i].y + data.Rects[i].h); } IM_ASSERT(buf_rects_n == total_glyph_count); IM_ASSERT(buf_packedchars_n == total_glyph_count); IM_ASSERT(buf_ranges_n == total_glyph_range_count); // Create texture TexHeight = ImUpperPowerOfTwo(TexHeight); TexPixelsAlpha8 = (unsigned char*)ImGui::MemAlloc(TexWidth * TexHeight); memset(TexPixelsAlpha8, 0, TexWidth * TexHeight); spc.pixels = TexPixelsAlpha8; spc.height = TexHeight; // Second pass: render characters for (size_t input_i = 0; input_i < InputData.size(); input_i++) { ImFontAtlasData& data = *InputData[input_i]; ret = stbtt_PackFontRangesRenderIntoRects(&spc, &data.FontInfo, data.Ranges, data.RangesCount, data.Rects); data.Rects = NULL; } // End packing stbtt_PackEnd(&spc); ImGui::MemFree(buf_rects); buf_rects = NULL; // Third pass: setup ImFont and glyphs for runtime for (size_t input_i = 0; input_i < InputData.size(); input_i++) { ImFontAtlasData& data = *InputData[input_i]; data.OutFont->ContainerAtlas = this; data.OutFont->FontSize = data.SizePixels; const float font_scale = stbtt_ScaleForPixelHeight(&data.FontInfo, data.SizePixels); int font_ascent, font_descent, font_line_gap; stbtt_GetFontVMetrics(&data.FontInfo, &font_ascent, &font_descent, &font_line_gap); const float uv_scale_x = 1.0f / TexWidth; const float uv_scale_y = 1.0f / TexHeight; const int character_spacing_x = 1; for (int i = 0; i < data.RangesCount; i++) { stbtt_pack_range& range = data.Ranges[i]; for (int char_idx = 0; char_idx < range.num_chars_in_range; char_idx += 1) { const int codepoint = range.first_unicode_char_in_range + char_idx; const stbtt_packedchar& pc = range.chardata_for_range[char_idx]; if (!pc.x0 && !pc.x1 && !pc.y0 && !pc.y1) continue; data.OutFont->Glyphs.resize(data.OutFont->Glyphs.size() + 1); ImFont::Glyph& glyph = data.OutFont->Glyphs.back(); glyph.Codepoint = (ImWchar)codepoint; glyph.Width = (signed short)pc.x1 - pc.x0 + 1; glyph.Height = (signed short)pc.y1 - pc.y0 + 1; glyph.XOffset = (signed short)(pc.xoff); glyph.YOffset = (signed short)(pc.yoff + (int)(font_ascent * font_scale)); glyph.XAdvance = (signed short)(pc.xadvance + character_spacing_x); // Bake spacing into XAdvance glyph.U0 = ((float)pc.x0 - 0.5f) * uv_scale_x; glyph.V0 = ((float)pc.y0 - 0.5f) * uv_scale_y; glyph.U1 = ((float)pc.x0 - 0.5f + glyph.Width) * uv_scale_x; glyph.V1 = ((float)pc.y0 - 0.5f + glyph.Height) * uv_scale_y; } } data.OutFont->BuildLookupTable(); } // Cleanup temporaries ImGui::MemFree(buf_packedchars); ImGui::MemFree(buf_ranges); buf_packedchars = NULL; buf_ranges = NULL; ClearInputData(); // Render into our custom data block RenderCustomTexData(1, &extra_rects); return true; } void ImFontAtlas::RenderCustomTexData(int pass, void* p_rects) { // . = white layer, X = black layer, others are blank const int TEX_DATA_W = 90; const int TEX_DATA_H = 27; const char texture_data[TEX_DATA_W*TEX_DATA_H+1] = { "..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX" "..- -X.....X- X.X - X.X -X.....X - X.....X" "--- -XXX.XXX- X...X - X...X -X....X - X....X" "X - X.X - X.....X - X.....X -X...X - X...X" "XX - X.X -X.......X- X.......X -X..X.X - X.X..X" "X.X - X.X -XXXX.XXXX- XXXX.XXXX -X.X X.X - X.X X.X" "X..X - X.X - X.X - X.X -XX X.X - X.X XX" "X...X - X.X - X.X - XX X.X XX - X.X - X.X " "X....X - X.X - X.X - X.X X.X X.X - X.X - X.X " "X.....X - X.X - X.X - X..X X.X X..X - X.X - X.X " "X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.X " "X.......X - X.X - X.X -X.....................X- X.X X.X-X.X X.X " "X........X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X..X-X..X.X " "X.........X -XXX.XXX- X.X - X..X X.X X..X - X...X-X...X " "X..........X-X.....X- X.X - X.X X.X X.X - X....X-X....X " "X......XXXXX-XXXXXXX- X.X - XX X.X XX - X.....X-X.....X " "X...X..X --------- X.X - X.X - XXXXXXX-XXXXXXX " "X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------" "X.X X..X - -X.......X- X.......X - XX XX - " "XX X..X - - X.....X - X.....X - X.X X.X - " " X..X - X...X - X...X - X..X X..X - " " XX - X.X - X.X - X...XXXXXXXXXXXXX...X - " "------------ - X - X -X.....................X- " " ----------------------------------- X...XXXXXXXXXXXXX...X - " " - X..X X..X - " " - X.X X.X - " " - XX XX - " }; ImVector<stbrp_rect>& rects = *(ImVector<stbrp_rect>*)p_rects; if (pass == 0) { stbrp_rect r; memset(&r, 0, sizeof(r)); r.w = (TEX_DATA_W*2)+1; r.h = TEX_DATA_H+1; rects.push_back(r); } else if (pass == 1) { // Copy pixels const stbrp_rect& r = rects[0]; for (int y = 0, n = 0; y < TEX_DATA_H; y++) for (int x = 0; x < TEX_DATA_W; x++, n++) { const int offset0 = (int)(r.x + x) + (int)(r.y + y) * TexWidth; const int offset1 = offset0 + 1 + TEX_DATA_W; TexPixelsAlpha8[offset0] = texture_data[n] == '.' ? 0xFF : 0x00; TexPixelsAlpha8[offset1] = texture_data[n] == 'X' ? 0xFF : 0x00; } const ImVec2 tex_uv_scale(1.0f / TexWidth, 1.0f / TexHeight); TexUvWhitePixel = ImVec2(r.x + 0.5f, r.y + 0.5f) * tex_uv_scale; const ImVec2 cursor_datas[ImGuiMouseCursor_Count_][3] = { // Pos ........ Size ......... Offset ...... { ImVec2(0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow { ImVec2(13,0), ImVec2(7,16), ImVec2( 4, 8) }, // ImGuiMouseCursor_TextInput { ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_Move { ImVec2(21,0), ImVec2( 9,23), ImVec2( 5,11) }, // ImGuiMouseCursor_ResizeNS { ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 5) }, // ImGuiMouseCursor_ResizeEW { ImVec2(73,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNESW { ImVec2(55,0), ImVec2(17,17), ImVec2( 9, 9) }, // ImGuiMouseCursor_ResizeNWSE }; for (int type = 0; type < ImGuiMouseCursor_Count_; type++) { ImGuiMouseCursorData& cursor_data = GImGui->MouseCursorData[type]; ImVec2 pos = cursor_datas[type][0] + ImVec2((float)r.x, (float)r.y); const ImVec2 size = cursor_datas[type][1]; cursor_data.Type = type; cursor_data.Size = size; cursor_data.Offset = cursor_datas[type][2]; cursor_data.TexUvMin[0] = (pos) * tex_uv_scale; cursor_data.TexUvMax[0] = (pos + size) * tex_uv_scale; pos.x += TEX_DATA_W+1; cursor_data.TexUvMin[1] = (pos) * tex_uv_scale; cursor_data.TexUvMax[1] = (pos + size) * tex_uv_scale; } } } //----------------------------------------------------------------------------- // ImFont //----------------------------------------------------------------------------- ImFont::ImFont() { Scale = 1.0f; FallbackChar = (ImWchar)'?'; Clear(); } ImFont::~ImFont() { // Invalidate active font so that the user gets a clear crash instead of a dangling pointer. // If you want to delete fonts you need to do it between Render() and NewFrame(). ImGuiState& g = *GImGui; if (g.Font == this) g.Font = NULL; Clear(); } void ImFont::Clear() { FontSize = 0.0f; DisplayOffset = ImVec2(-0.5f, 0.5f); ContainerAtlas = NULL; Glyphs.clear(); FallbackGlyph = NULL; FallbackXAdvance = 0.0f; IndexXAdvance.clear(); IndexLookup.clear(); } // Retrieve list of range (2 int per range, values are inclusive) const ImWchar* ImFontAtlas::GetGlyphRangesDefault() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesChinese() { static const ImWchar ranges[] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF, // Half-width characters 0x4e00, 0x9FAF, // CJK Ideograms 0, }; return &ranges[0]; } const ImWchar* ImFontAtlas::GetGlyphRangesJapanese() { // Store the 1946 ideograms code points as successive offsets from the initial unicode codepoint 0x4E00. Each offset has an implicit +1. // This encoding helps us reduce the source code size. static const short offsets_from_0x4E00[] = { -1,0,1,3,0,0,0,0,1,0,5,1,1,0,7,4,6,10,0,1,9,9,7,1,3,19,1,10,7,1,0,1,0,5,1,0,6,4,2,6,0,0,12,6,8,0,3,5,0,1,0,9,0,0,8,1,1,3,4,5,13,0,0,8,2,17, 4,3,1,1,9,6,0,0,0,2,1,3,2,22,1,9,11,1,13,1,3,12,0,5,9,2,0,6,12,5,3,12,4,1,2,16,1,1,4,6,5,3,0,6,13,15,5,12,8,14,0,0,6,15,3,6,0,18,8,1,6,14,1, 5,4,12,24,3,13,12,10,24,0,0,0,1,0,1,1,2,9,10,2,2,0,0,3,3,1,0,3,8,0,3,2,4,4,1,6,11,10,14,6,15,3,4,15,1,0,0,5,2,2,0,0,1,6,5,5,6,0,3,6,5,0,0,1,0, 11,2,2,8,4,7,0,10,0,1,2,17,19,3,0,2,5,0,6,2,4,4,6,1,1,11,2,0,3,1,2,1,2,10,7,6,3,16,0,8,24,0,0,3,1,1,3,0,1,6,0,0,0,2,0,1,5,15,0,1,0,0,2,11,19, 1,4,19,7,6,5,1,0,0,0,0,5,1,0,1,9,0,0,5,0,2,0,1,0,3,0,11,3,0,2,0,0,0,0,0,9,3,6,4,12,0,14,0,0,29,10,8,0,14,37,13,0,31,16,19,0,8,30,1,20,8,3,48, 21,1,0,12,0,10,44,34,42,54,11,18,82,0,2,1,2,12,1,0,6,2,17,2,12,7,0,7,17,4,2,6,24,23,8,23,39,2,16,23,1,0,5,1,2,15,14,5,6,2,11,0,8,6,2,2,2,14, 20,4,15,3,4,11,10,10,2,5,2,1,30,2,1,0,0,22,5,5,0,3,1,5,4,1,0,0,2,2,21,1,5,1,2,16,2,1,3,4,0,8,4,0,0,5,14,11,2,16,1,13,1,7,0,22,15,3,1,22,7,14, 22,19,11,24,18,46,10,20,64,45,3,2,0,4,5,0,1,4,25,1,0,0,2,10,0,0,0,1,0,1,2,0,0,9,1,2,0,0,0,2,5,2,1,1,5,5,8,1,1,1,5,1,4,9,1,3,0,1,0,1,1,2,0,0, 2,0,1,8,22,8,1,0,0,0,0,4,2,1,0,9,8,5,0,9,1,30,24,2,6,4,39,0,14,5,16,6,26,179,0,2,1,1,0,0,0,5,2,9,6,0,2,5,16,7,5,1,1,0,2,4,4,7,15,13,14,0,0, 3,0,1,0,0,0,2,1,6,4,5,1,4,9,0,3,1,8,0,0,10,5,0,43,0,2,6,8,4,0,2,0,0,9,6,0,9,3,1,6,20,14,6,1,4,0,7,2,3,0,2,0,5,0,3,1,0,3,9,7,0,3,4,0,4,9,1,6,0, 9,0,0,2,3,10,9,28,3,6,2,4,1,2,32,4,1,18,2,0,3,1,5,30,10,0,2,2,2,0,7,9,8,11,10,11,7,2,13,7,5,10,0,3,40,2,0,1,6,12,0,4,5,1,5,11,11,21,4,8,3,7, 8,8,33,5,23,0,0,19,8,8,2,3,0,6,1,1,1,5,1,27,4,2,5,0,3,5,6,3,1,0,3,1,12,5,3,3,2,0,7,7,2,1,0,4,0,1,1,2,0,10,10,6,2,5,9,7,5,15,15,21,6,11,5,20, 4,3,5,5,2,5,0,2,1,0,1,7,28,0,9,0,5,12,5,5,18,30,0,12,3,3,21,16,25,32,9,3,14,11,24,5,66,9,1,2,0,5,9,1,5,1,8,0,8,3,3,0,1,15,1,4,8,1,2,7,0,7,2, 8,3,7,5,3,7,10,2,1,0,0,2,25,0,6,4,0,10,0,4,2,4,1,12,5,38,4,0,4,1,10,5,9,4,0,14,4,2,5,18,20,21,1,3,0,5,0,7,0,3,7,1,3,1,1,8,1,0,0,0,3,2,5,2,11, 6,0,13,1,3,9,1,12,0,16,6,2,1,0,2,1,12,6,13,11,2,0,28,1,7,8,14,13,8,13,0,2,0,5,4,8,10,2,37,42,19,6,6,7,4,14,11,18,14,80,7,6,0,4,72,12,36,27, 7,7,0,14,17,19,164,27,0,5,10,7,3,13,6,14,0,2,2,5,3,0,6,13,0,0,10,29,0,4,0,3,13,0,3,1,6,51,1,5,28,2,0,8,0,20,2,4,0,25,2,10,13,10,0,16,4,0,1,0, 2,1,7,0,1,8,11,0,0,1,2,7,2,23,11,6,6,4,16,2,2,2,0,22,9,3,3,5,2,0,15,16,21,2,9,20,15,15,5,3,9,1,0,0,1,7,7,5,4,2,2,2,38,24,14,0,0,15,5,6,24,14, 5,5,11,0,21,12,0,3,8,4,11,1,8,0,11,27,7,2,4,9,21,59,0,1,39,3,60,62,3,0,12,11,0,3,30,11,0,13,88,4,15,5,28,13,1,4,48,17,17,4,28,32,46,0,16,0, 18,11,1,8,6,38,11,2,6,11,38,2,0,45,3,11,2,7,8,4,30,14,17,2,1,1,65,18,12,16,4,2,45,123,12,56,33,1,4,3,4,7,0,0,0,3,2,0,16,4,2,4,2,0,7,4,5,2,26, 2,25,6,11,6,1,16,2,6,17,77,15,3,35,0,1,0,5,1,0,38,16,6,3,12,3,3,3,0,9,3,1,3,5,2,9,0,18,0,25,1,3,32,1,72,46,6,2,7,1,3,14,17,0,28,1,40,13,0,20, 15,40,6,38,24,12,43,1,1,9,0,12,6,0,6,2,4,19,3,7,1,48,0,9,5,0,5,6,9,6,10,15,2,11,19,3,9,2,0,1,10,1,27,8,1,3,6,1,14,0,26,0,27,16,3,4,9,6,2,23, 9,10,5,25,2,1,6,1,1,48,15,9,15,14,3,4,26,60,29,13,37,21,1,6,4,0,2,11,22,23,16,16,2,2,1,3,0,5,1,6,4,0,0,4,0,0,8,3,0,2,5,0,7,1,7,3,13,2,4,10, 3,0,2,31,0,18,3,0,12,10,4,1,0,7,5,7,0,5,4,12,2,22,10,4,2,15,2,8,9,0,23,2,197,51,3,1,1,4,13,4,3,21,4,19,3,10,5,40,0,4,1,1,10,4,1,27,34,7,21, 2,17,2,9,6,4,2,3,0,4,2,7,8,2,5,1,15,21,3,4,4,2,2,17,22,1,5,22,4,26,7,0,32,1,11,42,15,4,1,2,5,0,19,3,1,8,6,0,10,1,9,2,13,30,8,2,24,17,19,1,4, 4,25,13,0,10,16,11,39,18,8,5,30,82,1,6,8,18,77,11,13,20,75,11,112,78,33,3,0,0,60,17,84,9,1,1,12,30,10,49,5,32,158,178,5,5,6,3,3,1,3,1,4,7,6, 19,31,21,0,2,9,5,6,27,4,9,8,1,76,18,12,1,4,0,3,3,6,3,12,2,8,30,16,2,25,1,5,5,4,3,0,6,10,2,3,1,0,5,1,19,3,0,8,1,5,2,6,0,0,0,19,1,2,0,5,1,2,5, 1,3,7,0,4,12,7,3,10,22,0,9,5,1,0,2,20,1,1,3,23,30,3,9,9,1,4,191,14,3,15,6,8,50,0,1,0,0,4,0,0,1,0,2,4,2,0,2,3,0,2,0,2,2,8,7,0,1,1,1,3,3,17,11, 91,1,9,3,2,13,4,24,15,41,3,13,3,1,20,4,125,29,30,1,0,4,12,2,21,4,5,5,19,11,0,13,11,86,2,18,0,7,1,8,8,2,2,22,1,2,6,5,2,0,1,2,8,0,2,0,5,2,1,0, 2,10,2,0,5,9,2,1,2,0,1,0,4,0,0,10,2,5,3,0,6,1,0,1,4,4,33,3,13,17,3,18,6,4,7,1,5,78,0,4,1,13,7,1,8,1,0,35,27,15,3,0,0,0,1,11,5,41,38,15,22,6, 14,14,2,1,11,6,20,63,5,8,27,7,11,2,2,40,58,23,50,54,56,293,8,8,1,5,1,14,0,1,12,37,89,8,8,8,2,10,6,0,0,0,4,5,2,1,0,1,1,2,7,0,3,3,0,4,6,0,3,2, 19,3,8,0,0,0,4,4,16,0,4,1,5,1,3,0,3,4,6,2,17,10,10,31,6,4,3,6,10,126,7,3,2,2,0,9,0,0,5,20,13,0,15,0,6,0,2,5,8,64,50,3,2,12,2,9,0,0,11,8,20, 109,2,18,23,0,0,9,61,3,0,28,41,77,27,19,17,81,5,2,14,5,83,57,252,14,154,263,14,20,8,13,6,57,39,38, }; static int ranges_unpacked = false; static ImWchar ranges[8 + IM_ARRAYSIZE(offsets_from_0x4E00)*2 + 1] = { 0x0020, 0x00FF, // Basic Latin + Latin Supplement 0x3000, 0x30FF, // Punctuations, Hiragana, Katakana 0x31F0, 0x31FF, // Katakana Phonetic Extensions 0xFF00, 0xFFEF, // Half-width characters }; if (!ranges_unpacked) { // Unpack int codepoint = 0x4e00; ImWchar* dst = &ranges[8]; for (int n = 0; n < IM_ARRAYSIZE(offsets_from_0x4E00); n++, dst += 2) dst[0] = dst[1] = (ImWchar)(codepoint += (offsets_from_0x4E00[n] + 1)); dst[0] = 0; ranges_unpacked = true; } return &ranges[0]; } void ImFont::BuildLookupTable() { int max_codepoint = 0; for (size_t i = 0; i != Glyphs.size(); i++) max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint); IndexXAdvance.clear(); IndexXAdvance.resize((size_t)max_codepoint + 1); IndexLookup.clear(); IndexLookup.resize((size_t)max_codepoint + 1); for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) { IndexXAdvance[i] = -1.0f; IndexLookup[i] = -1; } for (size_t i = 0; i < Glyphs.size(); i++) { const size_t codepoint = (int)Glyphs[i].Codepoint; IndexXAdvance[codepoint] = Glyphs[i].XAdvance; IndexLookup[codepoint] = (int)i; } // Create a glyph to handle TAB // FIXME: Needs proper TAB handling but it needs to be contextualized (can arbitrary say that each string starts at "column 0" if (FindGlyph((unsigned short)' ')) { if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times Glyphs.resize(Glyphs.size() + 1); ImFont::Glyph& tab_glyph = Glyphs.back(); tab_glyph = *FindGlyph((unsigned short)' '); tab_glyph.Codepoint = '\t'; tab_glyph.XAdvance *= 4; IndexXAdvance[(size_t)tab_glyph.Codepoint] = (float)tab_glyph.XAdvance; IndexLookup[(size_t)tab_glyph.Codepoint] = (int)(Glyphs.size()-1); } FallbackGlyph = NULL; FallbackGlyph = FindGlyph(FallbackChar); FallbackXAdvance = FallbackGlyph ? FallbackGlyph->XAdvance : 0.0f; for (size_t i = 0; i < (size_t)max_codepoint + 1; i++) if (IndexXAdvance[i] < 0.0f) IndexXAdvance[i] = FallbackXAdvance; } void ImFont::SetFallbackChar(ImWchar c) { FallbackChar = c; BuildLookupTable(); } const ImFont::Glyph* ImFont::FindGlyph(unsigned short c) const { if (c < (int)IndexLookup.size()) { const int i = IndexLookup[c]; if (i != -1) return &Glyphs[i]; } return FallbackGlyph; } // Convert UTF-8 to 32-bits character, process single character input. // Based on stb_from_utf8() from github.com/nothings/stb/ // We handle UTF-8 decoding error by skipping forward. static int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end) { unsigned int c = (unsigned int)-1; const unsigned char* str = (const unsigned char*)in_text; if (!(*str & 0x80)) { c = (unsigned int)(*str++); *out_char = c; return 1; } if ((*str & 0xe0) == 0xc0) { *out_char = 0; if (in_text_end && in_text_end - (const char*)str < 2) return 0; if (*str < 0xc2) return 0; c = (unsigned int)((*str++ & 0x1f) << 6); if ((*str & 0xc0) != 0x80) return 0; c += (*str++ & 0x3f); *out_char = c; return 2; } if ((*str & 0xf0) == 0xe0) { *out_char = 0; if (in_text_end && in_text_end - (const char*)str < 3) return 0; if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 0; if (*str == 0xed && str[1] > 0x9f) return 0; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x0f) << 12); if ((*str & 0xc0) != 0x80) return 0; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 0; c += (*str++ & 0x3f); *out_char = c; return 3; } if ((*str & 0xf8) == 0xf0) { *out_char = 0; if (in_text_end && in_text_end - (const char*)str < 4) return 0; if (*str > 0xf4) return 0; if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 0; if (*str == 0xf4 && str[1] > 0x8f) return 0; // str[1] < 0x80 is checked below c = (unsigned int)((*str++ & 0x07) << 18); if ((*str & 0xc0) != 0x80) return 0; c += (unsigned int)((*str++ & 0x3f) << 12); if ((*str & 0xc0) != 0x80) return 0; c += (unsigned int)((*str++ & 0x3f) << 6); if ((*str & 0xc0) != 0x80) return 0; c += (*str++ & 0x3f); // utf-8 encodings of values used in surrogate pairs are invalid if ((c & 0xFFFFF800) == 0xD800) return 0; *out_char = c; return 4; } *out_char = 0; return 0; } static ptrdiff_t ImTextStrFromUtf8(ImWchar* buf, size_t buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining) { ImWchar* buf_out = buf; ImWchar* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes *buf_out++ = (ImWchar)c; } *buf_out = 0; if (in_text_remaining) *in_text_remaining = in_text; return buf_out - buf; } static int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end) { int char_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { unsigned int c; in_text += ImTextCharFromUtf8(&c, in_text, in_text_end); if (c == 0) break; if (c < 0x10000) char_count++; } return char_count; } // Based on stb_to_utf8() from github.com/nothings/stb/ static int ImTextCharToUtf8(char* buf, size_t buf_size, unsigned int c) { if (c) { size_t i = 0; size_t n = buf_size; if (c < 0x80) { if (i+1 > n) return 0; buf[i++] = (char)c; return 1; } else if (c < 0x800) { if (i+2 > n) return 0; buf[i++] = (char)(0xc0 + (c >> 6)); buf[i++] = (char)(0x80 + (c & 0x3f)); return 2; } else if (c >= 0xdc00 && c < 0xe000) { return 0; } else if (c >= 0xd800 && c < 0xdc00) { if (i+4 > n) return 0; buf[i++] = (char)(0xf0 + (c >> 18)); buf[i++] = (char)(0x80 + ((c >> 12) & 0x3f)); buf[i++] = (char)(0x80 + ((c >> 6) & 0x3f)); buf[i++] = (char)(0x80 + ((c ) & 0x3f)); return 4; } //else if (c < 0x10000) { if (i+3 > n) return 0; buf[i++] = (char)(0xe0 + (c >> 12)); buf[i++] = (char)(0x80 + ((c>> 6) & 0x3f)); buf[i++] = (char)(0x80 + ((c ) & 0x3f)); return 3; } } return 0; } static ptrdiff_t ImTextStrToUtf8(char* buf, size_t buf_size, const ImWchar* in_text, const ImWchar* in_text_end) { char* buf_out = buf; const char* buf_end = buf + buf_size; while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text) { buf_out += ImTextCharToUtf8(buf_out, (uintptr_t)(buf_end-buf_out-1), (unsigned int)*in_text); in_text++; } *buf_out = 0; return buf_out - buf; } static int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end) { int bytes_count = 0; while ((!in_text_end || in_text < in_text_end) && *in_text) { char dummy[5]; // FIXME-OPT bytes_count += ImTextCharToUtf8(dummy, 5, (unsigned int)*in_text); in_text++; } return bytes_count; } const char* ImFont::CalcWordWrapPositionA(float scale, const char* text, const char* text_end, float wrap_width) const { // Simple word-wrapping for English, not full-featured. Please submit failing cases! // FIXME: Much possible improvements (don't cut things like "word !", "word!!!" but cut within "word,,,,", more sensible support for punctuations, support for Unicode punctuations, etc.) // For references, possible wrap point marked with ^ // "aaa bbb, ccc,ddd. eee fff. ggg!" // ^ ^ ^ ^ ^__ ^ ^ // List of hardcoded separators: .,;!?'" // Skip extra blanks after a line returns (that includes not counting them in width computation) // e.g. "Hello world" --> "Hello" "World" // Cut words that cannot possibly fit within one line. // e.g.: "The tropical fish" with ~5 characters worth of width --> "The tr" "opical" "fish" float line_width = 0.0f; float word_width = 0.0f; float blank_width = 0.0f; const char* word_end = text; const char* prev_word_end = NULL; bool inside_word = true; const char* s = text; while (s < text_end) { unsigned int c = (unsigned int)*s; const char* next_s; if (c < 0x80) next_s = s + 1; else next_s = s + ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; if (c == '\n') { line_width = word_width = blank_width = 0.0f; inside_word = true; s = next_s; continue; } const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; if (ImCharIsSpace(c)) { if (inside_word) { line_width += blank_width; blank_width = 0.0f; } blank_width += char_width; inside_word = false; } else { word_width += char_width; if (inside_word) { word_end = next_s; } else { prev_word_end = word_end; line_width += word_width + blank_width; word_width = blank_width = 0.0f; } // Allow wrapping after punctuation. inside_word = !(c == '.' || c == ',' || c == ';' || c == '!' || c == '?' || c == '\"'); } // We ignore blank width at the end of the line (they can be skipped) if (line_width + word_width >= wrap_width) { // Words that cannot possibly fit within an entire line will be cut anywhere. if (word_width < wrap_width) s = prev_word_end ? prev_word_end : word_end; break; } s = next_s; } return s; } ImVec2 ImFont::CalcTextSizeA(float size, float max_width, float wrap_width, const char* text_begin, const char* text_end, const char** remaining) const { if (!text_end) text_end = text_begin + strlen(text_begin); // FIXME-OPT: Need to avoid this. const float scale = size / FontSize; const float line_height = FontSize * scale; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; const char* s = text_begin; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - line_width); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { if (text_size.x < line_width) text_size.x = line_width; text_size.y += line_height; line_width = 0.0f; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) const char* prev_s = s; unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; } if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; continue; } const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; if (line_width + char_width >= max_width) { s = prev_s; break; } line_width += char_width; } if (line_width > 0 || text_size.y == 0.0f) { if (text_size.x < line_width) text_size.x = line_width; text_size.y += line_height; } if (remaining) *remaining = s; return text_size; } ImVec2 ImFont::CalcTextSizeW(float size, float max_width, const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining) const { if (!text_end) text_end = text_begin + ImStrlenW(text_begin); const float scale = size / FontSize; const float line_height = FontSize * scale; ImVec2 text_size = ImVec2(0,0); float line_width = 0.0f; const ImWchar* s = text_begin; while (s < text_end) { const unsigned int c = (unsigned int)(*s++); if (c == '\n') { text_size.x = ImMax(text_size.x, line_width); text_size.y += line_height; line_width = 0.0f; continue; } const float char_width = ((size_t)c < IndexXAdvance.size()) ? IndexXAdvance[(size_t)c] * scale : FallbackXAdvance; if (line_width + char_width >= max_width) { s--; break; } line_width += char_width; } if (line_width > 0 || text_size.y == 0.0f) { if (text_size.x < line_width) text_size.x = line_width; text_size.y += line_height; } if (remaining) *remaining = s; return text_size; } void ImFont::RenderText(float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect_ref, const char* text_begin, const char* text_end, ImDrawList* draw_list, float wrap_width, const ImVec2* cpu_clip_max) const { if (!text_end) text_end = text_begin + strlen(text_begin); const float scale = size / FontSize; const float line_height = FontSize * scale; // Align to be pixel perfect pos.x = (float)(int)pos.x + DisplayOffset.x; pos.y = (float)(int)pos.y + DisplayOffset.y; const bool word_wrap_enabled = (wrap_width > 0.0f); const char* word_wrap_eol = NULL; ImVec4 clip_rect = clip_rect_ref; if (cpu_clip_max) { clip_rect.z = ImMin(clip_rect.z, cpu_clip_max->x); clip_rect.w = ImMin(clip_rect.w, cpu_clip_max->y); } float x = pos.x; float y = pos.y; ImDrawVert* out_vertices = draw_list->vtx_write; const char* s = text_begin; while (s < text_end) { if (word_wrap_enabled) { // Calculate how far we can render. Requires two passes on the string data but keeps the code simple and not intrusive for what's essentially an uncommon feature. if (!word_wrap_eol) { word_wrap_eol = CalcWordWrapPositionA(scale, s, text_end, wrap_width - (x - pos.x)); if (word_wrap_eol == s) // Wrap_width is too small to fit anything. Force displaying 1 character to minimize the height discontinuity. word_wrap_eol++; // +1 may not be a character start point in UTF-8 but it's ok because we use s >= word_wrap_eol below } if (s >= word_wrap_eol) { x = pos.x; y += line_height; word_wrap_eol = NULL; // Wrapping skips upcoming blanks while (s < text_end) { const char c = *s; if (ImCharIsSpace(c)) { s++; } else if (c == '\n') { s++; break; } else { break; } } continue; } } // Decode and advance source (handle unlikely UTF-8 decoding failure by skipping to the next byte) unsigned int c = (unsigned int)*s; if (c < 0x80) { s += 1; } else { s += ImTextCharFromUtf8(&c, s, text_end); if (c == 0) break; } if (c == '\n') { x = pos.x; y += line_height; continue; } float char_width = 0.0f; if (const Glyph* glyph = FindGlyph((unsigned short)c)) { char_width = glyph->XAdvance * scale; if (c != ' ' && c != '\t') { // Clipping on Y is more likely float y1 = (float)(y + glyph->YOffset * scale); float y2 = (float)(y1 + glyph->Height * scale); if (y1 <= clip_rect.w && y2 >= clip_rect.y) { float x1 = (float)(x + glyph->XOffset * scale); float x2 = (float)(x1 + glyph->Width * scale); if (x1 <= clip_rect.z && x2 >= clip_rect.x) { // Render a character float u1 = glyph->U0; float v1 = glyph->V0; float u2 = glyph->U1; float v2 = glyph->V1; // CPU side clipping used to fit text in their frame when the frame is too small. Only does clipping for axis aligned quad and in the "max" direction (bottom-right) if (cpu_clip_max) { if (x2 > cpu_clip_max->x) { const float clip_tx = (cpu_clip_max->x - x1) / (x2 - x1); x2 = cpu_clip_max->x; u2 = u1 + clip_tx * (u2 - u1); } if (y2 > cpu_clip_max->y) { const float clip_ty = (cpu_clip_max->y - y1) / (y2 - y1); y2 = cpu_clip_max->y; v2 = v1 + clip_ty * (v2 - v1); } } // NB: we are not calling PrimRectUV() here because non-inlined causes too much overhead in a debug build. out_vertices[0].pos = ImVec2(x1, y1); out_vertices[0].uv = ImVec2(u1, v1); out_vertices[0].col = col; out_vertices[1].pos = ImVec2(x2, y1); out_vertices[1].uv = ImVec2(u2, v1); out_vertices[1].col = col; out_vertices[2].pos = ImVec2(x2, y2); out_vertices[2].uv = ImVec2(u2, v2); out_vertices[2].col = col; out_vertices[3] = out_vertices[0]; out_vertices[4] = out_vertices[2]; out_vertices[5].pos = ImVec2(x1, y2); out_vertices[5].uv = ImVec2(u1, v2); out_vertices[5].col = col; out_vertices += 6; } } } } x += char_width; } draw_list->vtx_write = out_vertices; } //----------------------------------------------------------------------------- // PLATFORM DEPENDANT HELPERS //----------------------------------------------------------------------------- #if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS) #ifndef _WINDOWS_ #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // Win32 API clipboard implementation static const char* GetClipboardTextFn_DefaultImpl() { static char* buf_local = NULL; if (buf_local) { ImGui::MemFree(buf_local); buf_local = NULL; } if (!OpenClipboard(NULL)) return NULL; HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT); if (wbuf_handle == NULL) return NULL; if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle)) { int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1; buf_local = (char*)ImGui::MemAlloc(buf_len * sizeof(char)); ImTextStrToUtf8(buf_local, buf_len, wbuf_global, NULL); } GlobalUnlock(wbuf_handle); CloseClipboard(); return buf_local; } // Win32 API clipboard implementation static void SetClipboardTextFn_DefaultImpl(const char* text) { if (!OpenClipboard(NULL)) return; const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1; HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar)); if (wbuf_handle == NULL) return; ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle); ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL); GlobalUnlock(wbuf_handle); EmptyClipboard(); SetClipboardData(CF_UNICODETEXT, wbuf_handle); CloseClipboard(); } #else // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static const char* GetClipboardTextFn_DefaultImpl() { return GImGui->PrivateClipboard; } // Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers static void SetClipboardTextFn_DefaultImpl(const char* text) { ImGuiState& g = *GImGui; if (g.PrivateClipboard) { ImGui::MemFree(g.PrivateClipboard); g.PrivateClipboard = NULL; } const char* text_end = text + strlen(text); g.PrivateClipboard = (char*)ImGui::MemAlloc((size_t)(text_end - text) + 1); memcpy(g.PrivateClipboard, text, (size_t)(text_end - text)); g.PrivateClipboard[(size_t)(text_end - text)] = 0; } #endif #if defined(_MSC_VER) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS) #ifndef _WINDOWS_ #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #include <Imm.h> #pragma comment(lib, "imm32") static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y) { // Notify OS Input Method Editor of text input position if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle) if (HIMC himc = ImmGetContext(hwnd)) { COMPOSITIONFORM cf; cf.ptCurrentPos.x = x; cf.ptCurrentPos.y = y; cf.dwStyle = CFS_FORCE_POSITION; ImmSetCompositionWindow(himc, &cf); } } #else static void ImeSetInputScreenPosFn_DefaultImpl(int, int) { } #endif #ifdef IMGUI_DISABLE_TEST_WINDOWS void ImGui::ShowUserGuide() {} void ImGui::ShowStyleEditor(ImGuiStyle*) {} void ImGui::ShowTestWindow(bool*) {} void ImGui::ShowMetricsWindow(bool*) {} #else //----------------------------------------------------------------------------- // HELP //----------------------------------------------------------------------------- void ImGui::ShowUserGuide() { ImGuiState& g = *GImGui; ImGui::BulletText("Double-click on title bar to collapse window."); ImGui::BulletText("Click and drag on lower right corner to resize window."); ImGui::BulletText("Click and drag on any empty space to move window."); ImGui::BulletText("Mouse Wheel to scroll."); if (g.IO.FontAllowUserScaling) ImGui::BulletText("CTRL+Mouse Wheel to zoom window contents."); ImGui::BulletText("TAB/SHIFT+TAB to cycle through keyboard editable fields."); ImGui::BulletText("CTRL+Click on a slider to input text."); ImGui::BulletText( "While editing text:\n" "- Hold SHIFT or use mouse to select text\n" "- CTRL+Left/Right to word jump\n" "- CTRL+A select all\n" "- CTRL+X,CTRL+C,CTRL+V clipboard\n" "- CTRL+Z,CTRL+Y undo/redo\n" "- ESCAPE to revert\n" "- You can apply arithmetic operators +,*,/ on numerical values.\n" " Use +- to subtract.\n"); } void ImGui::ShowStyleEditor(ImGuiStyle* ref) { ImGuiState& g = *GImGui; ImGuiStyle& style = g.Style; const ImGuiStyle def; // Default style if (ImGui::Button("Revert Style")) g.Style = ref ? *ref : def; if (ref) { ImGui::SameLine(); if (ImGui::Button("Save Style")) *ref = g.Style; } ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.55f); if (ImGui::TreeNode("Sizes")) { ImGui::SliderFloat("Alpha", &style.Alpha, 0.20f, 1.0f, "%.2f"); // Not exposing zero here so user doesn't "lose" the UI. But application code could have a toggle to switch between zero and non-zero. ImGui::SliderFloat2("WindowPadding", (float*)&style.WindowPadding, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat("WindowRounding", &style.WindowRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat("ChildWindowRounding", &style.ChildWindowRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat2("FramePadding", (float*)&style.FramePadding, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat("FrameRounding", &style.FrameRounding, 0.0f, 16.0f, "%.0f"); ImGui::SliderFloat2("ItemSpacing", (float*)&style.ItemSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("ItemInnerSpacing", (float*)&style.ItemInnerSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat2("TouchExtraPadding", (float*)&style.TouchExtraPadding, 0.0f, 10.0f, "%.0f"); ImGui::SliderFloat("IndentSpacing", &style.IndentSpacing, 0.0f, 20.0f, "%.0f"); ImGui::SliderFloat("ScrollBarWidth", &style.ScrollbarWidth, 1.0f, 20.0f, "%.0f"); ImGui::SliderFloat("GrabMinSize", &style.GrabMinSize, 1.0f, 20.0f, "%.0f"); ImGui::TreePop(); } if (ImGui::TreeNode("Colors")) { static int output_dest = 0; static bool output_only_modified = false; if (ImGui::Button("Output Colors")) { if (output_dest == 0) ImGui::LogToClipboard(); else ImGui::LogToTTY(); ImGui::LogText("ImGuiStyle& style = ImGui::GetStyle();" STR_NEWLINE); for (int i = 0; i < ImGuiCol_COUNT; i++) { const ImVec4& col = style.Colors[i]; const char* name = ImGui::GetStyleColName(i); if (!output_only_modified || memcmp(&col, (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) ImGui::LogText("style.Colors[ImGuiCol_%s]%*s= ImVec4(%.2ff, %.2ff, %.2ff, %.2ff);" STR_NEWLINE, name, 22 - strlen(name), "", col.x, col.y, col.z, col.w); } ImGui::LogFinish(); } ImGui::SameLine(); ImGui::PushItemWidth(150); ImGui::Combo("##output_type", &output_dest, "To Clipboard\0To TTY"); ImGui::PopItemWidth(); ImGui::SameLine(); ImGui::Checkbox("Only Modified Fields", &output_only_modified); static ImGuiColorEditMode edit_mode = ImGuiColorEditMode_RGB; ImGui::RadioButton("RGB", &edit_mode, ImGuiColorEditMode_RGB); ImGui::SameLine(); ImGui::RadioButton("HSV", &edit_mode, ImGuiColorEditMode_HSV); ImGui::SameLine(); ImGui::RadioButton("HEX", &edit_mode, ImGuiColorEditMode_HEX); //ImGui::Text("Tip: Click on colored square to change edit mode."); static ImGuiTextFilter filter; filter.Draw("Filter colors", 200); ImGui::BeginChild("#colors", ImVec2(0, 300), true); ImGui::ColorEditMode(edit_mode); for (int i = 0; i < ImGuiCol_COUNT; i++) { const char* name = ImGui::GetStyleColName(i); if (!filter.PassFilter(name)) continue; ImGui::PushID(i); ImGui::ColorEdit4(name, (float*)&style.Colors[i], true); if (memcmp(&style.Colors[i], (ref ? &ref->Colors[i] : &def.Colors[i]), sizeof(ImVec4)) != 0) { ImGui::SameLine(); if (ImGui::Button("Revert")) style.Colors[i] = ref ? ref->Colors[i] : def.Colors[i]; if (ref) { ImGui::SameLine(); if (ImGui::Button("Save")) ref->Colors[i] = style.Colors[i]; } } ImGui::PopID(); } ImGui::EndChild(); ImGui::TreePop(); } ImGui::PopItemWidth(); } //----------------------------------------------------------------------------- // SAMPLE CODE //----------------------------------------------------------------------------- static void ShowExampleAppConsole(bool* opened); static void ShowExampleAppLongText(bool* opened); static void ShowExampleAppAutoResize(bool* opened); static void ShowExampleAppFixedOverlay(bool* opened); static void ShowExampleAppManipulatingWindowTitle(bool* opened); static void ShowExampleAppCustomRendering(bool* opened); // Demonstrate ImGui features (unfortunately this makes this function a little bloated!) void ImGui::ShowTestWindow(bool* opened) { // Examples apps static bool show_app_metrics = false; static bool show_app_console = false; static bool show_app_long_text = false; static bool show_app_auto_resize = false; static bool show_app_fixed_overlay = false; static bool show_app_custom_rendering = false; static bool show_app_manipulating_window_title = false; if (show_app_metrics) ImGui::ShowMetricsWindow(&show_app_metrics); if (show_app_console) ShowExampleAppConsole(&show_app_console); if (show_app_long_text) ShowExampleAppLongText(&show_app_long_text); if (show_app_auto_resize) ShowExampleAppAutoResize(&show_app_auto_resize); if (show_app_fixed_overlay) ShowExampleAppFixedOverlay(&show_app_fixed_overlay); if (show_app_manipulating_window_title) ShowExampleAppManipulatingWindowTitle(&show_app_manipulating_window_title); if (show_app_custom_rendering) ShowExampleAppCustomRendering(&show_app_custom_rendering); static bool no_titlebar = false; static bool no_border = true; static bool no_resize = false; static bool no_move = false; static bool no_scrollbar = false; static bool no_collapse = false; static float bg_alpha = 0.65f; // Demonstrate the various window flags. Typically you would just use the default. ImGuiWindowFlags window_flags = 0; if (no_titlebar) window_flags |= ImGuiWindowFlags_NoTitleBar; if (!no_border) window_flags |= ImGuiWindowFlags_ShowBorders; if (no_resize) window_flags |= ImGuiWindowFlags_NoResize; if (no_move) window_flags |= ImGuiWindowFlags_NoMove; if (no_scrollbar) window_flags |= ImGuiWindowFlags_NoScrollbar; if (no_collapse) window_flags |= ImGuiWindowFlags_NoCollapse; if (!ImGui::Begin("ImGui Test", opened, ImVec2(550,680), bg_alpha, window_flags)) { // Early out if the window is collapsed, as an optimization. ImGui::End(); return; } //ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.65f); // 2/3 of the space for widget and 1/3 for labels ImGui::PushItemWidth(-140); // Right align, keep 140 pixels for labels ImGui::Text("ImGui says hello."); //ImGui::Text("MousePos (%g, %g)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); //ImGui::Text("MouseWheel %d", ImGui::GetIO().MouseWheel); //ImGui::Text("KeyMods %s%s%s", ImGui::GetIO().KeyCtrl ? "CTRL" : "", ImGui::GetIO().KeyShift ? "SHIFT" : "", ImGui::GetIO().KeyAlt? "ALT" : ""); //ImGui::Text("WantCaptureMouse: %d", ImGui::GetIO().WantCaptureMouse); //ImGui::Text("WantCaptureKeyboard: %d", ImGui::GetIO().WantCaptureKeyboard); ImGui::Spacing(); if (ImGui::CollapsingHeader("Help")) { ImGui::TextWrapped("This window is being created by the ShowTestWindow() function. Please refer to the code for programming reference.\n\nUser Guide:"); ImGui::ShowUserGuide(); } if (ImGui::CollapsingHeader("Window options")) { ImGui::Checkbox("no titlebar", &no_titlebar); ImGui::SameLine(150); ImGui::Checkbox("no border", &no_border); ImGui::SameLine(300); ImGui::Checkbox("no resize", &no_resize); ImGui::Checkbox("no move", &no_move); ImGui::SameLine(150); ImGui::Checkbox("no scrollbar", &no_scrollbar); ImGui::SameLine(300); ImGui::Checkbox("no collapse", &no_collapse); ImGui::SliderFloat("bg alpha", &bg_alpha, 0.0f, 1.0f); if (ImGui::TreeNode("Style")) { ImGui::ShowStyleEditor(); ImGui::TreePop(); } if (ImGui::TreeNode("Fonts")) { ImGui::TextWrapped("Tip: Load fonts with GetIO().Fonts->AddFontFromFileTTF()."); for (size_t i = 0; i < ImGui::GetIO().Fonts->Fonts.size(); i++) { ImFont* font = ImGui::GetIO().Fonts->Fonts[i]; ImGui::BulletText("Font %d: %.2f pixels, %d glyphs", i, font->FontSize, font->Glyphs.size()); ImGui::TreePush((void*)i); ImGui::PushFont(font); ImGui::Text("The quick brown fox jumps over the lazy dog"); ImGui::PopFont(); if (i > 0 && ImGui::Button("Set as default")) { ImGui::GetIO().Fonts->Fonts[i] = ImGui::GetIO().Fonts->Fonts[0]; ImGui::GetIO().Fonts->Fonts[0] = font; } ImGui::SliderFloat("font scale", &font->Scale, 0.3f, 2.0f, "%.1f"); // scale only this font ImGui::TreePop(); } static float window_scale = 1.0f; ImGui::SliderFloat("this window scale", &window_scale, 0.3f, 2.0f, "%.1f"); // scale only this window ImGui::SliderFloat("global scale", &ImGui::GetIO().FontGlobalScale, 0.3f, 2.0f, "%.1f"); // scale everything ImGui::SetWindowFontScale(window_scale); ImGui::TreePop(); } if (ImGui::TreeNode("Logging")) { ImGui::LogButtons(); ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Widgets")) { static bool a=false; if (ImGui::Button("Button")) { printf("Clicked\n"); a ^= 1; } if (a) { ImGui::SameLine(); ImGui::Text("Thanks for clicking me!"); } if (ImGui::TreeNode("Tree")) { for (size_t i = 0; i < 5; i++) { if (ImGui::TreeNode((void*)i, "Child %d", i)) { ImGui::Text("blah blah"); ImGui::SameLine(); if (ImGui::SmallButton("print")) printf("Child %d pressed", (int)i); ImGui::TreePop(); } } ImGui::TreePop(); } if (ImGui::TreeNode("Bullets")) { ImGui::BulletText("Bullet point 1"); ImGui::BulletText("Bullet point 2\nOn multiple lines"); ImGui::Bullet(); ImGui::Text("Bullet point 3 (two calls)"); ImGui::Bullet(); ImGui::SmallButton("Button 1"); ImGui::Bullet(); ImGui::SmallButton("Button 2"); ImGui::TreePop(); } if (ImGui::TreeNode("Colored Text")) { // Using shortcut. You can use PushStyleColor()/PopStyleColor() for more flexibility. ImGui::TextColored(ImVec4(1.0f,0.0f,1.0f,1.0f), "Pink"); ImGui::TextColored(ImVec4(1.0f,1.0f,0.0f,1.0f), "Yellow"); ImGui::TreePop(); } if (ImGui::TreeNode("Word Wrapping")) { // Using shortcut. You can use PushTextWrapPos()/PopTextWrapPos() for more flexibility. ImGui::TextWrapped("This text should automatically wrap on the edge of the window. The current implementation for text wrapping follows simple rules that works for English and possibly other languages."); ImGui::Spacing(); static float wrap_width = 200.0f; ImGui::SliderFloat("Wrap width", &wrap_width, -20, 600, "%.0f"); ImGui::Text("Test paragraph 1:"); ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); ImGui::Text("lazy dog. This paragraph is made to fit within %.0f pixels. The quick brown fox jumps over the lazy dog.", wrap_width); ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); ImGui::PopTextWrapPos(); ImGui::Text("Test paragraph 2:"); ImGui::GetWindowDrawList()->AddRectFilled(ImGui::GetCursorScreenPos() + ImVec2(wrap_width, 0.0f), ImGui::GetCursorScreenPos() + ImVec2(wrap_width+10, ImGui::GetTextLineHeight()), 0xFFFF00FF); ImGui::PushTextWrapPos(ImGui::GetCursorPos().x + wrap_width); ImGui::Text("aaaaaaaa bbbbbbbb, cccccccc,dddddddd. eeeeeeee ffffffff. gggggggg!hhhhhhhh"); ImGui::GetWindowDrawList()->AddRect(ImGui::GetItemRectMin(), ImGui::GetItemRectMax(), 0xFF00FFFF); ImGui::PopTextWrapPos(); ImGui::TreePop(); } if (ImGui::TreeNode("UTF-8 Text")) { // UTF-8 test with Japanese characters // (needs a suitable font, try Arial Unicode or M+ fonts http://mplus-fonts.sourceforge.jp/mplus-outline-fonts/index-en.html) // Most compiler appears to support UTF-8 in source code (with Visual Studio you need to save your file as 'UTF-8 without signature') // However for the sake for maximum portability here we are *not* including raw UTF-8 character in this source file, instead we encode the string with hexadecimal constants. // In your own application be reasonable and use UTF-8 in source or retrieve the data from file system! // Note that characters values are preserved even if the font cannot be displayed, so you can safely copy & paste garbled characters into another application. ImGui::TextWrapped("CJK text will only appears if the font was loaded with the appropriate CJK character ranges. Call io.Font->LoadFromFileTTF() manually to load extra character ranges."); ImGui::Text("Hiragana: \xe3\x81\x8b\xe3\x81\x8d\xe3\x81\x8f\xe3\x81\x91\xe3\x81\x93 (kakikukeko)"); ImGui::Text("Kanjis: \xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e (nihongo)"); static char buf[32] = "\xe6\x97\xa5\xe6\x9c\xac\xe8\xaa\x9e"; ImGui::InputText("UTF-8 input", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); } if (ImGui::TreeNode("Clipping")) { static ImVec2 size(80, 20); ImGui::TextWrapped("On a per-widget basis we are occasionally clipping text if it won't fit in its frame."); ImGui::SliderFloat2("size", (float*)&size, 5.0f, 200.0f); ImGui::Button("Line 1 hello\nLine 2 clip me!", size); ImGui::TextWrapped("Otherwise we are doing coarser clipping + passing a scissor rectangle to the renderer. The system is designed to try minimizing both execution and rendering cost."); ImGui::TreePop(); } if (ImGui::TreeNode("Images")) { ImGui::TextWrapped("Below we are displaying the font texture (which is the only texture we have access to in this demo). Use the 'ImTextureID' type as storage to pass pointers or identifier to your own texture data. Hover the texture for a zoomed view!"); ImVec2 tex_screen_pos = ImGui::GetCursorScreenPos(); float tex_w = (float)ImGui::GetIO().Fonts->TexWidth; float tex_h = (float)ImGui::GetIO().Fonts->TexHeight; ImTextureID tex_id = ImGui::GetIO().Fonts->TexID; ImGui::Image(tex_id, ImVec2(tex_w, tex_h), ImVec2(0,0), ImVec2(1,1), ImColor(255,255,255,255), ImColor(255,255,255,128)); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); float focus_sz = 32.0f; float focus_x = ImClamp(ImGui::GetMousePos().x - tex_screen_pos.x - focus_sz * 0.5f, 0.0f, tex_w - focus_sz); float focus_y = ImClamp(ImGui::GetMousePos().y - tex_screen_pos.y - focus_sz * 0.5f, 0.0f, tex_h - focus_sz); ImGui::Text("Min: (%.2f, %.2f)", focus_x, focus_y); ImGui::Text("Max: (%.2f, %.2f)", focus_x + focus_sz, focus_y + focus_sz); ImVec2 uv0 = ImVec2((focus_x) / tex_w, (focus_y) / tex_h); ImVec2 uv1 = ImVec2((focus_x + focus_sz) / tex_w, (focus_y + focus_sz) / tex_h); ImGui::Image(tex_id, ImVec2(128,128), uv0, uv1, ImColor(255,255,255,255), ImColor(255,255,255,128)); ImGui::EndTooltip(); } ImGui::TextWrapped("And now some textured buttons.."); static int pressed_count = 0; for (int i = 0; i < 8; i++) { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); int frame_padding = -1 + i; // -1 padding uses default padding if (ImGui::ImageButton(tex_id, ImVec2(32,32), ImVec2(0,0), ImVec2(32.0f/tex_w,32/tex_h), frame_padding)) pressed_count += 1; ImGui::PopID(); } ImGui::Text("Pressed %d times.", pressed_count); ImGui::TreePop(); } if (ImGui::TreeNode("Selectables")) { if (ImGui::TreeNode("Basic")) { static bool selected[3] = { false, true, false }; ImGui::Selectable("1. I am selectable", &selected[0]); ImGui::Selectable("2. I am selectable", &selected[1]); ImGui::Text("3. I am not selectable"); ImGui::Selectable("4. I am selectable", &selected[2]); ImGui::TreePop(); } if (ImGui::TreeNode("Rendering more text into the same block")) { static bool selected[3] = { false, false, false }; ImGui::Selectable("main.c", &selected[0]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); ImGui::Selectable("Hello.cpp", &selected[1]); ImGui::SameLine(300); ImGui::Text("12,345 bytes"); ImGui::Selectable("Hello.h", &selected[2]); ImGui::SameLine(300); ImGui::Text(" 2,345 bytes"); ImGui::TreePop(); } if (ImGui::TreeNode("Grid")) { static bool selected[16] = { true, false, false, false, false, true, false, false, false, false, true, false, false, false, false, true }; for (int i = 0; i < 16; i++) { ImGui::PushID(i); if (ImGui::Selectable("Me", &selected[i], ImVec2(50,50))) { int x = i % 4, y = i / 4; if (x > 0) selected[i - 1] ^= 1; if (x < 3) selected[i + 1] ^= 1; if (y > 0) selected[i - 4] ^= 1; if (y < 3) selected[i + 4] ^= 1; } if ((i % 4) < 3) ImGui::SameLine(); ImGui::PopID(); } ImGui::TreePop(); } ImGui::TreePop(); } if (ImGui::TreeNode("Popup")) { static bool popup_open = false; static int selected_fish = -1; const char* fishes[] = { "Bream", "Haddock", "Mackerel", "Pollock", "Tilefish" }; if (ImGui::Button("Select..")) popup_open = true; ImGui::SameLine(); ImGui::Text(selected_fish == -1 ? "<None>" : fishes[selected_fish]); if (popup_open) { ImGui::BeginPopup(&popup_open); ImGui::Text("Aquarium"); ImGui::Separator(); for (int i = 0; i < IM_ARRAYSIZE(fishes); i++) { if (ImGui::Selectable(fishes[i], false)) { selected_fish = i; popup_open = false; } } ImGui::EndPopup(); } ImGui::TreePop(); } if (ImGui::TreeNode("Filtered Text Input")) { static char buf1[64] = ""; ImGui::InputText("default", buf1, 64); static char buf2[64] = ""; ImGui::InputText("decimal", buf2, 64, ImGuiInputTextFlags_CharsDecimal); static char buf3[64] = ""; ImGui::InputText("hexadecimal", buf3, 64, ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase); static char buf4[64] = ""; ImGui::InputText("uppercase", buf4, 64, ImGuiInputTextFlags_CharsUppercase); static char buf5[64] = ""; ImGui::InputText("no blank", buf5, 64, ImGuiInputTextFlags_CharsNoBlank); struct TextFilters { static int FilterImGuiLetters(ImGuiTextEditCallbackData* data) { if (data->EventChar < 256 && strchr("imgui", (char)data->EventChar)) return 0; return 1; } }; static char buf6[64] = ""; ImGui::InputText("\"imgui\" letters", buf6, 64, ImGuiInputTextFlags_CallbackCharFilter, TextFilters::FilterImGuiLetters); ImGui::TreePop(); } static bool check = true; ImGui::Checkbox("checkbox", &check); static int e = 0; ImGui::RadioButton("radio a", &e, 0); ImGui::SameLine(); ImGui::RadioButton("radio b", &e, 1); ImGui::SameLine(); ImGui::RadioButton("radio c", &e, 2); // Color buttons, demonstrate using PushID() to add unique identifier in the ID stack, and changing style. for (int i = 0; i < 7; i++) { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleColor(ImGuiCol_Button, ImColor::HSV(i/7.0f, 0.6f, 0.6f)); ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImColor::HSV(i/7.0f, 0.7f, 0.7f)); ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImColor::HSV(i/7.0f, 0.8f, 0.8f)); ImGui::Button("Click"); ImGui::PopStyleColor(3); ImGui::PopID(); } ImGui::Text("Hover over me"); if (ImGui::IsItemHovered()) ImGui::SetTooltip("I am a tooltip"); ImGui::SameLine(); ImGui::Text("- or me"); if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::Text("I am a fancy tooltip"); static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Curve", arr, IM_ARRAYSIZE(arr)); ImGui::EndTooltip(); } // Testing IMGUI_ONCE_UPON_A_FRAME macro //for (int i = 0; i < 5; i++) //{ // IMGUI_ONCE_UPON_A_FRAME // { // ImGui::Text("This will be displayed only once."); // } //} ImGui::Separator(); ImGui::LabelText("label", "Value"); static int item = 1; ImGui::Combo("combo", &item, "aaaa\0bbbb\0cccc\0dddd\0eeee\0\0"); const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD", "EEEE", "FFFF", "GGGG", "HHHH", "IIII", "JJJJ", "KKKK" }; static int item2 = -1; ImGui::Combo("combo scroll", &item2, items, IM_ARRAYSIZE(items)); { static char str0[128] = "Hello, world!"; static int i0=123; static float f0=0.001f; ImGui::InputText("input text", str0, IM_ARRAYSIZE(str0)); ImGui::InputInt("input int", &i0); ImGui::InputFloat("input float", &f0, 0.01f, 1.0f); static float vec4a[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; ImGui::InputFloat3("input float3", vec4a); } { static int i1=50; static int i2=42; ImGui::DragInt("drag int", &i1, 1); ImGui::SameLine(); ImGui::TextColored(ImColor(170,170,170,255), "(?)"); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Click and drag to edit value.\nHold SHIFT/ALT for faster/slower edit.\nDouble-click or CTRL+click to input text"); ImGui::DragInt("drag int 0..100", &i2, 1, 0, 100, "%.0f%%"); static float f1=1.00f; static float f2=0.0067f; ImGui::DragFloat("drag float", &f1, 1.0f); ImGui::DragFloat("drag small float", &f2, 0.0001f, 0.0f, 0.0f, "%.06f ns"); } { static int i1=0; //static int i2=42; ImGui::SliderInt("slider int 0..3", &i1, 0, 3); //ImGui::SliderInt("slider int -100..100", &i2, -100, 100); static float f1=0.123f; static float f2=0.0f; ImGui::SliderFloat("slider float", &f1, 0.0f, 1.0f, "ratio = %.3f"); ImGui::SliderFloat("slider log float", &f2, -10.0f, 10.0f, "%.4f", 3.0f); static float angle = 0.0f; ImGui::SliderAngle("slider angle", &angle); } static float col1[3] = { 1.0f,0.0f,0.2f }; static float col2[4] = { 0.4f,0.7f,0.0f,0.5f }; ImGui::ColorEdit3("color 1", col1); ImGui::ColorEdit4("color 2", col2); const char* listbox_items[] = { "Apple", "Banana", "Cherry", "Kiwi", "Mango", "Orange", "Pineapple", "Strawberry", "Watermelon" }; static int listbox_item_current = 1; ImGui::ListBox("listbox\n(single select)", &listbox_item_current, listbox_items, IM_ARRAYSIZE(listbox_items), 4); //static int listbox_item_current2 = 2; //ImGui::PushItemWidth(-1); //ImGui::ListBox("##listbox2", &listbox_item_current2, listbox_items, IM_ARRAYSIZE(listbox_items), 4); //ImGui::PopItemWidth(); if (ImGui::TreeNode("Multi-component Widgets")) { ImGui::Unindent(); static float vec4f[4] = { 0.10f, 0.20f, 0.30f, 0.44f }; static int vec4i[4] = { 1, 5, 100, 255 }; ImGui::InputFloat2("input float2", vec4f); ImGui::DragFloat2("drag float2", vec4f, 0.01f, 0.0f, 1.0f); ImGui::SliderFloat2("slider float2", vec4f, 0.0f, 1.0f); ImGui::DragInt2("drag int2", vec4i, 1, 0, 255); ImGui::InputInt2("input int2", vec4i); ImGui::SliderInt2("slider int2", vec4i, 0, 255); ImGui::InputFloat3("input float3", vec4f); ImGui::DragFloat3("drag float3", vec4f, 0.01f, 0.0f, 1.0f); ImGui::SliderFloat3("slider float3", vec4f, 0.0f, 1.0f); ImGui::DragInt3("drag int3", vec4i, 1, 0, 255); ImGui::InputInt3("input int3", vec4i); ImGui::SliderInt3("slider int3", vec4i, 0, 255); ImGui::InputFloat4("input float4", vec4f); ImGui::DragFloat4("drag float4", vec4f, 0.01f, 0.0f, 1.0f); ImGui::SliderFloat4("slider float4", vec4f, 0.0f, 1.0f); ImGui::InputInt4("input int4", vec4i); ImGui::DragInt4("drag int4", vec4i, 1, 0, 255); ImGui::SliderInt4("slider int4", vec4i, 0, 255); ImGui::Indent(); ImGui::TreePop(); } if (ImGui::TreeNode("Vertical Sliders")) { ImGui::Unindent(); const float spacing = 4; ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(spacing, spacing)); static int int_value = 0; ImGui::VSliderInt("##int", ImVec2(18,160), &int_value, 0, 5); ImGui::SameLine(); static float values[7] = { 0.0f, 0.60f, 0.35f, 0.9f, 0.70f, 0.20f, 0.0f }; ImGui::PushID("set1"); for (int i = 0; i < 7; i++) { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleColor(ImGuiCol_FrameBg, ImColor::HSV(i/7.0f, 0.5f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgHovered, ImColor::HSV(i/7.0f, 0.6f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_FrameBgActive, ImColor::HSV(i/7.0f, 0.7f, 0.5f)); ImGui::PushStyleColor(ImGuiCol_SliderGrab, ImColor::HSV(i/7.0f, 0.9f, 0.9f)); ImGui::VSliderFloat("##v", ImVec2(18,160), &values[i], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values[i]); ImGui::PopStyleColor(4); ImGui::PopID(); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("set2"); static float values2[4] = { 0.20f, 0.80f, 0.40f, 0.25f }; const int rows = 3; const ImVec2 small_slider_size(18, (160.0f-(rows-1)*spacing)/rows); for (int nx = 0; nx < 4; nx++) { if (nx > 0) ImGui::SameLine(); ImGui::BeginGroup(); for (int ny = 0; ny < rows; ny++) { ImGui::PushID(nx*rows+ny); ImGui::VSliderFloat("##v", small_slider_size, &values2[nx], 0.0f, 1.0f, ""); if (ImGui::IsItemActive() || ImGui::IsItemHovered()) ImGui::SetTooltip("%.3f", values2[nx]); ImGui::PopID(); } ImGui::EndGroup(); } ImGui::PopID(); ImGui::SameLine(); ImGui::PushID("set3"); for (int i = 0; i < 4; i++) { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::PushStyleVar(ImGuiStyleVar_GrabMinSize, 40); ImGui::VSliderFloat("##v", ImVec2(40,160), &values[i], 0.0f, 1.0f, "%.2f"); ImGui::PopStyleVar(); ImGui::PopID(); } ImGui::PopID(); ImGui::Indent(); ImGui::TreePop(); } if (ImGui::TreeNode("Dragging")) { // You can use ImGui::GetItemActiveDragDelta() to query for the dragged amount on any widget. static ImVec2 value_raw(0.0f, 0.0f); static ImVec2 value_with_lock_threshold(0.0f, 0.0f); ImGui::Button("Drag Me"); if (ImGui::IsItemActive()) { value_raw = ImGui::GetMouseDragDelta(0, 0.0f); value_with_lock_threshold = ImGui::GetMouseDragDelta(0); //ImGui::SetTooltip("Delta: %.1f, %.1f", value.x, value.y); // Draw a line between the button and the mouse cursor ImDrawList* draw_list = ImGui::GetWindowDrawList(); draw_list->PushClipRectFullScreen(); draw_list->AddLine(ImGui::CalcItemRectClosestPoint(ImGui::GetIO().MousePos, true, -2.0f), ImGui::GetIO().MousePos, ImColor(ImGui::GetStyle().Colors[ImGuiCol_Button]), 4.0f); draw_list->PopClipRect(); } ImGui::SameLine(); ImGui::Text("Raw (%.1f, %.1f), WithLockThresold (%.1f, %.1f)", value_raw.x, value_raw.y, value_with_lock_threshold.x, value_with_lock_threshold.y); ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Graphs widgets")) { static float arr[] = { 0.6f, 0.1f, 1.0f, 0.5f, 0.92f, 0.1f, 0.2f }; ImGui::PlotLines("Frame Times", arr, IM_ARRAYSIZE(arr)); static bool pause; static ImVector<float> values; if (values.empty()) { values.resize(90); memset(&values.front(), 0, values.size()*sizeof(float)); } static size_t values_offset = 0; if (!pause) { // create dummy data at fixed 60 hz rate static float refresh_time = -1.0f; if (ImGui::GetTime() > refresh_time + 1.0f/60.0f) { refresh_time = ImGui::GetTime(); static float phase = 0.0f; values[values_offset] = cosf(phase); values_offset = (values_offset+1)%values.size(); phase += 0.10f*values_offset; } } ImGui::PlotLines("##Graph", &values.front(), (int)values.size(), (int)values_offset, "avg 0.0", -1.0f, 1.0f, ImVec2(0,80)); ImGui::SameLine(0, (int)ImGui::GetStyle().ItemInnerSpacing.x); ImGui::BeginGroup(); ImGui::Text("Graph"); ImGui::Checkbox("pause", &pause); ImGui::EndGroup(); ImGui::PlotHistogram("Histogram", arr, IM_ARRAYSIZE(arr), 0, NULL, 0.0f, 1.0f, ImVec2(0,80)); } if (ImGui::CollapsingHeader("Layout")) { if (ImGui::TreeNode("Widgets Alignment")) { static float f = 0.0f; ImGui::Text("Fixed: 100 pixels"); ImGui::PushItemWidth(100); ImGui::InputFloat("float##1", &f); ImGui::PopItemWidth(); ImGui::Text("Proportional: 50%% of window width"); ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f); ImGui::InputFloat("float##2", &f); ImGui::PopItemWidth(); ImGui::Text("Right-aligned: Leave 100 pixels for label"); ImGui::PushItemWidth(-100); ImGui::InputFloat("float##3", &f); ImGui::PopItemWidth(); ImGui::TreePop(); } if (ImGui::TreeNode("Basic Horizontal Layout")) { ImGui::TextWrapped("(Use ImGui::SameLine() to keep adding items to the right of the preceeding item)"); // Text ImGui::Text("Two items: Hello"); ImGui::SameLine(); ImGui::TextColored(ImVec4(1,1,0,1), "World"); // Adjust spacing ImGui::Text("More spacing: Hello"); ImGui::SameLine(0, 20); ImGui::TextColored(ImVec4(1,1,0,1), "World"); // Button ImGui::AlignFirstTextHeightToWidgets(); ImGui::Text("Normal buttons"); ImGui::SameLine(); ImGui::Button("Banana"); ImGui::SameLine(); ImGui::Button("Apple"); ImGui::SameLine(); ImGui::Button("Corniflower"); // Button ImGui::Text("Small buttons"); ImGui::SameLine(); ImGui::SmallButton("Like this one"); ImGui::SameLine(); ImGui::Text("can fit within a text block."); // Aligned to arbitrary position. Easy/cheap column. ImGui::Text("Aligned"); ImGui::SameLine(150); ImGui::Text("x=150"); ImGui::SameLine(300); ImGui::Text("x=300"); ImGui::Text("Aligned"); ImGui::SameLine(150); ImGui::SmallButton("x=150"); ImGui::SameLine(300); ImGui::SmallButton("x=300"); // Checkbox static bool c1=false,c2=false,c3=false,c4=false; ImGui::Checkbox("My", &c1); ImGui::SameLine(); ImGui::Checkbox("Tailor", &c2); ImGui::SameLine(); ImGui::Checkbox("Is", &c3); ImGui::SameLine(); ImGui::Checkbox("Rich", &c4); // Various static float f0=1.0f, f1=2.0f, f2=3.0f; ImGui::PushItemWidth(80); const char* items[] = { "AAAA", "BBBB", "CCCC", "DDDD" }; static int item = -1; ImGui::Combo("Combo", &item, items, IM_ARRAYSIZE(items)); ImGui::SameLine(); ImGui::SliderFloat("X", &f0, 0.0f,5.0f); ImGui::SameLine(); ImGui::SliderFloat("Y", &f1, 0.0f,5.0f); ImGui::SameLine(); ImGui::SliderFloat("Z", &f2, 0.0f,5.0f); ImGui::PopItemWidth(); ImGui::PushItemWidth(80); ImGui::Text("Lists:"); static int selection[4] = { 0, 1, 2, 3 }; for (int i = 0; i < 4; i++) { if (i > 0) ImGui::SameLine(); ImGui::PushID(i); ImGui::ListBox("", &selection[i], items, IM_ARRAYSIZE(items)); ImGui::PopID(); //if (ImGui::IsItemHovered()) ImGui::SetTooltip("ListBox %d hovered", i); } ImGui::PopItemWidth(); ImGui::TreePop(); } if (ImGui::TreeNode("Groups")) { ImGui::TextWrapped("(Using ImGui::BeginGroup()/EndGroup() to layout items)"); ImVec2 size; ImGui::BeginGroup(); { ImGui::BeginGroup(); ImGui::Button("AAA"); ImGui::SameLine(); ImGui::Button("BBB"); ImGui::SameLine(); ImGui::BeginGroup(); ImGui::Button("CCC"); ImGui::Button("DDD"); ImGui::EndGroup(); if (ImGui::IsItemHovered()) ImGui::SetTooltip("Group hovered"); ImGui::SameLine(); ImGui::Button("EEE"); ImGui::EndGroup(); // Capture the group size and create widgets using the same size size = ImGui::GetItemRectSize(); const float values[5] = { 0.5f, 0.20f, 0.80f, 0.60f, 0.25f }; ImGui::PlotHistogram("##values", values, IM_ARRAYSIZE(values), 0, NULL, 0.0f, 1.0f, size); } ImGui::Button("ACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); ImGui::SameLine(); ImGui::Button("REACTION", ImVec2((size.x - ImGui::GetStyle().ItemSpacing.x)*0.5f,size.y)); ImGui::EndGroup(); ImGui::SameLine(); ImGui::Button("LEVERAGE\nBUZZWORD", size); ImGui::SameLine(); ImGui::ListBoxHeader("List", size); ImGui::Selectable("Selected", true); ImGui::Selectable("Not Selected", false); ImGui::ListBoxFooter(); ImGui::TreePop(); } if (ImGui::TreeNode("Text Baseline Alignment")) { ImGui::TextWrapped("(This is testing the vertical alignment that occurs on text to keep it at the same baseline as widgets. Lines only composed of text or \"small\" widgets fit in less vertical spaces than lines with normal widgets)"); ImGui::Text("One\nTwo\nThree"); ImGui::SameLine(); ImGui::Text("Hello\nWorld"); ImGui::SameLine(); ImGui::Text("Banana"); ImGui::Text("Banana"); ImGui::SameLine(); ImGui::Text("Hello\nWorld"); ImGui::SameLine(); ImGui::Text("One\nTwo\nThree"); ImGui::Button("HOP"); ImGui::SameLine(); ImGui::Text("Banana"); ImGui::SameLine(); ImGui::Text("Hello\nWorld"); ImGui::SameLine(); ImGui::Text("Banana"); ImGui::Button("HOP"); ImGui::SameLine(); ImGui::Text("Hello\nWorld"); ImGui::SameLine(); ImGui::Text("Banana"); ImGui::Button("TEST"); ImGui::SameLine(); ImGui::Text("TEST"); ImGui::SameLine(); ImGui::SmallButton("TEST"); ImGui::AlignFirstTextHeightToWidgets(); // If your line starts with text, call this to align it to upcoming widgets. ImGui::Text("Text aligned to Widget"); ImGui::SameLine(); ImGui::Button("Widget"); ImGui::SameLine(); ImGui::Text("Widget"); ImGui::SameLine(); ImGui::SmallButton("Widget"); ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Child regions")) { ImGui::Text("Without border"); static int line = 50; bool goto_line = ImGui::Button("Goto"); ImGui::SameLine(); ImGui::PushItemWidth(100); goto_line |= ImGui::InputInt("##Line", &line, 0, 0, ImGuiInputTextFlags_EnterReturnsTrue); ImGui::PopItemWidth(); ImGui::BeginChild("Sub1", ImVec2(ImGui::GetWindowWidth() * 0.5f,300)); for (int i = 0; i < 100; i++) { ImGui::Text("%04d: scrollable region", i); if (goto_line && line == i) ImGui::SetScrollPosHere(); } if (goto_line && line >= 100) ImGui::SetScrollPosHere(); ImGui::EndChild(); ImGui::SameLine(); ImGui::PushStyleVar(ImGuiStyleVar_ChildWindowRounding, 5.0f); ImGui::BeginChild("Sub2", ImVec2(0,300), true); ImGui::Text("With border"); ImGui::Columns(2); for (int i = 0; i < 100; i++) { if (i == 50) ImGui::NextColumn(); char buf[32]; ImFormatString(buf, IM_ARRAYSIZE(buf), "%08x", i*5731); ImGui::Button(buf); } ImGui::EndChild(); ImGui::PopStyleVar(); } if (ImGui::CollapsingHeader("Columns")) { // Basic columns ImGui::Text("Basic:"); ImGui::Columns(4, "mycolumns"); ImGui::Separator(); ImGui::Text("ID"); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Path"); ImGui::NextColumn(); ImGui::Text("Flags"); ImGui::NextColumn(); ImGui::Separator(); const char* names[3] = { "Robert", "Stephanie", "C64" }; const char* paths[3] = { "/path/robert", "/path/stephanie", "/path/computer" }; for (int i = 0; i < 3; i++) { ImGui::Text("%04d", i); ImGui::NextColumn(); ImGui::Text(names[i]); ImGui::NextColumn(); ImGui::Text(paths[i]); ImGui::NextColumn(); ImGui::Text("...."); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::Separator(); ImGui::Spacing(); // Scrolling columns /* ImGui::Text("Scrolling:"); ImGui::BeginChild("##header", ImVec2(0, ImGui::GetTextLineHeightWithSpacing()+ImGui::GetStyle().ItemSpacing.y)); ImGui::Columns(3); ImGui::Text("ID"); ImGui::NextColumn(); ImGui::Text("Name"); ImGui::NextColumn(); ImGui::Text("Path"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::EndChild(); ImGui::BeginChild("##scrollingregion", ImVec2(0, 60)); ImGui::Columns(3); for (int i = 0; i < 10; i++) { ImGui::Text("%04d", i); ImGui::NextColumn(); ImGui::Text("Foobar"); ImGui::NextColumn(); ImGui::Text("/path/foobar/%04d/", i); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::EndChild(); ImGui::Separator(); ImGui::Spacing(); */ // Create multiple items in a same cell before switching to next column ImGui::Text("Mixed items:"); ImGui::Columns(3, "mixed"); ImGui::Separator(); static int e = 0; ImGui::Text("Hello"); ImGui::Button("Banana"); ImGui::RadioButton("radio a", &e, 0); ImGui::NextColumn(); ImGui::Text("ImGui"); ImGui::Button("Apple"); ImGui::RadioButton("radio b", &e, 1); static float foo = 1.0f; ImGui::InputFloat("red", &foo, 0.05f, 0, 3); ImGui::Text("An extra line here."); ImGui::NextColumn(); ImGui::Text("World!"); ImGui::Button("Corniflower"); ImGui::RadioButton("radio c", &e, 2); static float bar = 1.0f; ImGui::InputFloat("blue", &bar, 0.05f, 0, 3); ImGui::NextColumn(); if (ImGui::CollapsingHeader("Category A")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); if (ImGui::CollapsingHeader("Category B")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); if (ImGui::CollapsingHeader("Category C")) ImGui::Text("Blah blah blah"); ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Spacing(); // Tree items ImGui::Text("Tree items:"); ImGui::Columns(2, "tree items"); ImGui::Separator(); if (ImGui::TreeNode("Hello")) { ImGui::BulletText("World"); ImGui::TreePop(); } ImGui::NextColumn(); if (ImGui::TreeNode("Bonjour")) { ImGui::BulletText("Monde"); ImGui::TreePop(); } ImGui::NextColumn(); ImGui::Columns(1); ImGui::Separator(); ImGui::Spacing(); // Word-wrapping ImGui::Text("Word-wrapping:"); ImGui::Columns(2, "word-wrapping"); ImGui::Separator(); ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); ImGui::Text("Hello Left"); ImGui::NextColumn(); ImGui::TextWrapped("The quick brown fox jumps over the lazy dog."); ImGui::Text("Hello Right"); ImGui::Columns(1); ImGui::Separator(); ImGui::Spacing(); if (ImGui::TreeNode("Inside a tree..")) { if (ImGui::TreeNode("node 1 (with borders)")) { ImGui::Columns(4); for (int i = 0; i < 8; i++) { ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::TreePop(); } if (ImGui::TreeNode("node 2 (without borders)")) { ImGui::Columns(4, NULL, false); for (int i = 0; i < 8; i++) { ImGui::Text("%c%c%c", 'a'+i, 'a'+i, 'a'+i); ImGui::NextColumn(); } ImGui::Columns(1); ImGui::TreePop(); } ImGui::TreePop(); } } if (ImGui::CollapsingHeader("Filtering")) { static ImGuiTextFilter filter; ImGui::Text("Filter usage:\n" " \"\" display all lines\n" " \"xxx\" display lines containing \"xxx\"\n" " \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" " \"-xxx\" hide lines containing \"xxx\""); filter.Draw(); const char* lines[] = { "aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world" }; for (size_t i = 0; i < IM_ARRAYSIZE(lines); i++) if (filter.PassFilter(lines[i])) ImGui::BulletText("%s", lines[i]); } if (ImGui::CollapsingHeader("Keyboard, Mouse & Focus")) { if (ImGui::TreeNode("Tabbing")) { ImGui::Text("Use TAB/SHIFT+TAB to cycle thru keyboard editable fields."); static char buf[32] = "dummy"; ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); ImGui::InputText("3", buf, IM_ARRAYSIZE(buf)); ImGui::PushAllowKeyboardFocus(false); ImGui::InputText("4 (tab skip)", buf, IM_ARRAYSIZE(buf)); //ImGui::SameLine(); ImGui::Text("(?)"); if (ImGui::IsHovered()) ImGui::SetTooltip("Use ImGui::PushAllowKeyboardFocus(bool)\nto disable tabbing through certain widgets."); ImGui::PopAllowKeyboardFocus(); ImGui::InputText("5", buf, IM_ARRAYSIZE(buf)); ImGui::TreePop(); } if (ImGui::TreeNode("Focus from code")) { bool focus_1 = ImGui::Button("Focus on 1"); ImGui::SameLine(); bool focus_2 = ImGui::Button("Focus on 2"); ImGui::SameLine(); bool focus_3 = ImGui::Button("Focus on 3"); int has_focus = 0; static char buf[128] = "click on a button to set focus"; if (focus_1) ImGui::SetKeyboardFocusHere(); ImGui::InputText("1", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsItemActive()) has_focus = 1; if (focus_2) ImGui::SetKeyboardFocusHere(); ImGui::InputText("2", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsItemActive()) has_focus = 2; ImGui::PushAllowKeyboardFocus(false); if (focus_3) ImGui::SetKeyboardFocusHere(); ImGui::InputText("3 (tab skip)", buf, IM_ARRAYSIZE(buf)); if (ImGui::IsItemActive()) has_focus = 3; ImGui::PopAllowKeyboardFocus(); if (has_focus) ImGui::Text("Item with focus: %d", has_focus); else ImGui::Text("Item with focus: <none>"); ImGui::TextWrapped("Cursor & selection are preserved when refocusing last used item in code."); ImGui::TreePop(); } if (ImGui::TreeNode("Mouse cursors")) { ImGui::TextWrapped("(Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. You can also set io.MouseDrawCursor to ask ImGui to render the cursor for you in software)"); ImGui::Checkbox("io.MouseDrawCursor", &ImGui::GetIO().MouseDrawCursor); ImGui::Text("Hover to see mouse cursors:"); for (int i = 0; i < ImGuiMouseCursor_Count_; i++) { char label[32]; sprintf(label, "Mouse cursor %d", i); ImGui::Bullet(); ImGui::Selectable(label, false); if (ImGui::IsItemHovered()) ImGui::SetMouseCursor(i); } ImGui::TreePop(); } } if (ImGui::CollapsingHeader("App Examples")) { ImGui::Checkbox("Metrics", &show_app_metrics); ImGui::Checkbox("Console", &show_app_console); ImGui::Checkbox("Long text display", &show_app_long_text); ImGui::Checkbox("Auto-resizing window", &show_app_auto_resize); ImGui::Checkbox("Simple overlay", &show_app_fixed_overlay); ImGui::Checkbox("Manipulating window title", &show_app_manipulating_window_title); ImGui::Checkbox("Custom rendering", &show_app_custom_rendering); } ImGui::End(); } void ImGui::ShowMetricsWindow(bool* opened) { if (ImGui::Begin("ImGui Metrics", opened)) { ImGui::Text("ImGui %s", ImGui::GetVersion()); ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); ImGui::Text("%d vertices", ImGui::GetIO().MetricsRenderVertices); ImGui::Separator(); struct Funcs { static void NodeDrawList(ImDrawList* draw_list, const char* label) { bool node_opened = ImGui::TreeNode(draw_list, "%s: %d vtx, %d cmds", label, draw_list->vtx_buffer.size(), draw_list->commands.size()); if (draw_list == ImGui::GetWindowDrawList()) { ImGui::SameLine(); ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered) } if (!node_opened) return; for (const ImDrawCmd* pcmd = draw_list->commands.begin(); pcmd < draw_list->commands.end(); pcmd++) if (pcmd->user_callback) ImGui::BulletText("Callback %p, user_data %p", pcmd->user_callback, pcmd->user_callback_data); else ImGui::BulletText("Draw %d vtx, tex = %p", pcmd->vtx_count, pcmd->texture_id); ImGui::TreePop(); } static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label) { if (!ImGui::TreeNode(label, "%s (%d)", label, (int)windows.size())) return; for (int i = 0; i < (int)windows.size(); i++) Funcs::NodeWindow(windows[i], "Window"); ImGui::TreePop(); } static void NodeWindow(ImGuiWindow* window, const char* label) { if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Visible, window)) return; NodeDrawList(window->DrawList, "DrawList"); if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow"); if (window->DC.ChildWindows.size() > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows"); ImGui::TreePop(); } }; ImGuiState& g = *GImGui; // Access private state g.DisableHideTextAfterDoubleHash++; // Not exposed (yet). Disable processing that hides text after '##' markers. Funcs::NodeWindows(g.Windows, "Windows"); if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", (int)g.RenderDrawLists[0].size())) { for (int i = 0; i < (int)g.RenderDrawLists[0].size(); i++) Funcs::NodeDrawList(g.RenderDrawLists[0][i], "DrawList"); ImGui::TreePop(); } g.DisableHideTextAfterDoubleHash--; } ImGui::End(); } static void ShowExampleAppAutoResize(bool* opened) { if (!ImGui::Begin("Example: Auto-Resizing Window", opened, ImGuiWindowFlags_AlwaysAutoResize)) { ImGui::End(); return; } static int lines = 10; ImGui::TextWrapped("Window will resize every-frame to the size of its content. Note that you don't want to query the window size to output your content because that would create a feedback loop."); ImGui::SliderInt("Number of lines", &lines, 1, 20); for (int i = 0; i < lines; i++) ImGui::Text("%*sThis is line %d", i*4, "", i); // Pad with space to extend size horizontally ImGui::End(); } static void ShowExampleAppFixedOverlay(bool* opened) { ImGui::SetNextWindowPos(ImVec2(10,10)); if (!ImGui::Begin("Example: Fixed Overlay", opened, ImVec2(0,0), 0.3f, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoSavedSettings)) { ImGui::End(); return; } ImGui::Text("Simple overlay\non the top-left side of the screen."); ImGui::Separator(); ImGui::Text("Mouse Position: (%.1f,%.1f)", ImGui::GetIO().MousePos.x, ImGui::GetIO().MousePos.y); ImGui::End(); } static void ShowExampleAppManipulatingWindowTitle(bool* opened) { (void)opened; // By default, Windows are uniquely identified by their title. // You can use the "##" and "###" markers to manipulate the display/ID. Read FAQ at the top of this file! // Using "##" to display same title but have unique identifier. ImGui::SetNextWindowPos(ImVec2(100,100), ImGuiSetCond_FirstUseEver); ImGui::Begin("Same title as another window##1"); ImGui::Text("This is window 1.\nMy title is the same as window 2, but my identifier is unique."); ImGui::End(); ImGui::SetNextWindowPos(ImVec2(100,200), ImGuiSetCond_FirstUseEver); ImGui::Begin("Same title as another window##2"); ImGui::Text("This is window 2.\nMy title is the same as window 1, but my identifier is unique."); ImGui::End(); // Using "###" to display a changing title but keep a static identifier "AnimatedTitle" char buf[128]; ImFormatString(buf, IM_ARRAYSIZE(buf), "Animated title %c %d###AnimatedTitle", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], rand()); ImGui::SetNextWindowPos(ImVec2(100,300), ImGuiSetCond_FirstUseEver); ImGui::Begin(buf); ImGui::Text("This window has a changing title."); ImGui::End(); } static void ShowExampleAppCustomRendering(bool* opened) { ImGui::SetNextWindowSize(ImVec2(300,350), ImGuiSetCond_FirstUseEver); if (!ImGui::Begin("Example: Custom Rendering", opened)) { ImGui::End(); return; } // Tip: If you do a lot of custom rendering, you probably want to use your own geometrical types and benefit of overloaded operators, etc. // Define IM_VEC2_CLASS_EXTRA in imconfig.h to create implicit conversions between your types and ImVec2/ImVec4. // ImGui defines overloaded operators but they are internal to imgui.cpp and not exposed outside (to avoid messing with your types) // In this example we aren't using the operators. static ImVector<ImVec2> points; static bool adding_line = false; if (ImGui::Button("Clear")) points.clear(); if (points.size() >= 2) { ImGui::SameLine(); if (ImGui::Button("Undo")) { points.pop_back(); points.pop_back(); } } ImGui::Text("Left-click and drag to add lines"); ImGui::Text("Right-click to undo"); ImDrawList* draw_list = ImGui::GetWindowDrawList(); // Here we are using InvisibleButton() as a convenience to 1) advance the cursor and 2) allows us to use IsItemHovered() // However you can draw directly and poll mouse/keyboard by yourself. You can manipulate the cursor using GetCursorPos() and SetCursorPos(). // If you only use the ImDrawList API, you can notify the owner window of its extends by using SetCursorPos(max). ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates! ImVec2 canvas_size = ImVec2(ImMax(50.0f,ImGui::GetWindowContentRegionMax().x-ImGui::GetCursorPos().x), ImMax(50.0f,ImGui::GetWindowContentRegionMax().y-ImGui::GetCursorPos().y)); // Resize canvas what's available draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), 0xFFFFFFFF); bool adding_preview = false; ImGui::InvisibleButton("canvas", canvas_size); if (ImGui::IsItemHovered()) { ImVec2 mouse_pos_in_canvas = ImVec2(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y); if (!adding_line && ImGui::GetIO().MouseClicked[0]) { points.push_back(mouse_pos_in_canvas); adding_line = true; } if (adding_line) { adding_preview = true; points.push_back(mouse_pos_in_canvas); if (!ImGui::GetIO().MouseDown[0]) adding_line = adding_preview = false; } if (ImGui::GetIO().MouseClicked[1] && !points.empty()) { adding_line = false; points.pop_back(); points.pop_back(); } } draw_list->PushClipRect(ImVec4(canvas_pos.x, canvas_pos.y, canvas_pos.x+canvas_size.x, canvas_pos.y+canvas_size.y)); // clip lines within the canvas (if we resize it, etc.) for (int i = 0; i < (int)points.size() - 1; i += 2) draw_list->AddLine(ImVec2(canvas_pos.x + points[i].x, canvas_pos.y + points[i].y), ImVec2(canvas_pos.x + points[i+1].x, canvas_pos.y + points[i+1].y), 0xFF00FFFF); draw_list->PopClipRect(); if (adding_preview) points.pop_back(); ImGui::End(); } struct ExampleAppConsole { char InputBuf[256]; ImVector<char*> Items; bool ScrollToBottom; ImVector<char*> History; int HistoryPos; // -1: new line, 0..History.size()-1 browsing history. ImVector<const char*> Commands; ExampleAppConsole() { ClearLog(); HistoryPos = -1; Commands.push_back("HELP"); Commands.push_back("HISTORY"); Commands.push_back("CLEAR"); Commands.push_back("CLASSIFY"); // "classify" is here to provide an example of "C"+[tab] completing to "CL" and displaying matches. } ~ExampleAppConsole() { ClearLog(); for (size_t i = 0; i < Items.size(); i++) ImGui::MemFree(History[i]); } void ClearLog() { for (size_t i = 0; i < Items.size(); i++) ImGui::MemFree(Items[i]); Items.clear(); ScrollToBottom = true; } void AddLog(const char* fmt, ...) { char buf[1024]; va_list args; va_start(args, fmt); ImFormatStringV(buf, IM_ARRAYSIZE(buf), fmt, args); va_end(args); Items.push_back(ImStrdup(buf)); ScrollToBottom = true; } void Run(const char* title, bool* opened) { ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); if (!ImGui::Begin(title, opened)) { ImGui::End(); return; } ImGui::TextWrapped("This example implements a console with basic coloring, completion and history. A more elaborate implementation may want to store entries along with extra data such as timestamp, emitter, etc."); ImGui::TextWrapped("Enter 'HELP' for help, press TAB to use text completion."); // TODO: display from bottom // TODO: clip manually if (ImGui::SmallButton("Add Dummy Text")) { AddLog("%d some text", Items.size()); AddLog("some more text"); AddLog("display very important message here!"); } ImGui::SameLine(); if (ImGui::SmallButton("Add Dummy Error")) AddLog("[error] something went wrong"); ImGui::SameLine(); if (ImGui::SmallButton("Clear")) ClearLog(); //static float t = 0.0f; if (ImGui::GetTime() - t > 0.02f) { t = ImGui::GetTime(); AddLog("Spam %f", t); } ImGui::Separator(); ImGui::PushStyleVar(ImGuiStyleVar_FramePadding, ImVec2(0,0)); static ImGuiTextFilter filter; filter.Draw("Filter (\"incl,-excl\") (\"error\")", 180); //if (ImGui::IsItemHovered()) ImGui::SetKeyboardFocusHere(-1); // Auto focus on hover ImGui::PopStyleVar(); ImGui::Separator(); // Display every line as a separate entry so we can change their color or add custom widgets. If you only want raw text you can use ImGui::TextUnformatted(log.begin(), log.end()); // NB- if you have thousands of entries this approach may be too inefficient. You can seek and display only the lines that are visible - CalcListClipping() is a helper to compute this information. // If your items are of variable size you may want to implement code similar to what CalcListClipping() does. Or split your data into fixed height items to allow random-seeking into your list. ImGui::BeginChild("ScrollingRegion", ImVec2(0,-ImGui::GetTextLineHeightWithSpacing()*2)); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(4,1)); // Tighten spacing for (size_t i = 0; i < Items.size(); i++) { const char* item = Items[i]; if (!filter.PassFilter(item)) continue; ImVec4 col(1,1,1,1); // A better implement may store a type per-item. For the sample let's just parse the text. if (strstr(item, "[error]")) col = ImVec4(1.0f,0.4f,0.4f,1.0f); else if (strncmp(item, "# ", 2) == 0) col = ImVec4(1.0f,0.8f,0.6f,1.0f); ImGui::PushStyleColor(ImGuiCol_Text, col); ImGui::TextUnformatted(item); ImGui::PopStyleColor(); } if (ScrollToBottom) ImGui::SetScrollPosHere(); ScrollToBottom = false; ImGui::PopStyleVar(); ImGui::EndChild(); ImGui::Separator(); // Command-line if (ImGui::InputText("Input", InputBuf, IM_ARRAYSIZE(InputBuf), ImGuiInputTextFlags_EnterReturnsTrue|ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_CallbackHistory, &TextEditCallbackStub, (void*)this)) { char* input_end = InputBuf+strlen(InputBuf); while (input_end > InputBuf && input_end[-1] == ' ') input_end--; *input_end = 0; if (InputBuf[0]) ExecCommand(InputBuf); strcpy(InputBuf, ""); } // Demonstrate keeping auto focus on the input box if (ImGui::IsItemHovered() || (ImGui::IsRootWindowOrAnyChildFocused() && !ImGui::IsAnyItemActive() && !ImGui::IsMouseClicked(0))) ImGui::SetKeyboardFocusHere(-1); // Auto focus ImGui::End(); } void ExecCommand(const char* command_line) { AddLog("# %s\n", command_line); // Insert into history. First find match and delete it so it can be pushed to the back. This isn't trying to be smart or optimal. HistoryPos = -1; for (int i = (int)History.size()-1; i >= 0; i--) if (ImStricmp(History[i], command_line) == 0) { ImGui::MemFree(History[i]); History.erase(History.begin() + i); break; } History.push_back(ImStrdup(command_line)); // Process command if (ImStricmp(command_line, "CLEAR") == 0) { ClearLog(); } else if (ImStricmp(command_line, "HELP") == 0) { AddLog("Commands:"); for (size_t i = 0; i < Commands.size(); i++) AddLog("- %s", Commands[i]); } else if (ImStricmp(command_line, "HISTORY") == 0) { for (size_t i = History.size() >= 10 ? History.size() - 10 : 0; i < History.size(); i++) AddLog("%3d: %s\n", i, History[i]); } else { AddLog("Unknown command: '%s'\n", command_line); } } static int TextEditCallbackStub(ImGuiTextEditCallbackData* data) { ExampleAppConsole* console = (ExampleAppConsole*)data->UserData; return console->TextEditCallback(data); } int TextEditCallback(ImGuiTextEditCallbackData* data) { //AddLog("cursor: %d, selection: %d-%d", data->CursorPos, data->SelectionStart, data->SelectionEnd); switch (data->EventFlag) { case ImGuiInputTextFlags_CallbackCompletion: { // Example of TEXT COMPLETION // Locate beginning of current word const char* word_end = data->Buf + data->CursorPos; const char* word_start = word_end; while (word_start > data->Buf) { const char c = word_start[-1]; if (ImCharIsSpace(c) || c == ',' || c == ';') break; word_start--; } // Build a list of candidates ImVector<const char*> candidates; for (size_t i = 0; i < Commands.size(); i++) if (ImStrnicmp(Commands[i], word_start, (int)(word_end-word_start)) == 0) candidates.push_back(Commands[i]); if (candidates.size() == 0) { // No match AddLog("No match for \"%.*s\"!\n", word_end-word_start, word_start); } else if (candidates.size() == 1) { // Single match. Delete the beginning of the word and replace it entirely so we've got nice casing data->DeleteChars((int)(word_start-data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0]); data->InsertChars(data->CursorPos, " "); } else { // Multiple matches. Complete as much as we can, so inputing "C" will complete to "CL" and display "CLEAR" and "CLASSIFY" int match_len = (int)(word_end - word_start); for (;;) { int c = 0; bool all_candidates_matches = true; for (size_t i = 0; i < candidates.size() && all_candidates_matches; i++) if (i == 0) c = toupper(candidates[i][match_len]); else if (c != toupper(candidates[i][match_len])) all_candidates_matches = false; if (!all_candidates_matches) break; match_len++; } if (match_len > 0) { data->DeleteChars((int)(word_start - data->Buf), (int)(word_end-word_start)); data->InsertChars(data->CursorPos, candidates[0], candidates[0] + match_len); } // List matches AddLog("Possible matches:\n"); for (size_t i = 0; i < candidates.size(); i++) AddLog("- %s\n", candidates[i]); } break; } case ImGuiInputTextFlags_CallbackHistory: { // Example of HISTORY const int prev_history_pos = HistoryPos; if (data->EventKey == ImGuiKey_UpArrow) { if (HistoryPos == -1) HistoryPos = (int)(History.size() - 1); else if (HistoryPos > 0) HistoryPos--; } else if (data->EventKey == ImGuiKey_DownArrow) { if (HistoryPos != -1) if (++HistoryPos >= (int)History.size()) HistoryPos = -1; } // A better implementation would preserve the data on the current input line along with cursor position. if (prev_history_pos != HistoryPos) { ImFormatString(data->Buf, data->BufSize, "%s", (HistoryPos >= 0) ? History[HistoryPos] : ""); data->BufDirty = true; data->CursorPos = data->SelectionStart = data->SelectionEnd = (int)strlen(data->Buf); } } } return 0; } }; static void ShowExampleAppConsole(bool* opened) { static ExampleAppConsole console; console.Run("Example: Console", opened); } static void ShowExampleAppLongText(bool* opened) { ImGui::SetNextWindowSize(ImVec2(520,600), ImGuiSetCond_FirstUseEver); if (!ImGui::Begin("Example: Long text display", opened)) { ImGui::End(); return; } static int test_type = 0; static ImGuiTextBuffer log; static int lines = 0; ImGui::Text("Printing unusually long amount of text."); ImGui::Combo("Test type", &test_type, "Single call to TextUnformatted()\0Multiple calls to Text(), clipped manually\0Multiple calls to Text(), not clipped"); ImGui::Text("Buffer contents: %d lines, %d bytes", lines, log.size()); if (ImGui::Button("Clear")) { log.clear(); lines = 0; } ImGui::SameLine(); if (ImGui::Button("Add 1000 lines")) { for (int i = 0; i < 1000; i++) log.append("%i The quick brown fox jumps over the lazy dog\n", lines+i); lines += 1000; } ImGui::BeginChild("Log"); switch (test_type) { case 0: // Single call to TextUnformatted() with a big buffer ImGui::TextUnformatted(log.begin(), log.end()); break; case 1: // Multiple calls to Text(), manually coarsely clipped - demonstrate how to use the CalcListClipping() helper. ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); int display_start, display_end; ImGui::CalcListClipping(lines, ImGui::GetTextLineHeight(), &display_start, &display_end); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (display_start) * ImGui::GetTextLineHeight()); for (int i = display_start; i < display_end; i++) ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + (lines - display_end) * ImGui::GetTextLineHeight()); ImGui::PopStyleVar(); break; case 2: // Multiple calls to Text(), not clipped ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(0,0)); for (int i = 0; i < lines; i++) ImGui::Text("%i The quick brown fox jumps over the lazy dog\n", i); ImGui::PopStyleVar(); break; } ImGui::EndChild(); ImGui::End(); } // End of Sample code #endif //----------------------------------------------------------------------------- // FONT DATA //----------------------------------------------------------------------------- // Compressed with stb_compress() then converted to a C array. // Use the program in extra_fonts/binary_to_compressed_c.cpp to create the array from a TTF file. // Decompressor from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h //----------------------------------------------------------------------------- static unsigned int stb_decompress_length(unsigned char *input) { return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; } static unsigned char *stb__barrier, *stb__barrier2, *stb__barrier3, *stb__barrier4; static unsigned char *stb__dout; static void stb__match(unsigned char *data, unsigned int length) { // INVERSE of memmove... write each byte before copying the next... IM_ASSERT (stb__dout + length <= stb__barrier); if (stb__dout + length > stb__barrier) { stb__dout += length; return; } if (data < stb__barrier4) { stb__dout = stb__barrier+1; return; } while (length--) *stb__dout++ = *data++; } static void stb__lit(unsigned char *data, unsigned int length) { IM_ASSERT (stb__dout + length <= stb__barrier); if (stb__dout + length > stb__barrier) { stb__dout += length; return; } if (data < stb__barrier2) { stb__dout = stb__barrier+1; return; } memcpy(stb__dout, data, length); stb__dout += length; } #define stb__in2(x) ((i[x] << 8) + i[(x)+1]) #define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) #define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) static unsigned char *stb_decompress_token(unsigned char *i) { if (*i >= 0x20) { // use fewer if's for cases that expand small if (*i >= 0x80) stb__match(stb__dout-i[1]-1, i[0] - 0x80 + 1), i += 2; else if (*i >= 0x40) stb__match(stb__dout-(stb__in2(0) - 0x4000 + 1), i[2]+1), i += 3; else /* *i >= 0x20 */ stb__lit(i+1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); } else { // more ifs for cases that expand large, since overhead is amortized if (*i >= 0x18) stb__match(stb__dout-(stb__in3(0) - 0x180000 + 1), i[3]+1), i += 4; else if (*i >= 0x10) stb__match(stb__dout-(stb__in3(0) - 0x100000 + 1), stb__in2(3)+1), i += 5; else if (*i >= 0x08) stb__lit(i+2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); else if (*i == 0x07) stb__lit(i+3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); else if (*i == 0x06) stb__match(stb__dout-(stb__in3(1)+1), i[4]+1), i += 5; else if (*i == 0x04) stb__match(stb__dout-(stb__in3(1)+1), stb__in2(4)+1), i += 6; } return i; } static unsigned int stb_adler32(unsigned int adler32, unsigned char *buffer, unsigned int buflen) { const unsigned long ADLER_MOD = 65521; unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; unsigned long blocklen, i; blocklen = buflen % 5552; while (buflen) { for (i=0; i + 7 < blocklen; i += 8) { s1 += buffer[0], s2 += s1; s1 += buffer[1], s2 += s1; s1 += buffer[2], s2 += s1; s1 += buffer[3], s2 += s1; s1 += buffer[4], s2 += s1; s1 += buffer[5], s2 += s1; s1 += buffer[6], s2 += s1; s1 += buffer[7], s2 += s1; buffer += 8; } for (; i < blocklen; ++i) s1 += *buffer++, s2 += s1; s1 %= ADLER_MOD, s2 %= ADLER_MOD; buflen -= blocklen; blocklen = 5552; } return (unsigned int)(s2 << 16) + (unsigned int)s1; } static unsigned int stb_decompress(unsigned char *output, unsigned char *i, unsigned int length) { unsigned int olen; if (stb__in4(0) != 0x57bC0000) return 0; if (stb__in4(4) != 0) return 0; // error! stream is > 4GB olen = stb_decompress_length(i); stb__barrier2 = i; stb__barrier3 = i+length; stb__barrier = output + olen; stb__barrier4 = output; i += 16; stb__dout = output; for (;;) { unsigned char *old_i = i; i = stb_decompress_token(i); if (i == old_i) { if (*i == 0x05 && i[1] == 0xfa) { IM_ASSERT(stb__dout == output + olen); if (stb__dout != output + olen) return 0; if (stb_adler32(1, output, olen) != (unsigned int) stb__in4(2)) return 0; return olen; } else { IM_ASSERT(0); /* NOTREACHED */ return 0; } } IM_ASSERT(stb__dout <= output + olen); if (stb__dout > output + olen) return 0; } } //----------------------------------------------------------------------------- // ProggyClean.ttf // Copyright (c) 2004, 2005 Tristan Grimmer // MIT license (see License.txt in http://www.upperbounds.net/download/ProggyClean.ttf.zip) // Download and more information at http://upperbounds.net //----------------------------------------------------------------------------- static const unsigned int proggy_clean_ttf_compressed_size = 9583; static const unsigned int proggy_clean_ttf_compressed_data[9584/4] = { 0x0000bc57, 0x00000000, 0xf8a00000, 0x00000400, 0x00010037, 0x000c0000, 0x00030080, 0x2f534f40, 0x74eb8832, 0x01000090, 0x2c158248, 0x616d634e, 0x23120270, 0x03000075, 0x241382a0, 0x74766352, 0x82178220, 0xfc042102, 0x02380482, 0x66796c67, 0x5689af12, 0x04070000, 0x80920000, 0x64616568, 0xd36691d7, 0xcc201b82, 0x36210382, 0x27108268, 0xc3014208, 0x04010000, 0x243b0f82, 0x78746d68, 0x807e008a, 0x98010000, 0x06020000, 0x61636f6c, 0xd8b0738c, 0x82050000, 0x0402291e, 0x7078616d, 0xda00ae01, 0x28201f82, 0x202c1082, 0x656d616e, 0x96bb5925, 0x84990000, 0x9e2c1382, 0x74736f70, 0xef83aca6, 0x249b0000, 0xd22c3382, 0x70657270, 0x12010269, 0xf4040000, 0x08202f82, 0x012ecb84, 0x553c0000, 0x0f5fd5e9, 0x0300f53c, 0x00830008, 0x7767b722, 0x002b3f82, 0xa692bd00, 0xfe0000d7, 0x83800380, 0x21f1826f, 0x00850002, 0x41820120, 0x40fec026, 0x80030000, 0x05821083, 0x07830120, 0x0221038a, 0x24118200, 0x90000101, 0x82798200, 0x00022617, 0x00400008, 0x2009820a, 0x82098276, 0x82002006, 0x9001213b, 0x0223c883, 0x828a02bc, 0x858f2010, 0xc5012507, 0x00023200, 0x04210083, 0x91058309, 0x6c412b03, 0x40007374, 0xac200000, 0x00830008, 0x01000523, 0x834d8380, 0x80032103, 0x012101bf, 0x23b88280, 0x00800000, 0x0b830382, 0x07820120, 0x83800021, 0x88012001, 0x84002009, 0x2005870f, 0x870d8301, 0x2023901b, 0x83199501, 0x82002015, 0x84802000, 0x84238267, 0x88002027, 0x8561882d, 0x21058211, 0x13880000, 0x01800022, 0x05850d85, 0x0f828020, 0x03208384, 0x03200582, 0x47901b84, 0x1b850020, 0x1f821d82, 0x3f831d88, 0x3f410383, 0x84058405, 0x210982cd, 0x09830000, 0x03207789, 0xf38a1384, 0x01203782, 0x13872384, 0x0b88c983, 0x0d898f84, 0x00202982, 0x23900383, 0x87008021, 0x83df8301, 0x86118d03, 0x863f880d, 0x8f35880f, 0x2160820f, 0x04830300, 0x1c220382, 0x05820100, 0x4c000022, 0x09831182, 0x04001c24, 0x11823000, 0x0800082e, 0x00000200, 0xff007f00, 0xffffac20, 0x00220982, 0x09848100, 0xdf216682, 0x843586d5, 0x06012116, 0x04400684, 0xa58120d7, 0x00b127d8, 0x01b88d01, 0x2d8685ff, 0xc100c621, 0xf4be0801, 0x9e011c01, 0x88021402, 0x1403fc02, 0x9c035803, 0x1404de03, 0x50043204, 0xa2046204, 0x66051605, 0x1206bc05, 0xd6067406, 0x7e073807, 0x4e08ec07, 0x96086c08, 0x1009d008, 0x88094a09, 0x800a160a, 0x560b040b, 0x2e0cc80b, 0xea0c820c, 0xa40d5e0d, 0x500eea0d, 0x280f960e, 0x1210b00f, 0xe0107410, 0xb6115211, 0x6e120412, 0x4c13c412, 0xf613ac13, 0xae145814, 0x4015ea14, 0xa6158015, 0x1216b815, 0xc6167e16, 0x8e173417, 0x5618e017, 0xee18ba18, 0x96193619, 0x481ad419, 0xf01a9c1a, 0xc81b5c1b, 0x4c1c041c, 0xea1c961c, 0x921d2a1d, 0x401ed21d, 0xe01e8e1e, 0x761f241f, 0xa61fa61f, 0x01821020, 0x8a202e34, 0xc820b220, 0x74211421, 0xee219821, 0x86226222, 0x01820c23, 0x83238021, 0x23983c01, 0x24d823b0, 0x244a2400, 0x24902468, 0x250625ae, 0x25822560, 0x26f825f8, 0x82aa2658, 0xd8be0801, 0x9a274027, 0x68280a28, 0x0e29a828, 0xb8292029, 0x362af829, 0x602a602a, 0x2a2b022b, 0xac2b5e2b, 0x202ce62b, 0x9a2c342c, 0x5c2d282d, 0xaa2d782d, 0x262ee82d, 0x262fa62e, 0xf42fb62f, 0xc8305e30, 0xb4313e31, 0x9e321e32, 0x82331e33, 0x5c34ee33, 0x3a35ce34, 0xd4358635, 0x72362636, 0x7637e636, 0x3a38d837, 0x1239a638, 0xae397439, 0x9a3a2e3a, 0x7c3b063b, 0x3a3ce83b, 0x223d963c, 0xec3d863d, 0xc63e563e, 0x9a3f2a3f, 0x6a401240, 0x3641d040, 0x0842a241, 0x7a424042, 0xf042b842, 0xcc436243, 0x8a442a44, 0x5845ee44, 0xe245b645, 0xb4465446, 0x7a471447, 0x5448da47, 0x4049c648, 0x15462400, 0x034d0808, 0x0b000700, 0x13000f00, 0x1b001700, 0x23001f00, 0x2b002700, 0x33002f00, 0x3b003700, 0x43003f00, 0x4b004700, 0x53004f00, 0x5b005700, 0x63005f00, 0x6b006700, 0x73006f00, 0x7b007700, 0x83007f00, 0x8b008700, 0x00008f00, 0x15333511, 0x20039631, 0x20178205, 0xd3038221, 0x20739707, 0x25008580, 0x028080fc, 0x05be8080, 0x04204a85, 0x05ce0685, 0x0107002a, 0x02000080, 0x00000400, 0x250d8b41, 0x33350100, 0x03920715, 0x13820320, 0x858d0120, 0x0e8d0320, 0xff260d83, 0x00808000, 0x54820106, 0x04800223, 0x845b8c80, 0x41332059, 0x078b068f, 0x82000121, 0x82fe2039, 0x84802003, 0x83042004, 0x23598a0e, 0x00180000, 0x03210082, 0x42ab9080, 0x73942137, 0x2013bb41, 0x8f978205, 0x2027a39b, 0x20b68801, 0x84b286fd, 0x91c88407, 0x41032011, 0x11a51130, 0x15000027, 0x80ff8000, 0x11af4103, 0x841b0341, 0x8bd983fd, 0x9be99bc9, 0x8343831b, 0x21f1821f, 0xb58300ff, 0x0f84e889, 0xf78a0484, 0x8000ff22, 0x0020eeb3, 0x14200082, 0x2130ef41, 0xeb431300, 0x4133200a, 0xd7410ecb, 0x9a07200b, 0x2027871b, 0x21238221, 0xe7828080, 0xe784fd20, 0xe8848020, 0xfe808022, 0x08880d85, 0xba41fd20, 0x82248205, 0x85eab02a, 0x008022e7, 0x2cd74200, 0x44010021, 0xd34406eb, 0x44312013, 0xcf8b0eef, 0x0d422f8b, 0x82332007, 0x0001212f, 0x8023cf82, 0x83000180, 0x820583de, 0x830682d4, 0x820020d4, 0x82dc850a, 0x20e282e9, 0xb2ff85fe, 0x010327e9, 0x02000380, 0x0f440400, 0x0c634407, 0x68825982, 0x85048021, 0x260a825d, 0x010b0000, 0x4400ff00, 0x2746103f, 0x08d74209, 0x4d440720, 0x0eaf4406, 0xc3441d20, 0x23078406, 0xff800002, 0x04845b83, 0x8d05b241, 0x1781436f, 0x6b8c87a5, 0x1521878e, 0x06474505, 0x01210783, 0x84688c00, 0x8904828e, 0x441e8cf7, 0x0b270cff, 0x80008000, 0x45030003, 0xfb430fab, 0x080f4107, 0x410bf942, 0xd34307e5, 0x070d4207, 0x80800123, 0x205d85fe, 0x849183fe, 0x20128404, 0x82809702, 0x00002217, 0x41839a09, 0x6b4408cf, 0x0733440f, 0x3b460720, 0x82798707, 0x97802052, 0x0000296f, 0xff800004, 0x01800100, 0x0021ef89, 0x0a914625, 0x410a4d41, 0x00250ed4, 0x00050000, 0x056d4280, 0x210a7b46, 0x21481300, 0x46ed8512, 0x00210bd1, 0x89718202, 0x21738877, 0x2b850001, 0x00220582, 0x87450a00, 0x0ddb4606, 0x41079b42, 0x9d420c09, 0x0b09420b, 0x8d820720, 0x9742fc84, 0x42098909, 0x00241e0f, 0x00800014, 0x0b47da82, 0x0833442a, 0x49078d41, 0x2f450f13, 0x42278f17, 0x01200751, 0x22063742, 0x44808001, 0x20450519, 0x88068906, 0x83fe2019, 0x4203202a, 0x1a941a58, 0x00820020, 0xe7a40e20, 0x420ce146, 0x854307e9, 0x0fcb4713, 0xff20a182, 0xfe209b82, 0x0c867f8b, 0x0021aea4, 0x219fa40f, 0x7d41003b, 0x07194214, 0xbf440520, 0x071d4206, 0x6941a590, 0x80802309, 0x028900ff, 0xa9a4b685, 0xc5808021, 0x449b82ab, 0x152007eb, 0x42134d46, 0x61440a15, 0x051e4208, 0x222b0442, 0x47001100, 0xfd412913, 0x17194714, 0x410f5b41, 0x02220773, 0x09428080, 0x21a98208, 0xd4420001, 0x481c840d, 0x00232bc9, 0x42120000, 0xe74c261b, 0x149d4405, 0x07209d87, 0x410db944, 0x14421c81, 0x42fd2005, 0x80410bd2, 0x203d8531, 0x06874100, 0x48256f4a, 0xcb420c95, 0x13934113, 0x44075d44, 0x044c0855, 0x00ff2105, 0xfe228185, 0x45448000, 0x22c5b508, 0x410c0000, 0x7b412087, 0x1bb74514, 0x32429c85, 0x0a574805, 0x21208943, 0x8ba01300, 0x440dfb4e, 0x77431437, 0x245b4113, 0x200fb145, 0x41108ffe, 0x80203562, 0x00200082, 0x46362b42, 0x1742178d, 0x4527830f, 0x0f830b2f, 0x4a138146, 0x802409a1, 0xfe8000ff, 0x94419982, 0x09294320, 0x04000022, 0x49050f4f, 0xcb470a63, 0x48032008, 0x2b48067b, 0x85022008, 0x82638338, 0x00002209, 0x05af4806, 0x900e9f49, 0x84c5873f, 0x214285bd, 0x064900ff, 0x0c894607, 0x00000023, 0x4903820a, 0x714319f3, 0x0749410c, 0x8a07a145, 0x02152507, 0xfe808000, 0x74490386, 0x8080211b, 0x0c276f82, 0x00018000, 0x48028003, 0x2b2315db, 0x43002f00, 0x6f82142f, 0x44011521, 0x93510da7, 0x20e68508, 0x06494d80, 0x8e838020, 0x06821286, 0x124bff20, 0x25f3830c, 0x03800080, 0xe74a0380, 0x207b8715, 0x876b861d, 0x4a152007, 0x07870775, 0xf6876086, 0x8417674a, 0x0a0021f2, 0x431c9743, 0x8d421485, 0x200b830b, 0x06474d03, 0x71828020, 0x04510120, 0x42da8606, 0x1f831882, 0x001a0022, 0xff4d0082, 0x0b0f532c, 0x0d449b94, 0x4e312007, 0x074f12e7, 0x0bf3490b, 0xbb412120, 0x413f820a, 0xef490857, 0x80002313, 0xe2830001, 0x6441fc20, 0x8b802006, 0x00012108, 0xfd201582, 0x492c9b48, 0x802014ff, 0x51084347, 0x0f4327f3, 0x17bf4a14, 0x201b7944, 0x06964201, 0x134ffe20, 0x20d6830b, 0x25d78280, 0xfd800002, 0x05888000, 0x9318dc41, 0x21d282d4, 0xdb481800, 0x0dff542a, 0x45107743, 0xe14813f5, 0x0f034113, 0x83135d45, 0x47b28437, 0xe4510e73, 0x21f58e06, 0x2b8400fd, 0x1041fcac, 0x08db4b0b, 0x421fdb41, 0xdf4b18df, 0x011d210a, 0x420af350, 0x6e8308af, 0xac85cb86, 0x1e461082, 0x82b7a407, 0x411420a3, 0xa34130ab, 0x178f4124, 0x41139741, 0x86410d93, 0x82118511, 0x057243d8, 0x8941d9a4, 0x3093480c, 0x4a13474f, 0xfb5016a9, 0x07ad4108, 0x4a0f9d42, 0xfe200fad, 0x4708aa41, 0x83482dba, 0x288f4d06, 0xb398c3bb, 0x44267b41, 0xb34439d7, 0x0755410f, 0x200ebb45, 0x0f5f4215, 0x20191343, 0x06df5301, 0xf04c0220, 0x2ba64d07, 0x82050841, 0x430020ce, 0xa78f3627, 0x5213ff42, 0x2f970bc1, 0x4305ab55, 0xa084111b, 0x450bac45, 0x5f4238b8, 0x010c2106, 0x0220ed82, 0x441bb344, 0x875010af, 0x0737480f, 0x490c5747, 0x0c840c03, 0x4c204b42, 0x8ba905d7, 0x8b948793, 0x510c0c51, 0xfb4b24b9, 0x1b174107, 0x5709d74c, 0xd1410ca5, 0x079d480f, 0x201ff541, 0x06804780, 0x7d520120, 0x80002205, 0x20a983fe, 0x47bb83fe, 0x1b8409b4, 0x81580220, 0x4e00202c, 0x4f41282f, 0x0eab4f17, 0x57471520, 0x0e0f4808, 0x8221e041, 0x3e1b4a8b, 0x4407175d, 0x1b4b071f, 0x4a0f8b07, 0x174a0703, 0x0ba5411b, 0x430fb141, 0x0120057b, 0xfc20dd82, 0x4a056047, 0xf4850c0c, 0x01221982, 0x02828000, 0x1a5d088b, 0x20094108, 0x8c0e3941, 0x4900200e, 0x7744434f, 0x200b870b, 0x0e4b5a33, 0x2b41f78b, 0x8b138307, 0x0b9f450b, 0x2406f741, 0xfd808001, 0x09475a00, 0x84000121, 0x5980200e, 0x85450e5d, 0x832c8206, 0x4106831e, 0x00213814, 0x28b34810, 0x410c2f4b, 0x5f4a13d7, 0x0b2b4113, 0x6e43a883, 0x11174b05, 0x4b066a45, 0xcc470541, 0x5000202b, 0xcb472f4b, 0x44b59f0f, 0xc5430b5b, 0x0d654907, 0x21065544, 0xd6828080, 0xfe201982, 0x8230ec4a, 0x120025c2, 0x80ff8000, 0x4128d74d, 0x3320408b, 0x410a9f50, 0xdb822793, 0x822bd454, 0x61134b2e, 0x410b214a, 0xad4117c9, 0x0001211f, 0x4206854f, 0x4b430596, 0x06bb5530, 0x2025cf46, 0x0ddd5747, 0x500ea349, 0x0f840fa7, 0x5213c153, 0x634e08d1, 0x0bbe4809, 0x59316e4d, 0x5b50053f, 0x203f6323, 0x5117eb46, 0x94450a63, 0x246e410a, 0x63410020, 0x0bdb5f2f, 0x4233ab44, 0x39480757, 0x112d4a07, 0x7241118f, 0x000e2132, 0x9f286f41, 0x0f8762c3, 0x33350723, 0x094e6415, 0x2010925f, 0x067252fe, 0xd0438020, 0x63a68225, 0x11203a4f, 0x480e6360, 0x5748131f, 0x079b521f, 0x200e2f43, 0x864b8315, 0x113348e7, 0x85084e48, 0x06855008, 0x5880fd21, 0x7c420925, 0x0c414824, 0x37470c86, 0x1b8b422b, 0x5b0a8755, 0x23410c21, 0x0b83420b, 0x5a082047, 0xf482067f, 0xa80b4c47, 0x0c0021cf, 0x20207b42, 0x0fb74100, 0x420b8744, 0xeb43076f, 0x0f6f420b, 0x4261fe20, 0x439aa00c, 0x215034e3, 0x0ff9570f, 0x4b1f2d5d, 0x2d5d0c6f, 0x09634d0b, 0x1f51b8a0, 0x620f200c, 0xaf681e87, 0x24f94d07, 0x4e0f4945, 0xfe200c05, 0x22139742, 0x57048080, 0x23950c20, 0x97601585, 0x4813201f, 0xad620523, 0x200f8f0f, 0x9e638f15, 0x00002181, 0x41342341, 0x0f930f0b, 0x210b4b62, 0x978f0001, 0xfe200f84, 0x8425c863, 0x2704822b, 0x80000a00, 0x00038001, 0x610e9768, 0x834514bb, 0x0bc3430f, 0x2107e357, 0x80848080, 0x4400fe21, 0x2e410983, 0x00002a1a, 0x00000700, 0x800380ff, 0x0fdf5800, 0x59150021, 0xd142163d, 0x0c02410c, 0x01020025, 0x65800300, 0x00240853, 0x1d333501, 0x15220382, 0x35420001, 0x44002008, 0x376406d7, 0x096f6b19, 0x480bc142, 0x8f4908a7, 0x211f8b1f, 0x9e830001, 0x0584fe20, 0x4180fd21, 0x11850910, 0x8d198259, 0x000021d4, 0x5a08275d, 0x275d1983, 0x06d9420e, 0x9f08b36a, 0x0f7d47b5, 0x8d8a2f8b, 0x4c0e0b57, 0xe7410e17, 0x42d18c1a, 0xb351087a, 0x1ac36505, 0x4b4a2f20, 0x0b9f450d, 0x430beb53, 0xa7881015, 0xa5826a83, 0x80200f82, 0x86185a65, 0x4100208e, 0x176c3367, 0x0fe7650b, 0x4a17ad4b, 0x0f4217ed, 0x112e4206, 0x41113a42, 0xf7423169, 0x0cb34737, 0x560f8b46, 0xa75407e5, 0x5f01200f, 0x31590c48, 0x80802106, 0x42268841, 0x0020091e, 0x4207ef64, 0x69461df7, 0x138d4114, 0x820f5145, 0x53802090, 0xff200529, 0xb944b183, 0x417e8505, 0x00202561, 0x15210082, 0x42378200, 0x9b431cc3, 0x004f220d, 0x0dd54253, 0x4213f149, 0x7d41133b, 0x42c9870b, 0x802010f9, 0x420b2c42, 0x8f441138, 0x267c4408, 0x600cb743, 0x8f4109d3, 0x05ab701d, 0x83440020, 0x3521223f, 0x0b794733, 0xfb62fe20, 0x4afd2010, 0xaf410ae7, 0x25ce8525, 0x01080000, 0x7b6b0000, 0x0973710b, 0x82010021, 0x49038375, 0x33420767, 0x052c4212, 0x58464b85, 0x41fe2005, 0x50440c27, 0x000c2209, 0x1cb36b80, 0x9b06df44, 0x0f93566f, 0x52830220, 0xfe216e8d, 0x200f8200, 0x0fb86704, 0xb057238d, 0x050b5305, 0x7217eb47, 0xbd410b6b, 0x0f214610, 0x871f9956, 0x1e91567e, 0x2029b741, 0x20008200, 0x18b7410a, 0x27002322, 0x41095543, 0x0f8f0fb3, 0x41000121, 0x889d111c, 0x14207b82, 0x00200382, 0x73188761, 0x475013a7, 0x6e33200c, 0x234e0ea3, 0x9b138313, 0x08e54d17, 0x9711094e, 0x2ee74311, 0x4908875e, 0xd75d1f1f, 0x19ab5238, 0xa2084d48, 0x63a7a9b3, 0x55450b83, 0x0fd74213, 0x440d814c, 0x4f481673, 0x05714323, 0x13000022, 0x412e1f46, 0xdf493459, 0x21c7550f, 0x8408215f, 0x201d49cb, 0xb1103043, 0x0f0d65d7, 0x452b8d41, 0x594b0f8d, 0x0b004605, 0xb215eb46, 0x000a24d7, 0x47000080, 0x002118cf, 0x06436413, 0x420bd750, 0x2b500743, 0x076a470c, 0x4105c050, 0xd942053f, 0x0d00211a, 0x5f44779c, 0x0ce94805, 0x51558186, 0x14a54c0b, 0x49082b41, 0x0a4b0888, 0x8080261f, 0x0d000000, 0x20048201, 0x1deb6a03, 0x420cb372, 0x07201783, 0x4306854d, 0x8b830c59, 0x59093c74, 0x0020250f, 0x67070f4a, 0x2341160b, 0x00372105, 0x431c515d, 0x554e17ef, 0x0e5d6b05, 0x41115442, 0xb74a1ac1, 0x2243420a, 0x5b4f878f, 0x7507200f, 0x384b086f, 0x09d45409, 0x0020869a, 0x12200082, 0xab460382, 0x10075329, 0x54138346, 0xaf540fbf, 0x1ea75413, 0x9a0c9e54, 0x0f6b44c1, 0x41000021, 0x47412a4f, 0x07374907, 0x5310bf76, 0xff2009b4, 0x9a09a64c, 0x8200208d, 0x34c34500, 0x970fe141, 0x1fd74b0f, 0x440a3850, 0x206411f0, 0x27934609, 0x470c5d41, 0x555c2947, 0x1787540f, 0x6e0f234e, 0x7d540a1b, 0x1d736b08, 0x0026a088, 0x80000e00, 0x9b5200ff, 0x08ef4318, 0x450bff77, 0x1d4d0b83, 0x081f7006, 0xcb691b86, 0x4b022008, 0xc34b0b33, 0x1d0d4a0c, 0x8025a188, 0x0b000000, 0x52a38201, 0xbf7d0873, 0x0c234511, 0x8f0f894a, 0x4101200f, 0x0c880c9d, 0x2b418ea1, 0x06c74128, 0x66181341, 0x7b4c0bb9, 0x0c06630b, 0xfe200c87, 0x9ba10882, 0x27091765, 0x01000008, 0x02800380, 0x48113f4e, 0x29430cf5, 0x09a75a0b, 0x31618020, 0x6d802009, 0x61840e33, 0x8208bf51, 0x0c637d61, 0x7f092379, 0x4f470f4b, 0x1797510c, 0x46076157, 0xf5500fdf, 0x0f616910, 0x1171fe20, 0x82802006, 0x08696908, 0x41127a4c, 0x3f4a15f3, 0x01042607, 0x0200ff00, 0x1cf77700, 0xff204185, 0x00235b8d, 0x43100000, 0x3b22243f, 0x3b4d3f00, 0x0b937709, 0xad42f18f, 0x0b1f420f, 0x51084b43, 0x8020104a, 0xb557ff83, 0x052b7f2a, 0x0280ff22, 0x250beb78, 0x00170013, 0xbf6d2500, 0x07db760e, 0x410e2b7f, 0x00230e4f, 0x49030000, 0x0582055b, 0x07000326, 0x00000b00, 0x580bcd46, 0x00200cdd, 0x57078749, 0x8749160f, 0x0f994f0a, 0x41134761, 0x01200b31, 0xeb796883, 0x0b41500b, 0x0e90b38e, 0x202e7b51, 0x05d95801, 0x41080570, 0x1d530fc9, 0x0b937a0f, 0xaf8eb387, 0xf743b98f, 0x07c74227, 0x80000523, 0x0fcb4503, 0x430ca37b, 0x7782077f, 0x8d0a9947, 0x08af4666, 0xeb798020, 0x6459881e, 0xc3740bbf, 0x0feb6f0b, 0x20072748, 0x052b6102, 0x435e0584, 0x7d088308, 0x03200afd, 0x92109e41, 0x28aa8210, 0x80001500, 0x80030000, 0x0fdb5805, 0x209f4018, 0xa7418d87, 0x0aa3440f, 0x20314961, 0x073a52ff, 0x6108505d, 0x43181051, 0x00223457, 0xe7820500, 0x50028021, 0x81410d33, 0x063d7108, 0xdb41af84, 0x4d888205, 0x00201198, 0x463d835f, 0x152106d7, 0x0a355a33, 0x6917614e, 0x75411f4d, 0x184b8b07, 0x1809c344, 0x21091640, 0x0b828000, 0x42808021, 0x26790519, 0x86058605, 0x2428422d, 0x22123b42, 0x42000080, 0xf587513b, 0x7813677b, 0xaf4d139f, 0x00ff210c, 0x5e0a1d57, 0x3b421546, 0x01032736, 0x02000380, 0x41180480, 0x2f420f07, 0x0c624807, 0x00000025, 0x18000103, 0x83153741, 0x430120c3, 0x042106b2, 0x088d4d00, 0x2f830620, 0x1810434a, 0x18140345, 0x8507fb41, 0x5ee582ea, 0x0023116c, 0x8d000600, 0x053b56af, 0xa6554fa2, 0x0d704608, 0x40180d20, 0x47181a43, 0xd37b07ff, 0x0b79500c, 0x420fd745, 0x47450bd9, 0x8471830a, 0x095a777e, 0x84137542, 0x82002013, 0x2f401800, 0x0007213b, 0x4405e349, 0x0d550ff3, 0x16254c0c, 0x820ffe4a, 0x0400218a, 0x89066f41, 0x106b414f, 0xc84d0120, 0x80802206, 0x0c9a4b03, 0x00100025, 0x68000200, 0x9d8c2473, 0x44134344, 0xf36a0f33, 0x4678860f, 0x1b440a25, 0x41988c0a, 0x80201879, 0x43079b5e, 0x4a18080b, 0x0341190b, 0x1259530c, 0x43251552, 0x908205c8, 0x0cac4018, 0x86000421, 0x0e504aa2, 0x0020b891, 0xfb450082, 0x51132014, 0x8f5205f3, 0x35052108, 0x8505cb59, 0x0f6d4f70, 0x82150021, 0x29af5047, 0x4f004b24, 0x75795300, 0x1b595709, 0x460b6742, 0xbf4b0f0d, 0x5743870b, 0xcb6d1461, 0x08f64505, 0x4e05ab6c, 0x334126c3, 0x0bcb6b0d, 0x1811034d, 0x4111ef4b, 0x814f1ce5, 0x20af8227, 0x07fd7b80, 0x41188e84, 0xef410f33, 0x80802429, 0x410d0000, 0xa34205ab, 0x76b7881c, 0xff500b89, 0x0741430f, 0x20086f4a, 0x209d8200, 0x234c18fd, 0x05d4670a, 0x4509af51, 0x9642078d, 0x189e831d, 0x7c1cc74b, 0xcd4c07b9, 0x0e7c440f, 0x8b7b0320, 0x21108210, 0xc76c8080, 0x03002106, 0x6b23bf41, 0xc549060b, 0x7946180b, 0x0ff7530f, 0x17ad4618, 0x200ecd45, 0x208c83fd, 0x5e0488fe, 0x032009c6, 0x420d044e, 0x0d8f0d7f, 0x00820020, 0x18001021, 0x6d273b45, 0xfd4c0c93, 0xcf451813, 0x0fe5450f, 0x5a47c382, 0x820a8b0a, 0x282b4998, 0x410a8b5b, 0x4b232583, 0x54004f00, 0x978f0ce3, 0x500f1944, 0xa95f1709, 0x0280220b, 0x05ba7080, 0xa1530682, 0x06324c13, 0x91412582, 0x05536e2c, 0x63431020, 0x0f434706, 0x8c11374c, 0x176143d7, 0x4d0f454c, 0xd3680bed, 0x0bee4d17, 0x212b9a41, 0x0f530a00, 0x140d531c, 0x43139143, 0x95610e8d, 0x0f094415, 0x4205fb56, 0x1b4205cf, 0x17015225, 0x5e0c477f, 0xaf6e0aeb, 0x0ff36218, 0x04849a84, 0x0a454218, 0x9c430420, 0x23c6822b, 0x04000102, 0x45091b4b, 0xf05f0955, 0x82802007, 0x421c2023, 0x5218282b, 0x7b53173f, 0x0fe7480c, 0x74173b7f, 0x47751317, 0x634d1807, 0x0f6f430f, 0x24086547, 0xfc808002, 0x0b3c7f80, 0x10840120, 0x188d1282, 0x20096b43, 0x0fc24403, 0x00260faf, 0x0180000b, 0x3f500280, 0x18002019, 0x450b4941, 0xf3530fb9, 0x18002010, 0x8208a551, 0x06234d56, 0xcb58a39b, 0xc3421805, 0x1313461e, 0x0f855018, 0xd34b0120, 0x6cfe2008, 0x574f0885, 0x09204114, 0x07000029, 0x00008000, 0x44028002, 0x01420f57, 0x10c95c10, 0x11184c18, 0x80221185, 0x7f421e00, 0x00732240, 0x09cd4977, 0x6d0b2b42, 0x4f180f8f, 0x8f5a0bcb, 0x9b0f830f, 0x0fb9411f, 0x230b5756, 0x00fd8080, 0x82060745, 0x000121d5, 0x8e0fb277, 0x4a8d4211, 0x24061c53, 0x04000007, 0x12275280, 0x430c954c, 0x80201545, 0x200f764f, 0x20008200, 0x20ce8308, 0x09534f02, 0x660edf64, 0x73731771, 0xe7411807, 0x20a2820c, 0x13b64404, 0x8f5d6682, 0x1d6b4508, 0x0cff4d18, 0x3348c58f, 0x0fc34c07, 0x31558b84, 0x8398820f, 0x17514712, 0x240b0e46, 0x80000a00, 0x093b4502, 0x420f9759, 0xa54c0bf1, 0x0f2b470c, 0x410d314b, 0x2584170c, 0x73b30020, 0xb55fe782, 0x204d8410, 0x08e043fe, 0x4f147e41, 0x022008ab, 0x4b055159, 0x2950068f, 0x00022208, 0x48511880, 0x82002009, 0x00112300, 0x634dff00, 0x24415f27, 0x180f6d43, 0x4d0b5d45, 0x4d5f05ef, 0x01802317, 0x56188000, 0xa7840807, 0xc6450220, 0x21ca8229, 0x4b781a00, 0x3359182c, 0x0cf3470f, 0x180bef46, 0x420b0354, 0xff470b07, 0x4515200a, 0x9758239b, 0x4a80200c, 0xd2410a26, 0x05fb4a08, 0x4b05e241, 0x03200dc9, 0x92290941, 0x00002829, 0x00010900, 0x5b020001, 0x23201363, 0x460d776a, 0xef530fdb, 0x209a890c, 0x13fc4302, 0x00008024, 0xc4820104, 0x08820220, 0x20086b5b, 0x18518700, 0x8408d349, 0x0da449a1, 0x00080024, 0x7b690280, 0x4c438b1a, 0x01220f63, 0x4c878000, 0x5c149c53, 0xfb430868, 0x2f56181e, 0x0ccf7b1b, 0x0f075618, 0x2008e347, 0x14144104, 0x00207f83, 0x00207b82, 0x201adf47, 0x16c35a13, 0x540fdf47, 0x802006c8, 0x5418f185, 0x29430995, 0x00002419, 0x58001600, 0x5720316f, 0x4d051542, 0x4b7b1b03, 0x138f4707, 0xb747b787, 0x4aab8213, 0x058305fc, 0x20115759, 0x82128401, 0x0a0b44e8, 0x46800121, 0xe64210d0, 0x82129312, 0x4bffdffe, 0x3b41171b, 0x9b27870f, 0x808022ff, 0x085c68fe, 0x41800021, 0x01410b20, 0x001a213a, 0x47480082, 0x11374e12, 0x56130b4c, 0xdf4b0c65, 0x0b0f590b, 0x0f574c18, 0x830feb4b, 0x075f480f, 0x480b4755, 0x40490b73, 0x80012206, 0x09d74280, 0x80fe8022, 0x80210e86, 0x056643ff, 0x10820020, 0x420b2646, 0x0b58391a, 0xd74c1808, 0x078b4e22, 0x2007f55f, 0x4b491807, 0x83802017, 0x65aa82a7, 0x3152099e, 0x068b7616, 0x9b431220, 0x09bb742c, 0x500e376c, 0x8342179b, 0x0a4d5d0f, 0x8020a883, 0x180cd349, 0x2016bb4b, 0x14476004, 0x84136c43, 0x08cf7813, 0x4f4c0520, 0x156f420f, 0x20085f42, 0x6fd3be03, 0xd4d30803, 0xa7411420, 0x004b222c, 0x0d3b614f, 0x3f702120, 0x1393410a, 0x8f132745, 0x47421827, 0x41e08209, 0xb05e2bb9, 0x18b7410c, 0x18082647, 0x4107a748, 0xeb8826bf, 0x0ca76018, 0x733ecb41, 0xd0410d83, 0x43ebaf2a, 0x0420067f, 0x721dab4c, 0x472005bb, 0x4105d341, 0x334844cb, 0x20dba408, 0x47d6ac00, 0x034e3aef, 0x0f8f421b, 0x930f134d, 0x3521231f, 0xb7421533, 0x42f5ad0a, 0x1e961eaa, 0x17000022, 0x4c367b50, 0x7d491001, 0x0bf5520f, 0x4c18fda7, 0xb8460c55, 0x83fe2005, 0x00fe25b9, 0x80000180, 0x9e751085, 0x261b5c12, 0x82110341, 0x001123fb, 0x4518fe80, 0xf38c2753, 0x6d134979, 0x295107a7, 0xaf5f180f, 0x0fe3660c, 0x180b6079, 0x2007bd5f, 0x9aab9103, 0x2f4d1811, 0x05002109, 0x44254746, 0x1d200787, 0x450bab75, 0x4f180f57, 0x4f181361, 0x3b831795, 0xeb4b0120, 0x0b734805, 0x84078f48, 0x2e1b47bc, 0x00203383, 0xaf065f45, 0x831520d7, 0x130f51a7, 0x1797bf97, 0x2b47d783, 0x18fe2005, 0x4a18a44f, 0xa64d086d, 0x1ab0410d, 0x6205a258, 0xdbab069f, 0x4f06f778, 0xa963081d, 0x133b670a, 0x8323d141, 0x13195b23, 0x530f5e70, 0xe5ad0824, 0x58001421, 0x1f472b4b, 0x47bf410c, 0x82000121, 0x83fe20cb, 0x07424404, 0x68068243, 0xd7ad0d3d, 0x00010d26, 0x80020000, 0x4a1c6f43, 0x23681081, 0x10a14f13, 0x8a070e57, 0x430a848f, 0x7372243e, 0x4397a205, 0xb56c1021, 0x43978f0f, 0x64180505, 0x99aa0ff2, 0x0e000022, 0x20223341, 0x094b4f37, 0x074a3320, 0x2639410a, 0xfe208e84, 0x8b0e0048, 0x508020a3, 0x9e4308fe, 0x073f4115, 0xe3480420, 0x0c9b5f1b, 0x7c137743, 0x9a95185b, 0x6122b148, 0x979b08df, 0x0fe36c18, 0x48109358, 0x23441375, 0x0ffd5c0b, 0x180fc746, 0x2011d157, 0x07e95702, 0x58180120, 0x18770ac3, 0x51032008, 0x7d4118e3, 0x80802315, 0x3b4c1900, 0xbb5a1830, 0x0ceb6109, 0x5b0b3d42, 0x4f181369, 0x4f180b8d, 0x4f180f75, 0x355a1b81, 0x200d820d, 0x18e483fd, 0x4528854f, 0x89420846, 0x1321411f, 0x44086b60, 0x07421d77, 0x107d4405, 0x4113fd41, 0x5a181bf1, 0x4f180db3, 0x8021128f, 0x20f68280, 0x44a882fe, 0x334d249a, 0x052f6109, 0x1520c3a7, 0xef4eb783, 0x4ec39b1b, 0xc4c90ee7, 0x20060b4d, 0x256f4905, 0x4d0cf761, 0xcf9b1f13, 0xa213d74e, 0x0e1145d4, 0x50135b42, 0xcb4e398f, 0x20d79f27, 0x08865d80, 0x186d5018, 0xa90f7142, 0x067342d7, 0x3f450420, 0x65002021, 0xe3560771, 0x24d38f23, 0x15333531, 0x0eb94d01, 0x451c9f41, 0x384322fb, 0x00092108, 0x19af6b18, 0x6e0c6f5a, 0xbd770bfb, 0x22bb7718, 0x20090f57, 0x25e74204, 0x4207275a, 0xdb5408ef, 0x1769450f, 0x1b1b5518, 0x210b1f57, 0x5e4c8001, 0x55012006, 0x802107f1, 0x0a306a80, 0x45808021, 0x0d850b88, 0x31744f18, 0x1808ec54, 0x2009575b, 0x45ffa505, 0x1b420c73, 0x180f9f0f, 0x4a0cf748, 0x501805b2, 0x00210f40, 0x4d118f80, 0xd6823359, 0x072b5118, 0x314ad7aa, 0x8fc79f08, 0x45d78b1f, 0xfe20058f, 0x23325118, 0x7b54d9b5, 0x9fc38f46, 0x10bb410f, 0x41077b42, 0xc1410faf, 0x27cf441d, 0x46051b4f, 0x04200683, 0x2121d344, 0x8f530043, 0x8fcf9f0e, 0x21df8c1f, 0x50188000, 0x5d180e52, 0xfd201710, 0x4405c341, 0xd68528e3, 0x20071f6b, 0x1b734305, 0x6b080957, 0x7d422b1f, 0x67002006, 0x7f8317b1, 0x2024cb48, 0x08676e00, 0x8749a39b, 0x18132006, 0x410a6370, 0x8f490b47, 0x7e1f8f13, 0x551805c3, 0x4c180915, 0xfe200e2f, 0x244d5d18, 0x270bcf44, 0xff000019, 0x04800380, 0x5f253342, 0xff520df7, 0x13274c18, 0x5542dd93, 0x0776181b, 0xf94a1808, 0x084a4c0c, 0x4308ea5b, 0xde831150, 0x7900fd21, 0x00492c1e, 0x060f4510, 0x17410020, 0x0ce74526, 0x6206b341, 0x1f561083, 0x9d6c181b, 0x08a0500e, 0x112e4118, 0x60000421, 0xbf901202, 0x4408e241, 0xc7ab0513, 0xb40f0950, 0x055943c7, 0x4f18ff20, 0xc9ae1cad, 0x32b34f18, 0x7a180120, 0x3d520a05, 0x53d1b40a, 0x80200813, 0x1b815018, 0x832bf86f, 0x67731847, 0x297f4308, 0x6418d54e, 0x734213f7, 0x056b4b27, 0xdba5fe20, 0x1828aa4e, 0x2031a370, 0x06cb6101, 0x2040ad41, 0x07365300, 0x2558d985, 0x83fe200c, 0x0380211c, 0x542c4743, 0x052006b7, 0x6021df45, 0x897b0707, 0x18d3c010, 0x20090e70, 0x1d5843ff, 0x540a0e44, 0x002126c5, 0x322f7416, 0x636a5720, 0x0f317409, 0x610fe159, 0x294617e7, 0x08555213, 0x2006a75d, 0x6cec84fd, 0xfb5907be, 0x3a317405, 0x83808021, 0x180f20ea, 0x4626434a, 0x531818e3, 0xdb59172d, 0x0cbb460c, 0x2013d859, 0x18b94502, 0x8f46188d, 0x77521842, 0x0a184e38, 0x9585fd20, 0x6a180684, 0xc64507e9, 0x51cbb230, 0xd3440cf3, 0x17ff6a0f, 0x450f5b42, 0x276407c1, 0x4853180a, 0x21ccb010, 0xcf580013, 0x0c15442d, 0x410a1144, 0x1144359d, 0x5cfe2006, 0xa1410a43, 0x2bb64519, 0x2f5b7618, 0xb512b745, 0x0cfd6fd1, 0x42089f59, 0xb8450c70, 0x0000232d, 0x50180900, 0xb9491ae3, 0x0fc37610, 0x01210f83, 0x0f3b4100, 0xa01b2742, 0x0ccd426f, 0x6e8f6f94, 0x9c808021, 0xc7511870, 0x17c74b08, 0x9b147542, 0x44fe2079, 0xd5480c7e, 0x95ef861d, 0x101b597b, 0xf5417594, 0x9f471808, 0x86868d0e, 0x3733491c, 0x690f4d6d, 0x43440b83, 0x1ba94c0b, 0x660cd16b, 0x802008ae, 0x74126448, 0xcb4f38a3, 0x2cb74b0b, 0x47137755, 0xe3971777, 0x1b5d0120, 0x057a4108, 0x6e08664d, 0x17421478, 0x11af4208, 0x850c3f42, 0x08234f0c, 0x4321eb4a, 0xf3451095, 0x0f394e0f, 0x4310eb45, 0xc09707b1, 0x54431782, 0xaec08d1d, 0x0f434dbb, 0x9f0c0b45, 0x0a3b4dbb, 0x4618bdc7, 0x536032eb, 0x17354213, 0x4d134169, 0xc7a30c2f, 0x4e254342, 0x174332cf, 0x43cdae17, 0x6b4706e4, 0x0e16430d, 0x530b5542, 0x2f7c26bb, 0x13075f31, 0x43175342, 0x60181317, 0x6550114e, 0x28624710, 0x58070021, 0x59181683, 0x2d540cf5, 0x05d5660c, 0x20090c7b, 0x0e157e02, 0x8000ff2b, 0x14000080, 0x80ff8000, 0x27137e03, 0x336a4b20, 0x0f817107, 0x13876e18, 0x730f2f7e, 0x2f450b75, 0x6d02200b, 0x6d66094c, 0x4b802009, 0x15820a02, 0x2f45fe20, 0x5e032006, 0x00202fd9, 0x450af741, 0xeb412e0f, 0x0ff3411f, 0x420a8b65, 0xf7410eae, 0x1c664810, 0x540e1145, 0xbfa509f3, 0x42302f58, 0x80200c35, 0xcb066c47, 0x4b1120c1, 0x41492abb, 0x34854110, 0xa7097b72, 0x251545c7, 0x4b2c7f56, 0xc5b40bab, 0x940cd54e, 0x2e6151c8, 0x09f35f18, 0x4b420420, 0x09677121, 0x8f24f357, 0x1b5418e1, 0x08915a1f, 0x3143d894, 0x22541805, 0x1b9b4b0e, 0x8c0d3443, 0x1400240d, 0x18ff8000, 0x582e6387, 0xf99b2b3b, 0x8807a550, 0x17a14790, 0x2184fd20, 0x5758fe20, 0x2354882c, 0x15000080, 0x5e056751, 0x334c2c2f, 0x97c58f0c, 0x1fd7410f, 0x0d4d4018, 0x4114dc41, 0x04470ed6, 0x0dd54128, 0x00820020, 0x02011523, 0x22008700, 0x86480024, 0x0001240a, 0x8682001a, 0x0002240b, 0x866c000e, 0x8a03200b, 0x8a042017, 0x0005220b, 0x22218614, 0x84060000, 0x86012017, 0x8212200f, 0x250b8519, 0x000d0001, 0x0b850031, 0x07000224, 0x0b862600, 0x11000324, 0x0b862d00, 0x238a0420, 0x0a000524, 0x17863e00, 0x17840620, 0x01000324, 0x57820904, 0x0b85a783, 0x0b85a785, 0x0b85a785, 0x22000325, 0x85007a00, 0x85a7850b, 0x85a7850b, 0x22a7850b, 0x82300032, 0x00342201, 0x0805862f, 0x35003131, 0x54207962, 0x74736972, 0x47206e61, 0x6d6d6972, 0x65527265, 0x616c7567, 0x58545472, 0x6f725020, 0x43796767, 0x6e61656c, 0x30325454, 0x822f3430, 0x35313502, 0x79006200, 0x54002000, 0x69007200, 0x74007300, 0x6e006100, 0x47200f82, 0x6d240f84, 0x65006d00, 0x52200982, 0x67240582, 0x6c007500, 0x72201d82, 0x54222b82, 0x23825800, 0x19825020, 0x67006f22, 0x79220182, 0x1b824300, 0x3b846520, 0x1f825420, 0x41000021, 0x1422099b, 0x0b410000, 0x87088206, 0x01012102, 0x78080982, 0x01020101, 0x01040103, 0x01060105, 0x01080107, 0x010a0109, 0x010c010b, 0x010e010d, 0x0110010f, 0x01120111, 0x01140113, 0x01160115, 0x01180117, 0x011a0119, 0x011c011b, 0x011e011d, 0x0020011f, 0x00040003, 0x00060005, 0x00080007, 0x000a0009, 0x000c000b, 0x000e000d, 0x0010000f, 0x00120011, 0x00140013, 0x00160015, 0x00180017, 0x001a0019, 0x001c001b, 0x001e001d, 0x08bb821f, 0x22002142, 0x24002300, 0x26002500, 0x28002700, 0x2a002900, 0x2c002b00, 0x2e002d00, 0x30002f00, 0x32003100, 0x34003300, 0x36003500, 0x38003700, 0x3a003900, 0x3c003b00, 0x3e003d00, 0x40003f00, 0x42004100, 0x4b09f382, 0x00450044, 0x00470046, 0x00490048, 0x004b004a, 0x004d004c, 0x004f004e, 0x00510050, 0x00530052, 0x00550054, 0x00570056, 0x00590058, 0x005b005a, 0x005d005c, 0x005f005e, 0x01610060, 0x01220121, 0x01240123, 0x01260125, 0x01280127, 0x012a0129, 0x012c012b, 0x012e012d, 0x0130012f, 0x01320131, 0x01340133, 0x01360135, 0x01380137, 0x013a0139, 0x013c013b, 0x013e013d, 0x0140013f, 0x00ac0041, 0x008400a3, 0x00bd0085, 0x00e80096, 0x008e0086, 0x009d008b, 0x00a400a9, 0x008a00ef, 0x008300da, 0x00f20093, 0x008d00f3, 0x00880097, 0x00de00c3, 0x009e00f1, 0x00f500aa, 0x00f600f4, 0x00ad00a2, 0x00c700c9, 0x006200ae, 0x00900063, 0x00cb0064, 0x00c80065, 0x00cf00ca, 0x00cd00cc, 0x00e900ce, 0x00d30066, 0x00d100d0, 0x006700af, 0x009100f0, 0x00d400d6, 0x006800d5, 0x00ed00eb, 0x006a0089, 0x006b0069, 0x006c006d, 0x00a0006e, 0x0071006f, 0x00720070, 0x00750073, 0x00760074, 0x00ea0077, 0x007a0078, 0x007b0079, 0x007c007d, 0x00a100b8, 0x007e007f, 0x00810080, 0x00ee00ec, 0x6e750eba, 0x646f6369, 0x78302365, 0x31303030, 0x32200e8d, 0x33200e8d, 0x34200e8d, 0x35200e8d, 0x36200e8d, 0x37200e8d, 0x38200e8d, 0x39200e8d, 0x61200e8d, 0x62200e8d, 0x63200e8d, 0x64200e8d, 0x65200e8d, 0x66200e8d, 0x31210e8c, 0x8d0e8d30, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x8d3120ef, 0x66312def, 0x6c656406, 0x04657465, 0x6f727545, 0x3820ec8c, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x3820ec8d, 0x200ddc41, 0x0ddc4139, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0xef8d3920, 0x00663923, 0x48fa0500, 0x00f762f9, }; static void GetDefaultCompressedFontDataTTF(const void** ttf_compressed_data, unsigned int* ttf_compressed_size) { *ttf_compressed_data = proggy_clean_ttf_compressed_data; *ttf_compressed_size = proggy_clean_ttf_compressed_size; } //----------------------------------------------------------------------------- //---- Include imgui_user.inl at the end of imgui.cpp //---- So you can include code that extends ImGui using its private data/functions. #ifdef IMGUI_INCLUDE_IMGUI_USER_INL #include "imgui_user.inl" #endif //-----------------------------------------------------------------------------
[ "daniel@collin.com" ]
daniel@collin.com
dc8db6ba93a14d9a6a05656312e689cff87f3dd6
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_2700486_0/C++/mrussell/diamond.cpp
79dacc666892b998492298fb1804f48721772c5b
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
1,939
cpp
#include <iostream> #include <algorithm> using namespace std; unsigned nChoosek( unsigned n, unsigned k ) { if (k > n) return 0; if (k * 2 > n) k = n-k; if (k == 0) return 1; int result = n; for( int i = 2; i <= k; ++i ) { result *= (n-i+1); result /= i; } return result; } double probHasDiamond(unsigned n, unsigned k, int max) { unsigned num, denom; int i; if (n == max*2+1) return 1.; num = 0; denom = 0; // calc numerator for (i=k; i<=n; i++) { if ((i <= max) && (n - i) <= max) num += nChoosek(n, i); } // calc denominator for (i=0; i<=n; i++) { if ((i <= max) && (n - i) <= max) denom += nChoosek(n, i); } return ((double) num) / ((double) denom); } double find_traingular_numbers_between(int n, int xx, int y) { int last = 0, next = 0, c, x = 1, count = 0; while (next < n) { c = next; next = next + x; x += 1; last = c; count++; } if (x % 2 != 0) next += x; else last -= (x - 2); int max_x_plus_y; if (count % 2 != 0) max_x_plus_y = count - 1; else max_x_plus_y = count; //printf("max_x_plus_y %d\n", max_x_plus_y); int x_plus_y = abs(xx) + y; //printf("x_plus_y %d\n", x_plus_y); if (x_plus_y <= max_x_plus_y - 2) return 1.; else if (x_plus_y <= max_x_plus_y) { int new_y = y + 1; int new_n = n - last; int max = (next - last - 1) / 2; return probHasDiamond(new_n, new_y,max); } else return 0.; } int one(int t, int n, int x, int y) { // int n, k = 3, max = 4; // for (n = 1; n <= 9; n++) { // printf ("prob of %d,%d w/max of %d = %f\n", n, k, max, probHasDiamond(n,k,max)); // } double ans = find_traingular_numbers_between(n, x, y) ; printf("Case #%d: %f\n", t, ans); return 0; } int main() { int T, t; scanf("%d", &T); for (t = 1; t <= T; t++) { int n, x, y; scanf("%d %d %d", &n, &x, &y); one(t, n, x, y); } }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
cbb4c9ee1df98a42cac0b21568004c0cfdb825a5
52507f7928ba44b7266eddf0f1a9bf6fae7322a4
/SDK/BP_Thrown1HAxeProjectile_classes.h
eb592d3fd4007c8965d90ac6845961605576782b
[]
no_license
LuaFan2/mordhau-sdk
7268c9c65745b7af511429cfd3bf16aa109bc20c
ab10ad70bc80512e51a0319c2f9b5effddd47249
refs/heads/master
2022-11-30T08:14:30.825803
2020-08-13T16:31:27
2020-08-13T16:31:27
287,329,560
1
0
null
null
null
null
UTF-8
C++
false
false
693
h
#pragma once // Name: Mordhau, Version: 1.0.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass BP_Thrown1HAxeProjectile.BP_Thrown1HAxeProjectile_C // 0x0000 (0x08E0 - 0x08E0) class ABP_Thrown1HAxeProjectile_C : public ABP_ThrownSpinningProjectile_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass BP_Thrown1HAxeProjectile.BP_Thrown1HAxeProjectile_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "51294434+LuaFan2@users.noreply.github.com" ]
51294434+LuaFan2@users.noreply.github.com
e793912e1dfe8dbc2038b5f312ca28ff11911d6b
7a82399ae70babdc9f5d4aa7008882bda0e9b27d
/revision/2darray.cpp
447b839687deedd22bcf51816b8a6216fece675e
[]
no_license
vishal8802/algo_cb
d861ab23bb46d0d6f1a4714eb9f3c576d9cb8809
636141bd97954da283c7e11caa0238747bba4fd2
refs/heads/master
2020-08-11T16:54:24.446248
2019-10-19T07:19:40
2019-10-19T07:19:40
214,597,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,270
cpp
#include<bits/stdc++.h> using namespace std; int main(){ int r,c; cin>>r>>c; int a[r][c]; for(int i=0;i<r;i++) for(int j=0;j<c;j++) cin>>a[i][j]; for(int i=0;i<r;i++){ for(int j=0;j<c;j++) cout<<a[i][j]<<" "; cout<<endl; } // for(int i=0;i<r;i++){ // for(int j=0;j<c;j++) // cout<<a[j][i]<<" "; // cout<<endl; // } // for(int i=0;i<c;i++){ // if(i%2==0){ // for(int j=0;j<r;j++){ // cout<<a[j][i]<<" "; // } // } // else{ // for(int j=r-1;j>=0;j--){ // cout<<a[j][i]<<" "; // } // } // } int i,j; int sr=0,sc=0,ec=c-1,er=r-1; while(sr<=er && sc<=ec){ for(i=sc;i<=ec;i++) cout<<a[sr][i]<<" "; sr++; for(i=sr;i<=er;i++) cout<<a[i][ec]<<" "; ec--; if(sr<er){ for(i=ec;i>=sc;i--) cout<<a[er][i]<<" "; er--; } if(sc<ec){ for(i=er;i>=sr;i--) cout<<a[i][sc]<<" "; sc++; } } return 0; }
[ "svishal8802@gmail.com" ]
svishal8802@gmail.com
e30e0ec56fc7300a80b7d07fea7f4ee31cbeb95d
69e10019853d4a37c7e4003aa11d770ba86bb7f2
/TakeOwnerShip/RegFile.h
9923f5d353470eb1a90886e720b70eb6d0102ca1
[]
no_license
Tevic/TakeOwnerShip
1acefb2c13aac881f2b0548f5420475848f85661
bb0dbfa81712a98f61d901c73fca0656821d4e88
refs/heads/master
2021-01-01T18:41:47.853317
2014-10-18T08:03:43
2014-10-18T08:03:43
null
0
0
null
null
null
null
GB18030
C++
false
false
2,845
h
/*///////////////////////本类是操作注册表使用 有以下几个功能: 1.直接添加启动项; 2.直接删除启动项; 注意这两个功能必须使用不带参数对象初始化; 对大众函数进行操作必须使用 带参初始化其中是注册表指向和注册表子项 /////////////////// */ #pragma once #include"windows.h" #include"iostream" #include"vector" #include"string" using namespace std; #ifdef UNICODE typedef basic_string< wchar_t > mstring; #else typedef basic_string< char > mstring; #endif typedef struct reg { mstring strValue; SYSTEMTIME ftime; }KeyData; typedef struct value { mstring strName; mstring strValue; DWORD nType; }ValueData; //////////////////////// typedef vector<KeyData> VKeyData; typedef vector<KeyData>::iterator VKeyDatai; typedef vector<ValueData> VValueData; typedef vector<ValueData>::iterator VValueDatai; ///////////////// class CRegFile { public: CRegFile(void); /////////////只提供给启动项使用 /*A handle to an open registry key it can be one of the following predefined keys: HKEY_CLASSES_ROOT HKEY_CURRENT_CONFIG HKEY_CURRENT_USER HKEY_LOCAL_MACHINE HKEY_USERS */ CRegFile(HKEY hKey,TCHAR*hSubKey=NULL);/////////////提供给任何键 CRegFile(HKEY hKey,mstring& hSubKey); private: HKEY m_hKey; TCHAR* m_hSubKey; HKEY hKey;//////////////打开后句柄 // TCHAR*pEnumValueBuf;//////////枚举键值字符串 // TCHAR*pEnumRegBuf;////////////枚举子键字符串 private: bool OpenKeyReg(); bool CloseKeyReg(); public: bool CreateKeyReg(); bool DeleteKeyReg(); bool IsExistKeyReg(); bool SetValueReg(TCHAR* lpData,TCHAR* lpValueName=NULL, DWORD dwType=REG_SZ); bool SetValueReg(mstring& lpData,mstring& lpValueName, DWORD dwType=REG_SZ); bool QueryValueReg(mstring& lpData,TCHAR* lpValueName=NULL,DWORD*dwType=NULL); bool QueryValueReg(mstring& lpData,mstring& lpValueName,DWORD* dwType); bool DeleteValueReg(TCHAR* lpValueName=NULL); bool DeleteValueReg(mstring& lpValueName); bool IsExistValueReg(TCHAR* lpValueName=NULL); bool IsExistValueReg(mstring& lpValueName); bool EnumAllKeyReg(vector<KeyData>& stData); bool EnumAllValueReg(vector<ValueData>& stData); //////////////////启动项操作函数 bool AddRunValueReg(TCHAR* lpData,TCHAR* lpValueName=NULL, DWORD dwType=REG_SZ); bool AddRunValueReg(mstring& lpData,mstring& lpValueName, DWORD dwType=REG_SZ); bool DeleteRunValueReg(TCHAR* lpValueName=NULL); bool DeleteRunValueReg(mstring& lpValueName); bool IsExistRunValue(TCHAR* lpValueName=NULL); bool IsExistRunValue(mstring& lpValueName); bool EnumRunValueReg(vector<ValueData>& stData); bool QueryRunValueReg(mstring& lpData,TCHAR* lpValueName=NULL,DWORD*dwType=NULL); bool QueryRunValueReg(mstring& lpData,mstring& lpValueName,DWORD* dwType); ~CRegFile(void); private: void InitRun(); void EndRun(); };
[ "tevic.tt@gmail.com" ]
tevic.tt@gmail.com
1c19061e0bc9f3b3de223a163d25075ef16add49
5fa6538165b42d8f8f9010ffefd7eb19559afa64
/PA5/src/graphics.cpp
fd63b82d64df71a8403563b082351db5d36d5521
[]
no_license
david4jsus/cs480Valenzuela
6f9eb8a20893dafff23dddef6c5ef9196f9fda96
47f88938bcf2754834132b2bf65a09a714593eeb
refs/heads/master
2021-12-10T07:15:00.360964
2021-12-06T22:33:09
2021-12-06T22:33:09
146,481,540
0
1
null
null
null
null
UTF-8
C++
false
false
4,709
cpp
#include "graphics.h" Graphics::Graphics() { } Graphics::~Graphics() { } bool Graphics::Initialize(int width, int height, std::string file) { // Used for the linux OS #if !defined(__APPLE__) && !defined(MACOSX) // cout << glewGetString(GLEW_VERSION) << endl; glewExperimental = GL_TRUE; auto status = glewInit(); // This is here to grab the error that comes from glew init. // This error is an GL_INVALID_ENUM that has no effects on the performance glGetError(); //Check for error if (status != GLEW_OK) { std::cerr << "GLEW Error: " << glewGetErrorString(status) << "\n"; return false; } #endif // For OpenGL 3 GLuint vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); // Init Camera m_camera = new Camera(); if(!m_camera->Initialize(width, height)) { printf("Camera Failed to Initialize\n"); return false; } // Create objects Object* sun = new Object(file, 0, 0.0f, 0.1f, 0.01f, 1.0f); /* Object* planet = new Object(0, 6.0f, 0.2f, 0.5f, 0.6f); Object* moon = new Object(planet, 2.0f, 0.5f, 1.0f, 0.2f); Object* planet2 = new Object(0, 10.0f, 0.15f, 0.2f, 0.8f); Object* moon2 = new Object(planet2, 2.0f, 0.3f, 1.0f, 0.3f); Object* moon3 = new Object(moon2, 1.0f, 0.8f, 1.5f, 0.1f); */ m_cubes.push_back(sun); /* m_cubes.push_back(planet); m_cubes.push_back(moon); m_cubes.push_back(planet2); m_cubes.push_back(moon2); m_cubes.push_back(moon3); */ // Set up the shaders m_shader = new Shader(); if(!m_shader->Initialize()) { printf("Shader Failed to Initialize\n"); return false; } // Add the vertex shader if(!m_shader->AddShader(GL_VERTEX_SHADER)) { printf("Vertex Shader failed to Initialize\n"); return false; } // Add the fragment shader if(!m_shader->AddShader(GL_FRAGMENT_SHADER)) { printf("Fragment Shader failed to Initialize\n"); return false; } // Connect the program if(!m_shader->Finalize()) { printf("Program to Finalize\n"); return false; } // Locate the projection matrix in the shader m_projectionMatrix = m_shader->GetUniformLocation("projectionMatrix"); if (m_projectionMatrix == INVALID_UNIFORM_LOCATION) { printf("m_projectionMatrix not found\n"); return false; } // Locate the view matrix in the shader m_viewMatrix = m_shader->GetUniformLocation("viewMatrix"); if (m_viewMatrix == INVALID_UNIFORM_LOCATION) { printf("m_viewMatrix not found\n"); return false; } // Locate the model matrix in the shader m_modelMatrix = m_shader->GetUniformLocation("modelMatrix"); if (m_modelMatrix == INVALID_UNIFORM_LOCATION) { printf("m_modelMatrix not found\n"); return false; } //enable depth testing glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); return true; } void Graphics::Update(unsigned int dt) { // Update the objects for(unsigned int i = 0; i < m_cubes.size(); i++) { m_cubes[i]->Update(dt); } } Object* Graphics::getCube(int index) { return m_cubes[index]; } void Graphics::Render() { //clear the screen glClearColor(0.0, 0.0, 0.2, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Start the correct program m_shader->Enable(); // Send in the projection and view to the shader glUniformMatrix4fv(m_projectionMatrix, 1, GL_FALSE, glm::value_ptr(m_camera->GetProjection())); glUniformMatrix4fv(m_viewMatrix, 1, GL_FALSE, glm::value_ptr(m_camera->GetView())); // Render the objects for(unsigned int i = 0; i < m_cubes.size(); i++) { glUniformMatrix4fv(m_modelMatrix, 1, GL_FALSE, glm::value_ptr(m_cubes[i]->GetModel())); m_cubes[i]->Render(); } // Get any errors from OpenGL auto error = glGetError(); if ( error != GL_NO_ERROR ) { string val = ErrorString( error ); std::cout<< "Error initializing OpenGL! " << error << ", " << val << std::endl; } } std::string Graphics::ErrorString(GLenum error) { if(error == GL_INVALID_ENUM) { return "GL_INVALID_ENUM: An unacceptable value is specified for an enumerated argument."; } else if(error == GL_INVALID_VALUE) { return "GL_INVALID_VALUE: A numeric argument is out of range."; } else if(error == GL_INVALID_OPERATION) { return "GL_INVALID_OPERATION: The specified operation is not allowed in the current state."; } else if(error == GL_INVALID_FRAMEBUFFER_OPERATION) { return "GL_INVALID_FRAMEBUFFER_OPERATION: The framebuffer object is not complete."; } else if(error == GL_OUT_OF_MEMORY) { return "GL_OUT_OF_MEMORY: There is not enough memory left to execute the command."; } else { return "None"; } }
[ "david4jsus@gmail.com" ]
david4jsus@gmail.com
1003ae99b29da2f9356b42556d02d21649592d29
3a592c059fcdd6d3753433706c25f4be17828e52
/qdeepinfiledialoghelper.h
bec79075c9eadcb6406139ec3ee22240998fa6cf
[]
no_license
martyr-deepin/qt5deepintheme-plugin
c553da120c32d5bb0e1baffd1198ce99518f99dd
bec4c14c6a11b202bf562a8e3d6fcf808f5ed4ac
refs/heads/master
2021-12-14T18:04:50.550503
2016-11-21T02:12:00
2016-11-21T02:12:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
h
#ifndef QDEEPINFILEDIALOGHELPER_H #define QDEEPINFILEDIALOGHELPER_H #include <qpa/qplatformdialoghelper.h> #include <QPointer> QT_BEGIN_NAMESPACE class DFileDialogHandle; class QDeepinFileDialogHelper : public QPlatformFileDialogHelper { public: QDeepinFileDialogHelper(); ~QDeepinFileDialogHelper(); bool show(Qt::WindowFlags flags, Qt::WindowModality modality, QWindow *parent) Q_DECL_OVERRIDE; void exec() Q_DECL_OVERRIDE; void hide() Q_DECL_OVERRIDE; bool defaultNameFilterDisables() const Q_DECL_OVERRIDE; void setDirectory(const QUrl &directory) Q_DECL_OVERRIDE; QUrl directory() const Q_DECL_OVERRIDE; void selectFile(const QUrl &filename) Q_DECL_OVERRIDE; QList<QUrl> selectedFiles() const Q_DECL_OVERRIDE; void setFilter() Q_DECL_OVERRIDE; void selectNameFilter(const QString &filter) Q_DECL_OVERRIDE; QString selectedNameFilter() const Q_DECL_OVERRIDE; private: mutable QPointer<DFileDialogHandle> dialog; void ensureDialog() const; void applyOptions(); }; QT_END_NAMESPACE #endif // QDEEPINFILEDIALOGHELPER_H
[ "ccrr1314@live.com" ]
ccrr1314@live.com
b6eddd87ee1c50870cda63b26ebe7a70c686d5fc
0494c9caa519b27f3ed6390046fde03a313d2868
/src/chrome/browser/extensions/api/usb/usb_device_resource.cc
685d24dc6dc0073de68a8b5ee46e926019508b61
[ "BSD-3-Clause" ]
permissive
mhcchang/chromium30
9e9649bec6fb19fe0dc2c8b94c27c9d1fa69da2c
516718f9b7b95c4280257b2d319638d4728a90e1
refs/heads/master
2023-03-17T00:33:40.437560
2017-08-01T01:13:12
2017-08-01T01:13:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,157
cc
// 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/extensions/api/usb/usb_device_resource.h" #include <string> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/synchronization/lock.h" #include "chrome/browser/extensions/api/api_resource.h" #include "chrome/browser/usb/usb_device_handle.h" #include "chrome/common/extensions/api/usb.h" namespace extensions { static base::LazyInstance<ProfileKeyedAPIFactory< ApiResourceManager<UsbDeviceResource> > > g_factory = LAZY_INSTANCE_INITIALIZER; // static template <> ProfileKeyedAPIFactory<ApiResourceManager<UsbDeviceResource> >* ApiResourceManager<UsbDeviceResource>::GetFactoryInstance() { return &g_factory.Get(); } UsbDeviceResource::UsbDeviceResource(const std::string& owner_extension_id, scoped_refptr<UsbDeviceHandle> device) : ApiResource(owner_extension_id), device_(device) {} UsbDeviceResource::~UsbDeviceResource() {} } // namespace extensions
[ "1990zhaoshuang@163.com" ]
1990zhaoshuang@163.com
a791feddcc12f2078c2e1982b893086801c9e05a
3150b88fff942e4e483094c8bad72fa77eb5e5a1
/source/helpers/AsyncLogger.cpp
15a4aa4d3240e44e6f42235a81e3a6bbe6e71de2
[ "MIT" ]
permissive
devolution2409/NX-input-recorder
33985c2c594fc7e5732dc3755ace82a372170422
6d87a4dc0458cd2351288b76811224049fdd2ef7
refs/heads/master
2020-06-17T17:22:38.205462
2019-08-07T08:18:31
2019-08-07T08:18:31
195,990,674
3
1
null
null
null
null
UTF-8
C++
false
false
2,970
cpp
#include <cmath> #include <cstdio> #include <cstring> #include <string> #include <switch.h> #include "helpers/AsyncLogger.hpp" Result AsyncLogger::start() { if (is_running()) return -1; Result rc = threadCreate(&this->thread, writer_thread, (void *)this, 0x1000, 0x3b, -2); if (R_SUCCEEDED(rc)) { this->running = true; rc = threadStart(&this->thread); if (R_FAILED(rc)) threadClose(&this->thread); } this->running = R_SUCCEEDED(rc); return rc; } void AsyncLogger::stop() { if (!is_running()) return; this->running = false; threadWaitForExit(&this->thread); threadClose(&this->thread); } void AsyncLogger::writer_thread(void *args) { AsyncLogger *s_this = (AsyncLogger *)args; float freq = (float)armGetSystemTickFreq(); static const char *const lvl_strings[] = { "[TRACE]:", "[INFO]: ", "[WARN]: ", "[ERROR]:", "[FATAL]:"}; while (s_this->is_running() || !s_this->messages.empty()) { svcSleepThread(1e+6); for (message_t &message : s_this->messages) { float time_ms = (float)(message.tick - s_this->start_tick) / freq; fprintf(s_this->fp, "[%#.2fs] %s %s", time_ms, lvl_strings[message.lvl], message.string.c_str()); mutexLock(&s_this->dequeue_mutex); s_this->messages.pop_front(); mutexUnlock(&s_this->dequeue_mutex); } } } #ifdef DEBUG void AsyncLogger::data(const void *data, size_t size, unsigned int indent, const char *prefix, log_lvl lvl) { if (lvl < this->lvl || !is_running()) return; size_t prefix_len = (prefix) ? strlen(prefix) : 0; std::string str(prefix_len + ceil(size / 16.0) * (indent + 70) + 1, ' '); char *str_data = (char *)str.data(); if (prefix) strncpy(str_data, prefix, prefix_len); size_t data_idx = prefix_len + indent, ascii_idx = data_idx + 53; for (size_t i = 0; i < size; ++i) { str_data[data_idx + snprintf(&str_data[data_idx], 3, "%02x", ((u8 *)data)[i])] = ' '; str_data[ascii_idx] = (' ' <= ((u8 *)data)[i] && ((u8 *)data)[i] <= '~') ? ((u8 *)data)[i] : '.'; data_idx += 3; ++ascii_idx; if ((i + 1) % 16 == 0) { str_data[data_idx + 1] = '|'; str_data[ascii_idx] = '\n'; data_idx += indent + 21; ascii_idx = data_idx + 53; } else if ((i + 1) % 8 == 0) { ++data_idx; } else if (i + 1 == size) { str_data[data_idx + (16 - i % 16) * 3 - 1] = '|'; } } *(u16 *)&str_data[str.size() - 2] = '\n'; mutexLock(&this->dequeue_mutex); this->messages.push_back({armGetSystemTick(), lvl, str}); mutexUnlock(&this->dequeue_mutex); } #endif // DEBUG
[ "contact@davidbouet.fr" ]
contact@davidbouet.fr
4ed3221b1f50de4627d3b6cbd16d01a31a457585
b94bfc13c1e593bf7393ed6adbcd630cc6692b7a
/wfmaxplugins/toolbar/toolbar.h
515a8b52ffd592a47e60d1aca9c90da764a6ad6d
[]
no_license
WorldFoundry/WorldFoundry
341cd45695ab112a92cefd4ade692734e55695b4
5c507edddb84d2b27b7c248fb8aa79c2fdc7ce22
refs/heads/master
2021-01-25T07:27:49.731410
2010-05-06T19:14:28
2010-05-06T19:14:28
641,648
6
0
null
null
null
null
UTF-8
C++
false
false
2,145
h
/********************************************************************** *< FILE: util.h DESCRIPTION: CREATED BY: Rolf Berteig HISTORY: *> Copyright (c) 1994, All Rights Reserved. **********************************************************************/ #ifndef __UTIL__H #define __UTIL__H #include <max.h> #include "resource.h" #include <utilapi.h> #include "../lib/wf_id.hp" //TCHAR* GetString( int id ); extern ClassDesc* GetPropertiesDesc(); void Error( const char* szMsg ); #define NUM_ITEMS( _array_ ) ( sizeof( (_array_) ) / sizeof( *(_array_) ) ) extern HINSTANCE hInstance; class UpdateButtonsCallback : public RedrawViewsCallback { public: virtual void proc( Interface* ip ); }; struct DebuggingStream { int id; char* name; char* szSwitch; }; struct StreamDestination { char* name; char* szSwitch; }; class Toolbar : public UtilityObj { public: IUtil* iu; Interface* ip; HWND _hPanel; HWND _hPanelButtons; HWND _hPanelParameters; HWND _hPanelDebugStreams; HWND _hWnd; Toolbar(); ~Toolbar(); void BeginEditParams( Interface* ip, IUtil* iu ); void EndEditParams( Interface* ip, IUtil *iu ); void SelectionSetChanged( Interface* ip, IUtil* iu ); void DeleteThis() {} void Init( HWND hWnd ); void Destroy( HWND hWnd ); void Command( HWND, int ); void _setButtons_Level(); protected: char szWorldFoundryDir[ _MAX_PATH ]; char szLevelsDir[ _MAX_PATH ]; HFONT _font; UpdateButtonsCallback buttonsProc; void MakeLevel(); void RunLevel(); void CleanLevel(); void ExportSelectedObject(); void LintLevel(); int ReadCheckBox( HWND hwnd, const char* szKey, UINT button ); int ReadRadioButton( HWND hwnd, const char* szKey, UINT button, UINT buttonDefault ); int ReadInteger( HWND hwnd, const char* szKey, UINT button ); void ReadString( HWND hwnd, const char* szKey, UINT button ); void SaveCheckBox( HWND hwnd, const char* szKey, UINT button ); void SaveRadioButton( HWND hwnd, const char* szKey, UINT button ); void SaveInteger( HWND hwnd, const char* szKey, UINT button ); void SaveString( HWND hwnd, const char* szKey, UINT button ); }; extern Toolbar theToolbar; #endif
[ "wbnorris@gmail.com" ]
wbnorris@gmail.com
1d62a47d749ddf172556bae7c4a713f4d87ed47b
f1aaed1e27416025659317d1f679f7b3b14d654e
/Office/Indy/C6/IdLogStream.hpp
35676cee30f8ceb7c10ef8047bdca2254c1a1401
[]
no_license
radtek/Pos
cee37166f89a7fcac61de9febb3760d12b823ce5
f117845e83b41d65f18a4635a98659144d66f435
refs/heads/master
2020-11-25T19:49:37.755286
2016-09-16T14:55:17
2016-09-16T14:55:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
hpp
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'IdLogStream.pas' rev: 6.00 #ifndef IdLogStreamHPP #define IdLogStreamHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <IdIntercept.hpp> // Pascal unit #include <IdLogBase.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Idlogstream { //-- type declarations ------------------------------------------------------- class DELPHICLASS TIdLogStream; class PASCALIMPLEMENTATION TIdLogStream : public Idlogbase::TIdLogBase { typedef Idlogbase::TIdLogBase inherited; protected: Classes::TStream* FInputStream; Classes::TStream* FOutputStream; virtual void __fastcall LogStatus(const AnsiString AText); virtual void __fastcall LogReceivedData(const AnsiString AText, const AnsiString AData); virtual void __fastcall LogSentData(const AnsiString AText, const AnsiString AData); public: __property Classes::TStream* InputStream = {read=FInputStream, write=FInputStream}; __property Classes::TStream* OutputStream = {read=FOutputStream, write=FOutputStream}; public: #pragma option push -w-inl /* TIdLogBase.Create */ inline __fastcall virtual TIdLogStream(Classes::TComponent* AOwner) : Idlogbase::TIdLogBase(AOwner) { } #pragma option pop #pragma option push -w-inl /* TIdLogBase.Destroy */ inline __fastcall virtual ~TIdLogStream(void) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Idlogstream */ using namespace Idlogstream; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // IdLogStream
[ "ravish.sharma@menumate.com" ]
ravish.sharma@menumate.com
9bbe8fe2449021f32a39c38f7a9c8d0a89273c07
23ff6abb246a554505a5b8d66a2ca8b09d4683d5
/sqlite3/sqlite3.cpp
3f223f0cc68c87242d45e8b2a97ff0ea178402ff
[]
no_license
eugeniogarcia/c_plusplus
3d082498f0c1d2d3240a9b6cb57dd4b122635a42
42c5892b5047caf7f1cf8d8bd9be1982a884f53f
refs/heads/master
2022-11-29T13:29:20.059599
2020-06-07T18:46:40
2020-06-07T18:46:40
268,999,140
0
0
null
null
null
null
UTF-8
C++
false
false
871
cpp
#include <stdio.h> #include <sqlite3.h> static int callback(void* NotUsed, int argc, char** argv, char** azColName) { int i; for (i = 0; i < argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char** argv) { sqlite3* db; char* zErrMsg = 0; int rc; if (argc != 3) { fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return(1); } rc = sqlite3_open(argv[1], &db); if (rc) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if (rc != SQLITE_OK) { fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return 0; }
[ "egsmartin@gmail.com" ]
egsmartin@gmail.com
55b4b61be50eabbd96deecab1681a3279c98b2a0
4e355497cdc92141de9ec4d3c186abd50e6727ad
/src/ofApp.h
2daf10317df1a9800ba847e5266be76757cb5188
[]
no_license
GordeyChernyy/GrowStrokeLearn
5a88a428c9beadffdd9d63e84403419522022f2e
ee255d6b763710d413f93bb34f42db2c64f76728
refs/heads/master
2021-01-23T19:27:07.809962
2016-12-30T06:21:40
2016-12-30T06:21:40
61,807,266
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
#pragma once #include "ofMain.h" #include "ofxSvg.h" #include "VectorGrow.hpp" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); VectorGrow grow; ofEasyCam cam; };
[ "kewava@gmail.com" ]
kewava@gmail.com
59f90fa4f79dbe7a46891ffb83a1c6eac5bcc47a
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir8444/dir8720/dir10555/dir10556/file10611.cpp
bc549ed0b2ed9e793d2f1e5322e1fada7eede3a3
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file10611 #error "macro file10611 must be defined" #endif static const char* file10611String = "file10611";
[ "tgeng@google.com" ]
tgeng@google.com
7678235c9e489cadf8ad2b421615a4d80ec80e5d
d44215864e30ad8039a1a294875e4222e3d23ebd
/build/rviz-hydro-devel/src/rviz/properties/moc_float_edit.cxx
90916f2a9a2a924904c47e8739323669266d8f33
[]
no_license
prathyusha-shine/abhiyan1.0
5c3eebfbbacb8b364180b9c2bd377c73cf29e693
bf9be6462c132465ddbf8c20b1e9a4e1eabd596e
refs/heads/master
2020-12-31T01:23:32.911145
2015-05-31T06:19:16
2015-05-31T06:19:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,893
cxx
/**************************************************************************** ** Meta object code from reading C++ file 'float_edit.h' ** ** Created: Tue May 12 17:13:13 2015 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../../../src/rviz-hydro-devel/src/rviz/properties/float_edit.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'float_edit.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_rviz__FloatEdit[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 1, 19, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 17, 16, 16, 16, 0x08, // properties: name, type, flags 37, 31, 0x87195103, 0 // eod }; static const char qt_meta_stringdata_rviz__FloatEdit[] = { "rviz::FloatEdit\0\0updateValue()\0float\0" "value\0" }; void rviz::FloatEdit::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { Q_ASSERT(staticMetaObject.cast(_o)); FloatEdit *_t = static_cast<FloatEdit *>(_o); switch (_id) { case 0: _t->updateValue(); break; default: ; } } Q_UNUSED(_a); } const QMetaObjectExtraData rviz::FloatEdit::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject rviz::FloatEdit::staticMetaObject = { { &QLineEdit::staticMetaObject, qt_meta_stringdata_rviz__FloatEdit, qt_meta_data_rviz__FloatEdit, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &rviz::FloatEdit::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *rviz::FloatEdit::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *rviz::FloatEdit::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_rviz__FloatEdit)) return static_cast<void*>(const_cast< FloatEdit*>(this)); return QLineEdit::qt_metacast(_clname); } int rviz::FloatEdit::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QLineEdit::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 1) qt_static_metacall(this, _c, _id, _a); _id -= 1; } #ifndef QT_NO_PROPERTIES else if (_c == QMetaObject::ReadProperty) { void *_v = _a[0]; switch (_id) { case 0: *reinterpret_cast< float*>(_v) = getValue(); break; } _id -= 1; } else if (_c == QMetaObject::WriteProperty) { void *_v = _a[0]; switch (_id) { case 0: setValue(*reinterpret_cast< float*>(_v)); break; } _id -= 1; } else if (_c == QMetaObject::ResetProperty) { _id -= 1; } else if (_c == QMetaObject::QueryPropertyDesignable) { _id -= 1; } else if (_c == QMetaObject::QueryPropertyScriptable) { _id -= 1; } else if (_c == QMetaObject::QueryPropertyStored) { _id -= 1; } else if (_c == QMetaObject::QueryPropertyEditable) { _id -= 1; } else if (_c == QMetaObject::QueryPropertyUser) { _id -= 1; } #endif // QT_NO_PROPERTIES return _id; } QT_END_MOC_NAMESPACE
[ "sudha@sudha.(none)" ]
sudha@sudha.(none)
30679ab6da47a6e9a70fe918d8e2d150edebb3df
07fc0f5ac6c4462e4b7506e8dd4ba4730d692ba1
/cppdb/tags/0.0.3/src/driver_manager.cpp
3ccf8a3ed8b83d7174b2a34ae9b49153c95a85d4
[ "BSL-1.0", "MIT" ]
permissive
JackBro/CppCMS
eb7ffa0c14aa021b6165b6ca6fb6798c6f2572dc
a7895662dfaece41544b599aa5ebf232b63e3c4f
refs/heads/master
2021-01-12T08:33:38.895665
2016-04-04T12:52:48
2016-04-04T12:52:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,567
cpp
/////////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2010-2011 Artyom Beilis (Tonkikh) <artyomtnk@yahoo.com> // // 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) // // or (at your opinion) under: // // The MIT License // (See accompanying file MIT.txt or a copy at // http://www.opensource.org/licenses/mit-license.php) // /////////////////////////////////////////////////////////////////////////////// #define CPPDB_SOURCE #include <cppdb/driver_manager.h> #include <cppdb/shared_object.h> #include <cppdb/backend.h> #include <cppdb/utils.h> #include <cppdb/mutex.h> #include <vector> #include <list> extern "C" { #ifdef CPPDB_WITH_SQLITE3 cppdb::backend::connection *cppdb_sqlite3_get_connection(cppdb::connection_info const &cs); #endif #ifdef CPPDB_WITH_PQ cppdb::backend::connection *cppdb_postgresql_get_connection(cppdb::connection_info const &cs); #endif #ifdef CPPDB_WITH_ODBC cppdb::backend::connection *cppdb_odbc_get_connection(cppdb::connection_info const &cs); #endif #ifdef CPPDB_WITH_MYSQL cppdb::backend::connection *cppdb_mysql_get_connection(cppdb::connection_info const &cs); #endif } namespace cppdb { typedef backend::static_driver::connect_function_type connect_function_type; class so_driver : public backend::loadable_driver { public: so_driver(std::string const &name,std::vector<std::string> const &so_list) : connect_(0) { std::string symbol_name = "cppdb_" + name + "_get_connection"; for(unsigned i=0;i<so_list.size();i++) { so_ = shared_object::open(so_list[i]); if(so_) { so_->safe_resolve(symbol_name,connect_); break; } } if(!so_ || !connect_) { throw cppdb_error("cppdb::driver failed to load driver " + name + " - no module found"); } } virtual backend::connection *open(connection_info const &ci) { return connect_(ci); } private: connect_function_type connect_; ref_ptr<shared_object> so_; }; backend::connection *driver_manager::connect(std::string const &str) { connection_info conn(str); return connect(conn); } backend::connection *driver_manager::connect(connection_info const &conn) { ref_ptr<backend::driver> drv_ptr; drivers_type::iterator p; { // get driver mutex::guard lock(lock_); p=drivers_.find(conn.driver); if(p!=drivers_.end()) { drv_ptr = p->second; } else { drv_ptr = load_driver(conn); drivers_[conn.driver] = drv_ptr; } } return drv_ptr->connect(conn); } void driver_manager::collect_unused() { std::list<ref_ptr<backend::driver> > garbage; { mutex::guard lock(lock_); drivers_type::iterator p=drivers_.begin(),tmp; while(p!=drivers_.end()) { if(!p->second->in_use()) { garbage.push_back(p->second); tmp=p; ++p; drivers_.erase(tmp); } else { ++p; } } } garbage.clear(); } #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) || defined(__CYGWIN__) # define CPPDB_LIBRARY_SUFFIX_V1 "-" CPPDB_SOVERSION CPPDB_LIBRARY_SUFFIX # define CPPDB_LIBRARY_SUFFIX_V2 CPPDB_LIBRARY_SUFFIX #else # define CPPDB_LIBRARY_SUFFIX_V1 CPPDB_LIBRARY_SUFFIX "." CPPDB_SOVERSION # define CPPDB_LIBRARY_SUFFIX_V2 CPPDB_LIBRARY_SUFFIX #endif #if (defined(WIN32) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__) # define PATH_SEPARATOR ';' #else # define PATH_SEPARATOR ':' #endif ref_ptr<backend::driver> driver_manager::load_driver(connection_info const &conn) { std::vector<std::string> so_names; std::string module; std::vector<std::string> search_paths = search_paths_; std::string mpath=conn.get("@modules_path"); if(!mpath.empty()) { size_t sep = mpath.find(PATH_SEPARATOR); search_paths.push_back(mpath.substr(0,sep)); while(sep<mpath.size()) { size_t next = mpath.find(PATH_SEPARATOR,sep+1); search_paths.push_back(mpath.substr(sep+1,next - sep+1)); sep = next; } } if(!(module=conn.get("@module")).empty()) { so_names.push_back(module); } else { std::string so_name1 = CPPDB_LIBRARY_PREFIX "cppdb_" + conn.driver + CPPDB_LIBRARY_SUFFIX_V1; std::string so_name2 = CPPDB_LIBRARY_PREFIX "cppdb_" + conn.driver + CPPDB_LIBRARY_SUFFIX_V2; for(unsigned i=0;i<search_paths.size();i++) { so_names.push_back(search_paths[i]+"/" + so_name1); so_names.push_back(search_paths[i]+"/" + so_name2); } if(!no_default_directory_) { so_names.push_back(so_name1); so_names.push_back(so_name2); } } ref_ptr<backend::driver> drv=new so_driver(conn.driver,so_names); return drv; } void driver_manager::install_driver(std::string const &name,ref_ptr<backend::driver> drv) { if(!drv) { throw cppdb_error("cppdb::driver_manager::install_driver: Can't install empty driver"); } mutex::guard lock(lock_); drivers_[name]=drv; } driver_manager::driver_manager() : no_default_directory_(false) { } driver_manager::~driver_manager() { } void driver_manager::add_search_path(std::string const &p) { mutex::guard l(lock_); search_paths_.push_back(p); } void driver_manager::clear_search_paths() { mutex::guard l(lock_); search_paths_.clear(); } void driver_manager::use_default_search_path(bool v) { mutex::guard l(lock_); no_default_directory_ = !v; } driver_manager &driver_manager::instance() { static driver_manager instance; return instance; } namespace { struct initializer { initializer() { driver_manager::instance(); #ifdef CPPDB_WITH_SQLITE3 driver_manager::instance().install_driver( "sqlite3",new backend::static_driver(cppdb_sqlite3_get_connection) ); #endif #ifdef CPPDB_WITH_ODBC driver_manager::instance().install_driver( "odbc",new backend::static_driver(cppdb_odbc_get_connection) ); #endif #ifdef CPPDB_WITH_PQ driver_manager::instance().install_driver( "postgresql",new backend::static_driver(cppdb_postgresql_get_connection) ); #endif #ifdef CPPDB_WITH_MYSQL driver_manager::instance().install_driver( "mysql",new backend::static_driver(cppdb_mysql_get_connection) ); #endif } } init; } } // cppdb
[ "artyom-beilis@831565cc-8e21-4ad5-8334-98019c97bd36" ]
artyom-beilis@831565cc-8e21-4ad5-8334-98019c97bd36
0d1ace7d4167260d3ca2bb2439ad1f1c3fa93ab8
1abf985d2784efce3196976fc1b13ab91d6a2a9e
/studierstube/src/components/viewer/controlmode/SoTrackedViewpointMobileDisplayControlMode.cxx
14cf08afca9e3c6b022fc9f400fb0a968e2193a2
[]
no_license
dolphinking/mirror-studierstube
2550e246f270eb406109d4c3a2af7885cd7d86d0
57249d050e4195982c5380fcf78197073d3139a5
refs/heads/master
2021-01-11T02:19:48.803878
2012-09-14T13:01:15
2012-09-14T13:01:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,365
cxx
/* ======================================================================== * Copyright (C) 2005 Graz University of Technology * * This framework 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 framework 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 framework; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For further information please contact Dieter Schmalstieg under * <schmalstieg@icg.tu-graz.ac.at> or write to Dieter Schmalstieg, * Graz University of Technology, Inffeldgasse 16a, A8010 Graz, * Austria. * ======================================================================== * PROJECT: Studierstube * ======================================================================== */ /** The header file for the SoTrackedViewpointMobileDisplayControlMode class. * * @author Denis Kalkofen * * $Id: SoTrackedViewpointMobileDisplayControlMode.cxx 25 2005-11-28 16:11:59Z denis $ * @file */ /* ======================================================================= */ #include <stb/components/viewer/controlmode/SoTrackedViewpointMobileDisplayControlMode.h> #include <stb/components/viewer/controlmode/MultRotRot.h> #include <stb/components/viewer/SoOffAxisCamera.h> #include <stb/components/viewer/SoDisplay.h> #include <stb/kernel/Kernel.h> #include <stb/kernel/ComponentManager.h> #include <stb/components/event/event.h> #include <stb/components/event/SoTrakEngine.h> #include <Inventor/nodes/SoTransform.h> #include <Inventor/engines/SoTransformVec3f.h> BEGIN_NAMESPACE_STB SO_NODE_SOURCE(SoTrackedViewpointMobileDisplayControlMode); void SoTrackedViewpointMobileDisplayControlMode::initClass() { SO_NODE_INIT_CLASS(SoTrackedViewpointMobileDisplayControlMode, SoStbCameraControlMode, "SoStbCameraControlMode"); } SoTrackedViewpointMobileDisplayControlMode::SoTrackedViewpointMobileDisplayControlMode() { SO_NODE_CONSTRUCTOR(SoTrackedViewpointMobileDisplayControlMode); SO_NODE_ADD_FIELD(viewpointTrackerKey, ("")); SO_NODE_ADD_FIELD(viewpointTrackerValue, ("")); SO_NODE_ADD_FIELD(displayTrackerKey, ("")); SO_NODE_ADD_FIELD(displayTrackerValue, ("")); SO_NODE_ADD_FIELD(eyeOffset, (0.0, 0.0, 0.0)); SO_NODE_ADD_FIELD(displayOffset, (0.0, 0.0, 0.0)); SO_NODE_ADD_FIELD(displayRotationOffset, (SbVec3f( 0.f, 0.f, 1.f ), 0.f )); } SoTrackedViewpointMobileDisplayControlMode::~SoTrackedViewpointMobileDisplayControlMode() { //nil } bool SoTrackedViewpointMobileDisplayControlMode::activate() { if(stbCamera==NULL) return false; Event* event=(Event*)(Kernel::getInstance()->getComponentManager()->load("Event")); if(!event) { logPrintE("failed to load event system\n"); return false; } trHead=event->createSoTrakEngine(); trDisplay=event->createSoTrakEngine(); if(!trHead || !trDisplay) { logPrintE("SoTrackedDisplayControlMode could not get an SoTrakEngine\n"); return false; } trHead->key.set1Value(0,viewpointTrackerKey.getValue()); trHead->value.set1Value(0,viewpointTrackerValue.getValue()); trDisplay->key.set1Value(0,displayTrackerKey.getValue());; trDisplay->value.set1Value(0,displayTrackerValue.getValue());; connectHeadTracker(trHead); connectDisplayTracker(trDisplay); return true; } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::disconnectHeadTracker() { ((SoOffAxisCamera*)stbCamera->getCamera())->eyepointPosition.disconnect(); } void SoTrackedViewpointMobileDisplayControlMode::connectHeadTracker(SoTrakEngine* tracker) { disconnectHeadTracker(); // use engine to create tracker to world transformation matrix SoComposeMatrix *ctw = new SoComposeMatrix; ctw->translation.connectFrom(&tracker->translation); ctw->rotation.connectFrom(&tracker->rotation); connectHeadTrackerStep2(ctw); } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::connectHeadTracker(SoSFVec3f *trackerTranslation, SoSFRotation *trackerRotation) { disconnectHeadTracker(); // use engine to create tracker to world transformation matrix SoComposeMatrix *ctw = new SoComposeMatrix; ctw->translation.connectFrom(trackerTranslation); ctw->rotation.connectFrom(trackerRotation); connectHeadTrackerStep2(ctw); } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::connectHeadTrackerStep2(SoComposeMatrix *ctw) { // use engines to transform offsets SoTransformVec3f *te; te = new SoTransformVec3f; te->vector.connectFrom(&eyeOffset); te->matrix.connectFrom(&ctw->matrix); // connect eyepointPositions to transformed offsets ((SoOffAxisCamera*)stbCamera->getCamera())->eyepointPosition.connectFrom(&te->point); //stbCamera->getTransform()->translation.connectFrom(&te->point); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void SoTrackedViewpointMobileDisplayControlMode::connectDisplayTracker(SoTrakEngine* tracker) { disconnectDisplayTracker(); // use engine to create tracker to world transformation matrix SoComposeMatrix *ctw = new SoComposeMatrix; ctw->translation.connectFrom(&tracker->translation); ctw->rotation.connectFrom(&tracker->rotation); connectDisplayTrackerStep2(ctw); // use engines to calculate rotations MultRotRot *md = new MultRotRot; md->rotationA.connectFrom(&displayRotationOffset); md->rotationB.connectFrom(&tracker->rotation); // connect orientations to calculated rotations ((SoOffAxisCamera*)stbCamera->getCamera())->orientation.connectFrom(&md->product); // stbCamera->getTransform()->rotation.connectFrom(&md->product); } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::disconnectDisplayTracker() { ((SoOffAxisCamera*)stbCamera->getCamera())->position.disconnect(); ((SoOffAxisCamera*)stbCamera->getCamera())->orientation.disconnect(); } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::connectDisplayTracker(SoSFVec3f *trackerTranslation, SoSFRotation *trackerRotation) { disconnectDisplayTracker(); // use engine to create tracker to world transformation matrix SoComposeMatrix *ctw = new SoComposeMatrix; ctw->translation.connectFrom(trackerTranslation); ctw->rotation.connectFrom(trackerRotation); connectDisplayTrackerStep2(ctw); // use engines to calculate rotations MultRotRot *md = new MultRotRot; md->rotationA.connectFrom(&displayRotationOffset); md->rotationB.connectFrom(trackerRotation); // connect orientations to calculated rotations ((SoOffAxisCamera*)stbCamera->getCamera())->orientation.connectFrom(&md->product); } //---------------------------------------------------------------------------- void SoTrackedViewpointMobileDisplayControlMode::connectDisplayTrackerStep2(SoComposeMatrix *ctw) { // use engines to transform offsets SoTransformVec3f *tdo; tdo = new SoTransformVec3f; tdo->vector.connectFrom(&displayOffset); tdo->matrix.connectFrom(&ctw->matrix); // connect positions to transformed offsets ((SoOffAxisCamera*)stbCamera->getCamera())->position.connectFrom(&tdo->point); } END_NAMESPACE_STB
[ "s.astanin@gmail.com" ]
s.astanin@gmail.com
ee877525336caea4044c9d71f6981ea45b110ed0
c0da153d4203dd3803b9f5249668cf9fa1dc4162
/Learning C++/backtracking.cpp
32b28f9e71f81fd59121eb978aa82d1261d61d4d
[]
no_license
amasadpanda/Playground
2412985708aa81106f869efb76f48d778bdd2c40
ccd9b9f8d343aaf6aac4481cce889ed0cac740f2
refs/heads/master
2020-03-29T20:07:07.313263
2018-09-25T16:29:38
2018-09-25T16:29:38
150,296,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,796
cpp
#include <iostream> #define SPACE 0 #define WALL 1 #define EXIT 2 #define CHAR 3 #define X 20 #define Y 20 #define getrandom(min, max) \ ((rand()%(int)(((max) + 1)-(min)))+ (min)) int nextX(int i, int x) { switch(i) { case 0: return i; case 1: if((i+1) >= X) break; return i+1; case 2: return i; case 3: if((i-1) < 0) break; return i-1; } return -1; } int nextY(int i, int y) { switch(i) { case 0: if((y-1) < 0) break; return y-1; case 1: return y; case 2: if((y+1) >= Y) break; return y+1; case 3: return y; } return -1; } void printMaze(int** maze) { char map[4]; map[0] = ' '; map[1] = '#'; map[2] = 'E'; map[3] = 'O'; for(int i = 0; i < X; i++) { for(int j = 0; j < Y; j++) { std::cout << map[maze[i][j]]; } std::cout << std::endl; } } int backtrack(int** maze, int y, int x) { if(x == -1 || y == -1 || maze[y][x] != SPACE) return 0; if(maze[y][x] == EXIT) return 1; for(int i = 0; i < 4; i++) { if(backtrack(maze, nextY(i, y), nextX(i, x)) == 1); return 1; } return 0; } int main() { srand((int)time(0)); int** maze; maze = new int*[X]; for(int i = 0; i < X; i++) { maze[i] = new int[Y]; for(int j = 0; j < Y; j++) { maze[i][j] = getrandom(0,1); } } maze[getrandom(0,X)][getrandom(0,Y)] = EXIT; int startX, startY; do{ startX = getrandom(0,X); startY = getrandom(0,Y); }while(maze[startY][startX] == EXIT); maze[startY][startX] = CHAR; std::cout << "Starting maze..." << std::endl; printMaze(maze); std::cout << (backtrack(maze, startY, startX) > 0)?"Found an exit!\n":"Trapped...forever\n"; }
[ "amasadpanda@gmail.com" ]
amasadpanda@gmail.com
f995c147186ff3e22de16f48f682d41cc4517ff0
b4b271920857387caf087cc068ee48cb3b6aca1f
/src/compiler/backend/s390/instruction-selector-s390.cc
71dabadb9e0261a6bd7a409103bd2d31ff87db6b
[ "bzip2-1.0.6", "BSD-3-Clause", "Apache-2.0", "SunPro" ]
permissive
piscisaureus/v8
554da378c76858bf16b148cb9e1b77cd88fb1da7
82f52fa9e1ea407413ea63e108e89dbf8f7ccb45
refs/heads/master
2020-12-10T11:53:30.549962
2020-01-11T07:38:50
2020-01-13T08:33:35
233,569,538
0
0
NOASSERTION
2020-01-13T10:27:56
2020-01-13T10:27:55
null
UTF-8
C++
false
false
112,455
cc
// Copyright 2015 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/compiler/backend/instruction-selector-impl.h" #include "src/compiler/node-matchers.h" #include "src/compiler/node-properties.h" #include "src/execution/frame-constants.h" namespace v8 { namespace internal { namespace compiler { enum class OperandMode : uint32_t { kNone = 0u, // Immediate mode kShift32Imm = 1u << 0, kShift64Imm = 1u << 1, kInt32Imm = 1u << 2, kInt32Imm_Negate = 1u << 3, kUint32Imm = 1u << 4, kInt20Imm = 1u << 5, kUint12Imm = 1u << 6, // Instr format kAllowRRR = 1u << 7, kAllowRM = 1u << 8, kAllowRI = 1u << 9, kAllowRRI = 1u << 10, kAllowRRM = 1u << 11, // Useful combination kAllowImmediate = kAllowRI | kAllowRRI, kAllowMemoryOperand = kAllowRM | kAllowRRM, kAllowDistinctOps = kAllowRRR | kAllowRRI | kAllowRRM, kBitWiseCommonMode = kAllowRI, kArithmeticCommonMode = kAllowRM | kAllowRI }; using OperandModes = base::Flags<OperandMode, uint32_t>; DEFINE_OPERATORS_FOR_FLAGS(OperandModes) OperandModes immediateModeMask = OperandMode::kShift32Imm | OperandMode::kShift64Imm | OperandMode::kInt32Imm | OperandMode::kInt32Imm_Negate | OperandMode::kUint32Imm | OperandMode::kInt20Imm; #define AndCommonMode \ ((OperandMode::kAllowRM | \ (CpuFeatures::IsSupported(DISTINCT_OPS) ? OperandMode::kAllowRRR \ : OperandMode::kNone))) #define And64OperandMode AndCommonMode #define Or64OperandMode And64OperandMode #define Xor64OperandMode And64OperandMode #define And32OperandMode \ (AndCommonMode | OperandMode::kAllowRI | OperandMode::kUint32Imm) #define Or32OperandMode And32OperandMode #define Xor32OperandMode And32OperandMode #define Shift32OperandMode \ ((OperandMode::kAllowRI | OperandMode::kShift64Imm | \ (CpuFeatures::IsSupported(DISTINCT_OPS) \ ? (OperandMode::kAllowRRR | OperandMode::kAllowRRI) \ : OperandMode::kNone))) #define Shift64OperandMode \ ((OperandMode::kAllowRI | OperandMode::kShift64Imm | \ OperandMode::kAllowRRR | OperandMode::kAllowRRI)) #define AddOperandMode \ ((OperandMode::kArithmeticCommonMode | OperandMode::kInt32Imm | \ (CpuFeatures::IsSupported(DISTINCT_OPS) \ ? (OperandMode::kAllowRRR | OperandMode::kAllowRRI) \ : OperandMode::kArithmeticCommonMode))) #define SubOperandMode \ ((OperandMode::kArithmeticCommonMode | OperandMode::kInt32Imm_Negate | \ (CpuFeatures::IsSupported(DISTINCT_OPS) \ ? (OperandMode::kAllowRRR | OperandMode::kAllowRRI) \ : OperandMode::kArithmeticCommonMode))) #define MulOperandMode \ (OperandMode::kArithmeticCommonMode | OperandMode::kInt32Imm) // Adds S390-specific methods for generating operands. class S390OperandGenerator final : public OperandGenerator { public: explicit S390OperandGenerator(InstructionSelector* selector) : OperandGenerator(selector) {} InstructionOperand UseOperand(Node* node, OperandModes mode) { if (CanBeImmediate(node, mode)) { return UseImmediate(node); } return UseRegister(node); } InstructionOperand UseAnyExceptImmediate(Node* node) { if (NodeProperties::IsConstant(node)) return UseRegister(node); else return Use(node); } int64_t GetImmediate(Node* node) { if (node->opcode() == IrOpcode::kInt32Constant) return OpParameter<int32_t>(node->op()); else if (node->opcode() == IrOpcode::kInt64Constant) return OpParameter<int64_t>(node->op()); else UNIMPLEMENTED(); return 0L; } bool CanBeImmediate(Node* node, OperandModes mode) { int64_t value; if (node->opcode() == IrOpcode::kInt32Constant) value = OpParameter<int32_t>(node->op()); else if (node->opcode() == IrOpcode::kInt64Constant) value = OpParameter<int64_t>(node->op()); else return false; return CanBeImmediate(value, mode); } bool CanBeImmediate(int64_t value, OperandModes mode) { if (mode & OperandMode::kShift32Imm) return 0 <= value && value < 32; else if (mode & OperandMode::kShift64Imm) return 0 <= value && value < 64; else if (mode & OperandMode::kInt32Imm) return is_int32(value); else if (mode & OperandMode::kInt32Imm_Negate) return is_int32(-value); else if (mode & OperandMode::kUint32Imm) return is_uint32(value); else if (mode & OperandMode::kInt20Imm) return is_int20(value); else if (mode & OperandMode::kUint12Imm) return is_uint12(value); else return false; } bool CanBeMemoryOperand(InstructionCode opcode, Node* user, Node* input, int effect_level) { if (input->opcode() != IrOpcode::kLoad || !selector()->CanCover(user, input)) { return false; } if (effect_level != selector()->GetEffectLevel(input)) { return false; } MachineRepresentation rep = LoadRepresentationOf(input->op()).representation(); switch (opcode) { case kS390_Cmp64: case kS390_LoadAndTestWord64: return rep == MachineRepresentation::kWord64 || IsAnyTagged(rep); case kS390_LoadAndTestWord32: case kS390_Cmp32: return rep == MachineRepresentation::kWord32; default: break; } return false; } AddressingMode GenerateMemoryOperandInputs(Node* index, Node* base, Node* displacement, DisplacementMode displacement_mode, InstructionOperand inputs[], size_t* input_count) { AddressingMode mode = kMode_MRI; if (base != nullptr) { inputs[(*input_count)++] = UseRegister(base); if (index != nullptr) { inputs[(*input_count)++] = UseRegister(index); if (displacement != nullptr) { inputs[(*input_count)++] = displacement_mode ? UseNegatedImmediate(displacement) : UseImmediate(displacement); mode = kMode_MRRI; } else { mode = kMode_MRR; } } else { if (displacement == nullptr) { mode = kMode_MR; } else { inputs[(*input_count)++] = displacement_mode == kNegativeDisplacement ? UseNegatedImmediate(displacement) : UseImmediate(displacement); mode = kMode_MRI; } } } else { DCHECK_NOT_NULL(index); inputs[(*input_count)++] = UseRegister(index); if (displacement != nullptr) { inputs[(*input_count)++] = displacement_mode == kNegativeDisplacement ? UseNegatedImmediate(displacement) : UseImmediate(displacement); mode = kMode_MRI; } else { mode = kMode_MR; } } return mode; } AddressingMode GetEffectiveAddressMemoryOperand( Node* operand, InstructionOperand inputs[], size_t* input_count, OperandModes immediate_mode = OperandMode::kInt20Imm) { #if V8_TARGET_ARCH_S390X BaseWithIndexAndDisplacement64Matcher m(operand, AddressOption::kAllowInputSwap); #else BaseWithIndexAndDisplacement32Matcher m(operand, AddressOption::kAllowInputSwap); #endif DCHECK(m.matches()); if ((m.displacement() == nullptr || CanBeImmediate(m.displacement(), immediate_mode))) { DCHECK_EQ(0, m.scale()); return GenerateMemoryOperandInputs(m.index(), m.base(), m.displacement(), m.displacement_mode(), inputs, input_count); } else { inputs[(*input_count)++] = UseRegister(operand->InputAt(0)); inputs[(*input_count)++] = UseRegister(operand->InputAt(1)); return kMode_MRR; } } bool CanBeBetterLeftOperand(Node* node) const { return !selector()->IsLive(node); } MachineRepresentation GetRepresentation(Node* node) { return sequence()->GetRepresentation(selector()->GetVirtualRegister(node)); } bool Is64BitOperand(Node* node) { return MachineRepresentation::kWord64 == GetRepresentation(node); } }; namespace { bool S390OpcodeOnlySupport12BitDisp(ArchOpcode opcode) { switch (opcode) { case kS390_AddFloat: case kS390_AddDouble: case kS390_CmpFloat: case kS390_CmpDouble: case kS390_Float32ToDouble: return true; default: return false; } } bool S390OpcodeOnlySupport12BitDisp(InstructionCode op) { ArchOpcode opcode = ArchOpcodeField::decode(op); return S390OpcodeOnlySupport12BitDisp(opcode); } #define OpcodeImmMode(op) \ (S390OpcodeOnlySupport12BitDisp(op) ? OperandMode::kUint12Imm \ : OperandMode::kInt20Imm) ArchOpcode SelectLoadOpcode(Node* node) { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); ArchOpcode opcode = kArchNop; switch (load_rep.representation()) { case MachineRepresentation::kFloat32: opcode = kS390_LoadFloat32; break; case MachineRepresentation::kFloat64: opcode = kS390_LoadDouble; break; case MachineRepresentation::kBit: // Fall through. case MachineRepresentation::kWord8: opcode = load_rep.IsSigned() ? kS390_LoadWordS8 : kS390_LoadWordU8; break; case MachineRepresentation::kWord16: opcode = load_rep.IsSigned() ? kS390_LoadWordS16 : kS390_LoadWordU16; break; #if !V8_TARGET_ARCH_S390X case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: // Fall through. #endif case MachineRepresentation::kWord32: opcode = kS390_LoadWordU32; break; case MachineRepresentation::kSimd128: opcode = kS390_LoadSimd128; break; #if V8_TARGET_ARCH_S390X case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: // Fall through. case MachineRepresentation::kWord64: opcode = kS390_LoadWord64; break; #else case MachineRepresentation::kWord64: // Fall through. #endif case MachineRepresentation::kCompressedPointer: // Fall through. case MachineRepresentation::kCompressed: // Fall through. case MachineRepresentation::kNone: default: UNREACHABLE(); } return opcode; } #define RESULT_IS_WORD32_LIST(V) \ /* Float unary op*/ \ V(BitcastFloat32ToInt32) \ /* V(TruncateFloat64ToWord32) */ \ V(RoundFloat64ToInt32) \ V(TruncateFloat32ToInt32) \ V(TruncateFloat32ToUint32) \ V(TruncateFloat64ToUint32) \ V(ChangeFloat64ToInt32) \ V(ChangeFloat64ToUint32) \ /* Word32 unary op */ \ V(Word32Clz) \ V(Word32Popcnt) \ V(Float64ExtractLowWord32) \ V(Float64ExtractHighWord32) \ V(SignExtendWord8ToInt32) \ V(SignExtendWord16ToInt32) \ /* Word32 bin op */ \ V(Int32Add) \ V(Int32Sub) \ V(Int32Mul) \ V(Int32AddWithOverflow) \ V(Int32SubWithOverflow) \ V(Int32MulWithOverflow) \ V(Int32MulHigh) \ V(Uint32MulHigh) \ V(Int32Div) \ V(Uint32Div) \ V(Int32Mod) \ V(Uint32Mod) \ V(Word32Ror) \ V(Word32And) \ V(Word32Or) \ V(Word32Xor) \ V(Word32Shl) \ V(Word32Shr) \ V(Word32Sar) bool ProduceWord32Result(Node* node) { #if !V8_TARGET_ARCH_S390X return true; #else switch (node->opcode()) { #define VISITOR(name) case IrOpcode::k##name: RESULT_IS_WORD32_LIST(VISITOR) #undef VISITOR return true; // TODO(john.yan): consider the following case to be valid // case IrOpcode::kWord32Equal: // case IrOpcode::kInt32LessThan: // case IrOpcode::kInt32LessThanOrEqual: // case IrOpcode::kUint32LessThan: // case IrOpcode::kUint32LessThanOrEqual: // case IrOpcode::kUint32MulHigh: // // These 32-bit operations implicitly zero-extend to 64-bit on x64, so // the // // zero-extension is a no-op. // return true; // case IrOpcode::kProjection: { // Node* const value = node->InputAt(0); // switch (value->opcode()) { // case IrOpcode::kInt32AddWithOverflow: // case IrOpcode::kInt32SubWithOverflow: // case IrOpcode::kInt32MulWithOverflow: // return true; // default: // return false; // } // } case IrOpcode::kLoad: { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); switch (load_rep.representation()) { case MachineRepresentation::kWord32: return true; case MachineRepresentation::kWord8: if (load_rep.IsSigned()) return false; else return true; default: return false; } } default: return false; } #endif } static inline bool DoZeroExtForResult(Node* node) { #if V8_TARGET_ARCH_S390X return ProduceWord32Result(node); #else return false; #endif } // TODO(john.yan): Create VisiteShift to match dst = src shift (R+I) #if 0 void VisitShift() { } #endif #if V8_TARGET_ARCH_S390X void VisitTryTruncateDouble(InstructionSelector* selector, ArchOpcode opcode, Node* node) { S390OperandGenerator g(selector); InstructionOperand inputs[] = {g.UseRegister(node->InputAt(0))}; InstructionOperand outputs[2]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); Node* success_output = NodeProperties::FindProjection(node, 1); if (success_output) { outputs[output_count++] = g.DefineAsRegister(success_output); } selector->Emit(opcode, output_count, outputs, 1, inputs); } #endif template <class CanCombineWithLoad> void GenerateRightOperands(InstructionSelector* selector, Node* node, Node* right, InstructionCode* opcode, OperandModes* operand_mode, InstructionOperand* inputs, size_t* input_count, CanCombineWithLoad canCombineWithLoad) { S390OperandGenerator g(selector); if ((*operand_mode & OperandMode::kAllowImmediate) && g.CanBeImmediate(right, *operand_mode)) { inputs[(*input_count)++] = g.UseImmediate(right); // Can only be RI or RRI *operand_mode &= OperandMode::kAllowImmediate; } else if (*operand_mode & OperandMode::kAllowMemoryOperand) { NodeMatcher mright(right); if (mright.IsLoad() && selector->CanCover(node, right) && canCombineWithLoad(SelectLoadOpcode(right))) { AddressingMode mode = g.GetEffectiveAddressMemoryOperand( right, inputs, input_count, OpcodeImmMode(*opcode)); *opcode |= AddressingModeField::encode(mode); *operand_mode &= ~OperandMode::kAllowImmediate; if (*operand_mode & OperandMode::kAllowRM) *operand_mode &= ~OperandMode::kAllowDistinctOps; } else if (*operand_mode & OperandMode::kAllowRM) { DCHECK(!(*operand_mode & OperandMode::kAllowRRM)); inputs[(*input_count)++] = g.UseAnyExceptImmediate(right); // Can not be Immediate *operand_mode &= ~OperandMode::kAllowImmediate & ~OperandMode::kAllowDistinctOps; } else if (*operand_mode & OperandMode::kAllowRRM) { DCHECK(!(*operand_mode & OperandMode::kAllowRM)); inputs[(*input_count)++] = g.UseAnyExceptImmediate(right); // Can not be Immediate *operand_mode &= ~OperandMode::kAllowImmediate; } else { UNREACHABLE(); } } else { inputs[(*input_count)++] = g.UseRegister(right); // Can only be RR or RRR *operand_mode &= OperandMode::kAllowRRR; } } template <class CanCombineWithLoad> void GenerateBinOpOperands(InstructionSelector* selector, Node* node, Node* left, Node* right, InstructionCode* opcode, OperandModes* operand_mode, InstructionOperand* inputs, size_t* input_count, CanCombineWithLoad canCombineWithLoad) { S390OperandGenerator g(selector); // left is always register InstructionOperand const left_input = g.UseRegister(left); inputs[(*input_count)++] = left_input; if (left == right) { inputs[(*input_count)++] = left_input; // Can only be RR or RRR *operand_mode &= OperandMode::kAllowRRR; } else { GenerateRightOperands(selector, node, right, opcode, operand_mode, inputs, input_count, canCombineWithLoad); } } template <class CanCombineWithLoad> void VisitUnaryOp(InstructionSelector* selector, Node* node, InstructionCode opcode, OperandModes operand_mode, FlagsContinuation* cont, CanCombineWithLoad canCombineWithLoad); template <class CanCombineWithLoad> void VisitBinOp(InstructionSelector* selector, Node* node, InstructionCode opcode, OperandModes operand_mode, FlagsContinuation* cont, CanCombineWithLoad canCombineWithLoad); // Generate The following variations: // VisitWord32UnaryOp, VisitWord32BinOp, // VisitWord64UnaryOp, VisitWord64BinOp, // VisitFloat32UnaryOp, VisitFloat32BinOp, // VisitFloat64UnaryOp, VisitFloat64BinOp #define VISIT_OP_LIST_32(V) \ V(Word32, Unary, [](ArchOpcode opcode) { \ return opcode == kS390_LoadWordS32 || opcode == kS390_LoadWordU32; \ }) \ V(Word64, Unary, \ [](ArchOpcode opcode) { return opcode == kS390_LoadWord64; }) \ V(Float32, Unary, \ [](ArchOpcode opcode) { return opcode == kS390_LoadFloat32; }) \ V(Float64, Unary, \ [](ArchOpcode opcode) { return opcode == kS390_LoadDouble; }) \ V(Word32, Bin, [](ArchOpcode opcode) { \ return opcode == kS390_LoadWordS32 || opcode == kS390_LoadWordU32; \ }) \ V(Float32, Bin, \ [](ArchOpcode opcode) { return opcode == kS390_LoadFloat32; }) \ V(Float64, Bin, [](ArchOpcode opcode) { return opcode == kS390_LoadDouble; }) #if V8_TARGET_ARCH_S390X #define VISIT_OP_LIST(V) \ VISIT_OP_LIST_32(V) \ V(Word64, Bin, [](ArchOpcode opcode) { return opcode == kS390_LoadWord64; }) #else #define VISIT_OP_LIST VISIT_OP_LIST_32 #endif #define DECLARE_VISIT_HELPER_FUNCTIONS(type1, type2, canCombineWithLoad) \ static inline void Visit##type1##type2##Op( \ InstructionSelector* selector, Node* node, InstructionCode opcode, \ OperandModes operand_mode, FlagsContinuation* cont) { \ Visit##type2##Op(selector, node, opcode, operand_mode, cont, \ canCombineWithLoad); \ } \ static inline void Visit##type1##type2##Op( \ InstructionSelector* selector, Node* node, InstructionCode opcode, \ OperandModes operand_mode) { \ FlagsContinuation cont; \ Visit##type1##type2##Op(selector, node, opcode, operand_mode, &cont); \ } VISIT_OP_LIST(DECLARE_VISIT_HELPER_FUNCTIONS) #undef DECLARE_VISIT_HELPER_FUNCTIONS #undef VISIT_OP_LIST_32 #undef VISIT_OP_LIST template <class CanCombineWithLoad> void VisitUnaryOp(InstructionSelector* selector, Node* node, InstructionCode opcode, OperandModes operand_mode, FlagsContinuation* cont, CanCombineWithLoad canCombineWithLoad) { S390OperandGenerator g(selector); InstructionOperand inputs[8]; size_t input_count = 0; InstructionOperand outputs[2]; size_t output_count = 0; Node* input = node->InputAt(0); GenerateRightOperands(selector, node, input, &opcode, &operand_mode, inputs, &input_count, canCombineWithLoad); bool input_is_word32 = ProduceWord32Result(input); bool doZeroExt = DoZeroExtForResult(node); bool canEliminateZeroExt = input_is_word32; if (doZeroExt) { // Add zero-ext indication inputs[input_count++] = g.TempImmediate(!canEliminateZeroExt); } if (!cont->IsDeoptimize()) { // If we can deoptimize as a result of the binop, we need to make sure // that the deopt inputs are not overwritten by the binop result. One way // to achieve that is to declare the output register as same-as-first. if (doZeroExt && canEliminateZeroExt) { // we have to make sure result and left use the same register outputs[output_count++] = g.DefineSameAsFirst(node); } else { outputs[output_count++] = g.DefineAsRegister(node); } } else { outputs[output_count++] = g.DefineSameAsFirst(node); } DCHECK_NE(0u, input_count); DCHECK_NE(0u, output_count); DCHECK_GE(arraysize(inputs), input_count); DCHECK_GE(arraysize(outputs), output_count); selector->EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, cont); } template <class CanCombineWithLoad> void VisitBinOp(InstructionSelector* selector, Node* node, InstructionCode opcode, OperandModes operand_mode, FlagsContinuation* cont, CanCombineWithLoad canCombineWithLoad) { S390OperandGenerator g(selector); Int32BinopMatcher m(node); Node* left = m.left().node(); Node* right = m.right().node(); InstructionOperand inputs[8]; size_t input_count = 0; InstructionOperand outputs[2]; size_t output_count = 0; if (node->op()->HasProperty(Operator::kCommutative) && !g.CanBeImmediate(right, operand_mode) && (g.CanBeBetterLeftOperand(right))) { std::swap(left, right); } GenerateBinOpOperands(selector, node, left, right, &opcode, &operand_mode, inputs, &input_count, canCombineWithLoad); bool left_is_word32 = ProduceWord32Result(left); bool doZeroExt = DoZeroExtForResult(node); bool canEliminateZeroExt = left_is_word32; if (doZeroExt) { // Add zero-ext indication inputs[input_count++] = g.TempImmediate(!canEliminateZeroExt); } if ((operand_mode & OperandMode::kAllowDistinctOps) && // If we can deoptimize as a result of the binop, we need to make sure // that the deopt inputs are not overwritten by the binop result. One way // to achieve that is to declare the output register as same-as-first. !cont->IsDeoptimize()) { if (doZeroExt && canEliminateZeroExt) { // we have to make sure result and left use the same register outputs[output_count++] = g.DefineSameAsFirst(node); } else { outputs[output_count++] = g.DefineAsRegister(node); } } else { outputs[output_count++] = g.DefineSameAsFirst(node); } DCHECK_NE(0u, input_count); DCHECK_NE(0u, output_count); DCHECK_GE(arraysize(inputs), input_count); DCHECK_GE(arraysize(outputs), output_count); selector->EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, cont); } } // namespace void InstructionSelector::VisitStackSlot(Node* node) { StackSlotRepresentation rep = StackSlotRepresentationOf(node->op()); int slot = frame_->AllocateSpillSlot(rep.size()); OperandGenerator g(this); Emit(kArchStackSlot, g.DefineAsRegister(node), sequence()->AddImmediate(Constant(slot)), 0, nullptr); } void InstructionSelector::VisitAbortCSAAssert(Node* node) { S390OperandGenerator g(this); Emit(kArchAbortCSAAssert, g.NoOutput(), g.UseFixed(node->InputAt(0), r3)); } void InstructionSelector::VisitLoad(Node* node) { S390OperandGenerator g(this); InstructionCode opcode = SelectLoadOpcode(node); InstructionOperand outputs[1]; outputs[0] = g.DefineAsRegister(node); InstructionOperand inputs[3]; size_t input_count = 0; AddressingMode mode = g.GetEffectiveAddressMemoryOperand(node, inputs, &input_count); opcode |= AddressingModeField::encode(mode); if (node->opcode() == IrOpcode::kPoisonedLoad) { CHECK_NE(poisoning_level_, PoisoningMitigationLevel::kDontPoison); opcode |= MiscField::encode(kMemoryAccessPoisoned); } Emit(opcode, 1, outputs, input_count, inputs); } void InstructionSelector::VisitPoisonedLoad(Node* node) { VisitLoad(node); } void InstructionSelector::VisitProtectedLoad(Node* node) { // TODO(eholk) UNIMPLEMENTED(); } static void VisitGeneralStore( InstructionSelector* selector, Node* node, MachineRepresentation rep, WriteBarrierKind write_barrier_kind = kNoWriteBarrier) { S390OperandGenerator g(selector); Node* base = node->InputAt(0); Node* offset = node->InputAt(1); Node* value = node->InputAt(2); if (write_barrier_kind != kNoWriteBarrier && V8_LIKELY(!FLAG_disable_write_barriers)) { DCHECK(CanBeTaggedPointer(rep)); AddressingMode addressing_mode; InstructionOperand inputs[3]; size_t input_count = 0; inputs[input_count++] = g.UseUniqueRegister(base); // OutOfLineRecordWrite uses the offset in an 'AddP' instruction as well as // for the store itself, so we must check compatibility with both. if (g.CanBeImmediate(offset, OperandMode::kInt20Imm)) { inputs[input_count++] = g.UseImmediate(offset); addressing_mode = kMode_MRI; } else { inputs[input_count++] = g.UseUniqueRegister(offset); addressing_mode = kMode_MRR; } inputs[input_count++] = g.UseUniqueRegister(value); RecordWriteMode record_write_mode = WriteBarrierKindToRecordWriteMode(write_barrier_kind); InstructionOperand temps[] = {g.TempRegister(), g.TempRegister()}; size_t const temp_count = arraysize(temps); InstructionCode code = kArchStoreWithWriteBarrier; code |= AddressingModeField::encode(addressing_mode); code |= MiscField::encode(static_cast<int>(record_write_mode)); selector->Emit(code, 0, nullptr, input_count, inputs, temp_count, temps); } else { ArchOpcode opcode = kArchNop; NodeMatcher m(value); switch (rep) { case MachineRepresentation::kFloat32: opcode = kS390_StoreFloat32; break; case MachineRepresentation::kFloat64: opcode = kS390_StoreDouble; break; case MachineRepresentation::kBit: // Fall through. case MachineRepresentation::kWord8: opcode = kS390_StoreWord8; break; case MachineRepresentation::kWord16: opcode = kS390_StoreWord16; break; #if !V8_TARGET_ARCH_S390X case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: // Fall through. case MachineRepresentation::kCompressedPointer: // Fall through. case MachineRepresentation::kCompressed: // Fall through. #endif case MachineRepresentation::kWord32: opcode = kS390_StoreWord32; if (m.IsWord32ReverseBytes()) { opcode = kS390_StoreReverse32; value = value->InputAt(0); } break; case MachineRepresentation::kSimd128: opcode = kS390_StoreSimd128; if (m.IsSimd128ReverseBytes()) { opcode = kS390_StoreReverseSimd128; value = value->InputAt(0); } break; #if V8_TARGET_ARCH_S390X case MachineRepresentation::kTaggedSigned: // Fall through. case MachineRepresentation::kTaggedPointer: // Fall through. case MachineRepresentation::kTagged: // Fall through. case MachineRepresentation::kCompressedPointer: // Fall through. case MachineRepresentation::kCompressed: // Fall through. case MachineRepresentation::kWord64: opcode = kS390_StoreWord64; if (m.IsWord64ReverseBytes()) { opcode = kS390_StoreReverse64; value = value->InputAt(0); } break; #else case MachineRepresentation::kWord64: // Fall through. #endif case MachineRepresentation::kNone: UNREACHABLE(); return; } InstructionOperand inputs[4]; size_t input_count = 0; AddressingMode addressing_mode = g.GetEffectiveAddressMemoryOperand(node, inputs, &input_count); InstructionCode code = opcode | AddressingModeField::encode(addressing_mode); InstructionOperand value_operand = g.UseRegister(value); inputs[input_count++] = value_operand; selector->Emit(code, 0, static_cast<InstructionOperand*>(nullptr), input_count, inputs); } } void InstructionSelector::VisitStore(Node* node) { StoreRepresentation store_rep = StoreRepresentationOf(node->op()); WriteBarrierKind write_barrier_kind = store_rep.write_barrier_kind(); MachineRepresentation rep = store_rep.representation(); VisitGeneralStore(this, node, rep, write_barrier_kind); } void InstructionSelector::VisitProtectedStore(Node* node) { // TODO(eholk) UNIMPLEMENTED(); } // Architecture supports unaligned access, therefore VisitLoad is used instead void InstructionSelector::VisitUnalignedLoad(Node* node) { UNREACHABLE(); } // Architecture supports unaligned access, therefore VisitStore is used instead void InstructionSelector::VisitUnalignedStore(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitStackPointerGreaterThan( Node* node, FlagsContinuation* cont) { StackCheckKind kind = StackCheckKindOf(node->op()); InstructionCode opcode = kArchStackPointerGreaterThan | MiscField::encode(static_cast<int>(kind)); S390OperandGenerator g(this); // No outputs. InstructionOperand* const outputs = nullptr; const int output_count = 0; // Applying an offset to this stack check requires a temp register. Offsets // are only applied to the first stack check. If applying an offset, we must // ensure the input and temp registers do not alias, thus kUniqueRegister. InstructionOperand temps[] = {g.TempRegister()}; const int temp_count = (kind == StackCheckKind::kJSFunctionEntry) ? 1 : 0; const auto register_mode = (kind == StackCheckKind::kJSFunctionEntry) ? OperandGenerator::kUniqueRegister : OperandGenerator::kRegister; Node* const value = node->InputAt(0); InstructionOperand inputs[] = {g.UseRegisterWithMode(value, register_mode)}; static constexpr int input_count = arraysize(inputs); EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, temp_count, temps, cont); } #if 0 static inline bool IsContiguousMask32(uint32_t value, int* mb, int* me) { int mask_width = base::bits::CountPopulation(value); int mask_msb = base::bits::CountLeadingZeros32(value); int mask_lsb = base::bits::CountTrailingZeros32(value); if ((mask_width == 0) || (mask_msb + mask_width + mask_lsb != 32)) return false; *mb = mask_lsb + mask_width - 1; *me = mask_lsb; return true; } #endif #if V8_TARGET_ARCH_S390X static inline bool IsContiguousMask64(uint64_t value, int* mb, int* me) { int mask_width = base::bits::CountPopulation(value); int mask_msb = base::bits::CountLeadingZeros64(value); int mask_lsb = base::bits::CountTrailingZeros64(value); if ((mask_width == 0) || (mask_msb + mask_width + mask_lsb != 64)) return false; *mb = mask_lsb + mask_width - 1; *me = mask_lsb; return true; } #endif #if V8_TARGET_ARCH_S390X void InstructionSelector::VisitWord64And(Node* node) { S390OperandGenerator g(this); Int64BinopMatcher m(node); int mb = 0; int me = 0; if (m.right().HasValue() && IsContiguousMask64(m.right().Value(), &mb, &me)) { int sh = 0; Node* left = m.left().node(); if ((m.left().IsWord64Shr() || m.left().IsWord64Shl()) && CanCover(node, left)) { Int64BinopMatcher mleft(m.left().node()); if (mleft.right().IsInRange(0, 63)) { left = mleft.left().node(); sh = mleft.right().Value(); if (m.left().IsWord64Shr()) { // Adjust the mask such that it doesn't include any rotated bits. if (mb > 63 - sh) mb = 63 - sh; sh = (64 - sh) & 0x3F; } else { // Adjust the mask such that it doesn't include any rotated bits. if (me < sh) me = sh; } } } if (mb >= me) { bool match = false; ArchOpcode opcode; int mask; if (me == 0) { match = true; opcode = kS390_RotLeftAndClearLeft64; mask = mb; } else if (mb == 63) { match = true; opcode = kS390_RotLeftAndClearRight64; mask = me; } else if (sh && me <= sh && m.left().IsWord64Shl()) { match = true; opcode = kS390_RotLeftAndClear64; mask = mb; } if (match && CpuFeatures::IsSupported(GENERAL_INSTR_EXT)) { Emit(opcode, g.DefineAsRegister(node), g.UseRegister(left), g.TempImmediate(sh), g.TempImmediate(mask)); return; } } } VisitWord64BinOp(this, node, kS390_And64, And64OperandMode); } void InstructionSelector::VisitWord64Shl(Node* node) { S390OperandGenerator g(this); Int64BinopMatcher m(node); // TODO(mbrandy): eliminate left sign extension if right >= 32 if (m.left().IsWord64And() && m.right().IsInRange(0, 63)) { Int64BinopMatcher mleft(m.left().node()); int sh = m.right().Value(); int mb; int me; if (mleft.right().HasValue() && IsContiguousMask64(mleft.right().Value() << sh, &mb, &me)) { // Adjust the mask such that it doesn't include any rotated bits. if (me < sh) me = sh; if (mb >= me) { bool match = false; ArchOpcode opcode; int mask; if (me == 0) { match = true; opcode = kS390_RotLeftAndClearLeft64; mask = mb; } else if (mb == 63) { match = true; opcode = kS390_RotLeftAndClearRight64; mask = me; } else if (sh && me <= sh) { match = true; opcode = kS390_RotLeftAndClear64; mask = mb; } if (match && CpuFeatures::IsSupported(GENERAL_INSTR_EXT)) { Emit(opcode, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.TempImmediate(sh), g.TempImmediate(mask)); return; } } } } VisitWord64BinOp(this, node, kS390_ShiftLeft64, Shift64OperandMode); } void InstructionSelector::VisitWord64Shr(Node* node) { S390OperandGenerator g(this); Int64BinopMatcher m(node); if (m.left().IsWord64And() && m.right().IsInRange(0, 63)) { Int64BinopMatcher mleft(m.left().node()); int sh = m.right().Value(); int mb; int me; if (mleft.right().HasValue() && IsContiguousMask64((uint64_t)(mleft.right().Value()) >> sh, &mb, &me)) { // Adjust the mask such that it doesn't include any rotated bits. if (mb > 63 - sh) mb = 63 - sh; sh = (64 - sh) & 0x3F; if (mb >= me) { bool match = false; ArchOpcode opcode; int mask; if (me == 0) { match = true; opcode = kS390_RotLeftAndClearLeft64; mask = mb; } else if (mb == 63) { match = true; opcode = kS390_RotLeftAndClearRight64; mask = me; } if (match) { Emit(opcode, g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.TempImmediate(sh), g.TempImmediate(mask)); return; } } } } VisitWord64BinOp(this, node, kS390_ShiftRight64, Shift64OperandMode); } #endif static inline bool TryMatchSignExtInt16OrInt8FromWord32Sar( InstructionSelector* selector, Node* node) { S390OperandGenerator g(selector); Int32BinopMatcher m(node); if (selector->CanCover(node, m.left().node()) && m.left().IsWord32Shl()) { Int32BinopMatcher mleft(m.left().node()); if (mleft.right().Is(16) && m.right().Is(16)) { bool canEliminateZeroExt = ProduceWord32Result(mleft.left().node()); selector->Emit(kS390_SignExtendWord16ToInt32, canEliminateZeroExt ? g.DefineSameAsFirst(node) : g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.TempImmediate(!canEliminateZeroExt)); return true; } else if (mleft.right().Is(24) && m.right().Is(24)) { bool canEliminateZeroExt = ProduceWord32Result(mleft.left().node()); selector->Emit(kS390_SignExtendWord8ToInt32, canEliminateZeroExt ? g.DefineSameAsFirst(node) : g.DefineAsRegister(node), g.UseRegister(mleft.left().node()), g.TempImmediate(!canEliminateZeroExt)); return true; } } return false; } #if !V8_TARGET_ARCH_S390X void VisitPairBinop(InstructionSelector* selector, InstructionCode opcode, InstructionCode opcode2, Node* node) { S390OperandGenerator g(selector); Node* projection1 = NodeProperties::FindProjection(node, 1); if (projection1) { // We use UseUniqueRegister here to avoid register sharing with the output // registers. InstructionOperand inputs[] = { g.UseRegister(node->InputAt(0)), g.UseUniqueRegister(node->InputAt(1)), g.UseRegister(node->InputAt(2)), g.UseUniqueRegister(node->InputAt(3))}; InstructionOperand outputs[] = { g.DefineAsRegister(node), g.DefineAsRegister(NodeProperties::FindProjection(node, 1))}; selector->Emit(opcode, 2, outputs, 4, inputs); } else { // The high word of the result is not used, so we emit the standard 32 bit // instruction. selector->Emit(opcode2, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(0)), g.UseRegister(node->InputAt(2)), g.TempImmediate(0)); } } void InstructionSelector::VisitInt32PairAdd(Node* node) { VisitPairBinop(this, kS390_AddPair, kS390_Add32, node); } void InstructionSelector::VisitInt32PairSub(Node* node) { VisitPairBinop(this, kS390_SubPair, kS390_Sub32, node); } void InstructionSelector::VisitInt32PairMul(Node* node) { S390OperandGenerator g(this); Node* projection1 = NodeProperties::FindProjection(node, 1); if (projection1) { InstructionOperand inputs[] = {g.UseUniqueRegister(node->InputAt(0)), g.UseUniqueRegister(node->InputAt(1)), g.UseUniqueRegister(node->InputAt(2)), g.UseUniqueRegister(node->InputAt(3))}; InstructionOperand outputs[] = { g.DefineAsRegister(node), g.DefineAsRegister(NodeProperties::FindProjection(node, 1))}; Emit(kS390_MulPair, 2, outputs, 4, inputs); } else { // The high word of the result is not used, so we emit the standard 32 bit // instruction. Emit(kS390_Mul32, g.DefineSameAsFirst(node), g.UseRegister(node->InputAt(0)), g.Use(node->InputAt(2)), g.TempImmediate(0)); } } namespace { // Shared routine for multiple shift operations. void VisitPairShift(InstructionSelector* selector, InstructionCode opcode, Node* node) { S390OperandGenerator g(selector); // We use g.UseUniqueRegister here to guarantee that there is // no register aliasing of input registers with output registers. Int32Matcher m(node->InputAt(2)); InstructionOperand shift_operand; if (m.HasValue()) { shift_operand = g.UseImmediate(m.node()); } else { shift_operand = g.UseUniqueRegister(m.node()); } InstructionOperand inputs[] = {g.UseUniqueRegister(node->InputAt(0)), g.UseUniqueRegister(node->InputAt(1)), shift_operand}; Node* projection1 = NodeProperties::FindProjection(node, 1); InstructionOperand outputs[2]; InstructionOperand temps[1]; int32_t output_count = 0; int32_t temp_count = 0; outputs[output_count++] = g.DefineAsRegister(node); if (projection1) { outputs[output_count++] = g.DefineAsRegister(projection1); } else { temps[temp_count++] = g.TempRegister(); } selector->Emit(opcode, output_count, outputs, 3, inputs, temp_count, temps); } } // namespace void InstructionSelector::VisitWord32PairShl(Node* node) { VisitPairShift(this, kS390_ShiftLeftPair, node); } void InstructionSelector::VisitWord32PairShr(Node* node) { VisitPairShift(this, kS390_ShiftRightPair, node); } void InstructionSelector::VisitWord32PairSar(Node* node) { VisitPairShift(this, kS390_ShiftRightArithPair, node); } #endif void InstructionSelector::VisitWord32Ctz(Node* node) { UNREACHABLE(); } #if V8_TARGET_ARCH_S390X void InstructionSelector::VisitWord64Ctz(Node* node) { UNREACHABLE(); } #endif void InstructionSelector::VisitWord32ReverseBits(Node* node) { UNREACHABLE(); } #if V8_TARGET_ARCH_S390X void InstructionSelector::VisitWord64ReverseBits(Node* node) { UNREACHABLE(); } #endif void InstructionSelector::VisitInt32AbsWithOverflow(Node* node) { VisitWord32UnaryOp(this, node, kS390_Abs32, OperandMode::kNone); } void InstructionSelector::VisitInt64AbsWithOverflow(Node* node) { VisitWord64UnaryOp(this, node, kS390_Abs64, OperandMode::kNone); } void InstructionSelector::VisitWord64ReverseBytes(Node* node) { S390OperandGenerator g(this); Emit(kS390_LoadReverse64RR, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0))); } void InstructionSelector::VisitWord32ReverseBytes(Node* node) { S390OperandGenerator g(this); NodeMatcher input(node->InputAt(0)); if (CanCover(node, input.node()) && input.IsLoad()) { LoadRepresentation load_rep = LoadRepresentationOf(input.node()->op()); if (load_rep.representation() == MachineRepresentation::kWord32) { Node* base = input.node()->InputAt(0); Node* offset = input.node()->InputAt(1); Emit(kS390_LoadReverse32 | AddressingModeField::encode(kMode_MRR), // TODO(john.yan): one of the base and offset can be imm. g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(offset)); return; } } Emit(kS390_LoadReverse32RR, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0))); } void InstructionSelector::VisitSimd128ReverseBytes(Node* node) { S390OperandGenerator g(this); NodeMatcher input(node->InputAt(0)); if (CanCover(node, input.node()) && input.IsLoad()) { LoadRepresentation load_rep = LoadRepresentationOf(input.node()->op()); if (load_rep.representation() == MachineRepresentation::kSimd128) { Node* base = input.node()->InputAt(0); Node* offset = input.node()->InputAt(1); Emit(kS390_LoadReverseSimd128 | AddressingModeField::encode(kMode_MRR), // TODO(miladfar): one of the base and offset can be imm. g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(offset)); return; } } Emit(kS390_LoadReverseSimd128RR, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0))); } template <class Matcher, ArchOpcode neg_opcode> static inline bool TryMatchNegFromSub(InstructionSelector* selector, Node* node) { S390OperandGenerator g(selector); Matcher m(node); static_assert(neg_opcode == kS390_Neg32 || neg_opcode == kS390_Neg64, "Provided opcode is not a Neg opcode."); if (m.left().Is(0)) { Node* value = m.right().node(); bool doZeroExt = DoZeroExtForResult(node); bool canEliminateZeroExt = ProduceWord32Result(value); if (doZeroExt) { selector->Emit(neg_opcode, canEliminateZeroExt ? g.DefineSameAsFirst(node) : g.DefineAsRegister(node), g.UseRegister(value), g.TempImmediate(!canEliminateZeroExt)); } else { selector->Emit(neg_opcode, g.DefineAsRegister(node), g.UseRegister(value)); } return true; } return false; } template <class Matcher, ArchOpcode shift_op> bool TryMatchShiftFromMul(InstructionSelector* selector, Node* node) { S390OperandGenerator g(selector); Matcher m(node); Node* left = m.left().node(); Node* right = m.right().node(); if (g.CanBeImmediate(right, OperandMode::kInt32Imm) && base::bits::IsPowerOfTwo(g.GetImmediate(right))) { int power = 63 - base::bits::CountLeadingZeros64(g.GetImmediate(right)); bool doZeroExt = DoZeroExtForResult(node); bool canEliminateZeroExt = ProduceWord32Result(left); InstructionOperand dst = (doZeroExt && !canEliminateZeroExt && CpuFeatures::IsSupported(DISTINCT_OPS)) ? g.DefineAsRegister(node) : g.DefineSameAsFirst(node); if (doZeroExt) { selector->Emit(shift_op, dst, g.UseRegister(left), g.UseImmediate(power), g.TempImmediate(!canEliminateZeroExt)); } else { selector->Emit(shift_op, dst, g.UseRegister(left), g.UseImmediate(power)); } return true; } return false; } template <ArchOpcode opcode> static inline bool TryMatchInt32OpWithOverflow(InstructionSelector* selector, Node* node, OperandModes mode) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); VisitWord32BinOp(selector, node, opcode, mode, &cont); return true; } return false; } static inline bool TryMatchInt32AddWithOverflow(InstructionSelector* selector, Node* node) { return TryMatchInt32OpWithOverflow<kS390_Add32>(selector, node, AddOperandMode); } static inline bool TryMatchInt32SubWithOverflow(InstructionSelector* selector, Node* node) { return TryMatchInt32OpWithOverflow<kS390_Sub32>(selector, node, SubOperandMode); } static inline bool TryMatchInt32MulWithOverflow(InstructionSelector* selector, Node* node) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { if (CpuFeatures::IsSupported(MISC_INSTR_EXT2)) { TryMatchInt32OpWithOverflow<kS390_Mul32>( selector, node, OperandMode::kAllowRRR | OperandMode::kAllowRM); } else { FlagsContinuation cont = FlagsContinuation::ForSet(kNotEqual, ovf); VisitWord32BinOp(selector, node, kS390_Mul32WithOverflow, OperandMode::kInt32Imm | OperandMode::kAllowDistinctOps, &cont); } return true; } return TryMatchShiftFromMul<Int32BinopMatcher, kS390_ShiftLeft32>(selector, node); } #if V8_TARGET_ARCH_S390X template <ArchOpcode opcode> static inline bool TryMatchInt64OpWithOverflow(InstructionSelector* selector, Node* node, OperandModes mode) { if (Node* ovf = NodeProperties::FindProjection(node, 1)) { FlagsContinuation cont = FlagsContinuation::ForSet(kOverflow, ovf); VisitWord64BinOp(selector, node, opcode, mode, &cont); return true; } return false; } static inline bool TryMatchInt64AddWithOverflow(InstructionSelector* selector, Node* node) { return TryMatchInt64OpWithOverflow<kS390_Add64>(selector, node, AddOperandMode); } static inline bool TryMatchInt64SubWithOverflow(InstructionSelector* selector, Node* node) { return TryMatchInt64OpWithOverflow<kS390_Sub64>(selector, node, SubOperandMode); } #endif static inline bool TryMatchDoubleConstructFromInsert( InstructionSelector* selector, Node* node) { S390OperandGenerator g(selector); Node* left = node->InputAt(0); Node* right = node->InputAt(1); Node* lo32 = nullptr; Node* hi32 = nullptr; if (node->opcode() == IrOpcode::kFloat64InsertLowWord32) { lo32 = right; } else if (node->opcode() == IrOpcode::kFloat64InsertHighWord32) { hi32 = right; } else { return false; // doesn't match } if (left->opcode() == IrOpcode::kFloat64InsertLowWord32) { lo32 = left->InputAt(1); } else if (left->opcode() == IrOpcode::kFloat64InsertHighWord32) { hi32 = left->InputAt(1); } else { return false; // doesn't match } if (!lo32 || !hi32) return false; // doesn't match selector->Emit(kS390_DoubleConstruct, g.DefineAsRegister(node), g.UseRegister(hi32), g.UseRegister(lo32)); return true; } #define null ([]() { return false; }) // TODO(john.yan): place kAllowRM where available #define FLOAT_UNARY_OP_LIST_32(V) \ V(Float32, ChangeFloat32ToFloat64, kS390_Float32ToDouble, \ OperandMode::kAllowRM, null) \ V(Float32, BitcastFloat32ToInt32, kS390_BitcastFloat32ToInt32, \ OperandMode::kAllowRM, null) \ V(Float64, TruncateFloat64ToFloat32, kS390_DoubleToFloat32, \ OperandMode::kNone, null) \ V(Float64, TruncateFloat64ToWord32, kArchTruncateDoubleToI, \ OperandMode::kNone, null) \ V(Float64, RoundFloat64ToInt32, kS390_DoubleToInt32, OperandMode::kNone, \ null) \ V(Float32, TruncateFloat32ToInt32, kS390_Float32ToInt32, OperandMode::kNone, \ null) \ V(Float32, TruncateFloat32ToUint32, kS390_Float32ToUint32, \ OperandMode::kNone, null) \ V(Float64, TruncateFloat64ToUint32, kS390_DoubleToUint32, \ OperandMode::kNone, null) \ V(Float64, ChangeFloat64ToInt32, kS390_DoubleToInt32, OperandMode::kNone, \ null) \ V(Float64, ChangeFloat64ToUint32, kS390_DoubleToUint32, OperandMode::kNone, \ null) \ V(Float64, Float64SilenceNaN, kS390_Float64SilenceNaN, OperandMode::kNone, \ null) \ V(Float32, Float32Abs, kS390_AbsFloat, OperandMode::kNone, null) \ V(Float64, Float64Abs, kS390_AbsDouble, OperandMode::kNone, null) \ V(Float32, Float32Sqrt, kS390_SqrtFloat, OperandMode::kNone, null) \ V(Float64, Float64Sqrt, kS390_SqrtDouble, OperandMode::kNone, null) \ V(Float32, Float32RoundDown, kS390_FloorFloat, OperandMode::kNone, null) \ V(Float64, Float64RoundDown, kS390_FloorDouble, OperandMode::kNone, null) \ V(Float32, Float32RoundUp, kS390_CeilFloat, OperandMode::kNone, null) \ V(Float64, Float64RoundUp, kS390_CeilDouble, OperandMode::kNone, null) \ V(Float32, Float32RoundTruncate, kS390_TruncateFloat, OperandMode::kNone, \ null) \ V(Float64, Float64RoundTruncate, kS390_TruncateDouble, OperandMode::kNone, \ null) \ V(Float64, Float64RoundTiesAway, kS390_RoundDouble, OperandMode::kNone, \ null) \ V(Float32, Float32Neg, kS390_NegFloat, OperandMode::kNone, null) \ V(Float64, Float64Neg, kS390_NegDouble, OperandMode::kNone, null) \ /* TODO(john.yan): can use kAllowRM */ \ V(Word32, Float64ExtractLowWord32, kS390_DoubleExtractLowWord32, \ OperandMode::kNone, null) \ V(Word32, Float64ExtractHighWord32, kS390_DoubleExtractHighWord32, \ OperandMode::kNone, null) #define FLOAT_BIN_OP_LIST(V) \ V(Float32, Float32Add, kS390_AddFloat, OperandMode::kAllowRM, null) \ V(Float64, Float64Add, kS390_AddDouble, OperandMode::kAllowRM, null) \ V(Float32, Float32Sub, kS390_SubFloat, OperandMode::kAllowRM, null) \ V(Float64, Float64Sub, kS390_SubDouble, OperandMode::kAllowRM, null) \ V(Float32, Float32Mul, kS390_MulFloat, OperandMode::kAllowRM, null) \ V(Float64, Float64Mul, kS390_MulDouble, OperandMode::kAllowRM, null) \ V(Float32, Float32Div, kS390_DivFloat, OperandMode::kAllowRM, null) \ V(Float64, Float64Div, kS390_DivDouble, OperandMode::kAllowRM, null) \ V(Float32, Float32Max, kS390_MaxFloat, OperandMode::kNone, null) \ V(Float64, Float64Max, kS390_MaxDouble, OperandMode::kNone, null) \ V(Float32, Float32Min, kS390_MinFloat, OperandMode::kNone, null) \ V(Float64, Float64Min, kS390_MinDouble, OperandMode::kNone, null) #define WORD32_UNARY_OP_LIST_32(V) \ V(Word32, Word32Clz, kS390_Cntlz32, OperandMode::kNone, null) \ V(Word32, Word32Popcnt, kS390_Popcnt32, OperandMode::kNone, null) \ V(Word32, RoundInt32ToFloat32, kS390_Int32ToFloat32, OperandMode::kNone, \ null) \ V(Word32, RoundUint32ToFloat32, kS390_Uint32ToFloat32, OperandMode::kNone, \ null) \ V(Word32, ChangeInt32ToFloat64, kS390_Int32ToDouble, OperandMode::kNone, \ null) \ V(Word32, ChangeUint32ToFloat64, kS390_Uint32ToDouble, OperandMode::kNone, \ null) \ V(Word32, SignExtendWord8ToInt32, kS390_SignExtendWord8ToInt32, \ OperandMode::kNone, null) \ V(Word32, SignExtendWord16ToInt32, kS390_SignExtendWord16ToInt32, \ OperandMode::kNone, null) \ V(Word32, BitcastInt32ToFloat32, kS390_BitcastInt32ToFloat32, \ OperandMode::kNone, null) #ifdef V8_TARGET_ARCH_S390X #define FLOAT_UNARY_OP_LIST(V) \ FLOAT_UNARY_OP_LIST_32(V) \ V(Float64, ChangeFloat64ToUint64, kS390_DoubleToUint64, OperandMode::kNone, \ null) \ V(Float64, ChangeFloat64ToInt64, kS390_DoubleToInt64, OperandMode::kNone, \ null) \ V(Float64, TruncateFloat64ToInt64, kS390_DoubleToInt64, OperandMode::kNone, \ null) \ V(Float64, BitcastFloat64ToInt64, kS390_BitcastDoubleToInt64, \ OperandMode::kNone, null) #define WORD32_UNARY_OP_LIST(V) \ WORD32_UNARY_OP_LIST_32(V) \ V(Word32, ChangeInt32ToInt64, kS390_SignExtendWord32ToInt64, \ OperandMode::kNone, null) \ V(Word32, SignExtendWord8ToInt64, kS390_SignExtendWord8ToInt64, \ OperandMode::kNone, null) \ V(Word32, SignExtendWord16ToInt64, kS390_SignExtendWord16ToInt64, \ OperandMode::kNone, null) \ V(Word32, SignExtendWord32ToInt64, kS390_SignExtendWord32ToInt64, \ OperandMode::kNone, null) \ V(Word32, ChangeUint32ToUint64, kS390_Uint32ToUint64, OperandMode::kNone, \ [&]() -> bool { \ if (ProduceWord32Result(node->InputAt(0))) { \ EmitIdentity(node); \ return true; \ } \ return false; \ }) #else #define FLOAT_UNARY_OP_LIST(V) FLOAT_UNARY_OP_LIST_32(V) #define WORD32_UNARY_OP_LIST(V) WORD32_UNARY_OP_LIST_32(V) #endif #define WORD32_BIN_OP_LIST(V) \ V(Word32, Int32Add, kS390_Add32, AddOperandMode, null) \ V(Word32, Int32Sub, kS390_Sub32, SubOperandMode, ([&]() { \ return TryMatchNegFromSub<Int32BinopMatcher, kS390_Neg32>(this, node); \ })) \ V(Word32, Int32Mul, kS390_Mul32, MulOperandMode, ([&]() { \ return TryMatchShiftFromMul<Int32BinopMatcher, kS390_ShiftLeft32>(this, \ node); \ })) \ V(Word32, Int32AddWithOverflow, kS390_Add32, AddOperandMode, \ ([&]() { return TryMatchInt32AddWithOverflow(this, node); })) \ V(Word32, Int32SubWithOverflow, kS390_Sub32, SubOperandMode, \ ([&]() { return TryMatchInt32SubWithOverflow(this, node); })) \ V(Word32, Int32MulWithOverflow, kS390_Mul32, MulOperandMode, \ ([&]() { return TryMatchInt32MulWithOverflow(this, node); })) \ V(Word32, Int32MulHigh, kS390_MulHigh32, \ OperandMode::kInt32Imm | OperandMode::kAllowDistinctOps, null) \ V(Word32, Uint32MulHigh, kS390_MulHighU32, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word32, Int32Div, kS390_Div32, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word32, Uint32Div, kS390_DivU32, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word32, Int32Mod, kS390_Mod32, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word32, Uint32Mod, kS390_ModU32, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word32, Word32Ror, kS390_RotRight32, \ OperandMode::kAllowRI | OperandMode::kAllowRRR | OperandMode::kAllowRRI | \ OperandMode::kShift32Imm, \ null) \ V(Word32, Word32And, kS390_And32, And32OperandMode, null) \ V(Word32, Word32Or, kS390_Or32, Or32OperandMode, null) \ V(Word32, Word32Xor, kS390_Xor32, Xor32OperandMode, null) \ V(Word32, Word32Shl, kS390_ShiftLeft32, Shift32OperandMode, null) \ V(Word32, Word32Shr, kS390_ShiftRight32, Shift32OperandMode, null) \ V(Word32, Word32Sar, kS390_ShiftRightArith32, Shift32OperandMode, \ [&]() { return TryMatchSignExtInt16OrInt8FromWord32Sar(this, node); }) \ V(Word32, Float64InsertLowWord32, kS390_DoubleInsertLowWord32, \ OperandMode::kAllowRRR, \ [&]() -> bool { return TryMatchDoubleConstructFromInsert(this, node); }) \ V(Word32, Float64InsertHighWord32, kS390_DoubleInsertHighWord32, \ OperandMode::kAllowRRR, \ [&]() -> bool { return TryMatchDoubleConstructFromInsert(this, node); }) #define WORD64_UNARY_OP_LIST(V) \ V(Word64, Word64Popcnt, kS390_Popcnt64, OperandMode::kNone, null) \ V(Word64, Word64Clz, kS390_Cntlz64, OperandMode::kNone, null) \ V(Word64, TruncateInt64ToInt32, kS390_Int64ToInt32, OperandMode::kNone, \ null) \ V(Word64, RoundInt64ToFloat32, kS390_Int64ToFloat32, OperandMode::kNone, \ null) \ V(Word64, RoundInt64ToFloat64, kS390_Int64ToDouble, OperandMode::kNone, \ null) \ V(Word64, ChangeInt64ToFloat64, kS390_Int64ToDouble, OperandMode::kNone, \ null) \ V(Word64, RoundUint64ToFloat32, kS390_Uint64ToFloat32, OperandMode::kNone, \ null) \ V(Word64, RoundUint64ToFloat64, kS390_Uint64ToDouble, OperandMode::kNone, \ null) \ V(Word64, BitcastInt64ToFloat64, kS390_BitcastInt64ToDouble, \ OperandMode::kNone, null) #define WORD64_BIN_OP_LIST(V) \ V(Word64, Int64Add, kS390_Add64, AddOperandMode, null) \ V(Word64, Int64Sub, kS390_Sub64, SubOperandMode, ([&]() { \ return TryMatchNegFromSub<Int64BinopMatcher, kS390_Neg64>(this, node); \ })) \ V(Word64, Int64AddWithOverflow, kS390_Add64, AddOperandMode, \ ([&]() { return TryMatchInt64AddWithOverflow(this, node); })) \ V(Word64, Int64SubWithOverflow, kS390_Sub64, SubOperandMode, \ ([&]() { return TryMatchInt64SubWithOverflow(this, node); })) \ V(Word64, Int64Mul, kS390_Mul64, MulOperandMode, ([&]() { \ return TryMatchShiftFromMul<Int64BinopMatcher, kS390_ShiftLeft64>(this, \ node); \ })) \ V(Word64, Int64Div, kS390_Div64, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word64, Uint64Div, kS390_DivU64, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word64, Int64Mod, kS390_Mod64, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word64, Uint64Mod, kS390_ModU64, \ OperandMode::kAllowRRM | OperandMode::kAllowRRR, null) \ V(Word64, Word64Sar, kS390_ShiftRightArith64, Shift64OperandMode, null) \ V(Word64, Word64Ror, kS390_RotRight64, Shift64OperandMode, null) \ V(Word64, Word64Or, kS390_Or64, Or64OperandMode, null) \ V(Word64, Word64Xor, kS390_Xor64, Xor64OperandMode, null) #define DECLARE_UNARY_OP(type, name, op, mode, try_extra) \ void InstructionSelector::Visit##name(Node* node) { \ if (std::function<bool()>(try_extra)()) return; \ Visit##type##UnaryOp(this, node, op, mode); \ } #define DECLARE_BIN_OP(type, name, op, mode, try_extra) \ void InstructionSelector::Visit##name(Node* node) { \ if (std::function<bool()>(try_extra)()) return; \ Visit##type##BinOp(this, node, op, mode); \ } WORD32_BIN_OP_LIST(DECLARE_BIN_OP) WORD32_UNARY_OP_LIST(DECLARE_UNARY_OP) FLOAT_UNARY_OP_LIST(DECLARE_UNARY_OP) FLOAT_BIN_OP_LIST(DECLARE_BIN_OP) #if V8_TARGET_ARCH_S390X WORD64_UNARY_OP_LIST(DECLARE_UNARY_OP) WORD64_BIN_OP_LIST(DECLARE_BIN_OP) #endif #undef DECLARE_BIN_OP #undef DECLARE_UNARY_OP #undef WORD64_BIN_OP_LIST #undef WORD64_UNARY_OP_LIST #undef WORD32_BIN_OP_LIST #undef WORD32_UNARY_OP_LIST #undef FLOAT_UNARY_OP_LIST #undef WORD32_UNARY_OP_LIST_32 #undef FLOAT_BIN_OP_LIST #undef FLOAT_BIN_OP_LIST_32 #undef null #if V8_TARGET_ARCH_S390X void InstructionSelector::VisitTryTruncateFloat32ToInt64(Node* node) { VisitTryTruncateDouble(this, kS390_Float32ToInt64, node); } void InstructionSelector::VisitTryTruncateFloat64ToInt64(Node* node) { VisitTryTruncateDouble(this, kS390_DoubleToInt64, node); } void InstructionSelector::VisitTryTruncateFloat32ToUint64(Node* node) { VisitTryTruncateDouble(this, kS390_Float32ToUint64, node); } void InstructionSelector::VisitTryTruncateFloat64ToUint64(Node* node) { VisitTryTruncateDouble(this, kS390_DoubleToUint64, node); } #endif void InstructionSelector::VisitBitcastWord32ToWord64(Node* node) { DCHECK(SmiValuesAre31Bits()); DCHECK(COMPRESS_POINTERS_BOOL); EmitIdentity(node); } void InstructionSelector::VisitFloat64Mod(Node* node) { S390OperandGenerator g(this); Emit(kS390_ModDouble, g.DefineAsFixed(node, d1), g.UseFixed(node->InputAt(0), d1), g.UseFixed(node->InputAt(1), d2)) ->MarkAsCall(); } void InstructionSelector::VisitFloat64Ieee754Unop(Node* node, InstructionCode opcode) { S390OperandGenerator g(this); Emit(opcode, g.DefineAsFixed(node, d1), g.UseFixed(node->InputAt(0), d1)) ->MarkAsCall(); } void InstructionSelector::VisitFloat64Ieee754Binop(Node* node, InstructionCode opcode) { S390OperandGenerator g(this); Emit(opcode, g.DefineAsFixed(node, d1), g.UseFixed(node->InputAt(0), d1), g.UseFixed(node->InputAt(1), d2)) ->MarkAsCall(); } void InstructionSelector::VisitFloat32RoundTiesEven(Node* node) { UNREACHABLE(); } void InstructionSelector::VisitFloat64RoundTiesEven(Node* node) { UNREACHABLE(); } static bool CompareLogical(FlagsContinuation* cont) { switch (cont->condition()) { case kUnsignedLessThan: case kUnsignedGreaterThanOrEqual: case kUnsignedLessThanOrEqual: case kUnsignedGreaterThan: return true; default: return false; } UNREACHABLE(); } namespace { // Shared routine for multiple compare operations. void VisitCompare(InstructionSelector* selector, InstructionCode opcode, InstructionOperand left, InstructionOperand right, FlagsContinuation* cont) { selector->EmitWithContinuation(opcode, left, right, cont); } void VisitLoadAndTest(InstructionSelector* selector, InstructionCode opcode, Node* node, Node* value, FlagsContinuation* cont, bool discard_output = false); // Shared routine for multiple word compare operations. void VisitWordCompare(InstructionSelector* selector, Node* node, InstructionCode opcode, FlagsContinuation* cont, OperandModes immediate_mode) { S390OperandGenerator g(selector); Node* left = node->InputAt(0); Node* right = node->InputAt(1); DCHECK(IrOpcode::IsComparisonOpcode(node->opcode()) || node->opcode() == IrOpcode::kInt32Sub || node->opcode() == IrOpcode::kInt64Sub); InstructionOperand inputs[8]; InstructionOperand outputs[1]; size_t input_count = 0; size_t output_count = 0; // If one of the two inputs is an immediate, make sure it's on the right, or // if one of the two inputs is a memory operand, make sure it's on the left. int effect_level = selector->GetEffectLevel(node); if (cont->IsBranch()) { effect_level = selector->GetEffectLevel( cont->true_block()->PredecessorAt(0)->control_input()); } if ((!g.CanBeImmediate(right, immediate_mode) && g.CanBeImmediate(left, immediate_mode)) || (!g.CanBeMemoryOperand(opcode, node, right, effect_level) && g.CanBeMemoryOperand(opcode, node, left, effect_level))) { if (!node->op()->HasProperty(Operator::kCommutative)) cont->Commute(); std::swap(left, right); } // check if compare with 0 if (g.CanBeImmediate(right, immediate_mode) && g.GetImmediate(right) == 0) { DCHECK(opcode == kS390_Cmp32 || opcode == kS390_Cmp64); ArchOpcode load_and_test = (opcode == kS390_Cmp32) ? kS390_LoadAndTestWord32 : kS390_LoadAndTestWord64; return VisitLoadAndTest(selector, load_and_test, node, left, cont, true); } inputs[input_count++] = g.UseRegister(left); if (g.CanBeMemoryOperand(opcode, node, right, effect_level)) { // generate memory operand AddressingMode addressing_mode = g.GetEffectiveAddressMemoryOperand( right, inputs, &input_count, OpcodeImmMode(opcode)); opcode |= AddressingModeField::encode(addressing_mode); } else if (g.CanBeImmediate(right, immediate_mode)) { inputs[input_count++] = g.UseImmediate(right); } else { inputs[input_count++] = g.UseAnyExceptImmediate(right); } DCHECK(input_count <= 8 && output_count <= 1); selector->EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, cont); } void VisitWord32Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { OperandModes mode = (CompareLogical(cont) ? OperandMode::kUint32Imm : OperandMode::kInt32Imm); VisitWordCompare(selector, node, kS390_Cmp32, cont, mode); } #if V8_TARGET_ARCH_S390X void VisitWord64Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { OperandModes mode = (CompareLogical(cont) ? OperandMode::kUint32Imm : OperandMode::kInt32Imm); VisitWordCompare(selector, node, kS390_Cmp64, cont, mode); } #endif // Shared routine for multiple float32 compare operations. void VisitFloat32Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { VisitWordCompare(selector, node, kS390_CmpFloat, cont, OperandMode::kNone); } // Shared routine for multiple float64 compare operations. void VisitFloat64Compare(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { VisitWordCompare(selector, node, kS390_CmpDouble, cont, OperandMode::kNone); } void VisitTestUnderMask(InstructionSelector* selector, Node* node, FlagsContinuation* cont) { DCHECK(node->opcode() == IrOpcode::kWord32And || node->opcode() == IrOpcode::kWord64And); ArchOpcode opcode = (node->opcode() == IrOpcode::kWord32And) ? kS390_Tst32 : kS390_Tst64; S390OperandGenerator g(selector); Node* left = node->InputAt(0); Node* right = node->InputAt(1); if (!g.CanBeImmediate(right, OperandMode::kUint32Imm) && g.CanBeImmediate(left, OperandMode::kUint32Imm)) { std::swap(left, right); } VisitCompare(selector, opcode, g.UseRegister(left), g.UseOperand(right, OperandMode::kUint32Imm), cont); } void VisitLoadAndTest(InstructionSelector* selector, InstructionCode opcode, Node* node, Node* value, FlagsContinuation* cont, bool discard_output) { static_assert(kS390_LoadAndTestFloat64 - kS390_LoadAndTestWord32 == 3, "LoadAndTest Opcode shouldn't contain other opcodes."); // TODO(john.yan): Add support for Float32/Float64. DCHECK(opcode >= kS390_LoadAndTestWord32 || opcode <= kS390_LoadAndTestWord64); S390OperandGenerator g(selector); InstructionOperand inputs[8]; InstructionOperand outputs[2]; size_t input_count = 0; size_t output_count = 0; bool use_value = false; int effect_level = selector->GetEffectLevel(node); if (cont->IsBranch()) { effect_level = selector->GetEffectLevel( cont->true_block()->PredecessorAt(0)->control_input()); } if (g.CanBeMemoryOperand(opcode, node, value, effect_level)) { // generate memory operand AddressingMode addressing_mode = g.GetEffectiveAddressMemoryOperand(value, inputs, &input_count); opcode |= AddressingModeField::encode(addressing_mode); } else { inputs[input_count++] = g.UseAnyExceptImmediate(value); use_value = true; } if (!discard_output && !use_value) { outputs[output_count++] = g.DefineAsRegister(value); } DCHECK(input_count <= 8 && output_count <= 2); selector->EmitWithContinuation(opcode, output_count, outputs, input_count, inputs, cont); } } // namespace // Shared routine for word comparisons against zero. void InstructionSelector::VisitWordCompareZero(Node* user, Node* value, FlagsContinuation* cont) { // Try to combine with comparisons against 0 by simply inverting the branch. while (value->opcode() == IrOpcode::kWord32Equal && CanCover(user, value)) { Int32BinopMatcher m(value); if (!m.right().Is(0)) break; user = value; value = m.left().node(); cont->Negate(); } FlagsCondition fc = cont->condition(); if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kWord32Equal: { cont->OverwriteAndNegateIfEqual(kEqual); Int32BinopMatcher m(value); if (m.right().Is(0)) { // Try to combine the branch with a comparison. Node* const user = m.node(); Node* const value = m.left().node(); if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kInt32Sub: return VisitWord32Compare(this, value, cont); case IrOpcode::kWord32And: return VisitTestUnderMask(this, value, cont); default: break; } } } return VisitWord32Compare(this, value, cont); } case IrOpcode::kInt32LessThan: cont->OverwriteAndNegateIfEqual(kSignedLessThan); return VisitWord32Compare(this, value, cont); case IrOpcode::kInt32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual); return VisitWord32Compare(this, value, cont); case IrOpcode::kUint32LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitWord32Compare(this, value, cont); case IrOpcode::kUint32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitWord32Compare(this, value, cont); #if V8_TARGET_ARCH_S390X case IrOpcode::kWord64Equal: { cont->OverwriteAndNegateIfEqual(kEqual); Int64BinopMatcher m(value); if (m.right().Is(0)) { // Try to combine the branch with a comparison. Node* const user = m.node(); Node* const value = m.left().node(); if (CanCover(user, value)) { switch (value->opcode()) { case IrOpcode::kInt64Sub: return VisitWord64Compare(this, value, cont); case IrOpcode::kWord64And: return VisitTestUnderMask(this, value, cont); default: break; } } } return VisitWord64Compare(this, value, cont); } case IrOpcode::kInt64LessThan: cont->OverwriteAndNegateIfEqual(kSignedLessThan); return VisitWord64Compare(this, value, cont); case IrOpcode::kInt64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kSignedLessThanOrEqual); return VisitWord64Compare(this, value, cont); case IrOpcode::kUint64LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitWord64Compare(this, value, cont); case IrOpcode::kUint64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitWord64Compare(this, value, cont); #endif case IrOpcode::kFloat32Equal: cont->OverwriteAndNegateIfEqual(kEqual); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat32LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat32LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitFloat32Compare(this, value, cont); case IrOpcode::kFloat64Equal: cont->OverwriteAndNegateIfEqual(kEqual); return VisitFloat64Compare(this, value, cont); case IrOpcode::kFloat64LessThan: cont->OverwriteAndNegateIfEqual(kUnsignedLessThan); return VisitFloat64Compare(this, value, cont); case IrOpcode::kFloat64LessThanOrEqual: cont->OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual); return VisitFloat64Compare(this, value, cont); case IrOpcode::kProjection: // Check if this is the overflow output projection of an // <Operation>WithOverflow node. if (ProjectionIndexOf(value->op()) == 1u) { // We cannot combine the <Operation>WithOverflow with this branch // unless the 0th projection (the use of the actual value of the // <Operation> is either nullptr, which means there's no use of the // actual value, or was already defined, which means it is scheduled // *AFTER* this branch). Node* const node = value->InputAt(0); Node* const result = NodeProperties::FindProjection(node, 0); if (result == nullptr || IsDefined(result)) { switch (node->opcode()) { case IrOpcode::kInt32AddWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord32BinOp(this, node, kS390_Add32, AddOperandMode, cont); case IrOpcode::kInt32SubWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord32BinOp(this, node, kS390_Sub32, SubOperandMode, cont); case IrOpcode::kInt32MulWithOverflow: if (CpuFeatures::IsSupported(MISC_INSTR_EXT2)) { cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord32BinOp( this, node, kS390_Mul32, OperandMode::kAllowRRR | OperandMode::kAllowRM, cont); } else { cont->OverwriteAndNegateIfEqual(kNotEqual); return VisitWord32BinOp( this, node, kS390_Mul32WithOverflow, OperandMode::kInt32Imm | OperandMode::kAllowDistinctOps, cont); } case IrOpcode::kInt32AbsWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord32UnaryOp(this, node, kS390_Abs32, OperandMode::kNone, cont); #if V8_TARGET_ARCH_S390X case IrOpcode::kInt64AbsWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord64UnaryOp(this, node, kS390_Abs64, OperandMode::kNone, cont); case IrOpcode::kInt64AddWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord64BinOp(this, node, kS390_Add64, AddOperandMode, cont); case IrOpcode::kInt64SubWithOverflow: cont->OverwriteAndNegateIfEqual(kOverflow); return VisitWord64BinOp(this, node, kS390_Sub64, SubOperandMode, cont); #endif default: break; } } } break; case IrOpcode::kInt32Sub: if (fc == kNotEqual || fc == kEqual) return VisitWord32Compare(this, value, cont); break; case IrOpcode::kWord32And: return VisitTestUnderMask(this, value, cont); case IrOpcode::kLoad: { LoadRepresentation load_rep = LoadRepresentationOf(value->op()); switch (load_rep.representation()) { case MachineRepresentation::kWord32: return VisitLoadAndTest(this, kS390_LoadAndTestWord32, user, value, cont); default: break; } break; } case IrOpcode::kInt32Add: // can't handle overflow case. break; case IrOpcode::kWord32Or: if (fc == kNotEqual || fc == kEqual) return VisitWord32BinOp(this, value, kS390_Or32, Or32OperandMode, cont); break; case IrOpcode::kWord32Xor: if (fc == kNotEqual || fc == kEqual) return VisitWord32BinOp(this, value, kS390_Xor32, Xor32OperandMode, cont); break; case IrOpcode::kWord32Sar: case IrOpcode::kWord32Shl: case IrOpcode::kWord32Shr: case IrOpcode::kWord32Ror: // doesn't generate cc, so ignore. break; #if V8_TARGET_ARCH_S390X case IrOpcode::kInt64Sub: if (fc == kNotEqual || fc == kEqual) return VisitWord64Compare(this, value, cont); break; case IrOpcode::kWord64And: return VisitTestUnderMask(this, value, cont); case IrOpcode::kInt64Add: // can't handle overflow case. break; case IrOpcode::kWord64Or: if (fc == kNotEqual || fc == kEqual) return VisitWord64BinOp(this, value, kS390_Or64, Or64OperandMode, cont); break; case IrOpcode::kWord64Xor: if (fc == kNotEqual || fc == kEqual) return VisitWord64BinOp(this, value, kS390_Xor64, Xor64OperandMode, cont); break; case IrOpcode::kWord64Sar: case IrOpcode::kWord64Shl: case IrOpcode::kWord64Shr: case IrOpcode::kWord64Ror: // doesn't generate cc, so ignore break; #endif case IrOpcode::kStackPointerGreaterThan: cont->OverwriteAndNegateIfEqual(kStackPointerGreaterThanCondition); return VisitStackPointerGreaterThan(value, cont); default: break; } } // Branch could not be combined with a compare, emit LoadAndTest VisitLoadAndTest(this, kS390_LoadAndTestWord32, user, value, cont, true); } void InstructionSelector::VisitSwitch(Node* node, const SwitchInfo& sw) { S390OperandGenerator g(this); InstructionOperand value_operand = g.UseRegister(node->InputAt(0)); // Emit either ArchTableSwitch or ArchLookupSwitch. if (enable_switch_jump_table_ == kEnableSwitchJumpTable) { static const size_t kMaxTableSwitchValueRange = 2 << 16; size_t table_space_cost = 4 + sw.value_range(); size_t table_time_cost = 3; size_t lookup_space_cost = 3 + 2 * sw.case_count(); size_t lookup_time_cost = sw.case_count(); if (sw.case_count() > 0 && table_space_cost + 3 * table_time_cost <= lookup_space_cost + 3 * lookup_time_cost && sw.min_value() > std::numeric_limits<int32_t>::min() && sw.value_range() <= kMaxTableSwitchValueRange) { InstructionOperand index_operand = value_operand; if (sw.min_value()) { index_operand = g.TempRegister(); Emit(kS390_Lay | AddressingModeField::encode(kMode_MRI), index_operand, value_operand, g.TempImmediate(-sw.min_value())); } #if V8_TARGET_ARCH_S390X InstructionOperand index_operand_zero_ext = g.TempRegister(); Emit(kS390_Uint32ToUint64, index_operand_zero_ext, index_operand); index_operand = index_operand_zero_ext; #endif // Generate a table lookup. return EmitTableSwitch(sw, index_operand); } } // Generate a tree of conditional jumps. return EmitBinarySearchSwitch(sw, value_operand); } void InstructionSelector::VisitWord32Equal(Node* const node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); Int32BinopMatcher m(node); if (m.right().Is(0)) { return VisitLoadAndTest(this, kS390_LoadAndTestWord32, m.node(), m.left().node(), &cont, true); } VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitInt32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitInt32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThanOrEqual, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitUint32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitWord32Compare(this, node, &cont); } void InstructionSelector::VisitUint32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitWord32Compare(this, node, &cont); } #if V8_TARGET_ARCH_S390X void InstructionSelector::VisitWord64Equal(Node* const node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); Int64BinopMatcher m(node); if (m.right().Is(0)) { return VisitLoadAndTest(this, kS390_LoadAndTestWord64, m.node(), m.left().node(), &cont, true); } VisitWord64Compare(this, node, &cont); } void InstructionSelector::VisitInt64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThan, node); VisitWord64Compare(this, node, &cont); } void InstructionSelector::VisitInt64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kSignedLessThanOrEqual, node); VisitWord64Compare(this, node, &cont); } void InstructionSelector::VisitUint64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitWord64Compare(this, node, &cont); } void InstructionSelector::VisitUint64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitWord64Compare(this, node, &cont); } #endif void InstructionSelector::VisitFloat32Equal(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat32LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat32LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitFloat32Compare(this, node, &cont); } void InstructionSelector::VisitFloat64Equal(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kEqual, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::VisitFloat64LessThan(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThan, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::VisitFloat64LessThanOrEqual(Node* node) { FlagsContinuation cont = FlagsContinuation::ForSet(kUnsignedLessThanOrEqual, node); VisitFloat64Compare(this, node, &cont); } void InstructionSelector::EmitPrepareArguments( ZoneVector<PushParameter>* arguments, const CallDescriptor* call_descriptor, Node* node) { S390OperandGenerator g(this); // Prepare for C function call. if (call_descriptor->IsCFunctionCall()) { Emit(kArchPrepareCallCFunction | MiscField::encode(static_cast<int>( call_descriptor->ParameterCount())), 0, nullptr, 0, nullptr); // Poke any stack arguments. int slot = kStackFrameExtraParamSlot; for (PushParameter input : (*arguments)) { if (input.node == nullptr) continue; Emit(kS390_StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node), g.TempImmediate(slot)); ++slot; } } else { // Push any stack arguments. int num_slots = 0; int slot = 0; for (PushParameter input : *arguments) { if (input.node == nullptr) continue; num_slots += input.location.GetType().representation() == MachineRepresentation::kFloat64 ? kDoubleSize / kSystemPointerSize : 1; } Emit(kS390_StackClaim, g.NoOutput(), g.TempImmediate(num_slots)); for (PushParameter input : *arguments) { // Skip any alignment holes in pushed nodes. if (input.node) { Emit(kS390_StoreToStackSlot, g.NoOutput(), g.UseRegister(input.node), g.TempImmediate(slot)); slot += input.location.GetType().representation() == MachineRepresentation::kFloat64 ? (kDoubleSize / kSystemPointerSize) : 1; } } DCHECK(num_slots == slot); } } void InstructionSelector::VisitMemoryBarrier(Node* node) { S390OperandGenerator g(this); Emit(kArchNop, g.NoOutput()); } bool InstructionSelector::IsTailCallAddressImmediate() { return false; } int InstructionSelector::GetTempsCountForTailCallFromJSFunction() { return 3; } void InstructionSelector::VisitWord32AtomicLoad(Node* node) { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); DCHECK(load_rep.representation() == MachineRepresentation::kWord8 || load_rep.representation() == MachineRepresentation::kWord16 || load_rep.representation() == MachineRepresentation::kWord32); USE(load_rep); VisitLoad(node); } void InstructionSelector::VisitWord32AtomicStore(Node* node) { MachineRepresentation rep = AtomicStoreRepresentationOf(node->op()); VisitGeneralStore(this, node, rep); } void VisitAtomicExchange(InstructionSelector* selector, Node* node, ArchOpcode opcode) { S390OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); AddressingMode addressing_mode = kMode_MRR; InstructionOperand inputs[3]; size_t input_count = 0; inputs[input_count++] = g.UseUniqueRegister(base); inputs[input_count++] = g.UseUniqueRegister(index); inputs[input_count++] = g.UseUniqueRegister(value); InstructionOperand outputs[1]; outputs[0] = g.DefineAsRegister(node); InstructionCode code = opcode | AddressingModeField::encode(addressing_mode); selector->Emit(code, 1, outputs, input_count, inputs); } void InstructionSelector::VisitWord32AtomicExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Int8()) { opcode = kWord32AtomicExchangeInt8; } else if (type == MachineType::Uint8()) { opcode = kWord32AtomicExchangeUint8; } else if (type == MachineType::Int16()) { opcode = kWord32AtomicExchangeInt16; } else if (type == MachineType::Uint16()) { opcode = kWord32AtomicExchangeUint16; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = kWord32AtomicExchangeWord32; } else { UNREACHABLE(); return; } VisitAtomicExchange(this, node, opcode); } void InstructionSelector::VisitWord64AtomicExchange(Node* node) { ArchOpcode opcode = kArchNop; MachineType type = AtomicOpType(node->op()); if (type == MachineType::Uint8()) { opcode = kS390_Word64AtomicExchangeUint8; } else if (type == MachineType::Uint16()) { opcode = kS390_Word64AtomicExchangeUint16; } else if (type == MachineType::Uint32()) { opcode = kS390_Word64AtomicExchangeUint32; } else if (type == MachineType::Uint64()) { opcode = kS390_Word64AtomicExchangeUint64; } else { UNREACHABLE(); return; } VisitAtomicExchange(this, node, opcode); } void VisitAtomicCompareExchange(InstructionSelector* selector, Node* node, ArchOpcode opcode) { S390OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* old_value = node->InputAt(2); Node* new_value = node->InputAt(3); InstructionOperand inputs[4]; size_t input_count = 0; inputs[input_count++] = g.UseUniqueRegister(old_value); inputs[input_count++] = g.UseUniqueRegister(new_value); inputs[input_count++] = g.UseUniqueRegister(base); AddressingMode addressing_mode; if (g.CanBeImmediate(index, OperandMode::kInt20Imm)) { inputs[input_count++] = g.UseImmediate(index); addressing_mode = kMode_MRI; } else { inputs[input_count++] = g.UseUniqueRegister(index); addressing_mode = kMode_MRR; } InstructionOperand outputs[1]; size_t output_count = 0; outputs[output_count++] = g.DefineSameAsFirst(node); InstructionCode code = opcode | AddressingModeField::encode(addressing_mode); selector->Emit(code, output_count, outputs, input_count, inputs); } void InstructionSelector::VisitWord32AtomicCompareExchange(Node* node) { MachineType type = AtomicOpType(node->op()); ArchOpcode opcode = kArchNop; if (type == MachineType::Int8()) { opcode = kWord32AtomicCompareExchangeInt8; } else if (type == MachineType::Uint8()) { opcode = kWord32AtomicCompareExchangeUint8; } else if (type == MachineType::Int16()) { opcode = kWord32AtomicCompareExchangeInt16; } else if (type == MachineType::Uint16()) { opcode = kWord32AtomicCompareExchangeUint16; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = kWord32AtomicCompareExchangeWord32; } else { UNREACHABLE(); return; } VisitAtomicCompareExchange(this, node, opcode); } void InstructionSelector::VisitWord64AtomicCompareExchange(Node* node) { MachineType type = AtomicOpType(node->op()); ArchOpcode opcode = kArchNop; if (type == MachineType::Uint8()) { opcode = kS390_Word64AtomicCompareExchangeUint8; } else if (type == MachineType::Uint16()) { opcode = kS390_Word64AtomicCompareExchangeUint16; } else if (type == MachineType::Uint32()) { opcode = kS390_Word64AtomicCompareExchangeUint32; } else if (type == MachineType::Uint64()) { opcode = kS390_Word64AtomicCompareExchangeUint64; } else { UNREACHABLE(); return; } VisitAtomicCompareExchange(this, node, opcode); } void VisitAtomicBinop(InstructionSelector* selector, Node* node, ArchOpcode opcode) { S390OperandGenerator g(selector); Node* base = node->InputAt(0); Node* index = node->InputAt(1); Node* value = node->InputAt(2); InstructionOperand inputs[3]; size_t input_count = 0; inputs[input_count++] = g.UseUniqueRegister(base); AddressingMode addressing_mode; if (g.CanBeImmediate(index, OperandMode::kInt20Imm)) { inputs[input_count++] = g.UseImmediate(index); addressing_mode = kMode_MRI; } else { inputs[input_count++] = g.UseUniqueRegister(index); addressing_mode = kMode_MRR; } inputs[input_count++] = g.UseUniqueRegister(value); InstructionOperand outputs[1]; size_t output_count = 0; outputs[output_count++] = g.DefineAsRegister(node); InstructionOperand temps[1]; size_t temp_count = 0; temps[temp_count++] = g.TempRegister(); InstructionCode code = opcode | AddressingModeField::encode(addressing_mode); selector->Emit(code, output_count, outputs, input_count, inputs, temp_count, temps); } void InstructionSelector::VisitWord32AtomicBinaryOperation( Node* node, ArchOpcode int8_op, ArchOpcode uint8_op, ArchOpcode int16_op, ArchOpcode uint16_op, ArchOpcode word32_op) { MachineType type = AtomicOpType(node->op()); ArchOpcode opcode = kArchNop; if (type == MachineType::Int8()) { opcode = int8_op; } else if (type == MachineType::Uint8()) { opcode = uint8_op; } else if (type == MachineType::Int16()) { opcode = int16_op; } else if (type == MachineType::Uint16()) { opcode = uint16_op; } else if (type == MachineType::Int32() || type == MachineType::Uint32()) { opcode = word32_op; } else { UNREACHABLE(); return; } VisitAtomicBinop(this, node, opcode); } #define VISIT_ATOMIC_BINOP(op) \ void InstructionSelector::VisitWord32Atomic##op(Node* node) { \ VisitWord32AtomicBinaryOperation( \ node, kWord32Atomic##op##Int8, kWord32Atomic##op##Uint8, \ kWord32Atomic##op##Int16, kWord32Atomic##op##Uint16, \ kWord32Atomic##op##Word32); \ } VISIT_ATOMIC_BINOP(Add) VISIT_ATOMIC_BINOP(Sub) VISIT_ATOMIC_BINOP(And) VISIT_ATOMIC_BINOP(Or) VISIT_ATOMIC_BINOP(Xor) #undef VISIT_ATOMIC_BINOP void InstructionSelector::VisitWord64AtomicBinaryOperation( Node* node, ArchOpcode uint8_op, ArchOpcode uint16_op, ArchOpcode word32_op, ArchOpcode word64_op) { MachineType type = AtomicOpType(node->op()); ArchOpcode opcode = kArchNop; if (type == MachineType::Uint8()) { opcode = uint8_op; } else if (type == MachineType::Uint16()) { opcode = uint16_op; } else if (type == MachineType::Uint32()) { opcode = word32_op; } else if (type == MachineType::Uint64()) { opcode = word64_op; } else { UNREACHABLE(); return; } VisitAtomicBinop(this, node, opcode); } #define VISIT_ATOMIC64_BINOP(op) \ void InstructionSelector::VisitWord64Atomic##op(Node* node) { \ VisitWord64AtomicBinaryOperation( \ node, kS390_Word64Atomic##op##Uint8, kS390_Word64Atomic##op##Uint16, \ kS390_Word64Atomic##op##Uint32, kS390_Word64Atomic##op##Uint64); \ } VISIT_ATOMIC64_BINOP(Add) VISIT_ATOMIC64_BINOP(Sub) VISIT_ATOMIC64_BINOP(And) VISIT_ATOMIC64_BINOP(Or) VISIT_ATOMIC64_BINOP(Xor) #undef VISIT_ATOMIC64_BINOP void InstructionSelector::VisitWord64AtomicLoad(Node* node) { LoadRepresentation load_rep = LoadRepresentationOf(node->op()); USE(load_rep); VisitLoad(node); } void InstructionSelector::VisitWord64AtomicStore(Node* node) { MachineRepresentation rep = AtomicStoreRepresentationOf(node->op()); VisitGeneralStore(this, node, rep); } #define SIMD_TYPES(V) \ V(F32x4) \ V(I32x4) \ V(I16x8) \ V(I8x16) #define SIMD_BINOP_LIST(V) \ V(F32x4Add) \ V(F32x4AddHoriz) \ V(F32x4Sub) \ V(F32x4Mul) \ V(F32x4Eq) \ V(F32x4Ne) \ V(F32x4Lt) \ V(F32x4Le) \ V(I32x4Add) \ V(I32x4AddHoriz) \ V(I32x4Sub) \ V(I32x4Mul) \ V(I32x4MinS) \ V(I32x4MinU) \ V(I32x4MaxS) \ V(I32x4MaxU) \ V(I32x4Eq) \ V(I32x4Ne) \ V(I32x4GtS) \ V(I32x4GeS) \ V(I32x4GtU) \ V(I32x4GeU) \ V(I16x8Add) \ V(I16x8AddHoriz) \ V(I16x8Sub) \ V(I16x8Mul) \ V(I16x8MinS) \ V(I16x8MinU) \ V(I16x8MaxS) \ V(I16x8MaxU) \ V(I16x8Eq) \ V(I16x8Ne) \ V(I16x8GtS) \ V(I16x8GeS) \ V(I16x8GtU) \ V(I16x8GeU) \ V(I8x16Add) \ V(I8x16Sub) \ V(I8x16Mul) \ V(I8x16MinS) \ V(I8x16MinU) \ V(I8x16MaxS) \ V(I8x16MaxU) \ V(I8x16Eq) \ V(I8x16Ne) \ V(I8x16GtS) \ V(I8x16GeS) \ V(I8x16GtU) \ V(I8x16GeU) #define SIMD_VISIT_SPLAT(Type) \ void InstructionSelector::Visit##Type##Splat(Node* node) { \ S390OperandGenerator g(this); \ Emit(kS390_##Type##Splat, g.DefineAsRegister(node), \ g.UseRegister(node->InputAt(0))); \ } SIMD_TYPES(SIMD_VISIT_SPLAT) #undef SIMD_VISIT_SPLAT #define SIMD_VISIT_EXTRACT_LANE(Type, Sign) \ void InstructionSelector::Visit##Type##ExtractLane##Sign(Node* node) { \ S390OperandGenerator g(this); \ int32_t lane = OpParameter<int32_t>(node->op()); \ Emit(kS390_##Type##ExtractLane##Sign, g.DefineAsRegister(node), \ g.UseRegister(node->InputAt(0)), g.UseImmediate(lane)); \ } SIMD_VISIT_EXTRACT_LANE(F32x4, ) SIMD_VISIT_EXTRACT_LANE(I32x4, ) SIMD_VISIT_EXTRACT_LANE(I16x8, U) SIMD_VISIT_EXTRACT_LANE(I16x8, S) SIMD_VISIT_EXTRACT_LANE(I8x16, U) SIMD_VISIT_EXTRACT_LANE(I8x16, S) #undef SIMD_VISIT_EXTRACT_LANE #define SIMD_VISIT_REPLACE_LANE(Type) \ void InstructionSelector::Visit##Type##ReplaceLane(Node* node) { \ S390OperandGenerator g(this); \ int32_t lane = OpParameter<int32_t>(node->op()); \ Emit(kS390_##Type##ReplaceLane, g.DefineAsRegister(node), \ g.UseRegister(node->InputAt(0)), g.UseImmediate(lane), \ g.UseRegister(node->InputAt(1))); \ } SIMD_TYPES(SIMD_VISIT_REPLACE_LANE) #undef SIMD_VISIT_REPLACE_LANE #define SIMD_VISIT_BINOP(Opcode) \ void InstructionSelector::Visit##Opcode(Node* node) { \ S390OperandGenerator g(this); \ InstructionOperand temps[] = {g.TempSimd128Register(), \ g.TempSimd128Register()}; \ Emit(kS390_##Opcode, g.DefineAsRegister(node), \ g.UseUniqueRegister(node->InputAt(0)), \ g.UseUniqueRegister(node->InputAt(1)), arraysize(temps), temps); \ } SIMD_BINOP_LIST(SIMD_VISIT_BINOP) #undef SIMD_VISIT_BINOP #undef SIMD_BINOP_LIST #undef SIMD_TYPES void InstructionSelector::VisitI32x4Shl(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4ShrS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4ShrU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8Shl(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8ShrS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8ShrU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8AddSaturateS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8SubSaturateS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8AddSaturateU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8SubSaturateU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8RoundingAverageU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16RoundingAverageU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16AddSaturateS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16SubSaturateS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16AddSaturateU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16SubSaturateU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128And(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128Or(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128Xor(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128Not(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128Zero(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::EmitPrepareResults( ZoneVector<PushParameter>* results, const CallDescriptor* call_descriptor, Node* node) { S390OperandGenerator g(this); int reverse_slot = 0; for (PushParameter output : *results) { if (!output.location.IsCallerFrameSlot()) continue; // Skip any alignment holes in nodes. if (output.node != nullptr) { DCHECK(!call_descriptor->IsCFunctionCall()); if (output.location.GetType() == MachineType::Float32()) { MarkAsFloat32(output.node); } else if (output.location.GetType() == MachineType::Float64()) { MarkAsFloat64(output.node); } Emit(kS390_Peek, g.DefineAsRegister(output.node), g.UseImmediate(reverse_slot)); } reverse_slot += output.location.GetSizeInPointers(); } } void InstructionSelector::VisitF32x4Sqrt(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4Div(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4Min(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4Max(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS128Select(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4Abs(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4RecipSqrtApprox(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4RecipApprox(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4SConvertI32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF32x4UConvertI32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4SConvertF32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4UConvertF32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4SConvertI16x8Low(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4SConvertI16x8High(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4UConvertI16x8Low(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI32x4UConvertI16x8High(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8SConvertI8x16Low(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8SConvertI8x16High(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8UConvertI8x16Low(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8UConvertI8x16High(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8SConvertI32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI16x8UConvertI32x4(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16SConvertI16x8(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16UConvertI16x8(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x4AnyTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x4AllTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x8AnyTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x8AllTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x16AnyTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS1x16AllTrue(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16Shl(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16ShrS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI8x16ShrU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS8x16Shuffle(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitS8x16Swizzle(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Splat(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2ReplaceLane(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Abs(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Sqrt(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Add(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Sub(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Mul(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Div(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Eq(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Ne(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Lt(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Le(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2Neg(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2Add(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2Sub(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2Shl(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2ShrS(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitI64x2ShrU(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Min(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2Max(Node* node) { UNIMPLEMENTED(); } void InstructionSelector::VisitF64x2ExtractLane(Node* node) { UNIMPLEMENTED(); } // static MachineOperatorBuilder::Flags InstructionSelector::SupportedMachineOperatorFlags() { return MachineOperatorBuilder::kFloat32RoundDown | MachineOperatorBuilder::kFloat64RoundDown | MachineOperatorBuilder::kFloat32RoundUp | MachineOperatorBuilder::kFloat64RoundUp | MachineOperatorBuilder::kFloat32RoundTruncate | MachineOperatorBuilder::kFloat64RoundTruncate | MachineOperatorBuilder::kFloat64RoundTiesAway | MachineOperatorBuilder::kWord32Popcnt | MachineOperatorBuilder::kInt32AbsWithOverflow | MachineOperatorBuilder::kInt64AbsWithOverflow | MachineOperatorBuilder::kWord64Popcnt; } // static MachineOperatorBuilder::AlignmentRequirements InstructionSelector::AlignmentRequirements() { return MachineOperatorBuilder::AlignmentRequirements:: FullUnalignedAccessSupport(); } } // namespace compiler } // namespace internal } // namespace v8
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
327489eb3c22b6e9ee4fcc7475cea7f665893549
59ae6531e40bb482436a6984f4ef8dc97aaed410
/C++/SolveLP/addAeqConstr.h
b67f65e638cb24a47cfcb7f143c45e7369f1feae
[]
no_license
KaranBajwaUTS/Engineeing-Capstone
eb62115ea729fef0ca5e9a63b89e64a228fe128f
de8e61a1fba7b3c3bea0effebb8edb34132a9bcf
refs/heads/main
2023-08-14T22:57:41.339585
2021-09-22T07:34:32
2021-09-22T07:34:32
391,273,882
0
0
null
null
null
null
UTF-8
C++
false
false
765
h
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // // addAeqConstr.h // // Code generation for function 'addAeqConstr' // #ifndef ADDAEQCONSTR_H #define ADDAEQCONSTR_H // Include files #include "rtwtypes.h" #include <cstddef> #include <cstdlib> // Type Declarations struct c_struct_T; // Function Declarations namespace coder { namespace optim { namespace coder { namespace qpactiveset { namespace WorkingSet { void addAeqConstr(c_struct_T *obj, int idx_local); } } // namespace qpactiveset } // namespace coder } // namespace optim } // namespace coder #endif // End of code generation (addAeqConstr.h)
[ "86937289+KaranBajwaUTS@users.noreply.github.com" ]
86937289+KaranBajwaUTS@users.noreply.github.com
e2767e380dbac601564b7353acf859bab4f77e97
7ee09154dcac3e06ba4212941251efbf9fda4570
/Exam 2/exam2/Party.h
be39fe8135872af4efd8f8dc3e53ee3820ee2502
[]
no_license
krobinson20/Exam2-parties-
c18ac3b94fcf71230018b50ea65ea455a091fbce
51dbf13112bf73f13f47b728cd69b227b938583f
refs/heads/master
2020-03-13T09:10:14.248210
2018-04-25T20:31:30
2018-04-25T20:31:30
131,058,920
0
0
null
null
null
null
UTF-8
C++
false
false
481
h
#ifndef _PARTY_H_ #define _PARTY_H_ #include <string> #include "PartyTicket.h" /** * Abstract Base Class for Party. * This class just defines the methods that need to be implemented in its derived classes. */ class Party { public: Party() {}; /** * Adds a person to the party, and returns a party ticket */ virtual PartyTicket * add(std::string name) = 0; /** * List the people currently in the party */ virtual void list() = 0; }; #endif
[ "noreply@github.com" ]
noreply@github.com
3128eb86ff7d9c77eaafb3ca0dcfb0878286edd1
7e031bf284e3bce7feaf5c17145e2f63beafc17f
/CP guide/some test with strings.cpp
5584d6690fb1793834ea1b074a1d76d51f7d8664
[]
no_license
shubhampathak09/dynamic-programming-and-arrays
5d700c5ccb87043c6f6cd1f3c1e4a734e1e2a003
a8171ba30201f5b131b54129a430006adc0c3e89
refs/heads/master
2021-06-04T01:43:45.828968
2021-06-01T07:38:56
2021-06-01T07:38:56
132,006,790
1
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
#include<bits/stdc++.h> using namespace std; int main() { string s="figure it out already :p"; cout<<s; string s1; cout<<endl; getline(cin,s1); cout<<s1; }
[ "95shubham1@gmail.com" ]
95shubham1@gmail.com
387166990cd68c620715059570128966f3e154be
e5f68550bc300cee2b79b353540a25eafbfcf1a1
/leetcode/064/64.cpp
7b80adccc4a08e7e05abc5fd062056952ef62aa2
[]
no_license
xm45/OJ
216287f9bc0013c099552b0c6feaa03f25993387
54973534d20d38dc4e85d0c43a5d1b530967e88f
refs/heads/master
2021-01-17T20:48:36.759519
2016-08-10T13:01:39
2016-08-10T13:01:39
64,577,955
0
0
null
null
null
null
UTF-8
C++
false
false
612
cpp
class Solution { public: int minPathSum(vector<vector<int>>& grid) { int m = grid.size(); int n = m?grid[0].size():0; vector<vector<int>> dp(m,vector<int>(n,0)); for(int i = 0; i < m; i ++) for(int j = 0; j < n; j++) { dp[i][j] = INT_MAX; if(i) dp[i][j] = min(dp[i][j], dp[i-1][j] + grid[i][j]); if(j) dp[i][j] = min(dp[i][j], dp[i][j-1] + grid[i][j]); if(!i && !j) dp[i][j] = grid[i][j]; } return dp[m-1][n-1]; } };
[ "546396008@qq.com" ]
546396008@qq.com
81020142542fc8e7f288383c25fd87afb915c067
4f4b084a889207c4b38817b8b3a36e9c4b1d9739
/Source/ThresholdGame/Private/ThresholdGame/World/InteractiveObject.cpp
bf06e6995525184057ff74bf007db89498b9a4b3
[ "MIT" ]
permissive
phalasz/Threshold
adfa4bd582e55a7609056e1bc5ce2d81cb18f779
b0178e322548ca7cbe31cbf26943df3d4c616c8a
refs/heads/master
2023-01-13T22:24:11.338463
2020-11-17T21:00:23
2020-11-17T21:00:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
299
cpp
// Copyright (c) 2020 Spencer Melnick #include "ThresholdGame/World/InteractiveObject.h" void IInteractiveObject::AttachInteractionIndicator(AActor* Indicator) { Indicator->DetachFromActor(FDetachmentTransformRules::KeepWorldTransform); Indicator->SetActorLocation(GetInteractLocation()); }
[ "smelnick97@gmail.com" ]
smelnick97@gmail.com
392aac99735cd2dab2c691d97b26ee25e0a9eedd
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/082/489/CWE190_Integer_Overflow__char_rand_multiply_74b.cpp
fbfe050afe0f1470df87861428e3f219acbd9a15
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
2,029
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE190_Integer_Overflow__char_rand_multiply_74b.cpp Label Definition File: CWE190_Integer_Overflow.label.xml Template File: sources-sinks-74b.tmpl.cpp */ /* * @description * CWE: 190 Integer Overflow * BadSource: rand Set data to result of rand() * GoodSource: Set data to a small, non-zero number (two) * Sinks: multiply * GoodSink: Ensure there will not be an overflow before multiplying data by 2 * BadSink : If data is positive, multiply by 2, which can cause an overflow * Flow Variant: 74 Data flow: data passed in a map from one function to another in different source files * * */ #include "std_testcase.h" #include <map> using namespace std; namespace CWE190_Integer_Overflow__char_rand_multiply_74 { #ifndef OMITBAD void badSink(map<int, char> dataMap) { /* copy data out of dataMap */ char data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > CHAR_MAX, this will overflow */ char result = data * 2; printHexCharLine(result); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(map<int, char> dataMap) { char data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* POTENTIAL FLAW: if (data*2) > CHAR_MAX, this will overflow */ char result = data * 2; printHexCharLine(result); } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(map<int, char> dataMap) { char data = dataMap[2]; if(data > 0) /* ensure we won't have an underflow */ { /* FIX: Add a check to prevent an overflow from occurring */ if (data < (CHAR_MAX/2)) { char result = data * 2; printHexCharLine(result); } else { printLine("data value is too large to perform arithmetic safely."); } } } #endif /* OMITGOOD */ } /* close namespace */
[ "frank@fischer.com.mt" ]
frank@fischer.com.mt
d6634edae3c21ed29ed19c0a071bdad408aea0eb
d067b7954a3ec4bd92d4542e65ef8259d63b47a4
/.svn/pristine/d6/d6634edae3c21ed29ed19c0a071bdad408aea0eb.svn-base
326d46ead3b6b3d91e78a99f8333e01f31c070ee
[]
no_license
fact-project/mars_pulse_truth
b767f781cceb782ae014e5eba54ace4846dc4b50
c0db9cce9fbb2f866b69f53d7820dea65d96aa4f
refs/heads/master
2020-06-17T20:10:10.343838
2016-11-29T17:04:58
2016-11-29T17:04:58
74,973,456
0
0
null
null
null
null
UTF-8
C++
false
false
7,396
/* ======================================================================== *\ ! ! * ! * This file is part of MARS, the MAGIC Analysis and Reconstruction ! * Software. It is distributed to you in the hope that it can be a useful ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes. ! * It is distributed WITHOUT ANY WARRANTY. ! * ! * Permission to use, copy, modify and distribute this software and its ! * documentation for any purpose is hereby granted without fee, ! * provided that the above copyright notice appear in all copies and ! * that both that copyright notice and this permission notice appear ! * in supporting documentation. It is provided "as is" without express ! * or implied warranty. ! * ! ! ! Author(s): Thomas Bretz 07/2011 <mailto:thomas.bretz@epfl.ch> ! ! Copyright: MAGIC Software Development, 2000-2011 ! ! \* ======================================================================== */ ////////////////////////////////////////////////////////////////////////////// // // MRawFitsRead // // This tasks reads the fits data file in the form used by FACT. // // Input Containers: // -/- // // Output Containers: // MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawEvtTime // ////////////////////////////////////////////////////////////////////////////// #include "MRawFitsRead.h" #include <fstream> #include <TClass.h> #include "MLog.h" #include "MLogManip.h" #include "factfits.h" #include "MTime.h" #include "MArrayB.h" #include "MArrayS.h" #include "MParList.h" #include "MRawRunHeader.h" #include "MRawEvtHeader.h" #include "MRawEvtData.h" #include "MRawBoardsFACT.h" ClassImp(MRawFitsRead); using namespace std; // -------------------------------------------------------------------------- // // Default constructor. It tries to open the given file. // MRawFitsRead::MRawFitsRead(const char *fname, const char *name, const char *title) : MRawFileRead(fname, name, title), fRawBoards(0) { } const fits *MRawFitsRead::GetFitsFile() const { return static_cast<const fits*>(GetStream()); } Int_t MRawFitsRead::PreProcess(MParList *pList) { fRawBoards = (MRawBoardsFACT*)pList->FindCreateObj("MRawBoardsFACT"); if (!fRawBoards) return kFALSE; return MRawFileRead::PreProcess(pList); } Bool_t MRawFitsRead::LoadMap(const char *name) { fPixelMap.resize(1440); if (!name) return kTRUE; ifstream fin(name); int l = 0; string buf; while (getline(fin, buf, '\n')) { if (l>1439) break; const TString bf = TString(buf.c_str()).Strip(TString::kBoth); if (bf[0]=='#') continue; stringstream str(bf.Data()); int index, cbpx; str >> index; str >> cbpx; const int c = cbpx/1000; const int b = (cbpx/100)%10; const int p = (cbpx/10)%10; const int x = cbpx%10; const int hw = x+p*9+b*36+c*360; if (hw>1439) break; fPixelMap[hw] = index; l++; } if (l!=1440) { gLog << err << "ERROR - Problems reading " << name << endl; fPixelMap.resize(0); return kFALSE; } return kTRUE; } Bool_t MRawFitsRead::IsFits(const char *name) { return factfits(name).good(); } istream *MRawFitsRead::OpenFile(const char *filename) { return new factfits(filename); } Bool_t MRawFitsRead::ReadRunHeader(istream &stream) { factfits &fin = static_cast<factfits&>(stream); if (fin.GetStr("TELESCOP")!="FACT") { gLog << err << "Not a valid FACT FITS file (key TELESCOP not 'FACT')." << endl; return kFALSE; } fIsMc = fin.HasKey("ISMC"); const string type = fin.GetStr("RUNTYPE"); fRawRunHeader->SetValidMagicNumber(); fRawRunHeader->SetNumEvents(fin.GetNumRows());//GetUInt("NAXIS2")); fRawRunHeader->InitPixels(fin.GetUInt("NPIX")); fRawRunHeader->SetObservation(type=="4294967295"?"":fin.GetStr("RUNTYPE"), "FACT"); fRawRunHeader->SetRunInfo(0, fin.GetUInt("NIGHT"), fin.GetUInt("RUNID")); fRawRunHeader->InitFact(fin.GetUInt("NPIX")/9, 9, fin.GetUInt("NROI"), fPixelMap.size()==0?0:fPixelMap.data()); fRawRunHeader->SetFormat(0xf172, fIsMc ? 0 : fin.GetUInt("BLDVER")); fRawRunHeader->SetRunType(fIsMc ? 0x0100/*mc*/ : 0/*data*/); if (!fIsMc) { const string runstart = fin.GetStr("DATE-OBS"); const string runstop = fin.GetStr("DATE-END"); fRawRunHeader->SetRunTime(MTime(runstart.c_str()), MTime(runstop.c_str())); } for (int i=0; i<1000; i++) { const string clnamed = Form("CLNAME%d", i); if (!fin.HasKey(clnamed)) break; const string cltyped = Form("CLTYPE%d", i); const string clname = fin.GetStr(clnamed); const string cltype = fin.HasKey(cltyped) ? fin.GetStr(cltyped) : clname; MParContainer *par = (MParContainer*)fParList->FindCreateObj(cltype.c_str(), clname.c_str()); if (par && !par->SetupFits(fin)) { *fLog << err << "ERROR - Setting up " << par->GetDescriptor() << " failed." << endl; return kFALSE; } } return fin.HasKey("NPIX") && fin.HasKey("RUNID") && fin.HasKey("NROI") && fin.HasKey("NIGHT"); } Bool_t MRawFitsRead::InitReadData(istream &stream) { factfits &fin = static_cast<factfits&>(stream); MArrayB **data = reinterpret_cast<MArrayB**>(fRawEvtData1->DataMember("fHiGainFadcSamples")); MArrayS **cell = reinterpret_cast<MArrayS**>(fRawEvtData1->DataMember("fStartCells")); UInt_t *evtnum = reinterpret_cast<UInt_t*> (fRawEvtHeader->DataMember("fDAQEvtNumber")); // The 'wrong' cast is intentional because we read only two bytes from the file UShort_t *trg = reinterpret_cast<UShort_t*>(fRawEvtHeader->DataMember("fTrigPattern")); if (!data || !cell || !evtnum || !trg) return kFALSE; fRawEvtData1->ResetPixels(); fRawEvtData2->ResetPixels(0, 0); fRawEvtData1->InitStartCells(); if (!fin.SetRefAddress("EventNum", *evtnum)) return kFALSE; if (!fin.SetRefAddress("TriggerType", *trg)) return kFALSE; if (!fIsMc) { if (!fin.SetRefAddress("NumBoards", fNumBoards)) return kFALSE; fPCTime.resize(2); if (!fin.SetVecAddress("UnixTimeUTC", fPCTime)) if (!fin.SetVecAddress("PCTime", fPCTime)) return kFALSE; if (!fin.SetPtrAddress("BoardTime", fRawBoards->fFadTime, 40)) return kFALSE; } if (!fin.SetPtrAddress("Data", (int16_t*)(*data)->GetArray(), (*data)->GetSize()/2)) return kFALSE; if (!fin.SetPtrAddress("StartCellData", (uint16_t*)(*cell)->GetArray(), (*cell)->GetSize())) return kFALSE; fRawEvtData1->SetIndices(fRawRunHeader->GetPixAssignment()); return kTRUE; } Bool_t MRawFitsRead::ReadEvent(istream &stream) { if (!static_cast<factfits&>(stream).GetNextRow()) return kFALSE; if (!fIsMc) { // Skip incomplete events if (fNumBoards!=40) return kCONTINUE; fRawEvtTime->SetUnixTime(fPCTime[0], fPCTime[1]); } fRawEvtData1->SetReadyToSave(); fRawEvtData2->SetReadyToSave(); return kTRUE; } void MRawFitsRead::SkipEvent(istream &fin) { static_cast<factfits&>(fin).SkipNextRow(); }
[ "sebmuell@phys.ethz.ch" ]
sebmuell@phys.ethz.ch
49e9fe652a87e58647f4ba42d17dd7c500b12734
50abd6176ceeb0f244cb1022999eaa6bc655ce19
/SansNom4.cpp
383c5fc13d27bc990576a13618a00abb080ec113
[]
no_license
soufianefatih/algoritme
a30682359c9fb847ef7f2401ee90ecd6befa58a4
c5f06c01b7bfe8de15ab79cae510f525c6553dd4
refs/heads/main
2023-02-16T00:10:51.800656
2021-01-14T10:46:51
2021-01-14T10:46:51
327,591,345
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
#include<stdio.h> #include<stdio.h> int main () { int n , i ; float moyen ; while (n!=-1 || n>0) { printf("enter le valeur de n : \n"); scanf("%d",&n); if (n==-1) { break ; }i++ ; moyen = moyen +n ; } printf("le moyen est : %.2f",moyen/i); return 0 ; }
[ "fatihe.soufiane@gmail.com" ]
fatihe.soufiane@gmail.com
70bb315b8a33004371d609757722adf515e2be67
cdd26b7a42c44d93b1830c9ab6712ed2eac9e86b
/deps/src/jlcxx/include/jlcxx/array.hpp
caef8b5e47de7fd2f757c1fe11a9a5fe4471ef94
[ "MIT" ]
permissive
vvjn/Opcode.jl
506f40e8641f0d6f5cdf4d5058085ba6bdb42f71
f95086e7f9a6a597ed0de4ba0441c8571e8fbc14
refs/heads/master
2021-05-02T18:19:22.306883
2018-02-07T19:30:41
2018-02-07T19:30:41
120,661,169
0
0
null
null
null
null
UTF-8
C++
false
false
8,569
hpp
#ifndef JLCXX_ARRAY_HPP #define JLCXX_ARRAY_HPP #include "type_conversion.hpp" #include "tuple.hpp" namespace jlcxx { template<typename PointedT, typename CppT> struct ValueExtractor { inline CppT operator()(PointedT* p) { return convert_to_cpp<CppT>(*p); } }; template<typename PointedT> struct ValueExtractor<PointedT, PointedT> { inline PointedT& operator()(PointedT* p) { return *p; } }; template<typename PointedT, typename CppT> class array_iterator_base : public std::iterator<std::random_access_iterator_tag, PointedT> { private: PointedT* m_ptr; public: array_iterator_base() : m_ptr(nullptr) { } explicit array_iterator_base(PointedT* p) : m_ptr(p) { } template <class OtherPointedT, class OtherCppT> array_iterator_base(array_iterator_base<OtherPointedT, OtherCppT> const& other) : m_ptr(other.m_ptr) {} auto operator*() -> decltype(ValueExtractor<PointedT,CppT>()(m_ptr)) { return ValueExtractor<PointedT,CppT>()(m_ptr); } array_iterator_base<PointedT, CppT>& operator++() { ++m_ptr; return *this; } array_iterator_base<PointedT, CppT>& operator--() { --m_ptr; return *this; } array_iterator_base<PointedT, CppT>& operator+=(std::ptrdiff_t n) { m_ptr += n; return *this; } array_iterator_base<PointedT, CppT>& operator-=(std::ptrdiff_t n) { m_ptr -= n; return *this; } PointedT* ptr() const { return m_ptr; } }; /// Wrap a Julia 1D array in a C++ class. Array is allocated on the C++ side template<typename ValueT> class Array { public: Array(const size_t n = 0) { jl_value_t* array_type = apply_array_type(static_type_mapping<ValueT>::julia_type(), 1); m_array = jl_alloc_array_1d(array_type, n); } Array(jl_datatype_t* applied_type, const size_t n = 0) { jl_value_t* array_type = apply_array_type(applied_type, 1); m_array = jl_alloc_array_1d(array_type, n); } /// Append an element to the end of the list void push_back(const ValueT& val) { JL_GC_PUSH1(&m_array); const size_t pos = jl_array_len(m_array); jl_array_grow_end(m_array, 1); jl_arrayset(m_array, box(val), pos); JL_GC_POP(); } /// Access to the wrapped array jl_array_t* wrapped() { return m_array; } // access to the pointer for GC macros jl_array_t** gc_pointer() { return &m_array; } private: jl_array_t* m_array; }; /// Only provide read/write operator[] if the array contains non-boxed values template<typename PointedT, typename CppT> struct IndexedArrayRef { IndexedArrayRef(jl_array_t* arr) : m_array(arr) { } CppT operator[](const std::size_t i) const { return convert_to_cpp<CppT>(jl_arrayref(m_array, i)); } jl_array_t* m_array; }; template<typename ValueT> struct IndexedArrayRef<ValueT,ValueT> { IndexedArrayRef(jl_array_t* arr) : m_array(arr) { } ValueT& operator[](const std::size_t i) { return ((ValueT*)jl_array_data(m_array))[i]; } ValueT operator[](const std::size_t i) const { return ((ValueT*)jl_array_data(m_array))[i]; } jl_array_t* m_array; }; /// Reference a Julia array in an STL-compatible wrapper template<typename ValueT, int Dim = 1> class ArrayRef : public IndexedArrayRef<mapped_julia_type<ValueT>, ValueT> { public: ArrayRef(jl_array_t* arr) : IndexedArrayRef<mapped_julia_type<ValueT>, ValueT>(arr) { assert(wrapped() != nullptr); } /// Convert from existing C-array template<typename... SizesT> ArrayRef(ValueT* ptr, const SizesT... sizes); typedef mapped_julia_type<ValueT> julia_t; typedef array_iterator_base<julia_t, ValueT> iterator; typedef array_iterator_base<julia_t const, ValueT const> const_iterator; inline jl_array_t* wrapped() const { return IndexedArrayRef<julia_t, ValueT>::m_array; } iterator begin() { return iterator(static_cast<julia_t*>(jl_array_data(wrapped()))); } const_iterator begin() const { return const_iterator(static_cast<julia_t*>(jl_array_data(wrapped()))); } iterator end() { return iterator(static_cast<julia_t*>(jl_array_data(wrapped())) + jl_array_len(wrapped())); } const_iterator end() const { return const_iterator(static_cast<julia_t*>(jl_array_data(wrapped())) + jl_array_len(wrapped())); } void push_back(const ValueT& val) { JL_GC_PUSH1(&(IndexedArrayRef<julia_t, ValueT>::m_array)); const size_t pos = size(); jl_array_grow_end(wrapped(), 1); jl_arrayset(wrapped(), box(val), pos); JL_GC_POP(); } const ValueT* data() const { return (ValueT*)jl_array_data(wrapped()); } ValueT* data() { return (ValueT*)jl_array_data(wrapped()); } std::size_t size() const { return jl_array_len(wrapped()); } }; template<typename T, int Dim> struct IsValueType<ArrayRef<T,Dim>> : std::true_type {}; // Conversions template<typename T, int Dim> struct static_type_mapping<ArrayRef<T, Dim>> { typedef jl_array_t* type; static jl_datatype_t* julia_type() { return (jl_datatype_t*)apply_array_type(static_type_mapping<T>::julia_type(), Dim); } }; template<typename ValueT, int Dim> template<typename... SizesT> ArrayRef<ValueT, Dim>::ArrayRef(ValueT* c_ptr, const SizesT... sizes) : IndexedArrayRef<julia_t, ValueT>(nullptr) { jl_datatype_t* dt = static_type_mapping<ArrayRef<ValueT, Dim>>::julia_type(); jl_value_t *dims = nullptr; JL_GC_PUSH1(&dims); dims = convert_to_julia(std::make_tuple(static_cast<int_t>(sizes)...)); IndexedArrayRef<julia_t, ValueT>::m_array = jl_ptr_to_array((jl_value_t*)dt, c_ptr, dims, 0); JL_GC_POP(); } template<typename T, int Dim> struct ConvertToJulia<ArrayRef<T,Dim>, false, false, false> { template<typename ArrayRefT> jl_array_t* operator()(ArrayRefT&& arr) const { return arr.wrapped(); } }; template<typename T, int Dim> struct ConvertToCpp<ArrayRef<T,Dim>, false, false, false> { ArrayRef<T,Dim> operator()(jl_array_t* arr) const { return ArrayRef<T,Dim>(arr); } }; // Iterator operator implementation template<typename L, typename R> bool operator!=(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return r.ptr() != l.ptr(); } template<typename L, typename R> bool operator==(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return r.ptr() == l.ptr(); } template<typename L, typename R> bool operator<=(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return l.ptr() <= r.ptr(); } template<typename L, typename R> bool operator>=(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return l.ptr() >= r.ptr(); } template<typename L, typename R> bool operator>(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return l.ptr() > r.ptr(); } template<typename L, typename R> bool operator<(const array_iterator_base<L,L>& l, const array_iterator_base<R,R>& r) { return l.ptr() < r.ptr(); } template<typename T> array_iterator_base<T, T> operator+(const array_iterator_base<T,T>& l, const std::ptrdiff_t n) { return array_iterator_base<T, T>(l.ptr() + n); } template<typename T> array_iterator_base<T, T> operator+(const std::ptrdiff_t n, const array_iterator_base<T,T>& r) { return array_iterator_base<T, T>(r.ptr() + n); } template<typename T> array_iterator_base<T, T> operator-(const array_iterator_base<T,T>& l, const std::ptrdiff_t n) { return array_iterator_base<T, T>(l.ptr() - n); } template<typename T> std::ptrdiff_t operator-(const array_iterator_base<T,T>& l, const array_iterator_base<T,T>& r) { return l.ptr() - r.ptr(); } /// Julia Matrix parametric singleton type struct JuliaMatrix {}; template<> struct IsValueType<JuliaMatrix> : std::true_type {}; template<> struct static_type_mapping<JuliaMatrix> { typedef jl_datatype_t* type; static jl_datatype_t* julia_type() { static jl_tvar_t* this_tvar = jl_new_typevar(jl_symbol("T"), (jl_value_t*)jl_bottom_type, (jl_value_t*)jl_any_type); protect_from_gc(this_tvar); jl_value_t* boxed_2 = jl_box_long(2); jl_value_t* arr_t = nullptr; JL_GC_PUSH2(&boxed_2, &arr_t); arr_t = apply_type((jl_value_t*)jl_array_type, jl_svec2(this_tvar, jl_box_long(2))); jl_datatype_t* result = (jl_datatype_t*)apply_type((jl_value_t*)jl_type_type, jl_svec1(arr_t)); JL_GC_POP(); return result; } }; template<> struct ConvertToCpp<JuliaMatrix, false, false, false> { JuliaMatrix operator()(jl_datatype_t*) const { return JuliaMatrix(); } }; } #endif
[ "vvjnvt@gmail.com" ]
vvjnvt@gmail.com
77e9afaa5e7e94489e70f4455ff6602070bf3ff2
b52ab043d503cf0ba386b831c5bab869524cfa93
/src/qt/signverifymessagedialog.cpp
767bbde8f7b48cffa914a938cc1adce24987756a
[ "MIT" ]
permissive
mirzaei-ce/linux-cocabit
f3a07968d96442ac2d94d0b72dc446bb1ec830de
ceadf6346ab64b6bd93927d93dc52007b5fbb5a2
refs/heads/master
2021-05-06T12:27:00.077551
2017-12-04T14:41:56
2017-12-04T14:41:56
113,054,485
0
0
null
null
null
null
UTF-8
C++
false
false
9,354
cpp
// Copyright (c) 2011-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "signverifymessagedialog.h" #include "ui_signverifymessagedialog.h" #include "addressbookpage.h" #include "guiutil.h" #include "platformstyle.h" #include "walletmodel.h" #include "base58.h" #include "init.h" #include "main.h" // For strMessageMagic #include "wallet/wallet.h" #include <string> #include <vector> #include <QClipboard> SignVerifyMessageDialog::SignVerifyMessageDialog(const PlatformStyle *platformStyle, QWidget *parent) : QDialog(parent), ui(new Ui::SignVerifyMessageDialog), model(0), platformStyle(platformStyle) { ui->setupUi(this); ui->addressBookButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->pasteButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste")); ui->copySignatureButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/editcopy")); ui->signMessageButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/edit")); ui->clearButton_SM->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); ui->addressBookButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/address-book")); ui->verifyMessageButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/transaction_0")); ui->clearButton_VM->setIcon(platformStyle->SingleColorIcon(":/icons/remove")); #if QT_VERSION >= 0x040700 ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); #endif GUIUtil::setupAddressWidget(ui->addressIn_SM, this); GUIUtil::setupAddressWidget(ui->addressIn_VM, this); ui->addressIn_SM->installEventFilter(this); ui->messageIn_SM->installEventFilter(this); ui->signatureOut_SM->installEventFilter(this); ui->addressIn_VM->installEventFilter(this); ui->messageIn_VM->installEventFilter(this); ui->signatureIn_VM->installEventFilter(this); ui->signatureOut_SM->setFont(GUIUtil::fixedPitchFont()); ui->signatureIn_VM->setFont(GUIUtil::fixedPitchFont()); } SignVerifyMessageDialog::~SignVerifyMessageDialog() { delete ui; } void SignVerifyMessageDialog::setModel(WalletModel *model) { this->model = model; } void SignVerifyMessageDialog::setAddress_SM(const QString &address) { ui->addressIn_SM->setText(address); ui->messageIn_SM->setFocus(); } void SignVerifyMessageDialog::setAddress_VM(const QString &address) { ui->addressIn_VM->setText(address); ui->messageIn_VM->setFocus(); } void SignVerifyMessageDialog::showTab_SM(bool fShow) { ui->tabWidget->setCurrentIndex(0); if (fShow) this->show(); } void SignVerifyMessageDialog::showTab_VM(bool fShow) { ui->tabWidget->setCurrentIndex(1); if (fShow) this->show(); } void SignVerifyMessageDialog::on_addressBookButton_SM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_SM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_pasteButton_SM_clicked() { setAddress_SM(QApplication::clipboard()->text()); } void SignVerifyMessageDialog::on_signMessageButton_SM_clicked() { if (!model) return; /* Clear old signature to ensure users don't get confused on error with an old signature displayed */ ui->signatureOut_SM->clear(); CCocabitAddress addr(ui->addressIn_SM->text().toStdString()); if (!addr.IsValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_SM->setValid(false); ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if (!ctx.isValid()) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled.")); return; } CKey key; if (!pwalletMain->GetKey(keyID, key)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(tr("Private key for the entered address is not available.")); return; } CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_SM->document()->toPlainText().toStdString(); std::vector<unsigned char> vchSig; if (!key.SignCompact(ss.GetHash(), vchSig)) { ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>")); return; } ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>")); ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size()))); } void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked() { GUIUtil::setClipboard(ui->signatureOut_SM->text()); } void SignVerifyMessageDialog::on_clearButton_SM_clicked() { ui->addressIn_SM->clear(); ui->messageIn_SM->clear(); ui->signatureOut_SM->clear(); ui->statusLabel_SM->clear(); ui->addressIn_SM->setFocus(); } void SignVerifyMessageDialog::on_addressBookButton_VM_clicked() { if (model && model->getAddressTableModel()) { AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { setAddress_VM(dlg.getReturnValue()); } } } void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked() { CCocabitAddress addr(ui->addressIn_VM->text().toStdString()); if (!addr.IsValid()) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again.")); return; } CKeyID keyID; if (!addr.GetKeyID(keyID)) { ui->addressIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again.")); return; } bool fInvalid = false; std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid); if (fInvalid) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again.")); return; } CHashWriter ss(SER_GETHASH, 0); ss << strMessageMagic; ss << ui->messageIn_VM->document()->toPlainText().toStdString(); CPubKey pubkey; if (!pubkey.RecoverCompact(ss.GetHash(), vchSig)) { ui->signatureIn_VM->setValid(false); ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again.")); return; } if (!(CCocabitAddress(pubkey.GetID()) == addr)) { ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>")); return; } ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }"); ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>")); } void SignVerifyMessageDialog::on_clearButton_VM_clicked() { ui->addressIn_VM->clear(); ui->signatureIn_VM->clear(); ui->messageIn_VM->clear(); ui->statusLabel_VM->clear(); ui->addressIn_VM->setFocus(); } bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event) { if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn) { if (ui->tabWidget->currentIndex() == 0) { /* Clear status message on focus change */ ui->statusLabel_SM->clear(); /* Select generated signature */ if (object == ui->signatureOut_SM) { ui->signatureOut_SM->selectAll(); return true; } } else if (ui->tabWidget->currentIndex() == 1) { /* Clear status message on focus change */ ui->statusLabel_VM->clear(); } } return QDialog::eventFilter(object, event); }
[ "mirzaei@ce.sharif.edu" ]
mirzaei@ce.sharif.edu
7a30825e161398159e6774495fb88cc126f0c70d
60636938935209afcb88ce63f903771457e58051
/UpdatedDataStructures/Model/Nodes/HashNode.hpp
45183e58731380907903063b1ec7dac4cae4d9be
[]
no_license
SirB31415/UpdatedDataStructures
8463878b2bbc50cf27535e160b3bd64fe448e4dc
d495b10934d9a613c12c12e2f54568aaf2456e4a
refs/heads/master
2020-03-09T13:39:33.025834
2018-05-21T19:29:28
2018-05-21T19:29:28
128,816,651
0
0
null
null
null
null
UTF-8
C++
false
false
682
hpp
// // HashNode.hpp // UpdatedDataStructures // // Created by Brailow, Parker on 4/27/18. // Copyright © 2018 Brailow Inc. All rights reserved. // #ifndef HashNode_hpp #define HashNode_hpp #include "Node.hpp" template <class Type> class HashNode : public Node<Type> { private: long key; public: HashNode(); HashNode(Type data); long getKey() const; }; template <class Type> HashNode<Type> :: HashNode() { this->key = 0; } template <class Type> HashNode<Type> :: HashNode(Type data) : Node<Type>(data) { this->key = (long) &data; } template <class Type> long HashNode<Type> :: getKey() const { return this->key; } #endif /* HashNode_hpp */
[ "31518716+SirB31415@users.noreply.github.com" ]
31518716+SirB31415@users.noreply.github.com
21806559f487357a43cd5ef9e7bdc9e0479d7db4
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/a5/6a6e7df07187f7/main.cpp
20a059852d6f344d0e41a46b5a254e680ca3f7c8
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
2,316
cpp
#include <iostream> #include <tuple> using namespace std; template <typename T> T random_num() { return 0; } template<> int random_num<int>() { return 4; } template<> float random_num<float>() { return 4.2f; } // The idea is to build tuples recursively where the types are fixed at compile time // and the data is loaded dynamically (e.g. the random_num functions). // So one could write // auto res = construct<float, int>(); // where res is std::tuple<float, int> with values (4.2f, 4) template <size_t idx, typename Tup, typename... Args> struct Builder; // Append a dynamically generated value to the tuple template <size_t idx, typename Tup, typename First, typename... Args> struct Builder<idx, Tup, First, Args...> { static First get_num() { return random_num<First>(); } typedef std::declval<Tup>() tuple_start_t; typedef decltype(std::tuple_cat(std::declval<Tup>(), std::make_tuple(get_num()))) tuple_combine_t; typedef Builder<idx, Tup, First, Args...> current_builder_t; typedef Builder<idx + 1, tuple_combine_t, Args...> next_builder_t; static auto construct(Tup t) -> decltype(next_builder_t::construct(std::declval<tuple_combine_t>())) { First n = get_num(); // Get the numbers dynamically, with the types given in the parameter pack auto next_arg_pack = std::tuple_cat(t, std::make_tuple(n)); std::cout << idx << "\n"; return Builder<idx + 1, tuple_combine_t, Args...>::construct(next_arg_pack); } typedef decltype(current_builder_t::construct(std::declval<Tup>())) return_type; }; template <size_t idx, typename Tup> struct Builder<idx, Tup> { static Tup construct(Tup args) { return args; } }; template <typename... Args> using tuple_builder_start = Builder<2, std::tuple<>, Args...>; template <typename... Args> typename tuple_builder_start<Args...>::return_type construct() { return tuple_builder_start<Args...>::construct(std::make_tuple()); } int main() { // Should be std::tuple<int, float>, (4, 4.2f, 4) auto tup = construct<int, float, int>(); std::cout << std::get<0>(tup) << " " << std::get<1>(tup) << " " << std::get<2>(tup) << "\n"; return 0; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
a311635e9dadd02eac06ceafb55aa69e32b8a64c
a330f92c8d3d8073cfead80d8047a91e185d2d14
/SimpleCppMVCTicTacToeApp/SimpleMVCTicTacToeApp/TicTacView.h
518649fe60d5d34431880efd6d47f5b20288ddb8
[]
no_license
mobelus/CppSamples
593e0d6154050a272fe026a166bc7962f7f88420
59ec31d64dcb24ab6c2c3a4ed676a7d13dc0b344
refs/heads/master
2023-05-14T18:28:56.307681
2023-05-05T12:28:40
2023-05-05T12:28:40
180,388,303
0
0
null
null
null
null
UTF-8
C++
false
false
2,268
h
/* File: TicTacView.h Copyright (c) 2020-Present Reza Saffarpour 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. Licensed under the MIT License, you may not use this file except in compliance with the License. You may obtain a copy of the License at https://mit-license.org/ */ #ifndef TICTACVIEW_H #define TICTACVIEW_H #include <iostream> using namespace std; #define ROWCOUNT 3 #define COLUMNCOUNT 3 /** * View class */ class TicTacView { public: TicTacView(); virtual ~TicTacView(); void renderGameScreen(char * boardStatus, bool drawHint = true); void prepareStartingBodyQuestion(); void preparePlayerMoveQuestion(string freeCellNumber); void prepareAskToPlayAgainQuestion(); void announceWinner(char winnerID, string winnerName); void announceNoWinner(); int getUserNextMove(); private: void showBoardMap(char * boardStatus); void drawBoardLine(char * boardStatus, int lastRowNum); void drawBoardCellRow(char * dataArray, int lastRowNum); void showGameBoard(char * boardStatus); void drawGameBoardHint(char * boardStatus); void drawBoard(char * boardDataArray); }; #endif /* TICTACVIEW_H */
[ "noreply@github.com" ]
noreply@github.com
cfc6852530ba71714e52798bfd822d62a35e7c54
8dee1d35dc625e0da4b77f2ee64f5db10ef8e7f3
/src/streamline.cpp
e5928b4f12dadaf19df50744e38cd68d5cf8ba5b
[]
no_license
mberenjkoub/MorseSet
b3f867a010f6a495b6b63a24ea9b617b8bf1e3b3
29fbadd4aeb9f8e627dfb9d16a5ab0da0c003f69
refs/heads/master
2021-08-07T05:42:03.093638
2017-11-07T16:19:01
2017-11-07T16:19:01
109,858,042
0
0
null
null
null
null
UTF-8
C++
false
false
16,637
cpp
/* cuda-scc: CUDA SCC decomposition Author: Milan Ceska, Faculty of Informatics, Masaryk University, Czech Republic Mail: xceska@fi.muni.cz */ #include "SCC.h" //#include "scc_kernel.h" #include "load.h" #include <stdint.h> //#include <pthread.h> #include <set> #include <map> #include <string> #include <queue> #include <cstdio> #include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; void print_help() { printf("========================================================\n"); printf("CUDA SCC decomposition Tool, usage: \nScc Alg [-w=Num] [Ord] [Trimm] [COL] [COL-limit] [NumT] File \n"); printf("Input ::= d | g\n"); printf("Alg ::= t | f | c | o | a | s | p | r | u\n"); printf("Ord ::= 0 | 1\n"); printf("Trimm ::= 0 | 1\n"); printf("Num ::= 1 | ... | 16\n"); printf("COL ::= 0 | 1\n"); printf("COL-limit ::= 0 | ...\n"); printf("--------------------------------------------------------\n"); printf("Alg: decomposing algorithm\n"); printf("f - FB algorithm, c - Colouring/Heads-Off algorithm, o - OBF algorithm\n"); printf("t - Tarjan's algorithm:CPU, u - OBF:CPU\n"); printf("s - BFS:GPU, p - BFS:CPU(serial), r - BFS:CPU(parallel)\n"); printf("a - test suite: all available algorithms with most sensible settings\n"); printf("General parameters:\n"); printf("Num - number of threads used to generate graph.\n"); printf("Parameters for FB:\n"); printf("Trimm - use OWCTY elimination between iterations of FB.\n"); printf("Parameters for Colouring:\n"); printf("Ord - use maximal/minimal accepting predecessor.\n"); printf("Parameters for OBF:\n"); printf("Trimm - use OWCTY before the actual OBF algorithm,\n"); printf("COL - use Colouring on small enough SCC-closed subgraphs,\n"); printf("COL-limit - how small the subgraphs must be.\n"); printf("Parameters for BFS, OBF:CPU:\n"); printf("NumT - number of threads used for parallel reachability.\n"); printf("========================================================\n"); } //////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// // //int main(int argc, char** argv) //{ // //if ( argc < 3 ) { // //print_help(); // // return 1; // //} // // // CSR representation // uint32_t CSize; // column arrays size // uint32_t RSize; // range arrays size // // Forwards arrays // Edge * Fc; // forward columns // uint32_t * Fr = NULL; // forward ranges // // Backwards arrays // Edge * Bc; // backward columns // uint32_t * Br; // backward ranges // GraphGenerator * gen = NULL; // _DeviceSet = false; // // obtain a CSR graph representation // bool dve = true; // /*if ( argv[ argc - 1 ][ strlen( argv[ argc - 1 ] ) - 1 ] == 'r' ) // dve = false; // if ( dve ) { // int num = 1; // for ( int i = 2; i < argc - 1; i++ ) { // if ( argv[ i ][ 0 ] == '-' ) // num = atoi( argv[ i ] + 3 ); // } // gen = new GraphGenerator( argv[ argc - 1 ], num ); // if ( num > 1 ) // gen->p_generateGraph( 30000000 ); // else // gen->generateGraph( 30000000 ); // // gen->getGraph( &CSize, &RSize, &Fc, &Fr, &Bc, &Br ); // } // else */ // { // //loadFullGraph("scc_all\\Vertices_Forward.txt", &CSize, &RSize, &Fc, &Fr, &Bc, &Br); // loadFullGraph("scc_all\\Vertices_Forward_Benard_3000.txt", &CSize, &RSize, &Fc, &Fr, &Bc, &Br); // } // // char c = 'o';// argv[1][0]; // try { // switch (c) { // /* case 'f' : // { // FB_vertex * _m = new FB_vertex[ RSize - 1 ]; // pair <uint32_t, float> result = FB_Decomposition( CSize, RSize, Fc, Fr, Bc, Br, _m, ( argc > 3 ) ? bool( atoi( argv[ 2 ] )) : false, (argv[ 1 ][ 1 ] != '\0') ); // if ( argv[ 1 ][ 1 ] != '\0' ) // printf("%f", result.second); // delete [] _m; // } // break; // // case 'c' : // { // COL_vertex * _m = new COL_vertex[ RSize - 1 ]; // pair <uint32_t, float> result = COL_Decomposition( CSize, RSize, Fc, Fr, Bc, Br, _m, ( argc > 3 && !(atoi( argv[ 2 ] )) ) ? MAX : MIN, (argv[ 1 ][ 1 ] != '\0') ); // if ( argv[ 1 ][ 1 ] != '\0' ) // printf("%f", result.second); // delete [] _m; // } // break; */ // // case 'o': // { // OBF_vertex * _m = new OBF_vertex[RSize - 1]; // pair <uint32_t, float> result = OBF_Decomposition(CSize, RSize, Fc, Fr, Bc, Br, _m, /*(argc > 4) ? bool(atoi(argv[3])) :*/ false, // /*(argc > 5) ? atoi(argv[4]) :*/ 1000, /*(argc > 3) ? bool(atoi(argv[2])) :*/ true, true/*(argv[1][1] != '\0')*/); // //if (argv[1][1] != '\0') // printf("%f", result.second); // delete[] _m; // } // break; // /* // case 't' : // { // TR_vertex * _m = new TR_vertex[ RSize - 1 ]; // pair <uint32_t, float> result = TR_Decomposition( CSize, RSize, Fc, Fr, _m, (argv[ 1 ][ 1 ] != '\0') ); // if ( argv[ 1 ][ 1 ] != '\0' ) // printf("%f", result.second); // delete [] _m; // } // break; // // case 's' : // { // FB_vertex * _m = new FB_vertex[ RSize - 1 ]; // Forward_only( CSize, RSize, Fc, Fr, _m, ( argc > 3 ) ? atoi( argv[ 2 ] ) : 0 ); // delete [] _m; // } // break; // // case 'p' : // { // BFS_vertex * _m = new BFS_vertex[ RSize - 1 ]; // BFS( CSize, RSize, Fc, Fr, _m ); // delete [] _m; // } // break; // // case 'r' : // { // parallel_FWD( CSize, RSize, Fc, Fr, RSize - 1, ( argc > 3 ) ? atoi( argv[ 2 ] ) : 4 ); // } // break; // // case 'z' : // _CPU_BFS( CSize, RSize, Fc, Fr, RSize - 1, ( argc > 3 ) ? atoi( argv[ 2 ] ) : 4 ); // break; // // case 'y' : // { // CFB_vertex * _m = new CFB_vertex[ RSize - 1 ]; // _CPU_FB( CSize, RSize, Fc, Fr, Bc, Br, _m, RSize - 1, ( argc > 3 ) ? atoi( argv[ 2 ] ) : 4 ); // delete [] _m; // break; // } // case 'a' : // { // Edge * _Bc = new Edge[ CSize ]; // uint32_t * _Br = new uint32_t[ RSize ]; // Edge * _Fc = new Edge[ CSize ]; // uint32_t * _Fr = new uint32_t[ RSize ]; // // printf("SCC decomposition of graph %s ", argv[ argc - 1 ]); // printf("of %u Vertices, %u Edges and ", RSize - 2, CSize); // pair <uint32_t, float> result; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // TR_vertex * _tm = new TR_vertex[ RSize - 1 ]; // result = TR_Decomposition( CSize, RSize, _Fc, _Fr, _tm, true ); // printf("%u Components.\n\n", result.first); // printf("\n\t\t\t\tno Trimm\twith Trimm\n"); // printf("Tarjan's:\t\t\t%f\n", result.second); // delete [] _tm; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // BFS_vertex * _bm = new BFS_vertex[ RSize - 1 ]; // result = BFS( CSize, RSize, _Fc, _Fr, _bm, true ); // printf("CPU BFS:\t\t\t%f\n", result.second); // delete [] _bm; // // /* // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = parallel_FWD( CSize, RSize, _Fc, _Fr, RSize - 1, 3, true ); // printf("CPU BFS, 3 cores\t\t%f, %u vertices found\n", result.second, result.first); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = parallel_FWD( CSize, RSize, _Fc, _Fr, RSize - 1, 2, true ); // printf("CPU BFS, 2 cores\t\t%f, %u vertices found\n", result.second, result.first); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = parallel_FWD( CSize, RSize, _Fc, _Fr, RSize - 1, 4, true ); // printf("CPU BFS, 4 cores\t\t%f, %u vertices found\n", result.second, result.first); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = _CPU_BFS( CSize, RSize, _Fc, _Fr, RSize - 1, 1, true ); // printf("GCPU BFS, 1 cores\t\t%f\n", result.second); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = _CPU_BFS( CSize, RSize, _Fc, _Fr, RSize - 1, 2, true ); // printf("GCPU BFS, 2 cores\t\t%f\n", result.second); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = _CPU_BFS( CSize, RSize, _Fc, _Fr, RSize - 1, 3, true ); // printf("GCPU BFS, 3 cores\t\t%f\n", result.second); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // result = _CPU_BFS( CSize, RSize, _Fc, _Fr, RSize - 1, 4, true ); // printf("GCPU BFS, 4 cores\t\t%f\n", result.second); // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // CFB_vertex * _cfm = new CFB_vertex[ RSize - 1 ]; // result = _CPU_FB( CSize, RSize, _Fc, _Fr, _Bc, _Br, _cfm, RSize - 1, 4, true ); // printf("GCPU FB, 4 cores\t\t%f\n", result.second); // delete [] _cfm; // */ // /* // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // FB_vertex * _xm = new FB_vertex[ RSize - 1 ]; // result = Forward_only( CSize, RSize, _Fc, _Fr, _xm, 0, true ); // printf("GPU BFS:\t\t\t%f\n", result.second); // delete [] _xm; // // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // // FB_vertex * _fm = new FB_vertex[ RSize - 1 ]; // // result = FB_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _fm, false, true ); // // printf("%u Components.\n\n", result.first); // // printf("\n\t\t\t\tno Trimm\twith Trimm\n"); // // if ( result.second < Time_limit ) // // printf("FB:\t\t\t\t%f\t", result.second); // // else // // printf("FB:\t\t\t\t>%f\t", Time_limit); // // delete [] _fm; // // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // FB_vertex * _fm = new FB_vertex[ RSize - 1 ]; // result = FB_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _fm, false, true ); // if ( result.second < Time_limit ) // printf("FB:\t\t\t\t%f\t", result.second); // else // printf("FB:\t\t\t\t>%f\t", Time_limit); // delete [] _fm; // // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // FB_vertex * _fm2 = new FB_vertex[ RSize - 1 ]; // result = FB_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _fm2, true, true ); // if ( result.second < Time_limit ) // printf("%f\n", result.second); // else // printf(">%f\n", Time_limit); // delete [] _fm2; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // COL_vertex * _cm = new COL_vertex[ RSize - 1 ]; // result = COL_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _cm, MIN, true ); // if ( result.second < Time_limit ) // printf("Colouring Max-Min:\t\t%f\n", result.second); // else // printf("Colouring Max-Min:\t\t>%f\n", Time_limit); // delete [] _cm; // // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om01 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om01, false, 10000, false, true ); // if ( result.second < Time_limit ) // printf("OBF:\t\t\t\t%f\t", result.second); // else // printf("OBF:\t\t\t\t>%f\t", Time_limit); // delete [] _om01; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om, false, 10000, true, true ); // if ( result.second < Time_limit ) // printf("%f\n", result.second); // else // printf(">%f\n", Time_limit); // delete [] _om; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om21 = new OBF_vertex[ RSize - 1 ]; // uint32_t lim = (10000 < ((RSize - 2) / 100)) ? (RSize - 2) / 100 : 10000 ; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om21, true, lim, false, true ); // if ( result.second < Time_limit ) // printf("OBF+COL with %u limit:\t%f\t", lim, result.second); // else // printf("OBF+COL with %u limit:\t>%f\t", lim, Time_limit); // delete [] _om21; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om2 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om2, true, lim, true, true ); // if ( result.second < Time_limit ) // printf("%f\n", result.second); // else // printf(">%f\n", Time_limit); // delete [] _om2; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om31 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om31, true, 2 * lim, false, true ); // if ( result.second < Time_limit ) // printf("OBF+COL with %u limit:\t%f\t", 2 * lim, result.second); // else // printf("OBF+COL with %u limit:\t>%f\t", 2 * lim, Time_limit); // delete [] _om31; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om3 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om3, true, 2 * lim, true, true ); // if ( result.second < Time_limit ) // printf("%f\n", result.second); // else // printf(">%f\n", Time_limit); // delete [] _om3; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om41 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om41, true, 5 * lim, false, true ); // if ( result.second < Time_limit ) // printf("OBF+COL with %u limit:\t%f\t", 5 * lim, result.second); // else // printf("OBF+COL with %u limit:\t>%f\t", 5 * lim, Time_limit); // delete [] _om41; // // memcpy( _Fc, Fc, sizeof(Edge)*CSize ); // memcpy( _Fr, Fr, sizeof(uint32_t)*RSize ); // memcpy( _Bc, Bc, sizeof(Edge)*CSize ); // memcpy( _Br, Br, sizeof(uint32_t)*RSize ); // OBF_vertex * _om4 = new OBF_vertex[ RSize - 1 ]; // result = OBF_Decomposition( CSize, RSize, _Fc, _Fr, _Bc, _Br, _om4, true, 5 * lim, true, true ); // if ( result.second < Time_limit ) // printf("%f\n", result.second); // else // printf(">%f\n", Time_limit); // delete [] _om4; // printf("\n=======================================================\n\n"); // } // break; // */ // } // } // catch (const char * e) // { // printf("%s\n", e); // return 1; // } // // if (gen != NULL) // delete gen; // // if (!dve) { // delete[] Fr; // delete[] Fc; // delete[] Br; // delete[] Bc; // } // getchar(); // return 0; //}
[ "m.berenjkoub@gmail.com" ]
m.berenjkoub@gmail.com
e26b5d05dd093b49fbea00a286027c9d3922298a
b54c637d5c0e22b76f9f130949ccf2347ca98e9f
/Classes/Component/ExpComponent.cpp
8ab28a30afd4bbacade7dac959525bf8b5690106
[]
no_license
Fakeheart/wzry
c2305099c108bc7ea40db83e0f666b6967858561
1d27466211a4936439b81108bb9cc3c1db933f20
refs/heads/master
2020-05-31T07:14:03.552418
2019-06-02T08:12:19
2019-06-02T08:12:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,019
cpp
#include "ExpComponent.h" ExpComponent* ExpComponent::create(INT32 levelUpNeededExp) { ExpComponent* expComp = new (std::nothrow) ExpComponent; if (expComp && expComp->init(levelUpNeededExp)) { expComp->autorelease(); return expComp; } CC_SAFE_DELETE(expComp); return nullptr; } bool ExpComponent::init(INT32 levelUpNeededExp) { if (!Sprite::init()) { return false; } setTexture("rocker.png"); auto position = getPosition(); auto size = getContentSize(); _labelLevel = Label::create("1", "fonts/HELVETICAEXT-NORMAL.TTF", 20); _labelLevel->setPosition(position + size / 2 - Vec2(0, 2)); addChild(_labelLevel); _level = 1; _currentExp = 0; _levelUpNeededExp = levelUpNeededExp; return true; } bool ExpComponent::addExp(INT32 Exp) { _currentExp += Exp; if (_currentExp >= _levelUpNeededExp) { ++_level; _labelLevel->setString(StringUtils::format("%d", _level)); _currentExp -= _levelUpNeededExp; return true; } return false; }
[ "962461330@qq.com" ]
962461330@qq.com
acd0a79347b55e2e6f9282a85ba6dbdf9a6e2726
9855ec6453018614c249e3ecc4075398e200bbf0
/src/autoware/common/amathutils_lib/include/amathutils_lib/amathutils.hpp
af5d795f1762d834cfdf73136410edc5ad8cc1d6
[ "Apache-2.0" ]
permissive
qilei2333/autoware.ai-1.12.0
defc38995bbc6d57002a4c24a0848a0b7a15af26
0410bace9274966e5fdbe33862de1804b006a116
refs/heads/main
2023-07-16T09:11:26.280292
2021-09-04T13:03:27
2021-09-04T13:03:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,971
hpp
#ifndef __AMATHUTILS_HPP #define __AMATHUTILS_HPP #include <cmath> #include <iostream> // ROS Messages #include <geometry_msgs/Point.h> #include <geometry_msgs/Pose.h> #include <tf/tf.h> #include <tf2/utils.h> #include <tf2_geometry_msgs/tf2_geometry_msgs.h> namespace amathutils { #define G_MPSS 9.80665 // m/s^2 inline double rad2deg(double _angle) { return _angle * 180.0 / M_PI; } inline double deg2rad(double _angle) { return _angle / 180.0 * M_PI; } inline double mps2kmph(double _mpsval) { return (_mpsval * 3.6); // mps * 60sec * 60minutes / 1000m } inline double kmph2mps(double _kmphval) { return (_kmphval * 1000.0 / 60.0 / 60.0); // kmph * 1000m / 60sec / 60sec } inline double getGravityAcceleration(double _acceleration_mpss) { return _acceleration_mpss / G_MPSS; } inline double getAcceleration(double _v0, double _v, double _x) { return (_v * _v - _v0 * _v0) / 2.0 / _x; } inline double getTimefromAcceleration(double _v0, double _v, double _a) { return (_v - _v0) / _a; } geometry_msgs::Point getNearPtOnLine(const geometry_msgs::Point &_p, const geometry_msgs::Point &_a, const geometry_msgs::Point &_b); double find_distance(const geometry_msgs::Point &_from, const geometry_msgs::Point &_to); double find_distance(const geometry_msgs::Pose &_from, const geometry_msgs::Pose &_to); double find_angle(const geometry_msgs::Point &_from, const geometry_msgs::Point &_to); bool isIntersectLine(const geometry_msgs::Point &_l1_p1, const geometry_msgs::Point &_l1_p2, const geometry_msgs::Point &_l2_p1, const geometry_msgs::Point &_l2_p2); int isPointLeftFromLine(const geometry_msgs::Point &_target, const geometry_msgs::Point &_line_p1, const geometry_msgs::Point &_line_p2); /** * @fn distanceFromSegment * @brief calculates the distance between from a point to closest point on a line segment * @param _l1 first point of line segment * @param _l2 second point of line segment * @param _p the point to find distance * @return distance between point _p and line segment(_l1,_l2) */ double distanceFromSegment( const geometry_msgs::Point &_l1, const geometry_msgs::Point &_l2, const geometry_msgs::Point &_p); double getPoseYawAngle(const geometry_msgs::Pose &_pose); /** * @brief convert from yaw to ros-Quaternion * @param [in] yaw input yaw angle * @return quaternion */ geometry_msgs::Quaternion getQuaternionFromYaw(const double &_yaw); /** * @brief normalize angle into [-pi to pi] * @param [in] _angle input angle * @return normalized angle */ double normalizeRadian(const double _angle); double calcPosesAngleDiffRaw(const geometry_msgs::Pose &p_from, const geometry_msgs::Pose &_p_to); double calcPosesAngleDiffDeg(const geometry_msgs::Pose &_p_from, const geometry_msgs::Pose &_p_to); double calcPosesAngleDiffRad(const geometry_msgs::Pose &_p_from, const geometry_msgs::Pose &_p_to); } #endif
[ "1197833830@qq.com" ]
1197833830@qq.com
8997e33e540b4841b98b0fc146b88d6b79941982
0439d60e5fb8e707bfe095d349441b2e55e30b4c
/omi/Reforma/tests/solutions/ParcialB.cpp
a905515ceb6f2ff965d88736d1b2ad81bb836f2f
[]
no_license
ComiteMexicanoDeInformatica/OMI-2018
af08f92b7f10db0737077c03f9602189f4b76251
08402193ca9fa939d09f05357e82811c4883b32b
refs/heads/master
2021-05-01T16:07:33.975865
2018-05-06T19:36:41
2018-05-06T19:36:41
121,045,817
5
3
null
null
null
null
UTF-8
C++
false
false
388
cpp
#include <iostream> #define optimizar_io ios_base::sync_with_stdio(0);cin.tie(0); using namespace std; int A[100000]; int main(){ optimizar_io int n; cin >> n; for(int i = 0; i < n; i++) cin >> A[i]; int ans = 0; for(int i = 0; i < n; i++){ int j = i + 1; while(j < n && A[j] < A[j - 1]) j++; ans = max(ans, j - i); } cout << ans << "\n"; return 0; }
[ "me@freddy.mx" ]
me@freddy.mx
de46fb8db2bd41bcba621a1283082d042409ea0c
6a8c86b00be628f1c757f5d49d5babeadd36b50e
/src/key.h
d665ab607d00309530ca9e5f64b83e1ee4ec31a5
[ "MIT" ]
permissive
ezaruba/Espers
16b6dc7278dd69a5f1dfbfc69f246d138d44966c
532c6bf3d36aa649d183bdc180a3a3850d5b6be1
refs/heads/master
2020-03-06T23:52:56.047628
2018-02-07T18:16:12
2018-02-07T18:16:12
127,144,081
1
0
MIT
2018-03-28T13:25:52
2018-03-28T13:25:52
null
UTF-8
C++
false
false
10,783
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef ESPERS_KEY_H #define ESPERS_KEY_H #include <vector> #include "allocators.h" #include "serialize.h" #include "uint256.h" #include "hash.h" // secp256k1: // const unsigned int PRIVATE_KEY_SIZE = 279; // const unsigned int PUBLIC_KEY_SIZE = 65; // const unsigned int SIGNATURE_SIZE = 72; // // see www.keylength.com // script supports up to 75 for single byte push /** A reference to a CKey: the Hash160 of its serialized public key */ class CKeyID : public uint160 { public: CKeyID() : uint160(0) { } CKeyID(const uint160 &in) : uint160(in) { } }; /** A reference to a CScript: the Hash160 of its serialization (see script.h) */ class CScriptID : public uint160 { public: CScriptID() : uint160(0) { } CScriptID(const uint160 &in) : uint160(in) { } }; /** An encapsulated public key. */ class CPubKey { private: // Just store the serialized data. // Its length can very cheaply be computed from the first byte. unsigned char vch[65]; // Compute the length of a pubkey with a given first byte. unsigned int static GetLen(unsigned char chHeader) { if (chHeader == 2 || chHeader == 3) return 33; if (chHeader == 4 || chHeader == 6 || chHeader == 7) return 65; return 0; } // Set this key data to be invalid void Invalidate() { vch[0] = 0xFF; } public: // Construct an invalid public key. CPubKey() { Invalidate(); } // Initialize a public key using begin/end iterators to byte data. template<typename T> void Set(const T pbegin, const T pend) { int len = pend == pbegin ? 0 : GetLen(pbegin[0]); if (len && len == (pend-pbegin)) memcpy(vch, (unsigned char*)&pbegin[0], len); else Invalidate(); } // Construct a public key using begin/end iterators to byte data. template<typename T> CPubKey(const T pbegin, const T pend) { Set(pbegin, pend); } // Construct a public key from a byte vector. CPubKey(const std::vector<unsigned char> &vch) { Set(vch.begin(), vch.end()); } // Simple read-only vector-like interface to the pubkey data. unsigned int size() const { return GetLen(vch[0]); } const unsigned char *begin() const { return vch; } const unsigned char *end() const { return vch+size(); } const unsigned char &operator[](unsigned int pos) const { return vch[pos]; } // Comparator implementation. friend bool operator==(const CPubKey &a, const CPubKey &b) { return a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) == 0; } friend bool operator!=(const CPubKey &a, const CPubKey &b) { return !(a == b); } friend bool operator<(const CPubKey &a, const CPubKey &b) { return a.vch[0] < b.vch[0] || (a.vch[0] == b.vch[0] && memcmp(a.vch, b.vch, a.size()) < 0); } // Implement serialization, as if this was a byte vector. unsigned int GetSerializeSize(int nType, int nVersion) const { return size() + 1; } template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const { unsigned int len = size(); ::WriteCompactSize(s, len); s.write((char*)vch, len); } template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) { unsigned int len = ::ReadCompactSize(s); if (len <= 65) { s.read((char*)vch, len); } else { // invalid pubkey, skip available data char dummy; while (len--) s.read(&dummy, 1); Invalidate(); } } // Get the KeyID of this public key (hash of its serialization) CKeyID GetID() const { return CKeyID(Hash160(vch, vch+size())); } // Get the 256-bit hash of this public key. uint256 GetHash() const { return Hash(vch, vch+size()); } // Check syntactic correctness. // // Note that this is consensus critical as CheckSig() calls it! bool IsValid() const { return size() > 0; } // fully validate whether this is a valid public key (more expensive than IsValid()) bool IsFullyValid() const; // Check whether this is a compressed public key. bool IsCompressed() const { return size() == 33; } // Verify a DER signature (~72 bytes). // If this public key is not fully valid, the return value will be false. bool Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const; // Verify a compact signature (~65 bytes). // See CKey::SignCompact. bool VerifyCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) const; // Recover a public key from a compact signature. bool RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig); // Turn this public key into an uncompressed public key. bool Decompress(); // Derive BIP32 child pubkey. bool Derive(CPubKey& pubkeyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const; }; // secure_allocator is defined in allocators.h // CPrivKey is a serialized private key, with all parameters included (279 bytes) typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey; /** An encapsulated private key. */ class CKey { private: // Whether this private key is valid. We check for correctness when modifying the key // data, so fValid should always correspond to the actual state. bool fValid; // Whether the public key corresponding to this private key is (to be) compressed. bool fCompressed; // The actual byte data unsigned char vch[32]; // Check whether the 32-byte array pointed to be vch is valid keydata. bool static Check(const unsigned char *vch); public: // Construct an invalid private key. CKey() : fValid(false) { LockObject(vch); } // Copy constructor. This is necessary because of memlocking. CKey(const CKey &secret) : fValid(secret.fValid), fCompressed(secret.fCompressed) { LockObject(vch); memcpy(vch, secret.vch, sizeof(vch)); } // Destructor (again necessary because of memlocking). ~CKey() { UnlockObject(vch); } friend bool operator==(const CKey &a, const CKey &b) { return a.fCompressed == b.fCompressed && a.size() == b.size() && memcmp(&a.vch[0], &b.vch[0], a.size()) == 0; } // Initialize using begin and end iterators to byte data. template<typename T> void Set(const T pbegin, const T pend, bool fCompressedIn) { if (pend - pbegin != 32) { fValid = false; return; } if (Check(&pbegin[0])) { memcpy(vch, (unsigned char*)&pbegin[0], 32); fValid = true; fCompressed = fCompressedIn; } else { fValid = false; } } // Simple read-only vector-like interface. unsigned int size() const { return (fValid ? 32 : 0); } const unsigned char *begin() const { return vch; } const unsigned char *end() const { return vch + size(); } // Check whether this private key is valid. bool IsValid() const { return fValid; } // Check whether the public key corresponding to this private key is (to be) compressed. bool IsCompressed() const { return fCompressed; } // Initialize from a CPrivKey (serialized OpenSSL private key data). bool SetPrivKey(const CPrivKey &vchPrivKey, bool fCompressed); // Generate a new private key using a cryptographic PRNG. void MakeNewKey(bool fCompressed); // Convert the private key to a CPrivKey (serialized OpenSSL private key data). // This is expensive. CPrivKey GetPrivKey() const; // Compute the public key from a private key. // This is expensive. CPubKey GetPubKey() const; // Create a DER-serialized signature. bool Sign(const uint256 &hash, std::vector<unsigned char>& vchSig) const; // Create a compact signature (65 bytes), which allows reconstructing the used public key. // The format is one header byte, followed by two times 32 bytes for the serialized r and s values. // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y, // 0x1D = second key with even y, 0x1E = second key with odd y, // add 0x04 for compressed keys. bool SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const; // Derive BIP32 child key. bool Derive(CKey& keyChild, unsigned char ccChild[32], unsigned int nChild, const unsigned char cc[32]) const; // Load private key and check that public key matches. bool Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck); // Check whether an element of a signature (r or s) is valid. static bool CheckSignatureElement(const unsigned char *vch, int len, bool half); // Ensure that signature is DER-encoded static bool ReserealizeSignature(std::vector<unsigned char>& vchSig); }; struct CExtPubKey { unsigned char nDepth; unsigned char vchFingerprint[4]; unsigned int nChild; unsigned char vchChainCode[32]; CPubKey pubkey; friend bool operator==(const CExtPubKey &a, const CExtPubKey &b) { return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild && memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.pubkey == b.pubkey; } void Encode(unsigned char code[74]) const; void Decode(const unsigned char code[74]); bool Derive(CExtPubKey &out, unsigned int nChild) const; }; struct CExtKey { unsigned char nDepth; unsigned char vchFingerprint[4]; unsigned int nChild; unsigned char vchChainCode[32]; CKey key; friend bool operator==(const CExtKey &a, const CExtKey &b) { return a.nDepth == b.nDepth && memcmp(&a.vchFingerprint[0], &b.vchFingerprint[0], 4) == 0 && a.nChild == b.nChild && memcmp(&a.vchChainCode[0], &b.vchChainCode[0], 32) == 0 && a.key == b.key; } void Encode(unsigned char code[74]) const; void Decode(const unsigned char code[74]); bool Derive(CExtKey &out, unsigned int nChild) const; CExtPubKey Neuter() const; void SetMaster(const unsigned char *seed, unsigned int nSeedLen); }; /** Check that required EC support is available at runtime */ bool ECC_InitSanityCheck(void); #endif
[ "CryptoCoderz@gmail.com" ]
CryptoCoderz@gmail.com
90d2579c559fd3951f614880a35ea82caacb82b1
1c390cd4fd3605046914767485b49a929198b470
/atcoder/abc239_e.cpp
68cb9c0a9fa94045daca7db0ada83a284ee0ea4f
[]
no_license
wwwwodddd/Zukunft
f87fe736b53506f69ab18db674311dd60de04a43
03ffffee9a76e99f6e00bba6dbae91abc6994a34
refs/heads/master
2023-01-24T06:14:35.691292
2023-01-21T15:42:32
2023-01-21T15:42:32
163,685,977
7
8
null
null
null
null
UTF-8
C++
false
false
881
cpp
#include <bits/stdc++.h> using namespace std; int n, q, x, y; int w[100020]; int z[100020]; vector<int> a[100020]; vector<pair<int, int> > b[100020]; vector<int> dfs(int x, int y) { vector<int> u; u.push_back(w[x]); for (int i : a[x]) { if (i != y) { vector<int> v = dfs(i, x); copy(v.begin(), v.end(), back_inserter(u)); inplace_merge(u.begin(), u.end() - v.size(), u.end(), greater<int>()); u.resize(20); } } for (auto i : b[x]) { z[i.second] = u[i.first - 1]; } return u; } int main() { scanf("%d%d", &n, &q); for (int i = 1; i <= n; i++) { scanf("%d", &w[i]); } for (int i = 1; i < n; i++) { scanf("%d%d", &x, &y); a[x].push_back(y); a[y].push_back(x); } for (int i = 0; i < q; i++) { scanf("%d%d", &x, &y); b[x].push_back(make_pair(y, i)); } dfs(1, 0); for (int i = 0; i < q; i++) { printf("%d\n", z[i]); } return 0; }
[ "wwwwodddd@gmail.com" ]
wwwwodddd@gmail.com
8a00c4c7576d95aee9dc192745a7a8df90aad86f
3a3c43d6c1a3dbf95247fb9270f6f9010619a4a7
/CS10B/ZR_CS10B_5/ZR_CS10B_5.2.cpp
8c65e76b26d36a913ac5e36a79c049889195d50c
[]
no_license
zackr5759/Classwork-Year1
01e1785fa7e96f2dea7f6ea213e99274daa88bd7
7323f866f9c3c9239454057ef2dc9c5de0f7b0ab
refs/heads/master
2022-05-14T15:55:34.859467
2022-03-25T04:25:30
2022-03-25T05:41:23
190,300,745
2
0
null
2019-06-05T00:55:16
2019-06-05T00:49:31
null
UTF-8
C++
false
false
3,280
cpp
/* Zachary Robinson, CS10B, 2/28/2019, Dave Harden, ZR_CS10B_5.2 This program takes a user specified number of highscores with names attached. It allocates two arrays for the scores then calls initializeArrays to take in the actual scores and names from the user and assigns them to elements of the arrays. The program then calls sortData to rearrange the array elements from highest to lowest scoring player. Finally, the program calls displayData to print the list of scores. */ #include <iostream> #include <string> using namespace std; void initializeArrays(string names[], int scores[], int size); //Take user input and put scores and names //into their arrays. void sortData(string names[], int scores[], int size); //Loops through each number below the one being checked //and if bigger, swaps them. void displayData(const string names[], const int scores[], int size); //Displays contents of the two arrays. int main() { int size; cout << "How many scores will you enter?: "; cin >> size; string* names = new string[size]; //Allocate arrays from the heap based on the amount of scores to enter. int* scores = new int[size]; initializeArrays(names, scores, size); sortData(names, scores, size); displayData(names, scores, size); system("pause"); } void initializeArrays(string names[], int scores[], int size) { for (int count = 0; count < size; count++) { cout << "Enter the name for score # " << count + 1 << ": "; cin >> names[count]; cout << "Enter the score for score # " << count + 1 << ": "; cin >> scores[count]; } } void sortData(string names[], int scores[], int size) { int temp; string tempS; for (int count = 0; count < size - 1; count++) //This loop selects the top unsorted score. { for (int i = count + 1; i < size ; i++) //This loop runs through each score below the one being checked. { if (scores[count] < scores[i]) //If the lower score is bigger, they swap. { temp = scores[count]; scores[count] = scores[i]; scores[i] = temp; tempS = names[count]; names[count] = names[i]; names[i] = tempS; } } } } void displayData(const string names[], const int scores[], int size) { cout << "Top scorers: " << endl; for (int count = 0; count < size; count++) { cout << names[count] << ": " << scores[count] << endl; } } /* How many scores will you enter?: 4 Enter the name for score # 1: Suzy Enter the score for score # 1: 600 Enter the name for score # 2: Kim Enter the score for score # 2: 9900 Enter the name for score # 3: Armando Enter the score for score # 3: 8000 Enter the name for score # 4: Tim Enter the score for score # 4: 514 Top scorers: Kim: 9900 Armando: 8000 Suzy: 600 Tim: 514 How many scores will you enter?: 5 Enter the name for score # 1: a Enter the score for score # 1: 1 Enter the name for score # 2: b Enter the score for score # 2: 2 Enter the name for score # 3: c Enter the score for score # 3: 3 Enter the name for score # 4: d Enter the score for score # 4: 4 Enter the name for score # 5: e Enter the score for score # 5: 5 Top scorers: e: 5 d: 4 c: 3 b: 2 a: 1 */
[ "noreply@github.com" ]
noreply@github.com
1479a30c65e3897ab52cbbca174be4b238a772e6
1714b7387d8dae5a6169b4cf546657cb17db1a13
/Assg5/RBTree.hpp
bd0aab04668f31bcd64c316b79a6a46209922231
[]
no_license
parinaya-007/cs202-adsa
21071b72122eea62201d9aeac4ba76b7df3fb5aa
1d8f8fed6c151da245b5d8534dd775246292ce8f
refs/heads/master
2021-01-19T17:00:50.471685
2017-05-03T14:35:12
2017-05-03T14:35:12
88,298,952
0
0
null
null
null
null
UTF-8
C++
false
false
6,538
hpp
#ifndef RBTree_HPP_ #define RBTree_HPP_ 1 #include "BSTree.hpp" /* The color enumeration. * Please use this and not integers or characters to store the color of the node * in your red black tree. * Also create a class BinaryNode which should inherit from BinaryNode and has the attribute color in it. */ /*template <class Key, class Value> class BinaryNode : public BinaryNode<Key, Value> { public: Color color; BinaryNode(); BinaryNode(Key key, Value value); }; template <class Key,class Value> BinaryNode<Key,Value>::BinaryNode() { this->key=(Key)0; this->val=(Value)0; this->left=NULL; this->right=NULL; this->parent=NULL; } template <class Key,class Value> BinaryNode<Key,Value>::BinaryNode(Key key, Value value) { this->key=key; this->val=value; this->left=NULL; this->right=NULL; this->parent=NULL; } */ template <class Key, class Value> class RBTree : public BSTree<Key, Value> { /*It applies fixing mechanisms to make sure that the tree remains a valid red black tree after an insertion. */ public: RBTree() { this->root=NULL; } void insertRBFixup(BinaryNode<Key,Value>* root); void insert(Key k,Value v); /* It applies fixing mechanisms to make sure that the tree remains a valid red black tree after a deletion. */ void deleteRBFixup(BinaryNode<Key,Value>* root); void deletek(Key k); BinaryNode<Key,Value>* rightRotate(BinaryNode<Key,Value> *z); BinaryNode<Key,Value>* leftRotate(BinaryNode<Key,Value> *z); /* the black height of the red black tree which begins at node_ptr root */ int blackh(); void findk(BinaryNode<Key,Value> *root,Key& key,BinaryNode<Key,Value> **ret); int blackHeight(BinaryNode<Key,Value>* root); BinaryNode<Key,Value>* uncle(BinaryNode<Key,Value> *root); }; template <class Key, class Value> void RBTree<Key,Value>::findk(BinaryNode<Key,Value> *root,Key& key,BinaryNode<Key,Value> **ret) { if(root==NULL) *ret=NULL; if(key==root->key) { *ret=root; return; } else if(key<root->key) findk(root->left,key,ret); else findk(root->right,key,ret); } template <class Key, class Value> void RBTree<Key,Value>::insert(Key k,Value v) { pututil(&(this->root),k,v,this->root); BinaryNode<Key,Value> *ptr; findk(this->root,k,&ptr); //cout<<ptr->val; ptr->color=RED; insertRBFixup(ptr); } template <class Key, class Value> BinaryNode<Key,Value>* RBTree<Key,Value>::uncle(BinaryNode<Key,Value> *root) { if(root==NULL) return NULL; else if(root->parent==NULL) return NULL; else if(root->parent->parent==NULL) return NULL; else { if(root->parent->parent->left==root->parent) return root->parent->parent->right; else return root->parent->parent->left; } } template <class Key, class Value> void RBTree<Key,Value>::insertRBFixup(BinaryNode<Key,Value>* root) { //if(root==NULL) cout<<"hi"; if(root==this->root) root->color=BLACK; else if(root->parent->color!=BLACK) { //cout<<root->val; BinaryNode<Key,Value> *unc=uncle(root); Color col; if(unc) { if(unc->color==RED) { unc->color=BLACK; root->parent->color=BLACK; root->parent->parent->color=RED; insertRBFixup(root->parent->parent); } else if(unc->color==BLACK) { BinaryNode<Key,Value>* x=root; BinaryNode<Key,Value>* p=root->parent; BinaryNode<Key,Value>* g=root->parent->parent; if(p==g->left && x==p->left) { rightRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->left && x==p->right) { leftRotate(p); rightRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->right && x==p->right) { leftRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->right && x==p->left) { rightRotate(p); leftRotate(g); col=g->color; g->color=p->color; p->color=col; } } } else { BinaryNode<Key,Value>* x=root; BinaryNode<Key,Value>* p=root->parent; BinaryNode<Key,Value>* g=root->parent->parent; if(p==g->left && x==p->left) { rightRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->left && x==p->right) { leftRotate(p); rightRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->right && x==p->right) { leftRotate(g); col=g->color; g->color=p->color; p->color=col; } else if(p==g->right && x==p->left) { rightRotate(p); leftRotate(g); col=g->color; g->color=p->color; p->color=col; } } } } template <class Key, class Value> void RBTree<Key,Value>::deletek(Key k) { } template <class Key, class Value> void RBTree<Key,Value>::deleteRBFixup(BinaryNode<Key,Value>* root) { } template <class Key, class Value> int RBTree<Key,Value>::blackh() { return blackHeight(this->root); } template <class Key, class Value> int RBTree<Key,Value>::blackHeight(BinaryNode<Key,Value> * current) { if(current==NULL) return 0; else if(current->left == NULL || current->right ==NULL) return 1; else if(current->left->color == BLACK) return (1+blackHeight(current->left)); else return blackHeight(current->left); } template <class Key,class Value> BinaryNode<Key,Value>* RBTree<Key,Value>::rightRotate(BinaryNode<Key,Value> *z) { BinaryNode<Key,Value> *y = z->left; BinaryNode<Key,Value> *T2 = y->right; y->parent = z->parent; if(z->parent==NULL) {this->root=y;} else if(z->parent->left==z) {z->parent->left=y;} else if(z->parent->right==z) {z->parent->right=y;} if(T2) T2->parent=z; z->parent= y; z->left = T2; y->right = z; return y; } template <class Key,class Value> BinaryNode<Key,Value>* RBTree<Key,Value>::leftRotate(BinaryNode<Key,Value> *z) { BinaryNode<Key,Value> *y = z->right; BinaryNode<Key,Value> *T2 = y->left; y->parent = z->parent; if(z->parent==NULL) {this->root=y;} else if(z->parent->left==z) {z->parent->left=y;} else if(z->parent->right==z) {z->parent->right=y;} if(T2) T2->parent=z; z->parent= y; z->right = T2; y->left = z; return y; } #endif /* ifndef RBTree_HPP_ */
[ "parinayachaturvedi@gmail.com" ]
parinayachaturvedi@gmail.com
432014084e964077b467e8a954ce92caae3e7749
7dc67a956d5516c8c8d9234861ec21b8d9111213
/Leet2015/Leet2015/Pow.cpp
25cebe456da1b6ab74d06ac8addc2b6bdb302418
[]
no_license
flameshimmer/leet2015
285a1f4f0c31789e1012a7c056797915662611ba
45297dfe330a16f001fb0b2c8cc3df99b2c76dda
refs/heads/master
2021-01-22T05:15:40.849200
2015-08-15T19:46:43
2015-08-15T19:46:43
31,512,278
0
0
null
null
null
null
UTF-8
C++
false
false
840
cpp
#include "stdafx.h" //Implement pow(x, n). namespace Solution1 { double pow(double x, int n) { if (n == 0) { return 1; } if (n == 1) { return x; } bool isNeg = n < 0; if (isNeg) { n = -n; } double half = pow(x, n / 2); double result; if (n % 2 == 1) { result = half * half * x; } else { result = half* half; } return isNeg ? 1 / result : result; } namespace other { double pow(double x, int n) { if (n == 0) { return 1; } if (n == 1) { return x; } bool isNeg = n < 0; if (isNeg) { n = -n; } double half = x; double result = 1; while (n>0) { if (n % 2 == 1) { result *= half; } half *= half; n = n / 2; } return isNeg ? 1 / result : result; } } void Pow() { using namespace other; other::pow(5.0, 5); other::pow(6.0, 4); } }
[ "nm1072@gmail.com" ]
nm1072@gmail.com
b2622eeb369ae0f4950639009eb63bc56e289792
febf32873cd46c5cd143f9bf878c43f0c0073825
/Square.h
ca73b5b86aad6161b9f261f32eee17f7ce15c88e
[]
no_license
natali1821/figures
81d5265b99ee65c10f79e2980d89b59cc790ee56
5d1f55ece4721913f9e0a8121434bba14e42054c
refs/heads/master
2023-03-22T06:56:52.690958
2021-03-15T15:35:49
2021-03-15T15:35:49
348,019,175
0
0
null
null
null
null
UTF-8
C++
false
false
172
h
#ifndef SQUARE_H_INCLUDED #define SQUARE_H_INCLUDED #include "Rectangle.h" class Square : public Rectangle { public: Square(double a); }; #endif // SQUARE_H_INCLUDED
[ "ermolina_natali@bk.ru" ]
ermolina_natali@bk.ru
12d50dfd4a5be308546f1556dbedb9c31ce8faf1
90937e7447ad1ccc65a67389e94833ae029d58be
/old/ext_examples/futexes_are_tricky/inter_process_synchronization.cpp
151c7a7cbc3f247dd0ea9c17d9440c75bffeb65f
[]
no_license
mauro7x/futex
85669551aa9986063671518e468f953621324e66
07fa0337c871fb62fa761d7984df225acfd52e25
refs/heads/master
2023-06-09T09:34:22.819663
2021-06-29T19:39:42
2021-06-29T19:39:42
293,366,312
1
0
null
null
null
null
UTF-8
C++
false
false
778
cpp
// 7. Inter-Process #include <fcntl.h> #include <sys/mman.h> #include <sys/stat.h> #include "paper_interfaces.h" class Mutex2 { private: int val; public: Mutex2() : val(0) {} void lock() { int c; if ((c = cmpxchg(val, 0, 1)) != 0) do { if (c == 2 || cmpxchg(val, 1, 2) != 0) futex_wait(&val, 2); } while ((c = cmpxchg(val, 0, 2)) != 0); } void unlock() { if (atomic_dec(val) != 1) { val = 0; futex_wake(&val, 1); } } }; int main() { int fd = shm_open("/global-mutex", O_RDWR, 0); void *p = mmap(NULL, sizeof(Mutex2), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); Mutex2 *m = new (p) Mutex2(); return 0; }
[ "mparafati@fi.uba.ar" ]
mparafati@fi.uba.ar
c34361c9f242b02c8f0b60aa657197dca6b677a1
9eb2245869dcc3abd3a28c6064396542869dab60
/benchspec/CPU/510.parest_r/src/source/lac/chunk_sparse_matrix.cc
8e6af641a22422873738dab3d20ae68157cbf53b
[]
no_license
lapnd/CPU2017
882b18d50bd88e0a87500484a9d6678143e58582
42dac4b76117b1ba4a08e41b54ad9cfd3db50317
refs/heads/master
2023-03-23T23:34:58.350363
2021-03-24T10:01:03
2021-03-24T10:01:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
706
cc
//--------------------------------------------------------------------------- // $Id: chunk_sparse_matrix.cc 16496 2008-08-06 05:00:56Z bangerth $ // Version: $Name$ // // Copyright (C) 2008 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //--------------------------------------------------------------------------- #include <lac/chunk_sparse_matrix.templates.h> #include <lac/block_vector.h> DEAL_II_NAMESPACE_OPEN #include "../lac/chunk_sparse_matrix.inst" DEAL_II_NAMESPACE_CLOSE
[ "cuda@hp-arm64-09-02.nvidia.com" ]
cuda@hp-arm64-09-02.nvidia.com
33c1e8d429e00e13f2cb46e84f0f8f9824670a8d
f5d1d394cc345c1c2c8df104597eacc274edcb4d
/PizzaDelivery/src/Pizza.cpp
1ee393dddbe4deef70c5165744c11370772053bb
[]
no_license
IvanLazarov1/workspace2
2c83a87857b6300f26e1d1c40a42793ea2d18075
14ca375c521f6ffc6442698894eb504c555c8e13
refs/heads/master
2021-01-20T12:42:02.623282
2017-06-23T20:31:20
2017-06-23T20:31:20
90,395,415
0
0
null
null
null
null
UTF-8
C++
false
false
455
cpp
/* * Pizza.cpp * * Created on: Apr 20, 2017 * Author: asdf */ #include "Pizza.h" using namespace std; Pizza::Pizza(string name, size_t price) { setName(name); setPrice(price); } Pizza::~Pizza() { // Auto-generated destructor stub } string Pizza::getName() { return m_name; } void Pizza::setName(string name) { m_name = name; } size_t Pizza::getPrice(){ return m_price; } void Pizza::setPrice(size_t price) { m_price = price; }
[ "vrx@abv.bg" ]
vrx@abv.bg
8f6a9fa56f970cb3134060e6ffda18fb08c5a456
10b105c96b8759b0ce69052a051d3e4b0cd6c970
/airstrike/ResourceHolder/ResourceHolder.hpp
a246724bffcd91ea672b7918bce3d221dab6c961
[]
no_license
montreal91/airstrike-sfml
4e83b3e1e24adffa09e72925dcd020617623ac4a
e397b28ea4b9c1397c7b6a00cd45ce9aeb335c5b
refs/heads/master
2021-01-14T12:16:07.770971
2015-07-02T11:54:39
2015-07-02T11:54:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
744
hpp
#ifndef __RESOURCE_HOLDER_H__ #define __RESOURCE_HOLDER_H__ #include <cassert> #include <map> #include <memory> #include <stdexcept> #include <string> #include <SFML/Graphics.hpp> template <typename Resource, typename Identifier> class AResourceHolder { public: void LoadResourceFromFile( Identifier id, const std::string& filename ); template <typename Parameter> void LoadResourceFromFile( Identifier id, const std::string& filename, const Parameter& second_param ); Resource& GetResource( Identifier id ); const Resource& GetResource( Identifier id ) const; private: std::map<Identifier, Resource*> resource_map; }; #include "ResourceHolder.inl" #endif
[ "montreal@ip-192-168-0-109.is74.loc" ]
montreal@ip-192-168-0-109.is74.loc
c1ec8c0968bfda63fbe227f7e1682c92ac599909
4b630e22db0216720e3097bdebe62a884e554012
/1106/exp1.cpp
76493f289c84d614626e480108d49014f2c4e3ea
[]
no_license
nyanshell/Gestapolur-Code-Storage
98da5662164cf4dac931a876200e595ae2b667df
3bd949da41dc8d7cacfe1792a2b3acaaeaa38c66
refs/heads/master
2021-05-28T04:37:29.718337
2012-05-30T07:26:04
2012-05-30T07:26:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,287
cpp
//5 #include<iostream> #include<string> #define MAXN 1000//最多容纳的学生数目 #define MAXM 1000//最多容纳的课程数目 using namespace std; class student { public: string name; int id; int totc; string cl[ MAXM ]; int score[ MAXM ]; }; student stu[ MAXN ]; int stot;//学生总数 void count( ) { int val[ 6 ];//各个分数段的人数 int i , j ; for( i = 1 ; i <= stot ; ++ i ) for( j = 1 ; j <= stu[ i ].totc ; ++ j ) if( stu[ i ].score[ j ] > 89 ) ++val[ 1 ]; else if( stu[ i ].score[ j ] > 79) ++val[ 2 ]; else if( stu[ i ].score[ j ] > 69) ++val[ 3 ]; else if( stu[ i ].score[ j ] > 59) ++val[ 4 ]; else ++val[ 5 ]; cout<<"优秀 "<<val[ 1 ]<<"人,占总人数的 "<<double(val[ 1 ])/double(stot); cout<<"良好"<<val[ 2 ]<<"人,占总人数的 "<<double(val[ 2 ])/double(stot); cout<<"中等"<<val[ 3 ]<<"人,占总人数的 "<<double(val[ 3 ])/double(stot); cout<<"及格"<<val[ 4 ]<<"人,占总人数的 "<<double(val[ 4 ])/double(stot); cout<<"不及格"<<val[ 5 ]<<"人,占总人数的 "<<double(val[ 5 ])/double(stot); return ; } int main() { int n , i , j , k , ins = 1 , stid , id; string m,name; while( ins ){ cout<<" 1.输入数据\n 2.显示所有输入数据\n 3.查询学生成绩\n 4.统计成绩分布\n 其他:退出 \n"; cin>>ins; if( ins == 1 )//输入某门课的学生数据 { cout<<"输入课程名称m和该课程n个学生的成绩: \n"; cin>>m>>n; for( i = 1 ; i <= n ; ++ i ) { cout<<"输入学生ID和学生名字\n"; cin>>stid>>name;//学生id,名字 for( i = 1 ; i <= stot ; ++ i )//在所有学生中查找该学生并添加该门课的成绩 if( stid == stu[ i ].id ) { ++stu[ i ].totc; cin>>stu[ i ].score[ stu[ i ].totc ];//输入成绩 stu[ i ].cl[ stu[ i ].totc ] = m; break; } if( i == stot + 1 )//如果没有这个学生,则增加该学生 { ++stot; stu[ stot ].name = name; ++stu[ stot ].totc; cin>>stu[ stot ].score[ stu[ stot ].totc ]; stu[ stot ].cl[ stu[ stot ].totc ] = m ; } } } else if( ins == 2 )//显示所有输入数据 { for( i = 1 ; i <= stot ; ++ i ) { cout<<stu[ i ].name<<" "<<stu[ i ].id<<"\n"; for( j = 1 ; j <= stu[ i ].totc ; ++ j ) cout<<stu[ i ].cl[ j ]<<" "<<stu[ i ].score[ j ]<<"\n"; } } else if( ins == 3 )//search { cout<<"输入 1 + 学生ID 或 2 + 学生名字 查找学生\n"; cin>>ins; if( ins == 1 ) { cin>>id; for( i = 1 ; i <= stot ; ++ i ) if( stu[ i ].id == id ) { cout<<stu[ i ].name<<" "<<stu[ i ].id<<"\n"; for( j = 1 ; j <= stu[ i ].totc ; ++ j ) cout<<stu[ i ].cl[ j ]<<" "<<stu[ i ].score[ j ]<<"\n"; break; } if( i == stot + 1 ) cout<<"没有找到\n"; } else { cin>>name; for( i = 1 ; i <= stot ; ++ i ) if( stu[ i ].name == name ) { cout<<stu[ i ].name<<" "<<stu[ i ].id<<"\n"; for( j = 1 ; j <= stu[ i ].totc ; ++ j ) cout<<stu[ i ].cl[ j ]<<" "<<stu[ i ].score[ j ]<<"\n"; break; } if( i == stot + 1 ) cout<<"没有找到\n"; } } else if( ins == 4 )//统计成绩分布 count(); else break; } return 0; }
[ "gestapolur@gmail" ]
gestapolur@gmail
24293692fab55e424bb2c3ff1d1e1ea084eda909
79a2b47b6a6c903a243773b0c69ab25623edcbe0
/Task2/Lab1_2/Lights.cpp
fcd5e423dc197888d640f4ea70a0eb562257ce2f
[]
no_license
7kia/CG
3a9bb11f3018d16c38c809d79536ec0dea7703df
5a532afd685113b3a13a03dd03b08bf86cfef4bd
refs/heads/master
2020-04-12T09:03:30.731305
2016-12-18T17:49:53
2016-12-18T17:50:13
61,549,242
0
0
null
null
null
null
UTF-8
C++
false
false
2,255
cpp
#include "stdafx.h" #include "Lights.h" #include <iostream> #include <glm/gtc/type_ptr.hpp> namespace { } CAbstractLightSource::CAbstractLightSource(unsigned index) : m_index(index) { } void CAbstractLightSource::SetupImpl() const { // Включаем источник света с заданным индексом. // Источник действует только когда включен режим GL_LIGHTING! glEnable(GLenum(m_index)); glLightfv(m_index, GL_AMBIENT, glm::value_ptr(m_ambient)); glLightfv(m_index, GL_DIFFUSE, glm::value_ptr(m_diffuse)); glLightfv(m_index, GL_SPECULAR, glm::value_ptr(m_specular)); } unsigned CAbstractLightSource::GetIndex() const { return m_index; } CDirectedLightSource::CDirectedLightSource(unsigned index) : CAbstractLightSource(index) , CHaveDirection() { } void CDirectedLightSource::Setup() const { SetupImpl(); // Если GL_POSITION установить как (x, y, z, 0), т.е. как вектор // в однородных координатах, источник света будет направленным. glLightfv(GetIndex(), GL_POSITION, glm::value_ptr(m_direction)); } CPositionLightSource::CPositionLightSource(unsigned index) : CAbstractLightSource(index) , CHavePosition() { m_position = { 0.f, 0.f, 0.f, 1.f }; } void CPositionLightSource::Setup() const { SetupImpl(); // Если GL_POSITION установить как (x, y, z, 1), т.е. как точку // в однородных координатах, источник света будет точечным. glLightfv(GetIndex(), GL_POSITION, glm::value_ptr(m_position)); } CPhongModelMaterial::CPhongModelMaterial() : CHaveEmission() , CHaveAmbient() , CHaveDiffuse() , CHaveSpecular() , CHaveShininess() { } void CPhongModelMaterial::Setup() const { glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, glm::value_ptr(m_emission)); glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, glm::value_ptr(m_ambient)); glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, glm::value_ptr(m_diffuse)); glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, glm::value_ptr(m_specular)); glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, m_shininess); }
[ "il7kia@yandex.ru" ]
il7kia@yandex.ru
6fd3e39e469999baa098c1096fd05c7634f1e890
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/old_hunk_4705.cpp
45f2e40c12c7d74793b1e394c67f8b530cd9e590
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
756
cpp
const char **pathspec = get_pathspec(prefix, argv); if (!pathspec) die("invalid path specification"); if (patch_mode) return interactive_checkout(new.name, pathspec, &opts); /* Checkout paths */ if (opts.new_branch) { if (argc == 1) { die("git checkout: updating paths is incompatible with switching branches.\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]); } else { die("git checkout: updating paths is incompatible with switching branches."); } } if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge) die("git checkout: --ours/--theirs, --force and --merge are incompatible when\nchecking out of the index."); return checkout_paths(source_tree, pathspec, &opts); }
[ "993273596@qq.com" ]
993273596@qq.com
4abfef38dd2c919ef281cb4b08d1da8ffa9d02cd
053f1a3df314db938107e6aec66ecdd8caf75042
/10048 - Audiophobia/audiophobia.cpp
76df4325158e6a38a9e8ad4f2ab7fab81838bc9e
[]
no_license
yuting-zhang/UVa
70cedd7f12b1cdca31688f2926ceac8c4c48f8e5
9ab1380d62f1b9479b8a82af7233d6f2a7d07732
refs/heads/master
2021-01-20T17:03:30.651083
2017-03-01T07:15:57
2017-03-01T07:15:57
48,550,831
4
0
null
null
null
null
UTF-8
C++
false
false
2,540
cpp
#include <iostream> #include <cstdio> #include <vector> #include <algorithm> #include <utility> using namespace std; class DisjointSets{ public: void assign(int n){ s.assign(n, -1); } int find(int elem){ return s[elem] < 0 ? elem : s[elem] = find(s[elem]); } bool isSameSet(int elem1, int elem2){ return find(elem1) == find(elem2); } void setUnion(int elem1, int elem2){ int root1 = find(elem1), root2 = find(elem2); if (root1 != root2){ int newSize = s[root1] + s[root2]; if (s[root1] <= s[root2]){ s[root2] = root1; s[root1] = newSize; } else{ s[root1] = root2; s[root2] = newSize; } } } private: vector<int> s; }; vector<vector<pair<int, int>>> adjList; vector<pair<int, pair<int, int>>> edgeList; int C, S, Q; DisjointSets dsets; vector<bool> visited; int answer; bool DFS(int node, int dest){ visited[node] = true; if (node == dest) return true; for (pair<int, int>& it: adjList[node]){ int next = it.first, d = it.second; if (!visited[next] && DFS(next, dest)){ answer = max(d, answer); return true; } } return false; } int main(){ int test_case = 0; while (scanf("%d %d %d", &C, &S, &Q) && (C || S || Q)){ test_case++; if (test_case > 1) printf("\n"); printf("Case #%d\n", test_case); adjList.assign(C, vector<pair<int, int>>()); edgeList.assign(S, pair<int, pair<int, int>>()); dsets.assign(C); for (int i = 0; i < S; i++){ int c1, c2, d; scanf("%d %d %d", &c1, &c2, &d); c1--, c2--; edgeList[i] = {d, {c1, c2}}; } sort(edgeList.begin(), edgeList.end()); for (auto it: edgeList){ int d = it.first, u = it.second.first, v = it.second.second; if (!dsets.isSameSet(u, v)){ adjList[u].push_back({v, d}); adjList[v].push_back({u, d}); dsets.setUnion(u, v); } } for (int i = 0; i < Q; i++){ int c1, c2; answer = 0; visited.assign(C, false); scanf("%d %d", &c1, &c2); c1--, c2--; if (DFS(c1, c2)) printf("%d\n", answer); else printf("no path\n"); } } return 0; }
[ "ytyt96@live.com" ]
ytyt96@live.com
ec27a96b49201b3383867ed112e6d347424e87cb
ac0b9c85542e6d1ef59c5e9df4618ddf22223ae0
/kratos/applications/structural_application/constitutive_laws/vonmiseskinemver3d.h
654792f5b74bb4e5269509c26c8e8e4be6296e1d
[]
no_license
UPC-EnricBonet/trunk
30cb6fbd717c1e78d95ec66bc0f6df1a041b2b72
1cecfe201c8c9a1b87b2d87faf8e505b7b1f772d
refs/heads/master
2021-06-04T05:10:06.060945
2016-07-15T15:29:00
2016-07-15T15:29:00
33,677,051
3
0
null
null
null
null
UTF-8
C++
false
false
10,057
h
/* ============================================================================== KratosStructuralApplication A library based on: Kratos A General Purpose Software for Multi-Physics Finite Element Analysis Version 1.0 (Released on march 05, 2007). Copyright 2007 Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel pooyan@cimne.upc.edu rrossi@cimne.upc.edu janosch.stascheit@rub.de nagel@sd.rub.de - CIMNE (International Center for Numerical Methods in Engineering), Gran Capita' s/n, 08034 Barcelona, Spain - Ruhr-University Bochum, Institute for Structural Mechanics, Germany 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 condition: Distribution of this code for any commercial purpose is permissible ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS. 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. ============================================================================== */ /* ********************************************************* * * Last Modified by: $Author: janosch $ * Date: $Date: 2008-10-23 12:22:22 $ * Revision: $Revision: 1.1 $ * * ***********************************************************/ #if !defined(KRATOS_VON_MISES_KINEMVER_3D_H_INCLUDED ) #define KRATOS_VON_MISES_3D_KINEMVER_H_INCLUDED // System includes // External includes // Project includes #include "includes/define.h" #include "includes/serializer.h" #include "includes/variables.h" #include "includes/constitutive_law.h" namespace Kratos { /** * Defines an elastic-plastic constitutive law in 3D space with linear isotropic hardening. * This material law is defined by the parameters K (Kompression modulus), MU (Shear modulus), Y0 (Yielding Stress), * H (Hardening Modulus) and ALPHA (Hardening Parameter). */ class VonMisesKinemVer3D : public ConstitutiveLaw<Node<3> > { public: /** * Type Definitions */ typedef ConstitutiveLaw<Node<3> > BaseType; /** * Counted pointer of VonMisesKinemVer3D */ KRATOS_CLASS_POINTER_DEFINITION(VonMisesKinemVer3D); /** * Life Cycle */ /** * Default constructor. */ VonMisesKinemVer3D(); virtual ConstitutiveLaw<Node<3> >::Pointer Clone() const { ConstitutiveLaw<Node<3> >::Pointer p_clone(new VonMisesKinemVer3D()); return p_clone; } /** * Destructor. */ virtual ~VonMisesKinemVer3D(); /** * Operators */ /** * Operations */ bool Has( const Variable<double>& rThisVariable ); bool Has( const Variable<Vector>& rThisVariable ); bool Has( const Variable<Matrix>& rThisVariable ); double GetValue( const Variable<double>& rThisVariable ); Vector GetValue( const Variable<Vector>& rThisVariable ); Matrix GetValue( const Variable<Matrix>& rThisVariable ); void SetValue( const Variable<double>& rThisVariable, const double& rValue, const ProcessInfo& rCurrentProcessInfo ); void SetValue( const Variable<array_1d<double, 3> >& rThisVariable, const array_1d<double, 3>& rValue, const ProcessInfo& rCurrentProcessInfo ); void SetValue( const Variable<Vector>& rThisVariable, const Vector& rValue, const ProcessInfo& rCurrentProcessInfo ); void SetValue( const Variable<Matrix>& rThisVariable, const Matrix& rValue, const ProcessInfo& rCurrentProcessInfo ); /** * Material parameters are inizialized */ void InitializeMaterial( const Properties& props, const GeometryType& geom, const Vector& ShapeFunctionsValues ); /** * Calculates the constitutive matrix for a given strain vector * @param StrainVector the current vector of strains the constitutive * matrix is to be generated for * @param rResult Matrix the result will be stored in */ void CalculateConstitutiveMatrix(const Vector& StrainVector, Matrix& rResult); /** * Calculates the stresses for given strain state * @param StrainVector the current vector of strains * @param rResult the stress vector corresponding to the given strains */ void CalculateStress(const Vector& StrainVector, Vector& rResult); // void CalculateStressAndTangentMatrix(Vector& StressVector, // const Vector& StrainVector, // Matrix& algorithmicTangent); // void VonMisesKinemVer3D::CalculateCauchyStresses( Vector& rCauchy_StressVector, const Matrix& rF, Vector& rPK2_StressVector, const Vector& GreenLagrangeStrainVector); /** * As this constitutive law describes only linear elastic material properties * this function is rather useless and in fact does nothing */ void InitializeSolutionStep( const Properties& props, const GeometryType& geom, //this is just to give the array of nodes const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo); void UpdateMaterial( const Vector& StrainVector, const Properties& props, const GeometryType& geom, //this is just to give the array of nodes const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo); void FinalizeSolutionStep( const Properties& props, const GeometryType& geom, //this is just to give the array of nodes const Vector& ShapeFunctionsValues , const ProcessInfo& CurrentProcessInfo); /** * Calculates the cauchy stresses. For a given deformation and stress state * the cauchy stress vector is calculated * @param Cauchy_StressVector the result vector of cauchy stresses (will be overwritten) * @param F the current deformation gradient * @param PK2_StressVector the current second Piola-Kirchhoff-Stress vector * @param GreenLagrangeStrainVector the current Green-Lagrangian strains */ // void CalculateCauchyStresses( Vector& Cauchy_StressVector, // const Matrix& F, // const Vector& PK2_StressVector, // const Vector& GreenLagrangeStrainVector); /** * converts a strain vector styled variable into its form, which the * deviatoric parts are no longer multiplied by 2 */ // void Calculate(const Variable<Matrix >& rVariable, Matrix& rResult, const ProcessInfo& rCurrentProcessInfo); /** * Input and output */ /** * Turn back information as a string. */ //virtual String Info() const; /** * Print information about this object. */ //virtual void PrintInfo(std::ostream& rOStream) const; /** * Print object's data. */ //virtual void PrintData(std::ostream& rOStream) const; protected: /** * there are no protected class members */ private: ///@} ///@name Serialization ///@{ friend class Serializer; virtual void save(Serializer& rSerializer) const { KRATOS_SERIALIZE_SAVE_BASE_CLASS(rSerializer, ConstitutiveLaw); } virtual void load(Serializer& rSerializer) { KRATOS_SERIALIZE_LOAD_BASE_CLASS(rSerializer, ConstitutiveLaw); } /** * Static Member Variables */ /** * calculates elastic-plastic constitutive matrix with Kompression modulus, Shear modulus, Yielding Stress, * Hardening Modulus and Hardening Parameter. * @param K the Kompression Modulus * @param MU the Shear Modulus * @return the linear elastic constitutive matrix */ void CalculateElasticMatrix(Matrix& C, double K, double MU); // double mK,mMU,mY0,mH,mALPHA,mdALPHA; double f_history; // Matrix mC; // Matrix mCtangent; // Matrix mCtangent_neu; // Vector mInSituStress; // Vector mCurrentStress; // Vector mPlasticStrainVector; // Vector mOldPlasticStrainVector; // Vector dPlasticStrainVector; // Vector ElasticStrainVector; // Vector DevElasticTrialStrainVector; double mK; double mMU; double mSigmaY0; double mH; double mAlpha; double mCurrentAlpha; double mBeta; Vector mRho; Vector mCurrentRho; Vector mCurrentStress; Vector mPlasticStrainVector; Vector mCurrentPlasticStrainVector; Matrix mCtangent; Matrix mCelastic; Vector mInSituStress; Matrix mIdev; /** * Un accessible methods */ /** * Assignment operator. */ //VonMisesKinemVer3D& operator=(const VonMisesIsotropVerPlaneStressWrinklingNew& rOther); /** * Copy constructor. */ //VonMisesKinemVer3D(const VonMisesIsotropVerPlaneStressWrinklingNew& rOther); }; // Class VonMisesKinemVer3D } // namespace Kratos. #endif // KRATOS_VON_MISES_3D_H_INCLUDED defined
[ "enriquebonetgil@hotmail.com" ]
enriquebonetgil@hotmail.com
ab8e79c316ac3383120449bc46136a67ea322e0d
964743cc9072f09d3d60a88ddd90971e48e8a956
/NewGeneUI/NewGene/Infrastructure/UIAction/vgmanagement.h
06d8968fb2f4d7363c77e3489481e641ed2f78c2
[]
no_license
daniel347x/newgene
f6a7abae718bc4b3813c6adf2c2f991dca535954
dc0b5ddaeea441d905d627a4145d7a3e2eda78b5
refs/heads/master
2022-06-27T17:19:42.205690
2022-06-21T21:52:07
2022-06-21T21:52:07
9,526,888
0
2
null
2022-06-21T21:52:08
2013-04-18T16:55:22
C
UTF-8
C++
false
false
3,650
h
#ifndef VGMANAGEMENT_H #define VGMANAGEMENT_H #include "../../../../NewGeneBackEnd/UIAction/ActionWidgets.h" #include "../Project/inputprojectworkqueue.h" #include "../Project/outputprojectworkqueue.h" #include "../Messager/uimessager.h" #include "../Messager/uimessagersingleshot.h" #include "../UIAction/uiuiactionmanager.h" #include "uiaction.h" #include "../Project/uiinputproject.h" #include "../Project/uioutputproject.h" class CreateVG_ : public DoInputAction<ACTION_CREATE_VG> { public: CreateVG_(WidgetActionItemRequest_ACTION_CREATE_VG & action_request_, InputProjectWorkQueue * queue_) : DoInputAction<ACTION_CREATE_VG>(static_cast<WidgetActionItemRequest_ACTION_CREATE_VG>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().CreateVG(messager.get(), action_request, queue->get()->backend()); } }; class DeleteVG_ : public DoInputAction<ACTION_DELETE_VG> { public: DeleteVG_(WidgetActionItemRequest_ACTION_DELETE_VG & action_request_, InputProjectWorkQueue * queue_) : DoInputAction<ACTION_DELETE_VG>(static_cast<WidgetActionItemRequest_ACTION_DELETE_VG>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().DeleteVG(messager.get(), action_request, queue->get()->backend()); } }; class SetVGDescriptions_ : public DoInputAction<ACTION_SET_VG_DESCRIPTIONS> { public: SetVGDescriptions_(WidgetActionItemRequest_ACTION_SET_VG_DESCRIPTIONS & action_request_, InputProjectWorkQueue * queue_) : DoInputAction<ACTION_SET_VG_DESCRIPTIONS>(static_cast<WidgetActionItemRequest_ACTION_SET_VG_DESCRIPTIONS>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().SetVGDescriptions(messager.get(), action_request, queue->get()->backend()); } }; class RefreshVG_ : public DoInputAction<ACTION_REFRESH_VG> { public: RefreshVG_(WidgetActionItemRequest_ACTION_REFRESH_VG & action_request_, InputProjectWorkQueue * queue_) : DoInputAction<ACTION_REFRESH_VG>(static_cast<WidgetActionItemRequest_ACTION_REFRESH_VG>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().RefreshVG(messager.get(), action_request, queue->get()->backend()); } }; class DeleteVG_Output : public DoOutputAction<ACTION_DELETE_VG> { public: DeleteVG_Output(WidgetActionItemRequest_ACTION_DELETE_VG & action_request_, OutputProjectWorkQueue * queue_) : DoOutputAction<ACTION_DELETE_VG>(static_cast<WidgetActionItemRequest_ACTION_DELETE_VG>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().DeleteVGOutput(messager.get(), action_request, queue->get()->backend()); } }; class SetVGDescriptions_Output : public DoOutputAction<ACTION_SET_VG_DESCRIPTIONS> { public: SetVGDescriptions_Output(WidgetActionItemRequest_ACTION_SET_VG_DESCRIPTIONS & action_request_, OutputProjectWorkQueue * queue_) : DoOutputAction<ACTION_SET_VG_DESCRIPTIONS>(static_cast<WidgetActionItemRequest_ACTION_SET_VG_DESCRIPTIONS>(action_request_), queue_) { } void operator()() { UIMessagerSingleShot messager(queue->get()->messager); uiactionManagerUI().getBackendManager().SetVGDescriptionsOutput(messager.get(), action_request, queue->get()->backend()); } }; #endif // VGMANAGEMENT_H
[ "daniel347x@gmail.com" ]
daniel347x@gmail.com
d505cc958f10b24ce1998d31813809fe20038e46
427aa69c17b2a7db3343d0db98e5405bb92bc00d
/WanderMath/EulerAngles.h
d2640e2923054af53c56378eeca86047ec7c869f
[]
no_license
WanderPig/WanderMath
f6b1c0416709d1135b01a2eaf69fbb0cbd4dc8e8
41c5e0b21d4be900f3fe11dc93d5623cb1ba18d8
refs/heads/master
2016-09-03T07:24:12.840446
2013-01-05T07:21:53
2013-01-05T07:21:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,599
h
////////////////////////////////////////////////////////////////// // // name: EulerAngles.h // func: 利用欧拉角定位方向 // disc: 来源于3D Math Primer for Graphics and Game Development // /////////////////////////////////////////////////////////////////// #pragma once // 声明 class Quaternion; class Matrix4X3; class RotationMatrix; // 欧拉角类 class EulerAngles { public: EulerAngles(); EulerAngles(float h, float p, float b):heading(h),pitch(p),bank(b){} void Init(float h, float p, float b) { heading = h; pitch = p; bank = b; } // 归零 void Zero() { heading = pitch = bank = 0.0f; } // 将角度标准化 化到-PI到PI void Canonize(); // 用一个由物体坐标系向惯性坐标系转化的四元数初始化欧拉角 void FromObjectToInertialQuaternion(const Quaternion &q); // 用一个由惯性坐标系向物体坐标系转化的四元数初始化欧拉角 void FromInertialToObjectQuaternion(const Quaternion &q); // 用一个由物体坐标系向世界坐标系转化的4X3矩阵初始化欧拉角 void FromObjectToWorldMatrix(const Matrix4X3 &m); // 用一个由世界坐标系向物体坐标系转化的4X3矩阵初始化欧拉角 void FromWorldToObjectMatrix(const Matrix4X3 &m); // 用一个旋转矩阵初始化欧拉角 void FormRotationMatrix(const RotationMatrix &m); public: // 航向 float heading; // 俯仰 float pitch; // 左右倾斜 float bank; };
[ "121640121" ]
121640121
5f841415cabd853b1e512625907b67e78d342a06
e2e3a6e53e5ac62d216b2e6359865c763bf45432
/Chapter6/EXC6_33.cpp
84ae024cc850b08439982130018fc6ee2f4c89f1
[]
no_license
AyiStar/CppPrimer
b34b4fc7843977e2ead715c6772147d0e9d35875
7b48ba28d2fc41581edcb4812e69e2c98fa90ab0
refs/heads/master
2021-01-11T00:22:21.265069
2017-03-15T12:16:26
2017-03-15T12:16:26
77,778,019
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
// // Created by ayistar on 1/14/17. // // write a recursive function // to print the contents of a vector #include <iostream> #include <vector> void PrintVec(std::vector<int>::iterator beg, std::vector<int>::iterator end) { if(beg == end) return; else{ std::cout << *beg << std::endl; PrintVec(++beg, end); } } int main() { std::vector<int> v = {2,3,5,7,11,13,17,19}; PrintVec(v.begin(), v.end()); return 0; }
[ "824476660@qq.com" ]
824476660@qq.com
7992fe27e417e9422dffd13077ff9fc3165ceeae
ddc92ff5a327517745f29abc10f8ba16f3dc3873
/sensor/firmware/RFM95.h
07829d8c1bef92cfef5c898cea7ab5bf4a1026b3
[]
no_license
ElectronicsWorks/sense
830ba2f6721d058bc3ce252f56c4c3d28dc279df
dd6ce4a4a68533cef15df3da95e86104e67a6d51
refs/heads/master
2023-02-28T14:19:10.919261
2021-02-01T11:24:38
2021-02-01T11:24:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,548
h
#pragma once #include "TypeDef.h" #include "Module.h" #include <string.h> #include "Chrono.h" // SX127X_REG_VERSION #define RFM95_CHIP_VERSION 0x11 #define SX127X_SYNC_WORD 0x12 // 7 0 default LoRa sync word class RFM95 { public: // constructor RFM95(Module* mod); // basic methods int8_t begin(float freq = 434.0, float bw = 125.0, uint8_t sf = 9, uint8_t cr = 7, uint8_t syncWord = SX127X_SYNC_WORD, int8_t power = 17, uint8_t currentLimit = 100, uint16_t preambleLength = 8, uint8_t gain = 0); int8_t transmit(uint8_t* data, uint8_t len); int8_t receive(uint8_t* data, uint8_t& len); int8_t receive(uint8_t* data, uint8_t& len, chrono::millis timeout); int8_t startReceiving(); int8_t getReceivedPackage(uint8_t* data, uint8_t& len, bool& gotIt); int8_t stopReceiving(); int8_t sleep(); int8_t standby(); // configuration methods int8_t setFrequency(float freq); int8_t setSyncWord(uint8_t syncWord); int8_t setCurrentLimit(uint8_t currentLimit); int8_t setPreambleLength(uint16_t preambleLength); int8_t setBandwidth(float bw); int8_t setSpreadingFactor(uint8_t sf); int8_t setCodingRate(uint8_t cr); int8_t setOutputPower(int8_t power); int8_t setGain(uint8_t gain); int16_t getRSSI(); float getSNR(); int8_t setBitRate(float br); int8_t setFrequencyDeviation(float freqDev); chrono::millis computeAirTimeUpperBound(uint8_t length); #ifdef KITELIB_DEBUG void regDump(); #endif protected: Module* _mod; float _freq; float _bw; uint8_t _sf; uint8_t _cr; uint16_t _preambleLength; bool _sleeping = false; bool _isReceivingPacket = false; struct TC { int16_t symbolLengthUS = 0; int16_t t1 = 0; int16_t t2 = 0; int16_t rxTimeoutSymbols = 0; int16_t rxTimeoutMS = 0; } _tc; int8_t tx(char* data, uint8_t length); int8_t rxSingle(char* data, uint8_t* length); int8_t setFrequencyRaw(float newFreq); int8_t setBandwidthRaw(uint8_t newBandwidth); int8_t setSpreadingFactorRaw(uint8_t newSpreadingFactor); int8_t setCodingRateRaw(uint8_t newCodingRate); int8_t config(); uint8_t getActiveModem(); void refreshTimeoutConstants(); void refreshRXTimeoutConstants(); private: bool findChip(uint8_t ver); int8_t setMode(uint8_t mode, bool checked = true); int8_t setActiveModem(uint8_t modem); void clearIRQFlags(); };
[ "catalin.vasile@gmail.com" ]
catalin.vasile@gmail.com
6696aab9bdd85d568e0cde98f8360f31fa6d1e92
3ce8e51d8d0dbbe08a50438cea183ae5c3f41c37
/cpp/src/leetcode/list_merge_k_sorted_lists.cpp
0f9e7d5a309829916e0bb6d1709cb029717df635
[]
no_license
dabaosod011/leetcode
889f336de174fdf74637f9002a751ad3fd426927
994c9bd69c7e5e3732b766ad8e61b78326064e38
refs/heads/master
2020-04-05T16:11:11.261423
2016-12-07T02:41:45
2016-12-07T02:41:45
23,316,721
0
0
null
null
null
null
UTF-8
C++
false
false
2,894
cpp
#include "lc_header.h" /** * https://oj.leetcode.com/problems/merge-k-sorted-lists/ */ namespace merge_k_sorted_lists { class Solution { public: ListNode *mergeKLists(vector<ListNode *> &lists) { if(lists.size() == 0) return NULL; if(lists.size() == 1) return lists[0]; ListNode *head = lists[0]; for (int i=1; i<lists.size(); i++) { // merge head and lists[i] ListNode *second = lists[i]; ListNode *newhead = NULL; if(head == NULL) { newhead = second; continue; } if(second == NULL) { newhead = head; continue; } if(head->val < second->val) { newhead = head; head = head->next; } else { newhead = second; second = second->next; } ListNode *newtail = newhead; while(head!=NULL && second!=NULL) { if(head->val < second->val) { newtail->next = head; head = head->next; } else { newtail->next = second; second = second->next; } newtail = newtail->next; } if(head != NULL) newtail->next = head; if(second != NULL) newtail->next = second; head = newhead; } return head; } }; }; BOOST_AUTO_TEST_SUITE( merge_k_sorted_lists_test ) boost::shared_ptr<merge_k_sorted_lists::Solution> solution_(new merge_k_sorted_lists::Solution()); BOOST_AUTO_TEST_CASE( case1 ) { std::cout << "running merge_k_sorted_lists_test case1..." <<std::endl; std::vector<int> nodes1 = boost::assign::list_of(1)(4)(7)(10)(12)(16)(17)(18)(19)(20); std::vector<int> nodes2 = boost::assign::list_of(2)(5)(8)(11)(13)(21)(22)(23)(24)(25); std::vector<int> nodes3 = boost::assign::list_of(3)(6)(9)(12)(15)(26)(27)(28)(29)(30); ListNode *head1 = createLinkedList(nodes1); ListNode *head2 = createLinkedList(nodes2); ListNode *head3 = createLinkedList(nodes3); vector<ListNode* > lists; lists.push_back(head1); lists.push_back(head2); lists.push_back(head3); ListNode *head = solution_->mergeKLists(lists); dispayLinkedList(head); destoryLinkedlist(head); } BOOST_AUTO_TEST_CASE( case2 ) { std::cout << "running merge_k_sorted_lists_test case2..." <<std::endl; vector<ListNode* > lists; for (int i=0; i < 20000; i++) { std::vector<int> nodes; nodes.push_back(std::rand()); ListNode *head1 = createLinkedList(nodes); lists.push_back(head1); } ListNode *newhead = solution_->mergeKLists(lists); /*dispayLinkedList(newhead);*/ destoryLinkedlist(newhead); } BOOST_AUTO_TEST_CASE( case3 ) { std::cout << "running merge_k_sorted_lists_test case3..." <<std::endl; ListNode *head = NULL; vector<ListNode* > lists; lists.push_back(head); ListNode *newhead = solution_->mergeKLists(lists); dispayLinkedList(newhead); destoryLinkedlist(newhead); } BOOST_AUTO_TEST_SUITE_END()
[ "dabaosod011@gmail.com" ]
dabaosod011@gmail.com
d77963457f3cafc3f2b769f222165743b9b1e3e5
5b956901fceb2c6549d74c5904644c4fdd40d900
/old_project/0/source/temp/graphics_/opengl/opengl_index_buffer.cpp
5bf67b8928648560c82f92a12852b434df48629f
[ "MIT", "BSD-2-Clause" ]
permissive
tsukushibito/tempura_old
a65e251a9341b39f845b09552caca49ffa0c1496
173773e9180adbb0b4fe3b89f28399314f26ac7d
refs/heads/master
2021-09-28T18:53:17.311156
2018-11-19T15:22:08
2018-11-19T15:22:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,045
cpp
#include "temp/graphics_/opengl/opengl_index_buffer.h" #ifdef TEMP_GRAPHICS_OPENGL #include "temp/graphics_/opengl/opengl_define.h" #include "temp/graphics_/opengl/opengl_common.h" namespace temp { namespace graphics_ { namespace opengl { const ByteData OpenGLIndexBuffer::data() const { auto future = device_thread_->pushJob([this]() { glCallWithErrorCheck(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, nativeHandle()); GLint size; glCallWithErrorCheck(glGetBufferParameteriv, GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size); ByteData byte_data(size); auto mapped = glCallWithErrorCheck(glMapBuffer, GL_ELEMENT_ARRAY_BUFFER, GL_READ_ONLY); memcpy(&byte_data[0], mapped, size); glCallWithErrorCheck(glUnmapBuffer, GL_ELEMENT_ARRAY_BUFFER); glCallWithErrorCheck(glBindBuffer, GL_ELEMENT_ARRAY_BUFFER, 0); return byte_data; }); return future.get(); } } } } #endif
[ "yusuke@yusuke-mac.local" ]
yusuke@yusuke-mac.local
f0b6167c756d4b2351a8a57ef72732aaa7466405
be573168682c525e0f2021e1011673e98fc704cd
/graph/gfgraph_view.cpp
658e59e4ea6aad313100dd2e8d665a0a22338fba
[]
no_license
janesma/grafips
ced0ea3855f4ccea24a6bd1d386a8b05f9c88039
cb8a58ee052d19ddd2fc922ae471447d72d93935
refs/heads/master
2020-12-26T04:26:16.107150
2016-07-26T21:11:56
2016-07-26T21:11:56
24,871,831
1
1
null
null
null
null
UTF-8
C++
false
false
12,243
cpp
// Copyright (C) Intel Corp. 2014. 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 (including the // next paragraph) 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 COPYRIGHT OWNER(S) AND/OR ITS SUPPLIERS 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. // **********************************************************************/ // * Authors: // * Mark Janes <mark.a.janes@intel.com> // **********************************************************************/ #include "graph/gfgraph_view.h" #include <assert.h> #include <math.h> #include <QtOpenGL> #include <GLES2/gl2.h> #include <map> #include <vector> using Grafips::GraphViewRenderer; using Grafips::GraphView; #define GL_CHECK() CheckError(__FILE__, __LINE__) const char * GraphViewRenderer::vshader = "attribute vec2 coord2d;\n" "uniform float x_range; /* max milliseconds to display */\n" "uniform float max_y; /* max y value */\n" "void main(void) {\n" " /* map the x value (ms age) into the range -1 <-> 1 */\n" " float x = -2.0 * (coord2d.x / x_range) + 1.0;\n" " /* map the x value (data point) into the range -1 <-> 1 */\n" " float y = -2.0 * (coord2d.y / max_y) + 1.0;\n" " gl_Position = vec4(x, y, 0, 1);\n" "}"; const char * GraphViewRenderer::fshader = "uniform vec4 line_color;" "void main(void) {" " gl_FragColor = line_color;" "}"; float tick_lines_color[4] = { 0, 0, 0, .2 }; float black[4] = { 0, 0, 0, 1 }; float brown[4] = {165.0 / 255.0, 42.0/255.0, 42.0/255.0, 1}; float blue[4] = {0.0 / 255.0, 0.0/255.0, 255.0/255.0, 1}; float slategrey[4] = {112.0 / 255.0, 128.0/255.0, 144.0/255.0, 1}; float cornflowerblue[4] = {100.0 / 255.0, 149.0/255.0, 237.0/255.0, 1}; float orchid[4] = {218.0 / 255.0, 112.0/255.0, 214.0/255.0, 1}; GraphViewRenderer::GraphViewRenderer(const GraphView *v, GraphSetSubscriber *s, const PublisherInterface &p) : m_subscriber(s), m_graph_max(0), m_stopped(false) { connect(this, SIGNAL(maxChanged()), v, SLOT(update())); glGenBuffers(1, &vbo); GL_CHECK(); glBindBuffer(GL_ARRAY_BUFFER, vbo); GL_CHECK(); const int vs = glCreateShader(GL_VERTEX_SHADER); GL_CHECK(); int len = strlen(vshader); glShaderSource(vs, 1, &vshader, &len); GL_CHECK(); glCompileShader(vs); PrintCompileError(vs); const int fs = glCreateShader(GL_FRAGMENT_SHADER); GL_CHECK(); len = strlen(fshader); glShaderSource(fs, 1, &fshader, &len); GL_CHECK(); glCompileShader(fs); PrintCompileError(fs); prog = glCreateProgram(); glAttachShader(prog, vs); GL_CHECK(); glAttachShader(prog, fs); GL_CHECK(); glLinkProgram(prog); GL_CHECK(); attribute_coord2d = glGetAttribLocation(prog, "coord2d"); GL_CHECK(); uniform_x_range = glGetUniformLocation(prog, "x_range"); GL_CHECK(); uniform_max_y = glGetUniformLocation(prog, "max_y"); GL_CHECK(); uniform_line_color = glGetUniformLocation(prog, "line_color"); GL_CHECK(); glBindBuffer(GL_ARRAY_BUFFER, 0); GL_CHECK(); } QOpenGLFramebufferObject * GraphViewRenderer::createFramebufferObject(const QSize &size) { QOpenGLFramebufferObjectFormat format; format.setSamples(20); return new QOpenGLFramebufferObject(size, format); } GraphViewRenderer::~GraphViewRenderer() { while (!m_sets.empty()) { m_subscriber->RemoveSet(m_sets.begin()->first); delete m_sets.begin()->second; m_sets.erase(m_sets.begin()); } } void GraphViewRenderer::RenderPoints(const GraphSet::PointVec &data, const float* color, float max_y) { if (data.empty() ) return; // static unsigned int last_size = 0; // if (last_size != data.size()) // { // std::cout << "size: " << data.size() << std::endl; // for (unsigned int i = 0; i < data.size(); ++i ) // { // std::cout << data[i].x << "," << data[i].y << std::endl; // } // } // last_size = data.size(); glBindBuffer(GL_ARRAY_BUFFER, vbo); GL_CHECK(); glBufferData(GL_ARRAY_BUFFER, data.size() * sizeof(GraphSet::Point), data.data(), GL_STATIC_DRAW); GL_CHECK(); glEnableVertexAttribArray(attribute_coord2d); GL_CHECK(); glVertexAttribPointer(attribute_coord2d, // attribute 2, // number of elements // per vertex, here // (x,y) GL_FLOAT, // the type of each element GL_FALSE, // take our values as-is 0, // no space between values 0); // use the vertex buffer object GL_CHECK(); // GLint t = GetTimeOffset(); // assert(t >= 0); // assert(t <2000); // float x_offset = t / 1000.0; GL_CHECK(); glUniform4f(uniform_line_color, color[0], color[1], color[2], color[3]); glUniform1f(uniform_x_range, 60000); GL_CHECK(); glUniform1f(uniform_max_y, max_y); GL_CHECK(); glDrawArrays(GL_LINE_STRIP, 0, data.size()); GL_CHECK(); // x_offset = -2.0 + (t / 1000.0); // glDrawArrays(GL_LINE_STRIP, 0, t); // GL_CHECK(); glDisableVertexAttribArray(attribute_coord2d); GL_CHECK(); glBindBuffer(GL_ARRAY_BUFFER, 0); GL_CHECK(); } void GraphViewRenderer::UpdateMax() { float max = 0; for (std::map<int, GraphSet *>::const_iterator set = m_sets.begin(); set != m_sets.end(); ++set) { const float set_max = set->second->GetMax(); if (set_max > max) max = set_max; } if (max <= m_graph_max && max > m_graph_max * .9) // max is still in the range being graphed return; if (max == 0) return; const int power_of_ten_exponent = log10(max) - 1; const float power_of_ten = exp10f(power_of_ten_exponent); int mantissa = max / power_of_ten; // add a bit of space to the top of the graph mantissa += 1; if ((mantissa) * power_of_ten != m_graph_max) { m_graph_max = mantissa * power_of_ten; emit maxChanged(); } } // to support freezing the graph after disconnect, we need to keep the // last valid render time. If we don't continue to render() after // disconnect, the UI will be misdrawn during window resize. static unsigned int last_time; void GraphViewRenderer::render() { UpdateMax(); float horizontal_line_interval = m_graph_max / 5; glClearColor(1, 1, 1, 1); GL_CHECK(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); GL_CHECK(); glUseProgram(prog); GL_CHECK(); // render the cross-lines representing 20,40,60,80 % float horizontal_line = horizontal_line_interval; glLineWidth(2); m_data.resize(2); m_data[0].x = 100 * 1000; m_data[1].x = 0; while (horizontal_line && horizontal_line < m_graph_max) { m_data[0].y = horizontal_line; m_data[1].y = horizontal_line; RenderPoints(m_data, tick_lines_color, m_graph_max); horizontal_line += horizontal_line_interval; } // render the per-10s vertical lines if (! m_stopped) // after disconnect, continue to render the last view of the graph // data. last_time = get_ms_time(); const unsigned int t = last_time; unsigned int age_of_10_sec = t % 10000; // const float offset_t = 1.0 - (static_cast<float>(t % 10000))/10000.0; // const float line_distance = 2.0 * 10.0 / 60.0; // vertical line m_data[0].y = -1; m_data[1].y = 2 * m_graph_max; m_data[0].x = age_of_10_sec; m_data[1].x = age_of_10_sec; // m_data[1].x = m_data[0].x; m_data[1].y = 1; while (age_of_10_sec < 60 * 1000) { // std::cout << m_data[0].x << ", " << m_data[0].y << " : "; // std::cout << m_data[1].x << ", " << m_data[1].y << std::endl; RenderPoints(m_data, tick_lines_color, m_graph_max); age_of_10_sec += 10 * 1000; m_data[0].x = age_of_10_sec; m_data[1].x = age_of_10_sec; } glLineWidth(1); for (std::map<int, GraphSet *>::iterator set = m_sets.begin(); set != m_sets.end(); ++set) { set->second->GetData(&m_data, t); float * color = black; auto color_find = m_id_colors.find(set->first); if (color_find != m_id_colors.end()) color = color_find->second; RenderPoints(m_data, color, m_graph_max); } update(); } void GraphViewRenderer::CheckError(const char * file, int line) { if (glGetError() == GL_NO_ERROR) return; printf("ERROR: %s:%i\n", file, line); exit(-1); } void GraphViewRenderer::PrintCompileError(GLint shader) { GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); if (status == GL_TRUE) return; static const int MAXLEN = 1024; std::vector<char> log(MAXLEN); GLsizei len; glGetShaderInfoLog(shader, MAXLEN, &len, log.data()); printf("ERROR -- compile failed: %s\n", log.data()); } void GraphViewRenderer::synchronize(QQuickFramebufferObject * item) { // inform the GraphView of the max, so it can draw the y-axis units GraphView *gv = dynamic_cast<GraphView*>(item); if (gv->isStopped()) { m_stopped = true; return; } if (0 != m_graph_max) { assert(gv != NULL); gv->setGraphMax(m_graph_max); } gv->GetColors(&m_id_colors); // call the subscriber to make a one-time request for the metrics // to be graphed. if (!m_sets.empty()) return; std::vector<int> ids; m_subscriber->GetIDs(&ids); for (std::vector<int>::iterator i = ids.begin(); i != ids.end(); ++i) { const int id = *i; GraphSet *gs = new GraphSet(); m_sets[id] = gs; m_subscriber->AddSet(id, gs); } } GraphView::GraphView() : m_pub(NULL), m_subscriber(), m_stopped(false) { setTextureFollowsItemSize(true); } QQuickFramebufferObject::Renderer * GraphView::createRenderer() const { assert(m_pub); // causes synchronize() to be called in GraphViewRenderer, after // metric descriptions are received. connect(m_pub, SIGNAL(onEnabled()), this, SLOT(update())); QQuickFramebufferObject::Renderer * renderer = new GraphViewRenderer(this, // not sure why createRenderer has to be const const_cast<GraphSetSubscriber*>(&m_subscriber), *m_pub); return renderer; } GraphView::~GraphView() { } void GraphView::setGraphMax(float m) { if (m_graph_max == m) return; m_graph_max = m; emit onGraphMax(); } void GraphView::setColor(int id, QString color) { m_colors[id] = color; update(); } void GraphView::GetColors(std::map<int, float*> *c) { for (auto i = m_colors.begin(); i != m_colors.end(); ++i) { if (i->second.compare("black") == 0) { (*c)[i->first] = black; continue; } if (i->second.compare("brown") == 0) { (*c)[i->first] = brown; continue; } if (i->second.compare("blue") == 0) { (*c)[i->first] = blue; continue; } if (i->second.compare("slategrey") == 0) { (*c)[i->first] = slategrey; continue; } if (i->second.compare("cornflowerblue") == 0) { (*c)[i->first] = cornflowerblue; continue; } if (i->second.compare("orchid") == 0) { (*c)[i->first] = orchid; continue; } } } void GraphView::stop() { m_stopped = true; update(); }
[ "mark.a.janes@intel.com" ]
mark.a.janes@intel.com
37d18cb821fa6e3a7557b253d41fcf60e0605661
b062712093ef492b158d495d0f03c1b544f69e97
/Sources fournies/graphe.h
5f9a429ee6841ea0c8ef6816ea6eb0ccf463189a
[]
no_license
VinceBro/algo_tp2
695de753b8e8932a44132208ae9bc71f5fb25842
06295f5da59e4746bdcf57f358322082247cc4ed
refs/heads/master
2020-09-01T17:43:33.027088
2019-11-10T01:19:11
2019-11-10T01:19:11
219,018,660
0
0
null
null
null
null
UTF-8
C++
false
false
1,122
h
// // Graphe.h // Classe pour graphes orientés pondérés (non négativement) avec listes d'adjacence // // Mario Marchand automne 2016. // #ifndef GRAPH_H #define GRAPH_H #include <vector> #include <list> #include <set> #include <stack> #include <queue> #include <limits> #include <iostream> #include <algorithm> //! \brief Classe pour graphes orientés pondérés (non négativement) avec listes d'adjacence class Graphe { public: explicit Graphe(size_t = 0); void resize(size_t); void ajouterArc(size_t i, size_t j, unsigned int poids); void enleverArc(size_t i, size_t j); unsigned int getPoids(size_t i, size_t j) const; size_t getNbSommets() const; size_t getNbArcs() const; unsigned int plusCourtChemin(size_t p_origine, size_t p_destination, std::vector<size_t> & p_chemin) const; private: struct Arc { Arc(size_t dest, unsigned int p) : destination(dest), poids(p) { } size_t destination; unsigned int poids; }; std::vector<std::list<Arc> > m_listesAdj; /*!< les listes d'adjacence */ unsigned long m_nbArcs; }; #endif //GRAPH_H
[ "vincent.breault.1@ulaval.ca" ]
vincent.breault.1@ulaval.ca
3c8e6ce03781c320aba142e04a346eb60586dec7
492502cbfdda5425c95e59718b897e2a74363fbe
/Plugins/CustomPin/Source/CustomPin/Public/Pin/NestedNamesFromConfigPin.h
2bb500bb8279dc8ee35ed006325387de0f93d0bb
[ "Apache-2.0" ]
permissive
Malilith/UE4-HowTo-CustomPin
efca9fd5be6173840a3d647e04a00c2e912042af
b9331a5d3d036534901fa8e20c0a4c6f010d18af
refs/heads/master
2022-06-06T08:59:50.517060
2020-04-23T12:24:05
2020-04-23T12:24:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,061
h
// Copyright 2020-present Nans Pellicari (nans.pellicari@gmail.com). // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include "CoreMinimal.h" #include "SGraphPin.h" #include "SlateBasics.h" #include "Widgets/DeclarativeSyntaxSupport.h" #include "Widgets/SWidget.h" class SNameComboBox; // You can also check files in the engine to see a lot of examples here: // [UE4 directory]\Engine\Source\Editor\GraphEditor\Private\KismetPins\SGraphPinCollisionProfile.h class SNestedNamesFromConfigPin : public SGraphPin { public: SLATE_BEGIN_ARGS(SNestedNamesFromConfigPin) {} SLATE_END_ARGS() public: void Construct(const FArguments& InArgs, UEdGraphPin* InGraphPinObj); protected: // this override is used to display slate widget used for customization. virtual TSharedRef<SWidget> GetDefaultValueWidget() override; void OnCategorySelected(TSharedPtr<FName> ItemSelected, ESelectInfo::Type SelectInfo); void OnNameSelected(TSharedPtr<FName> ItemSelected, ESelectInfo::Type SelectInfo); void OnCategoryComboBoxOpening(); void OnNameComboBoxOpening(); void UpdateNames(const FName& Name); TSharedPtr<FName> GetSelectedName(const bool bIsCategory) const; void SetPropertyWithName(const FName& Category, const FName& Name); void GetPropertyAsName(const bool bIsCategory, FName& OutName) const; private: TMap<TSharedPtr<FName>, TArray<TSharedPtr<FName>>> AttributesList; TArray<TSharedPtr<FName>> Categories; TArray<TSharedPtr<FName>> SubNames; TSharedPtr<SNameComboBox> ConfigComboBox; TSharedPtr<SNameComboBox> NameComboBox; };
[ "nans.pellicari@gmail.com" ]
nans.pellicari@gmail.com
e4d8322358e3a508a5741a5071155fe1d1461f1f
59c94d223c8e1eb1720d608b9fc040af22f09e3a
/zircon/system/ulib/fit/include/lib/fit/traits.h
933005e5d1fc778273ab0346307a277e6a297492
[ "BSD-3-Clause", "MIT" ]
permissive
bootingman/fuchsia2
67f527712e505c4dca000a9d54d3be1a4def3afa
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
refs/heads/master
2022-12-25T20:28:37.134803
2019-05-14T08:26:08
2019-05-14T08:26:08
186,606,695
1
1
BSD-3-Clause
2022-12-16T21:17:16
2019-05-14T11:17:16
C++
UTF-8
C++
false
false
4,070
h
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef LIB_FIT_TRAITS_H_ #define LIB_FIT_TRAITS_H_ #include <tuple> #include <type_traits> namespace fit { // C++ 14 compatible implementation of std::void_t. #if defined(__cplusplus) && __cplusplus >= 201703L template <typename... T> using void_t = std::void_t<T...>; #else template <typename... T> struct make_void { typedef void type; }; template <typename... T> using void_t = typename make_void<T...>::type; #endif // Encapsulates capture of a parameter pack. Typical use is to use instances of this empty struct // for type dispatch in function template deduction/overload resolution. // // Example: // template <typename Callable, typename... Args> // auto inspect_args(Callable c, parameter_pack<Args...>) { // // do something with Args... // } // // template <typename Callable> // auto inspect_args(Callable c) { // return inspect_args(std::move(c), typename callable_traits<Callable>::args{}); // } template <typename... T> struct parameter_pack { static constexpr size_t size = sizeof...(T); template <size_t i> using at = typename std::tuple_element_t<i, std::tuple<T...>>; }; // |callable_traits| captures elements of interest from function-like types (functions, function // pointers, and functors, including lambdas). Due to common usage patterns, const and non-const // functors are treated identically. // // Member types: // |args| - a |parameter_pack| that captures the parameter types of the function. See // |parameter_pack| for usage and details. // |return_type| - the return type of the function. // |type| - the underlying functor or function pointer type. This member is absent if // |callable_traits| are requested for a raw function signature (as opposed to a // function pointer or functor; e.g. |callable_traits<void()>|). // |signature| - the type of the equivalent function. template <typename T> struct callable_traits : public callable_traits<decltype(&T::operator())> {}; // Treat mutable call operators the same as const call operators. // // It would be equivalent to erase the const instead, but the common case is lambdas, which are // const, so prefer to nest less deeply for the common const case. template <typename FunctorType, typename ReturnType, typename... ArgTypes> struct callable_traits<ReturnType (FunctorType::*)(ArgTypes...)> : public callable_traits<ReturnType (FunctorType::*)(ArgTypes...) const> {}; // Common functor specialization. template <typename FunctorType, typename ReturnType, typename... ArgTypes> struct callable_traits<ReturnType (FunctorType::*)(ArgTypes...) const> : public callable_traits<ReturnType (*)(ArgTypes...)> { using type = FunctorType; }; // Function pointer specialization. template <typename ReturnType, typename... ArgTypes> struct callable_traits<ReturnType (*)(ArgTypes...)> : public callable_traits<ReturnType(ArgTypes...)> { using type = ReturnType (*)(ArgTypes...); }; // Base specialization. template <typename ReturnType, typename... ArgTypes> struct callable_traits<ReturnType(ArgTypes...)> { using signature = ReturnType(ArgTypes...); using return_type = ReturnType; using args = parameter_pack<ArgTypes...>; callable_traits() = delete; }; // Determines whether a type has an operator() that can be invoked. template <typename T, typename = void_t<>> struct is_callable : public std::false_type {}; template <typename ReturnType, typename... ArgTypes> struct is_callable<ReturnType (*)(ArgTypes...)> : public std::true_type {}; template <typename FunctorType, typename ReturnType, typename... ArgTypes> struct is_callable<ReturnType (FunctorType::*)(ArgTypes...)> : public std::true_type {}; template <typename T> struct is_callable<T, void_t<decltype(&T::operator())>> : public std::true_type {}; } // namespace fit #endif // LIB_FIT_TRAITS_H_
[ "jeffbrown@google.com" ]
jeffbrown@google.com
cc9ddc104908905ae6c67162c4338fd7e0ea4f17
492c0703062d9e2fef67459a48f2303132a839b4
/bisonc++/options/cleandir.cc
ccfb8b633708f9344f211381e987355d656a97e1
[]
no_license
yujincheng08/bisoncpp
0896f39c741f8202befc59335ff3f0d4de51f175
0e478259ba00630898862fa0d698ed9428bed7c0
refs/heads/master
2021-01-23T05:04:01.080690
2017-05-31T13:43:04
2017-05-31T13:43:04
92,949,495
2
0
null
2017-05-31T13:38:41
2017-05-31T13:38:40
null
UTF-8
C++
false
false
163
cc
#include "options.ih" void Options::cleanDir(string &dir, bool append) { dir = undelimit(dir); if (append && *dir.rbegin() != '/') dir += '/'; }
[ "f.b.brokken@rug.nl" ]
f.b.brokken@rug.nl
4923babcdeaad0963b1bff0927e60d424eb9c774
67f793e52366c5f32e6a472e369a59aac0351aff
/DataStructure/PriorityQueue/AbstractPriorityQueue.hpp
29df0b14392c0202f3b2fbefda2a706ccdb46b57
[]
no_license
dev-yong/DataStructure
d639e9cd1e1776e43ee784a2fdfd647e04548f3b
00ca4664962bd8e984f5697d877ea2ee4e5503f5
refs/heads/master
2022-03-13T09:59:49.295065
2019-10-28T07:40:14
2019-10-28T07:40:14
215,066,039
0
0
null
null
null
null
UTF-8
C++
false
false
532
hpp
// // AbstractPriorityQueue.hpp // DataStructure // // Created by 이광용 on 2019/10/17. // Copyright © 2019 GwangYongLee. All rights reserved. // #ifndef AbstractPriorityQueue_hpp #define AbstractPriorityQueue_hpp #include <iostream> #include "../BinaryHeap/BinaryHeap.cpp" template <typename Type> class AbstractPriorityQueue { public: virtual ~AbstractPriorityQueue() {}; virtual Type front() = 0; virtual int pop() = 0; virtual void push(Type element) = 0; }; #endif /* AbstractPriorityQueue_hpp */
[ "rhkdrmfh@gmail.com" ]
rhkdrmfh@gmail.com
733819c0d525f2e9b39bd97d01517fad7d876359
84ea17552c2fd77bc85af22f755ae04326486bb5
/Ablaze-Core/src/Graphics/Context.cpp
b469ede976d4b3bc877c891781437d6c964f053d
[]
no_license
Totomosic/Ablaze
98159c0897b85b236cf18fc8362501c3873e49f4
e2313602d80d8622c810d3d0d55074cda037d287
refs/heads/master
2020-06-25T20:58:29.377957
2017-08-18T07:42:20
2017-08-18T07:42:20
96,988,561
1
1
null
null
null
null
UTF-8
C++
false
false
264
cpp
#include "Context.h" namespace Ablaze { Window* Context::window = nullptr; Window* Context::Window() { return window; } void Context::SetWindow(Ablaze::Window* win) { window = win; } bool Context::Initialised() { return window != nullptr; } }
[ "jordan.thomas.morrison@gmail.com" ]
jordan.thomas.morrison@gmail.com
2babd2516e1374c5a05e576277bcf602d5dac848
3f227076a0676cd0f74def3bfe050f889da2e70a
/coin.h
d9fbf2b235340ea80220cab89b48e60afed2a3be
[]
no_license
Daniel-ca-re/pac-man
6b4e337791b4a9244f07283d501c2bf6e3a379a2
cc6b9d9386243a2e23a9fbbdeed818517c0fadd1
refs/heads/master
2023-02-01T17:08:07.100415
2020-12-18T14:43:05
2020-12-18T14:43:05
322,123,592
0
0
null
null
null
null
UTF-8
C++
false
false
497
h
#ifndef COIN_H #define COIN_H #include <QGraphicsItem> #include <QPainter> class coin: public QGraphicsItem { int r; int posx,posy; public: coin(); coin(int r_, int x ,int y); int getR()const; void setR(int radio); int getPosx()const; void setPosx(int px); int getPosy() const; void setPosy(int py); QRectF boundingRect() const; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget =nullptr); }; #endif // COIN_H
[ "70850709+Daniel-ca-re@users.noreply.github.com" ]
70850709+Daniel-ca-re@users.noreply.github.com
cb172e4f8cbcdd9680fa18074db29340eec6b461
88ae8695987ada722184307301e221e1ba3cc2fa
/chrome/browser/ui/passwords/bubble_controllers/password_bubble_controller_base.h
8860080865722b60e74f5b55b503c85da4a2e0f8
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
2,604
h
// Copyright 2020 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_BROWSER_UI_PASSWORDS_BUBBLE_CONTROLLERS_PASSWORD_BUBBLE_CONTROLLER_BASE_H_ #define CHROME_BROWSER_UI_PASSWORDS_BUBBLE_CONTROLLERS_PASSWORD_BUBBLE_CONTROLLER_BASE_H_ #include "base/memory/weak_ptr.h" #include "components/password_manager/core/browser/password_manager_metrics_util.h" namespace content { class WebContents; } namespace password_manager { class PasswordFormMetricsRecorder; } class PasswordsModelDelegate; class Profile; // This is the base class for all bubble controllers. There should be a bubble // controller per view. Bubble controller provides the data and controls the // password management actions for the corresponding view. class PasswordBubbleControllerBase { public: enum class PasswordAction { kRemovePassword, kAddPassword }; enum class DisplayReason { kAutomatic, kUserAction }; PasswordBubbleControllerBase( base::WeakPtr<PasswordsModelDelegate> delegate, password_manager::metrics_util::UIDisplayDisposition display_disposition); PasswordBubbleControllerBase(const PasswordBubbleControllerBase&) = delete; PasswordBubbleControllerBase& operator=(const PasswordBubbleControllerBase&) = delete; virtual ~PasswordBubbleControllerBase(); // Subclasses must override this method to provide the proper title. virtual std::u16string GetTitle() const = 0; // Subclasses must override this method to report their interactions. virtual void ReportInteractions() = 0; // The method MAY BE called to record the statistics while the bubble is // being closed. Otherwise, it is called later on when the controller is // destroyed. void OnBubbleClosing(); Profile* GetProfile() const; content::WebContents* GetWebContents() const; bool interaction_reported() const { return interaction_reported_; } protected: // Reference to metrics recorder of the PasswordForm presented to the user by // |this|. We hold on to this because |delegate_| may not be able to provide // the reference anymore when we need it. scoped_refptr<password_manager::PasswordFormMetricsRecorder> metrics_recorder_; // A bridge to ManagePasswordsUIController instance. base::WeakPtr<PasswordsModelDelegate> delegate_; private: // True if the model has already recorded all the necessary statistics when // the bubble is closing. bool interaction_reported_ = false; }; #endif // CHROME_BROWSER_UI_PASSWORDS_BUBBLE_CONTROLLERS_PASSWORD_BUBBLE_CONTROLLER_BASE_H_
[ "jengelh@inai.de" ]
jengelh@inai.de
cefe08f5716499645b8d20ee37dc314981d85829
d9f94ea8f3cc232456bf95b67952a5923debc45d
/2012-08-10/J.cpp
c45835d99ab1f43ba45316a105c80cd8c5b09aec
[]
no_license
ftiasch/mithril
063bdd1d71d8216d727ac7f0faf7954e86653fd6
1bf5805af01409cc21c769debc6e93e48e71a46e
refs/heads/master
2020-05-19T11:48:36.290717
2013-10-05T08:39:46
2013-10-05T08:39:46
5,078,340
7
2
null
null
null
null
UTF-8
C++
false
false
1,553
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <complex> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <cstring> #include <ctime> #include <cassert> using namespace std; int main() { int n; while (cin >> n) { int m = n; int ans = 1; for (int i = 2; i * i <= m; i++) { if (m % i == 0) { int cnt = 0; while (m % i == 0) { m /= i; cnt ++; } cnt = (cnt + 1) / 2; for (int j = 0; j < cnt; j++) { ans *= i; } } } ans *= m; set<int> S; vector<int> lst; lst.push_back(1); S.insert(1); while (true) { int newv = (lst.back() + ans) % n; if (S.insert(newv).second) { lst.push_back(newv); } else { break; } } if (lst.size() <= 2) { lst.clear(); lst.push_back(1); lst.push_back(0); } printf("%d\n", lst.size()); for (int i = 0; i < lst.size(); i++) { if (i > 0) { putchar(' '); } printf("%d", lst[i]); } puts(""); } }
[ "mithril@acm.sjtu.edu.cn" ]
mithril@acm.sjtu.edu.cn
bf8f4f35e3c540554abbbd806c8dc41551264888
1a77b5eac40055032b72e27e720ac5d43451bbd6
/フォーム対応/VisualC++/MFC/Chap5/Dr34_2/Dr34_2/MainFrm.cpp
079ef8080fcb581e3c8cfda86ca16e798abb28fc
[]
no_license
motonobu-t/algorithm
8c8d360ebb982a0262069bb968022fe79f2c84c2
ca7b29d53860eb06a357eb268f44f47ec9cb63f7
refs/heads/master
2021-01-22T21:38:34.195001
2017-05-15T12:00:51
2017-05-15T12:01:00
85,451,237
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,110
cpp
// MainFrm.cpp : CMainFrame クラスの実装 // #include "stdafx.h" #include "Dr34_2.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // ステータス ライン インジケータ ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame コンストラクション/デストラクション CMainFrame::CMainFrame() { // TODO: メンバ初期化コードをここに追加してください。 } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("ツール バーの作成に失敗しました。\n"); return -1; // 作成できませんでした。 } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("ステータス バーの作成に失敗しました。\n"); return -1; // 作成できませんでした。 } // TODO: ツール バーをドッキング可能にしない場合は、これらの 3 行を削除してください。 m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: この位置で CREATESTRUCT cs を修正して Window クラスまたはスタイルを // 修正してください。 return TRUE; } // CMainFrame 診断 #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame メッセージ ハンドラ
[ "rx_78_bd@yahoo.co.jp" ]
rx_78_bd@yahoo.co.jp
0a5d15510bd0e3157cfaf9ef8d3de3bf917a4c5d
0fec062f2cf2c6d6229ee5a51491cd3d53d7d7d5
/module1/z1.cpp
6804d2cbb7d78c5c2e6535e749ed28d90e8a5e4a
[]
no_license
MaxSamokhin/algorithms
0e19ef534a7f37ee906765b980f3d5fd62a2da02
cc8adc796a1c5746399e1b76bda3ff31d1055e03
refs/heads/master
2020-03-08T23:24:09.128649
2018-04-07T15:39:54
2018-04-07T15:39:54
128,462,822
0
0
null
null
null
null
UTF-8
C++
false
false
923
cpp
#include <iostream> #include <assert.h> /*1_6. ​Дан массив целых чисел A[0..n). Не используя других массивов переставить элементы массива A в обратном порядке за O(n). in : 4 3 9 -5 2 out : 2 -5 9 3 */ void get_reversal(int* arr, int size) { int buff = 0; for (int i = 0; i < size / 2; i++) { buff = arr[i]; arr[i] = arr[size - 1 - i]; arr[size - 1 - i] = buff; } } void print_arr(int* arr, int size) { for (int i = 0; i < size; ++i) { std::cout << arr[i] << " "; } } int main() { int size_arr = 0; std::cin >> size_arr; assert(size_arr > 0); int* arr = new int[size_arr]; for (int i = 0; i < size_arr; ++i) { std::cin >> arr[i]; } get_reversal(arr, size_arr); print_arr(arr, size_arr); delete [] arr; return 0; }
[ "samokhinmax@gmail.com" ]
samokhinmax@gmail.com
0410a31dcc009f896fbfc7124bb3b97ce86ada46
407207dfe25dc304f5b771240a0f4fa4f3994f92
/Statistics/SamplingCpp/Stratum/For/981534.cpp
f7298a6df6aa496b0935a1d4f660749f7d29dccb
[]
no_license
imnate/Paper
fc06b5bd3c0a3b792e2f6ae54cf555bb149d3879
5829c1a1fd4a79e00d2170d7732f3d1807b13155
refs/heads/master
2021-01-20T14:28:34.820662
2017-06-19T18:08:15
2017-06-19T18:08:15
90,613,838
0
0
null
null
null
null
BIG5
C++
false
false
339
cpp
#include<iostream> using namespace std; int main() { int n; int ans1=1; int ans2=1; int ans3=1; cout<<"請輸入階乘數:"<<endl; cin>>n; for(int i=n;i>0;i--) { ans1=ans1*i; } cout<<"答案:"<<endl<<ans1<<endl; cout<<"請輸入階乘數:"<<endl; cin>>n; cout<<"請輸入階乘數:"<<endl; cin>>n; return 0; }
[ "gogx16@gmail.com" ]
gogx16@gmail.com
16720e4a89bfa517eac07eb7e81296e1f8fcc65f
aad625e6da08beca00437d37751fd24c77089f71
/GariKro GUI/admindialog.cpp
968394c3ed52825b921788fd42834031843e87de
[]
no_license
ahsannaqvii/Car-Rental-System-OOP
7085c67aa7d3b960ab0c4efc2e5af99e507f5c07
62753d2dbfce4e1ac27156db4e4702b583011e18
refs/heads/master
2022-10-04T00:15:52.569406
2020-06-12T20:04:21
2020-06-12T20:04:21
255,639,293
0
0
null
null
null
null
UTF-8
C++
false
false
1,217
cpp
#include "admindialog.h" #include "ui_admindialog.h" #include "adminsetcharges.h" #include "adminsearchdriver.h" #include "adminadddriver.h" #include "adminsearchuser.h" #include "adminremovedriver.h" adminDialog::adminDialog(QWidget *parent) : QDialog(parent), ui(new Ui::adminDialog) { ui->setupUi(this); } adminDialog::~adminDialog() { delete ui; } void adminDialog::on_pushButton_SetCharges_clicked() { hide(); adminSetCharges admS; admS.setModal(true); admS.exec(); } void adminDialog::on_pushButton_2_AddDriver_clicked() { hide(); adminAddDriver adminAdd; adminAdd.setModal(true); adminAdd.exec(); } void adminDialog::on_pushButton_3_SearchDriver_clicked() { hide(); adminSearchDriver adminSearch; adminSearch.setModal(true); adminSearch.exec(); } void adminDialog::on_pushButton_4_SearchUser_clicked() { hide(); adminSearchUser adminSearch; adminSearch.setModal(true); adminSearch.exec(); } void adminDialog::on_pushButton_5_RemoveDriver_clicked() { hide(); adminRemoveDriver adminRemove; adminRemove.setModal(true); adminRemove.exec(); } void adminDialog::on_pushButton_7_Exit_clicked() { exit(1); }
[ "syedahsan13@hotmail.com" ]
syedahsan13@hotmail.com
bbd9a6b5dfb429cfe5f59f9e75bcbfd53269f388
9500d3c808215edc1ca906206343c282d99f9979
/ED-03A/Monitoria08 - O Retorno/6_Game/core.h
44c9f531a42119768c7e0c59be61bb3551dd3d77
[]
no_license
HenrickyL/Monitoria_2020-1
2ea7f6646113e1737d0955c7f86f07d483049d6d
e55ad9d2e9326a5881af8420cc1449339f58a6a8
refs/heads/master
2021-04-04T03:24:35.501039
2020-10-21T00:08:01
2020-10-21T00:08:01
248,421,031
0
0
null
null
null
null
UTF-8
C++
false
false
1,908
h
#ifndef CORE_H #define CORE_H struct Point{ int x; int y; }; class Game{ public: Game(int w, int h); // construtor - alocamos coisas, e definimos valores inic ~Game();//destrutor - desalocamos private: int** _base; char ** _screen; Point* _pos; Point* _dim; public: // métodos void update(); void draw(); private: //metodos privados //cria a matriz de numeros void creteBase(); // converte a matriz de interio para char void creteScreen(); //printar a tela void printScreen(); public: //printar a matriz void printNum(); }; #endif // struct Point{ // int x; // int y; // }; // struct dimension{ // int width; // int height; // }; // //variável que que vai printar a tela // /* // função de atualização gráfica // use a função // system("clear"); // para limpar a tela // */ // void draw(int** screen, int w, int h, int* tick); // //função de atualização do sistema // void update(int** screen, int w, int h, Point* p, bool* run, int* tick); // /////////////////////////////////////////// // /* // criar uma matriz de inteiros em h linhas e w colunas, esta matriz tem que estar zerada // */ // int** createScreen(int w, int h); // /* // Converte uma matriz de inteiros para uma matriz de caracteres // onde 0 são espaços e 1 é '@' / 'O' // */ // char** convertScreen(int** screen, int w, int h); // /* // Função que desenha a matriz de caraceteres na tela // */ // void printScreen(char** strScreen, int w, int h); // /* // Função que recebe a matriz de inteiros e coloca "1" na posiçaõ p // */ // void injectionBall(int** screen, int w, int h, Point* p); // /* // Função que define a movimentaçaõ // */ // void receiveOptions(int** screen,int w, int h, Point* p, bool* run);
[ "henrickyL1@gmail.com" ]
henrickyL1@gmail.com
fc651c27a94ed60b8d6cf523ea76dff25c6ecf88
7638c1ea3488e0234fec3e6993deeae7505cde28
/pathfind/Pathfinding/Pathfinding/Lee.cpp
4850c8d33239f9872b346c2dccfff5825dc211a6
[]
no_license
kieranwu/CMP201-Pathfinding
7d1b6d261ba710ec3a152d2937b0d3741c6c34df
5a90f4629e1746662a71c563811aadb89b1a4200
refs/heads/master
2022-03-29T11:17:26.848639
2019-12-09T15:37:59
2019-12-09T15:37:59
224,717,454
0
0
null
null
null
null
UTF-8
C++
false
false
6,440
cpp
#include "Lee.h" //Constructor Lee::Lee() { } //Destructor Lee::~Lee() { } //This varible will simply print the map to the console void Lee::showGrid() { //loop for width and height for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { //print value to console cout << grid[j][i] << " "; } //next row cout << endl; } } //This function will save all the important variables needed for the algorithm to run void Lee::setUp(int** map,Coord tempStart, Coord tempEnd, int W, int H) { Start = tempStart; End = tempEnd; grid = map; width = W; height = H; isPath = true; } //This function will look at the value of the position in the map and do different things bool Lee::findType(int i, int j, int num, bool end) { //Checks if End is false (End is already found) if (end == false) { //set temp to the value of the map position passed in int temp = grid[i][j]; //switch statement to respond to the value of temp // If the value is -3 then it is the end of the map, it will set the value to num+1 (number of step) and return true // If the value is -2 then it is a wall so it will just exit //If the value is -1 then it is a free space and set the the value to num +1 switch (temp) { case -3: grid[i][j] = num + 1; return true; break; case -2: break; case -1: grid[i][j] = num + 1; break; } //if not the end it will return false return false; } else { //return true as it is the end; return true; } } //This function implements the Lee pathfinding algorithm void Lee::pathfinder() { //initialise local variables bool end = false; int num = 0; //set the start of the map to 0 grid[Start.x][Start.y] = 0; //Loop while end is false while (end == false) { //Loop for width and height for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { //Check if location is = num (if where the function is looking at on the map is the value of what step its on) if (grid[i][j] == num) { //Check above //This will check if the row is greater 0 if (i > 0) { //run the findtype function passing in the location above and what step its on end = findType(i - 1, j, num, end); } //Check Below //This will check if the row is less than height -1 if (i < height-1) { //run the findtype function passing in the location below and what step its on end = findType(i + 1, j, num, end); } //Check Left //This will check if the column is greater than 0 if (j > 0) { //run the findtype function passing in the location left and what step its on end = findType(i, j - 1, num, end); } //Check right //This will check if the column is less than the width if (j < width-1) { //run the findtype function passing in the location right and what step its on end = findType(i, j + 1, num, end); } } } } //increment num (next step) num++; //Check if the number of steps taken is double the height (moved throughout the whole map and end is still false) if (num > height*2) { //set end to true and path to false end = true; isPath = false; } } } //This function will save the algorithm has taken void Lee::savePath() { //initialise local variables bool fin = false; Coord temp; int x = End.x; int y = End.y; int num = grid[x][y]; //push the end into the path vector path.push_back(End); //Loop while fin is false and there is a path while (!fin && isPath) { //This will check if the y is not 0 (not at the top of the map) and if the value above is the previous step if (y != 0 && (grid[x][y - 1] == num - 1)) { //decrease y by one and push current location into path y -= 1; temp.x = x; temp.y = y; path.push_back(temp); } //otherwise this will check if the x is not 0 (not on the far left) and if the value to the left is the previous step else if ((x != 0) && (grid[x - 1][y] == num - 1)) { //decrease x by one and push current location into path x -= 1; temp.x = x; temp.y = y; path.push_back(temp); } //otherwise this will check if the x is not the width of the map (not on the far right) and if the value to the right is the previous step else if (x != width -1 && (grid[x + 1][y] == num - 1)) { //increase x by one and push current location into path x += 1; temp.x = x; temp.y = y; path.push_back(temp); } //otherwise this will check if the value is not the height of the map (not on the bottom) and if the value below is the previous step else if (y != height - 1&& (grid[x][y + 1] == num - 1)) { //increase y by one and push the current location into path y += 1; temp.x = x; temp.y = y; path.push_back(temp); } //set num to the value of the location on the map num = grid[x][y]; //check if num is 0 (start of the path) if (num == 0) { //set fin to true fin = true; } } } //This function will show the path the algorithm has taken void Lee::showEnd() { system("CLS"); // clears the console //Loop for width and height for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { //Check if location is not a wall if (grid[i][j] != -2) { //set value to 0 grid[i][j] = 0; } } } //reset end point to -3 grid[End.x][End.y] = -3; //initialise local variable int num = 0; int x, y; //Checks if there is a path if (isPath) { //Loop for the size of path vector for (int i = path.size() - 1; i >= 0; i--) { system("CLS"); // clears the console // Sleep(600); //change the value of each location of the map in order of the path x = path[i].x; y = path[i].y; grid[x][y] = num; num++; } //print the map showGrid(); } else { //print no path to console cout << "NO PATH" << endl; } } //This function will clear the vectors so that they can be used again void Lee::clearVector() { //set A to the size of the vector - A must be set before hand as the size will decrease as the loop runs int A = path.size(); for (int i = 0; i < A; i++) { path.pop_back(); } }
[ "noreply@github.com" ]
noreply@github.com
291c08af0fc25e071a0779982f8ea9a432a0cee2
390b9b5bd3832414ccb3b6b518f590a9e0f74f7d
/Day-52/Binary-Tree-to-DLL.cpp
f728e8436312ab2b5e202a42c840dc3759e33c25
[]
no_license
hitu1304/100DaysCodingChallenge
0021a023676c851015f2e7b28856148b6befb645
358ae69944ee2d3ebb8bbf95b5937b07bb1279a9
refs/heads/main
2023-06-14T08:04:27.948509
2021-07-10T13:11:39
2021-07-10T13:11:39
353,709,342
2
1
null
null
null
null
UTF-8
C++
false
false
868
cpp
/*Approach-> Store inorder traversal of tree and create a CDLL.*/ class Solution { public: //Function to convert binary tree to doubly linked list and return it. void in(Node *p,vector<int>&v) { if(p) { in(p->left,v); v.push_back(p->data); in(p->right,v); } } Node * bToDLL(Node *root) { vector<int>v={}; in(root,v); int i=0; Node *t=new Node; t->data=v[i]; t->left=t->right=NULL; Node *head=t,*p,*q; for(i=1;i<v.size();i++) { q=new Node; q->data=v[i]; q->left=q->right=NULL; q->left=t; t->right=q; t=q; } return head; } }; ///Time Complexity: O(N).
[ "hiteshgendre2000@gmail.com" ]
hiteshgendre2000@gmail.com
a45febd72dc6c3e228893e73e154303c8c97adc4
8a5b3cfb11331758d9c0abebeb943cb87c72a309
/c++/file/file_lock.cpp
e0bba2cf22345f952e802e64ac6ab6ea15ad6081
[]
no_license
leo23/demo
1d609fcdc9b96d3c9d535488dd4a5551804451b6
14994d8845213b6f5a204423ef4a7b35390c9403
refs/heads/master
2022-10-20T17:19:19.758367
2020-07-01T01:31:09
2020-07-01T01:31:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
658
cpp
#include <stdio.h> #include <fcntl.h> #include <unistd.h> #include <acl-lib/acl_cpp/lib_acl.hpp> int main(void) { const char* filepath = "file.dummy"; acl::fstream fp; if (fp.open(filepath, O_RDWR | O_CREAT, 0600) == false) { printf("open %s error %s\r\n", filepath, acl::last_serror()); return 1; } printf("begin to lock %s\r\n", filepath); if (!fp.lock()) { printf("lock %s error=%s\r\n", filepath, acl::last_serror()); return 1; } printf("lock %s ok\r\n", filepath); sleep(5); if (!fp.unlock()) { printf("unlock %s error %s\r\n", filepath, acl::last_serror()); return 1; } printf("unlock %s ok\r\n", filepath); return 0; }
[ "zhengshuxin@gmail.com" ]
zhengshuxin@gmail.com