blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
75c90c632d83b0a761454ef7f19dbbc89bf87b5e | 93fbf65a76bbeb5d8e915c14e5601ae363b3057f | /5th sem DAA Lab/BucketSort.cpp | 0b14897285cd16940e1a31104dc5398d98ccbc19 | [] | no_license | sauravjaiswa/Coding-Problems | fd864a7678a961a422902eef42a29218cdd2367f | cb978f90d7dcaec75af84cba05d141fdf4f243a0 | refs/heads/master | 2023-04-14T11:34:03.138424 | 2021-03-25T17:46:47 | 2021-03-25T17:46:47 | 309,085,423 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 741 | cpp | //Bucket Sort
#include<bits/stdc++.h>
using namespace std;
void bucketSort(float a[],int n){
//cout<<n<<"\n";
int i,j,key,ind;
priority_queue<float, vector<float>, greater<float> > li[n];
for(i=0;i<n;i++)
{
key=n*a[i];
li[key].push(a[i]);
}
ind=0;
for(i=0;i<n;i++){
cout<<i<<" -> ";
while(!li[i].empty()){
cout<<li[i].top()<<" ";
a[ind++]=li[i].top();
li[i].pop();
}
cout<<"\n";
}
}
int main(){
float a[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
int n=sizeof(a)/sizeof(a[0]);
bucketSort(a,n);
int i;
cout<<"Sorted array is \n";
for(i=0;i<n;i++)
cout<<a[i]<<" ";
return 0;
}
| [
"41826172+sauravjaiswa@users.noreply.github.com"
] | 41826172+sauravjaiswa@users.noreply.github.com |
3d70a9cfa44987c8454ee2fe5f61b0449cede8fd | e9facd1e741f8142a12ba31c0bdb31a36dadeb44 | /src/swifttx.h | 68eea2c433b9e53ba7bfb85f6841f02502e8ed96 | [
"MIT"
] | permissive | calypsodevs/seocoin | 72c227af2a289c8a9b20dc5cdbf536ba52d97a1a | 54d07145016df9c965efe94d7158750342fb5116 | refs/heads/master | 2020-04-27T08:08:19.773173 | 2019-03-11T22:23:56 | 2019-03-11T22:23:56 | 174,160,176 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,877 | h | // Copyright (c) 2009-2012 The Dash developers
// Copyright (c) 2015-2018 The SEOCOIN developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SWIFTTX_H
#define SWIFTTX_H
#include "base58.h"
#include "key.h"
#include "main.h"
#include "net.h"
#include "spork.h"
#include "sync.h"
#include "util.h"
/*
At 15 signatures, 1/2 of the masternode network can be owned by
one party without comprimising the security of SwiftX
(1000/2150.0)**10 = 0.00047382219560689856
(1000/2900.0)**10 = 2.3769498616783657e-05
### getting 5 of 10 signatures w/ 1000 nodes of 2900
(1000/2900.0)**5 = 0.004875397277841433
*/
#define SWIFTTX_SIGNATURES_REQUIRED 6
#define SWIFTTX_SIGNATURES_TOTAL 10
using namespace std;
using namespace boost;
class CConsensusVote;
class CTransaction;
class CTransactionLock;
static const int MIN_SWIFTTX_PROTO_VERSION = 70103;
extern map<uint256, CTransaction> mapTxLockReq;
extern map<uint256, CTransaction> mapTxLockReqRejected;
extern map<uint256, CConsensusVote> mapTxLockVote;
extern map<uint256, CTransactionLock> mapTxLocks;
extern std::map<COutPoint, uint256> mapLockedInputs;
extern int nCompleteTXLocks;
int64_t CreateNewLock(CTransaction tx);
bool IsIXTXValid(const CTransaction& txCollateral);
// if two conflicting locks are approved by the network, they will cancel out
bool CheckForConflictingLocks(CTransaction& tx);
void ProcessMessageSwiftTX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
//check if we need to vote on this transaction
void DoConsensusVote(CTransaction& tx, int64_t nBlockHeight);
//process consensus vote message
bool ProcessConsensusVote(CNode* pnode, CConsensusVote& ctx);
// keep transaction locks in memory for an hour
void CleanTransactionLocksList();
// get the accepted transaction lock signatures
int GetTransactionLockSignatures(uint256 txHash);
int64_t GetAverageVoteTime();
class CConsensusVote
{
public:
CTxIn vinMasternode;
uint256 txHash;
int nBlockHeight;
std::vector<unsigned char> vchMasterNodeSignature;
uint256 GetHash() const;
bool SignatureValid();
bool Sign();
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(txHash);
READWRITE(vinMasternode);
READWRITE(vchMasterNodeSignature);
READWRITE(nBlockHeight);
}
};
class CTransactionLock
{
public:
int nBlockHeight;
uint256 txHash;
std::vector<CConsensusVote> vecConsensusVotes;
int nExpiration;
int nTimeout;
bool SignaturesValid();
int CountSignatures();
void AddSignature(CConsensusVote& cv);
uint256 GetHash()
{
return txHash;
}
};
#endif
| [
"calypsodevs@gmail.com"
] | calypsodevs@gmail.com |
3f8e98b7ca66a482cc60fbe888e338ad4b4ee50c | dca653bb975528bd1b8ab2547f6ef4f48e15b7b7 | /tags/wxPy-2.9.5.0/src/msw/richtooltip.cpp | 9a50ab2271b172b3e5932505f7cd5c849f35a1dd | [] | no_license | czxxjtu/wxPython-1 | 51ca2f62ff6c01722e50742d1813f4be378c0517 | 6a7473c258ea4105f44e31d140ea5c0ae6bc46d8 | refs/heads/master | 2021-01-15T12:09:59.328778 | 2015-01-05T20:55:10 | 2015-01-05T20:55:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,029 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: src/msw/richtooltip.cpp
// Purpose: Native MSW implementation of wxRichToolTip.
// Author: Vadim Zeitlin
// Created: 2011-10-18
// RCS-ID: $Id$
// Copyright: (c) 2011 Vadim Zeitlin <vadim@wxwidgets.org>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// for compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_RICHTOOLTIP
#ifndef WX_PRECOMP
#include "wx/treectrl.h"
#endif // WX_PRECOMP
#include "wx/private/richtooltip.h"
#include "wx/generic/private/richtooltip.h"
#include "wx/msw/private.h"
#include "wx/msw/uxtheme.h"
// Provide definitions missing from some compilers SDK headers.
#ifndef TTI_NONE
enum
{
TTI_NONE,
TTI_INFO,
TTI_WARNING,
TTI_ERROR
};
#endif // !defined(TTI_XXX)
#ifndef Edit_ShowBalloonTip
struct EDITBALLOONTIP
{
DWORD cbStruct;
LPCWSTR pszTitle;
LPCWSTR pszText;
int ttiIcon;
};
#define Edit_ShowBalloonTip(hwnd, pebt) \
(BOOL)::SendMessage((hwnd), 0x1503 /* EM_SHOWBALLOONTIP */, 0, (LPARAM)(pebt))
#endif // !defined(Edit_ShowBalloonTip)
// ============================================================================
// wxRichToolTipMSWImpl: the real implementation.
// ============================================================================
class wxRichToolTipMSWImpl : public wxRichToolTipGenericImpl
{
public:
wxRichToolTipMSWImpl(const wxString& title, const wxString& message) :
wxRichToolTipGenericImpl(title, message)
{
// So far so good...
m_canUseNative = true;
m_ttiIcon = TTI_NONE;
}
virtual void SetBackgroundColour(const wxColour& col,
const wxColour& colEnd)
{
// Setting background colour is not supported neither.
m_canUseNative = false;
wxRichToolTipGenericImpl::SetBackgroundColour(col, colEnd);
}
virtual void SetCustomIcon(const wxIcon& icon)
{
// Custom icons are not supported by EM_SHOWBALLOONTIP.
m_canUseNative = false;
wxRichToolTipGenericImpl::SetCustomIcon(icon);
}
virtual void SetStandardIcon(int icon)
{
wxRichToolTipGenericImpl::SetStandardIcon(icon);
if ( !m_canUseNative )
return;
switch ( icon & wxICON_MASK )
{
case wxICON_WARNING:
m_ttiIcon = TTI_WARNING;
break;
case wxICON_ERROR:
m_ttiIcon = TTI_ERROR;
break;
case wxICON_INFORMATION:
m_ttiIcon = TTI_INFO;
break;
case wxICON_QUESTION:
wxFAIL_MSG("Question icon doesn't make sense for a tooltip");
break;
case wxICON_NONE:
m_ttiIcon = TTI_NONE;
break;
}
}
virtual void SetTimeout(unsigned millisecondsTimeout,
unsigned millisecondsDelay)
{
// We don't support changing the timeout or the delay
// (maybe TTM_SETDELAYTIME could be used for this?).
m_canUseNative = false;
wxRichToolTipGenericImpl::SetTimeout(millisecondsTimeout,
millisecondsDelay);
}
virtual void SetTipKind(wxTipKind tipKind)
{
// Setting non-default tip is not supported.
if ( tipKind != wxTipKind_Auto )
m_canUseNative = false;
wxRichToolTipGenericImpl::SetTipKind(tipKind);
}
virtual void SetTitleFont(const wxFont& font)
{
// Setting non-default font is not supported.
m_canUseNative = false;
wxRichToolTipGenericImpl::SetTitleFont(font);
}
virtual void ShowFor(wxWindow* win, const wxRect* rect)
{
// TODO: We could use native tooltip control to show native balloon
// tooltips for any window but right now we use the simple
// EM_SHOWBALLOONTIP API which can only be used with text
// controls.
if ( m_canUseNative && !rect )
{
wxTextCtrl* const text = wxDynamicCast(win, wxTextCtrl);
if ( text )
{
EDITBALLOONTIP ebt;
ebt.cbStruct = sizeof(EDITBALLOONTIP);
ebt.pszTitle = m_title.wc_str();
ebt.pszText = m_message.wc_str();
ebt.ttiIcon = m_ttiIcon;
if ( Edit_ShowBalloonTip(GetHwndOf(text), &ebt) )
return;
}
}
// Don't set m_canUseNative to false here, we could be able to use the
// native tooltips if we're called for a different window the next
// time.
wxRichToolTipGenericImpl::ShowFor(win, rect);
}
private:
// If this is false, we've been requested to do something that the native
// version doesn't support and so need to fall back to the generic one.
bool m_canUseNative;
// One of TTI_NONE, TTI_INFO, TTI_WARNING or TTI_ERROR.
int m_ttiIcon;
};
/* static */
wxRichToolTipImpl*
wxRichToolTipImpl::Create(const wxString& title, const wxString& message)
{
// EM_SHOWBALLOONTIP is only implemented by comctl32.dll v6 so don't even
// bother using the native implementation if we're not using themes.
if ( wxUxThemeEngine::GetIfActive() )
return new wxRichToolTipMSWImpl(title, message);
return new wxRichToolTipGenericImpl(title, message);
}
#endif // wxUSE_RICHTOOLTIP
| [
"RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775"
] | RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 |
2f03fdc89a0fdb8b4c7c9d06b12c633ee71b7e86 | c6508f10a5651f599520518b206b47e997e4c170 | /yui/maxDepthNode.cpp | 7779345748910035ee68dd68dcc1ef57b74ef549 | [] | no_license | rootid/prog.channel | 892dc4abf883cd43e19431956613f123e21b51be | 427ddd6fe15d3e0f7ab23e7bfd48b4a9364be5ef | refs/heads/master | 2020-04-09T18:25:25.459281 | 2015-07-13T21:51:31 | 2015-07-13T21:51:31 | 29,564,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 336 | cpp | #include<iostream>
using namespace std;
int maxDepthNode (BTNode* root,int level) {
if (!root) {
return 0;
}
if (root->left == NULL && root->right == NULL && (level &1)) {
return level;
}
return max (maxDepthNode (root->left,level+1) ,maxDepthNode (root->right,level+1));
}
int main () {
}
| [
"vsinhsawant@gmail.com"
] | vsinhsawant@gmail.com |
ec6d706774adcc6b6b5dc34214702d61fe584a0f | 173eb2bd5273ce6b92f796f5f667b5a26e0ef81c | /GameX/ResourceHolder.h | 1c8ca56a46b0b9e8b414cfb0d398784954939a04 | [] | no_license | dheerajsuthar/gamex | 9020f64113b0c24d7ea50de9f79bb2f887c283ef | f52240304be7f69b624a1c9666a9c830ea00b284 | refs/heads/master | 2020-03-27T20:53:38.634922 | 2018-09-02T16:04:41 | 2018-09-02T16:04:41 | 147,100,632 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | h | #pragma once
#include <map>
#include <memory>
#include <assert.h>
#include <SFML/Graphics.hpp>
#include "Textures.h"
template<class Resource, class Identifier>
class ResourceHolder {
public:
void load(Identifier id, const std::string &filePath) {
std::unique_ptr<Resource> texture(new Resource());
if (!texture->loadFromFile(filePath)) {
throw std::runtime_error("Error loading " + filePath);
}
auto inserted = mResourceMap.insert(std::make_pair(id, std::move(texture)));
assert(inserted.second);
}
template<class SecondParam>
void load(Identifier id, const std::string &filePath, SecondParam param) {
std::unique_ptr<Resource> texture(new Resource());
if (!texture->loadFromFile(filePath, param)) {
throw std::runtime_error("Error loading " + filePath);
}
auto inserted = mResourceMap.insert(std::make_pair(id, std::move(texture)));
assert(inserted.second);
}
Resource& get(Identifier id) {
auto found = mResourceMap.find(id);
return *(found->second);
}
private:
std::map<Identifier, std::unique_ptr<Resource>> mResourceMap;
}; | [
"anjisharma1456@gmail.com"
] | anjisharma1456@gmail.com |
0f0310699d98aadda90605f638eade2fb5c7bc52 | 3209cd58acf8e6f4f68ebd8b9d859bb2bc7fbed9 | /storage/src/vespa/storage/bucketdb/btree_lockable_map.hpp | c14afce1a7a26f7a34019e5e7c60d4d5fa60d32a | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | amahussein/vespa | 0fc374027249215a89cb79029490ae14c819844d | 29d266ae1e5c95e25002b97822953fdd02b1451e | refs/heads/master | 2022-12-16T17:38:21.702706 | 2020-09-23T15:46:28 | 2020-09-23T15:46:28 | 264,194,922 | 0 | 0 | Apache-2.0 | 2020-05-15T13:02:24 | 2020-05-15T13:02:23 | null | UTF-8 | C++ | false | false | 18,991 | hpp | // Copyright Verizon Media. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include "btree_lockable_map.h"
#include "generic_btree_bucket_database.hpp"
#include <vespa/vespalib/btree/btreebuilder.h>
#include <vespa/vespalib/btree/btreenodeallocator.hpp>
#include <vespa/vespalib/btree/btreenode.hpp>
#include <vespa/vespalib/btree/btreenodestore.hpp>
#include <vespa/vespalib/btree/btreeiterator.hpp>
#include <vespa/vespalib/btree/btreeroot.hpp>
#include <vespa/vespalib/btree/btreebuilder.hpp>
#include <vespa/vespalib/btree/btree.hpp>
#include <vespa/vespalib/btree/btreestore.hpp>
#include <vespa/vespalib/datastore/datastore.h>
#include <vespa/vespalib/stllike/hash_map.hpp>
#include <vespa/vespalib/stllike/hash_set.hpp>
#include <thread>
#include <sstream>
// Major TODOs in the short term:
// - Introduce snapshotting for readers
// - Greatly improve performance for DB iteration for readers by avoiding
// requirement to lock individual buckets and perform O(n) lbound seeks
// just to do a sweep.
namespace storage::bucketdb {
using vespalib::datastore::EntryRef;
using vespalib::ConstArrayRef;
using document::BucketId;
template <typename T>
struct BTreeLockableMap<T>::ValueTraits {
using ValueType = T;
using ConstValueRef = const T&;
using DataStoreType = vespalib::datastore::DataStore<ValueType>;
static void init_data_store(DataStoreType& store) {
store.enableFreeLists();
}
static EntryRef entry_ref_from_value(uint64_t value) {
return EntryRef(value & 0xffffffffULL);
}
static ValueType make_invalid_value() {
return ValueType();
}
static uint64_t wrap_and_store_value(DataStoreType& store, const ValueType& value) noexcept {
return store.addEntry(value).ref();
}
static void remove_by_wrapped_value(DataStoreType& store, uint64_t value) noexcept {
store.holdElem(entry_ref_from_value(value), 1);
}
static ValueType unwrap_from_key_value(const DataStoreType& store, [[maybe_unused]] uint64_t key, uint64_t value) {
return store.getEntry(entry_ref_from_value(value));
}
static ConstValueRef unwrap_const_ref_from_key_value(const DataStoreType& store, [[maybe_unused]] uint64_t key, uint64_t value) {
return store.getEntry(entry_ref_from_value(value));
}
};
template <typename T>
BTreeLockableMap<T>::BTreeLockableMap()
: _impl(std::make_unique<GenericBTreeBucketDatabase<ValueTraits>>(1024/*data store array count*/))
{}
template <typename T>
BTreeLockableMap<T>::~BTreeLockableMap() = default;
template <typename T>
BTreeLockableMap<T>::LockIdSet::LockIdSet() : Hash() {}
template <typename T>
BTreeLockableMap<T>::LockIdSet::~LockIdSet() = default;
template <typename T>
size_t BTreeLockableMap<T>::LockIdSet::getMemoryUsage() const {
return Hash::getMemoryConsumption();
}
template <typename T>
BTreeLockableMap<T>::LockWaiters::LockWaiters() : _id(0), _map() {}
template <typename T>
BTreeLockableMap<T>::LockWaiters::~LockWaiters() = default;
template <typename T>
size_t BTreeLockableMap<T>::LockWaiters::insert(const LockId & lid) {
Key id(_id++);
_map.insert(typename WaiterMap::value_type(id, lid));
return id;
}
template <typename T>
bool BTreeLockableMap<T>::operator==(const BTreeLockableMap& other) const {
std::lock_guard guard(_lock);
std::lock_guard guard2(other._lock);
if (_impl->size() != other._impl->size()) {
return false;
}
auto lhs = _impl->begin();
auto rhs = other._impl->begin();
for (; lhs.valid(); ++lhs, ++rhs) {
assert(rhs.valid());
if (lhs.getKey() != rhs.getKey()) {
return false;
}
if (_impl->const_value_ref_from_valid_iterator(lhs)
!= other._impl->const_value_ref_from_valid_iterator(rhs))
{
return false;
}
}
return true;
}
template <typename T>
bool BTreeLockableMap<T>::operator<(const BTreeLockableMap& other) const {
std::lock_guard guard(_lock);
std::lock_guard guard2(other._lock);
auto lhs = _impl->begin();
auto rhs = other._impl->begin();
for (; lhs.valid() && rhs.valid(); ++lhs, ++rhs) {
if (lhs.getKey() != rhs.getKey()) {
return (lhs.getKey() < rhs.getKey());
}
if (_impl->const_value_ref_from_valid_iterator(lhs)
!= other._impl->const_value_ref_from_valid_iterator(rhs))
{
return (_impl->const_value_ref_from_valid_iterator(lhs)
< other._impl->const_value_ref_from_valid_iterator(rhs));
}
}
if (lhs.valid() == rhs.valid()) {
return false; // All keys are equal in maps of equal size.
}
return rhs.valid(); // Rhs still valid, lhs is not; ergo lhs is "less".
}
template <typename T>
size_t BTreeLockableMap<T>::size() const noexcept {
std::lock_guard guard(_lock);
return _impl->size();
}
template <typename T>
size_t BTreeLockableMap<T>::getMemoryUsage() const noexcept {
std::lock_guard guard(_lock);
const auto impl_usage = _impl->memory_usage();
return (impl_usage.allocatedBytes() + _lockedKeys.getMemoryUsage() +
sizeof(std::mutex) + sizeof(std::condition_variable));
}
template <typename T>
vespalib::MemoryUsage BTreeLockableMap<T>::detailed_memory_usage() const noexcept {
std::lock_guard guard(_lock);
return _impl->memory_usage();
}
template <typename T>
bool BTreeLockableMap<T>::empty() const noexcept {
std::lock_guard guard(_lock);
return _impl->empty();
}
template <typename T>
void BTreeLockableMap<T>::swap(BTreeLockableMap& other) {
std::lock_guard guard(_lock);
std::lock_guard guard2(other._lock);
_impl.swap(other._impl);
}
template <typename T>
void BTreeLockableMap<T>::acquireKey(const LockId& lid, std::unique_lock<std::mutex>& guard) {
if (_lockedKeys.exists(lid)) {
auto waitId = _lockWaiters.insert(lid);
while (_lockedKeys.exists(lid)) {
_cond.wait(guard);
}
_lockWaiters.erase(waitId);
}
}
template <typename T>
typename BTreeLockableMap<T>::WrappedEntry
BTreeLockableMap<T>::get(const key_type& key, const char* clientId, bool createIfNonExisting) {
LockId lid(key, clientId);
std::unique_lock guard(_lock);
acquireKey(lid, guard);
auto iter = _impl->find(key);
bool preExisted = iter.valid();
if (!preExisted && createIfNonExisting) {
_impl->update_by_raw_key(key, mapped_type());
// TODO avoid double lookup, though this is in an unlikely branch so shouldn't matter much.
iter = _impl->find(key);
assert(iter.valid());
}
if (!iter.valid()) {
return WrappedEntry();
}
_lockedKeys.insert(lid);
return WrappedEntry(*this, key, _impl->entry_from_iterator(iter), clientId, preExisted);
}
template <typename T>
bool BTreeLockableMap<T>::erase(const key_type& key, const char* client_id, bool has_lock) {
LockId lid(key, client_id);
std::unique_lock guard(_lock);
if (!has_lock) {
acquireKey(lid, guard);
}
return _impl->remove_by_raw_key(key);
}
template <typename T>
void BTreeLockableMap<T>::insert(const key_type& key, const mapped_type& value,
const char* clientId, bool has_lock, bool& pre_existed)
{
LockId lid(key, clientId);
std::unique_lock guard(_lock);
if (!has_lock) {
acquireKey(lid, guard);
}
pre_existed = _impl->update_by_raw_key(key, value);
}
template <typename T>
void BTreeLockableMap<T>::clear() {
std::lock_guard guard(_lock);
_impl->clear();
}
template <typename T>
bool BTreeLockableMap<T>::findNextKey(key_type& key, mapped_type& val,
const char* clientId,
std::unique_lock<std::mutex> &guard)
{
// Wait for next value to unlock.
auto it = _impl->lower_bound(key);
while (it.valid() && _lockedKeys.exists(LockId(it.getKey(), ""))) {
auto wait_id = _lockWaiters.insert(LockId(it.getKey(), clientId));
_cond.wait(guard);
_lockWaiters.erase(wait_id);
it = _impl->lower_bound(key);
}
if (!it.valid()) {
return true;
}
key = it.getKey();
val = _impl->entry_from_iterator(it);
return false;
}
template <typename T>
bool BTreeLockableMap<T>::handleDecision(key_type& key, mapped_type& val,
Decision decision)
{
switch (decision) {
case Decision::UPDATE:
_impl->update_by_raw_key(key, val);
break;
case Decision::REMOVE:
// Invalidating is fine, since the caller doesn't hold long-lived iterators.
_impl->remove_by_raw_key(key);
break;
case Decision::ABORT:
return true;
case Decision::CONTINUE:
break;
default:
HDR_ABORT("should not be reached");
}
return false;
}
template <typename T>
void BTreeLockableMap<T>::do_for_each_mutable(std::function<Decision(uint64_t, mapped_type&)> func,
const char* clientId,
const key_type& first,
const key_type& last)
{
key_type key = first;
mapped_type val;
std::unique_lock guard(_lock);
while (true) {
if (findNextKey(key, val, clientId, guard) || key > last) {
return;
}
Decision d(func(key, val));
if (handleDecision(key, val, d)) {
return;
}
++key;
}
}
template <typename T>
void BTreeLockableMap<T>::do_for_each(std::function<Decision(uint64_t, const mapped_type&)> func,
const char* clientId,
const key_type& first,
const key_type& last)
{
key_type key = first;
mapped_type val;
std::unique_lock guard(_lock);
while (true) {
if (findNextKey(key, val, clientId, guard) || key > last) {
return;
}
Decision d(func(key, val));
assert(d == Decision::ABORT || d == Decision::CONTINUE);
if (handleDecision(key, val, d)) {
return;
}
++key;
}
}
template <typename T>
bool BTreeLockableMap<T>::processNextChunk(std::function<Decision(uint64_t, const mapped_type&)>& func,
key_type& key,
const char* client_id,
const uint32_t chunk_size)
{
mapped_type val;
std::unique_lock guard(_lock);
for (uint32_t processed = 0; processed < chunk_size; ++processed) {
if (findNextKey(key, val, client_id, guard)) {
return false;
}
Decision d(func(const_cast<const key_type&>(key), val));
if (handleDecision(key, val, d)) {
return false;
}
++key;
}
return true;
}
template <typename T>
void BTreeLockableMap<T>::do_for_each_chunked(std::function<Decision(uint64_t, const mapped_type&)> func,
const char* client_id,
vespalib::duration yield_time,
uint32_t chunk_size)
{
key_type key{};
while (processNextChunk(func, key, client_id, chunk_size)) {
// Rationale: delay iteration for as short a time as possible while
// allowing another thread blocked on the main DB mutex to acquire it
// in the meantime. Simply yielding the thread does not have the
// intended effect with the Linux scheduler.
// This is a pragmatic stop-gap solution; a more robust change requires
// the redesign of bucket DB locking and signalling semantics in the
// face of blocked point lookups.
std::this_thread::sleep_for(yield_time);
}
}
template <typename T>
class BTreeLockableMap<T>::ReadGuardImpl final : public bucketdb::ReadGuard<T> {
typename ImplType::ReadSnapshot _snapshot;
public:
explicit ReadGuardImpl(const BTreeLockableMap<T>& db);
~ReadGuardImpl() override;
std::vector<T> find_parents_and_self(const document::BucketId& bucket) const override;
std::vector<T> find_parents_self_and_children(const document::BucketId& bucket) const override;
void for_each(std::function<void(uint64_t, const T&)> func) const override;
[[nodiscard]] uint64_t generation() const noexcept override;
};
template <typename T>
BTreeLockableMap<T>::ReadGuardImpl::ReadGuardImpl(const BTreeLockableMap<T>& db)
: _snapshot(*db._impl)
{}
template <typename T>
BTreeLockableMap<T>::ReadGuardImpl::~ReadGuardImpl() = default;
template <typename T>
std::vector<T>
BTreeLockableMap<T>::ReadGuardImpl::find_parents_and_self(const document::BucketId& bucket) const {
std::vector<T> entries;
_snapshot.template find_parents_and_self<ByConstRef>(
bucket,
[&entries]([[maybe_unused]] uint64_t key, const T& entry){
entries.emplace_back(entry);
});
return entries;
}
template <typename T>
std::vector<T>
BTreeLockableMap<T>::ReadGuardImpl::find_parents_self_and_children(const document::BucketId& bucket) const {
std::vector<T> entries;
_snapshot.template find_parents_self_and_children<ByConstRef>(
bucket,
[&entries]([[maybe_unused]] uint64_t key, const T& entry){
entries.emplace_back(entry);
});
return entries;
}
template <typename T>
void BTreeLockableMap<T>::ReadGuardImpl::for_each(std::function<void(uint64_t, const T&)> func) const {
_snapshot.template for_each<ByConstRef>(std::move(func));
}
template <typename T>
uint64_t BTreeLockableMap<T>::ReadGuardImpl::generation() const noexcept {
return _snapshot.generation();
}
template <typename T>
std::unique_ptr<ReadGuard<T>> BTreeLockableMap<T>::do_acquire_read_guard() const {
return std::make_unique<ReadGuardImpl>(*this);
}
template <typename T>
void BTreeLockableMap<T>::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
std::lock_guard guard(_lock);
out << "BTreeLockableMap {\n" << indent << " ";
if (verbose) {
for (auto it = _impl->begin(); it.valid(); ++it) {
out << "Key: " << BucketId(BucketId::keyToBucketId(it.getKey()))
<< " Value: " << _impl->entry_from_iterator(it) << "\n" << indent << " ";
}
out << "\n" << indent << " Locked keys: ";
_lockedKeys.print(out, verbose, indent + " ");
}
out << "} : ";
}
template <typename T>
void BTreeLockableMap<T>::LockIdSet::print(std::ostream& out, bool verbose,
const std::string& indent) const
{
out << "hash {";
for (const auto& entry : *this) {
if (verbose) {
out << "\n" << indent << " ";
} else {
out << " ";
}
out << entry;
}
if (verbose) {
out << "\n" << indent;
}
out << " }";
}
template <typename T>
void BTreeLockableMap<T>::unlock(const key_type& key) {
std::lock_guard guard(_lock);
_lockedKeys.erase(LockId(key, ""));
_cond.notify_all();
}
template <typename T>
void BTreeLockableMap<T>::addAndLockResults(
const std::vector<BucketId::Type>& keys,
const char* clientId,
std::map<BucketId, WrappedEntry>& results,
std::unique_lock<std::mutex> &guard)
{
// Wait until all buckets are free to be added, then add them all.
while (true) {
bool allOk = true;
key_type waitingFor(0);
for (const auto key : keys) {
if (_lockedKeys.exists(LockId(key, clientId))) {
waitingFor = key;
allOk = false;
break;
}
}
if (!allOk) {
auto waitId = _lockWaiters.insert(LockId(waitingFor, clientId));
_cond.wait(guard);
_lockWaiters.erase(waitId);
} else {
for (const auto key : keys) {
auto iter = _impl->find(key);
if (iter.valid()) {
_lockedKeys.insert(LockId(key, clientId));
results[BucketId(BucketId::keyToBucketId(key))] = WrappedEntry(
*this, key, _impl->entry_from_iterator(iter), clientId, true);
}
}
break;
}
}
}
template <typename T>
typename BTreeLockableMap<T>::EntryMap
BTreeLockableMap<T>::getContained(const BucketId& bucket,
const char* clientId)
{
std::unique_lock guard(_lock);
std::map<BucketId, WrappedEntry> results;
std::vector<BucketId::Type> keys;
_impl->template find_parents_and_self<ByConstRef>(bucket, [&keys](uint64_t key, [[maybe_unused]]const auto& value){
keys.emplace_back(key);
});
if (!keys.empty()) {
addAndLockResults(keys, clientId, results, guard);
}
return results;
}
template <typename T>
void BTreeLockableMap<T>::getAllWithoutLocking(const BucketId& bucket,
std::vector<BucketId::Type>& keys)
{
_impl->template find_parents_self_and_children<ByConstRef>(bucket, [&keys](uint64_t key, [[maybe_unused]]const auto& value){
keys.emplace_back(key);
});
}
/**
* Returns the given bucket, its super buckets and its sub buckets.
*/
template <typename T>
typename BTreeLockableMap<T>::EntryMap
BTreeLockableMap<T>::getAll(const BucketId& bucket, const char* clientId) {
std::unique_lock guard(_lock);
std::map<BucketId, WrappedEntry> results;
std::vector<BucketId::Type> keys;
getAllWithoutLocking(bucket, keys);
addAndLockResults(keys, clientId, results, guard);
return results;
}
template <typename T>
bool BTreeLockableMap<T>::isConsistent(const BTreeLockableMap::WrappedEntry& entry) {
std::lock_guard guard(_lock);
uint64_t n_buckets = 0;
_impl->template find_parents_self_and_children<ByConstRef>(entry.getBucketId(),
[&n_buckets]([[maybe_unused]] uint64_t key, [[maybe_unused]] const auto& value) {
++n_buckets;
});
return (n_buckets == 1);
}
template <typename T>
void BTreeLockableMap<T>::showLockClients(vespalib::asciistream& out) const {
std::lock_guard guard(_lock);
out << "Currently grabbed locks:";
for (const auto& locked : _lockedKeys) {
out << "\n "
<< BucketId(BucketId::keyToBucketId(locked._key))
<< " - " << locked._owner;
}
out << "\nClients waiting for keys:";
for (const auto& waiter : _lockWaiters) {
out << "\n "
<< BucketId(BucketId::keyToBucketId(waiter.second._key))
<< " - " << waiter.second._owner;
}
}
}
| [
"vekterli@verizonmedia.com"
] | vekterli@verizonmedia.com |
4d62f792d25d34fd1f684b166042dd814f205a0c | a786f46124d2cfe2378a280b6f9cced9a04c2e74 | /Hello_QtGuiApplication/Hello_QtGuiApplication.cpp | 5530393a6211d3d69ffb425d2cbb2d3c0f60c9d6 | [] | no_license | westshellX/QtTestSolution | 416f64da621c14fb656c2fa06ea69393a5392f55 | 91db752b3459334f794e0a07839fa28dab45f84e | refs/heads/master | 2021-07-17T05:55:58.821756 | 2020-06-09T01:49:23 | 2020-06-09T01:49:23 | 167,539,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | #include "Hello_QtGuiApplication.h"
Hello_QtGuiApplication::Hello_QtGuiApplication(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
}
| [
"jia.dong.xing@163.com"
] | jia.dong.xing@163.com |
88f6bcc5e0f405a4c58227cdbc5d2d021cbd16b4 | f6ef05957b8e84df6854e5da3fff1d62c37d3ce4 | /Blue-Flame-Engine/Core/BF/Graphics/Animation/Animation.h | 9447276302800cb52bf376680e9b255ce09cd863 | [
"MIT"
] | permissive | mustafa-sibai/Blue-Flame-Engine | 8a69d0b83b07382b7a0d993d7e679f35e6824fd4 | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | refs/heads/master | 2022-11-07T06:21:06.464308 | 2019-08-09T07:43:03 | 2019-08-09T07:43:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | h | #pragma once
#include "BF/Graphics/Animation/Sequence.h"
#include "BF/Graphics/Renderers/SpriteRendererComponents/Sprite.h"
#include "BF/Common.h"
namespace BF
{
namespace Graphics
{
namespace Animation
{
class AnimationSystem;
class BFE_API Animation
{
friend class BF::Graphics::Animation::AnimationSystem;
private:
Sequence* sequence;
BF::Graphics::API::Texture2D* texture;
bool play;
float timer;
int currentKeyFrameIndex;
bool renderFrame;
public:
enum class State { None, Started, Ended };
State state;
bool loop;
public:
Animation(BF::Graphics::API::Texture2D* texture, Sequence* sequence, bool loop);
~Animation();
void Play();
void Pause();
};
}
}
} | [
"mustafa@vault16software.com"
] | mustafa@vault16software.com |
d0608a5f78108b10aca57173ee28108fc98c8525 | 1bf15d79fce7a474c24f40df334ea2995046edd8 | /src/curses_wrapper.hpp | 258d9f7310b8407cd27ce2300ce55052d81702f7 | [] | no_license | vanill4Sky/so-dpp | d909120b654f4db73b1753a36c4aabc7d8564b2f | 2a334fde4a48c7a5d1db1c061d2d5bb560e33ec9 | refs/heads/master | 2022-11-05T11:22:42.758179 | 2020-06-26T09:51:32 | 2020-06-26T09:51:32 | 252,477,156 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | hpp | #pragma once
#include "utils.hpp"
#include "window.hpp"
namespace dpp
{
class curses_wrapper;
class window;
class curses_wrapper
{
public:
curses_wrapper();
~curses_wrapper();
dpp::window& get_main_window();
dpp::window make_window(utils::vec2<size_t> size, utils::vec2<size_t> pos) const;
static unsigned int color_pair_id(unsigned int fg, unsigned int bg);
private:
void init_colorpairs() const;
dpp::window main_window;
};
}
| [
"wojtek-s22@wp.pl"
] | wojtek-s22@wp.pl |
848c0f5fef16777440ce5414787d3e657ba7ca92 | 535d1b93fbe05923e2defac0f7c218bd64559e0d | /CarmenJuego/Proyecto/Carmen/bin/windows/obj/src/lime/graphics/opengl/ext/APPLE_texture_max_level.cpp | 9054c7c0530f119381eefe62b65e7b904760ede9 | [] | no_license | XxKarikyXx/ProgVJ1 | af9a9f4d7608912e1b2bab9726266b9f4ef5f44d | d26e335379a001cce21d7cd87461d75169391222 | refs/heads/develop | 2020-03-13T12:44:19.172929 | 2018-06-05T17:58:01 | 2018-06-05T17:58:01 | 131,125,411 | 0 | 0 | null | 2018-05-09T05:12:42 | 2018-04-26T08:35:17 | Haxe | UTF-8 | C++ | false | true | 4,353 | cpp | // Generated by Haxe 3.4.2 (git build master @ 890f8c7)
#include <hxcpp.h>
#ifndef INCLUDED_lime_graphics_opengl_ext_APPLE_texture_max_level
#include <lime/graphics/opengl/ext/APPLE_texture_max_level.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_2b1cc31c43c675de_9_new,"lime.graphics.opengl.ext.APPLE_texture_max_level","new",0xb41c1cd0,"lime.graphics.opengl.ext.APPLE_texture_max_level.new","lime/graphics/opengl/ext/APPLE_texture_max_level.hx",9,0x1e6a97c2)
namespace lime{
namespace graphics{
namespace opengl{
namespace ext{
void APPLE_texture_max_level_obj::__construct(){
HX_STACKFRAME(&_hx_pos_2b1cc31c43c675de_9_new)
HXDLIN( 9) this->TEXTURE_MAX_LEVEL_APPLE = (int)33085;
}
Dynamic APPLE_texture_max_level_obj::__CreateEmpty() { return new APPLE_texture_max_level_obj; }
void *APPLE_texture_max_level_obj::_hx_vtable = 0;
Dynamic APPLE_texture_max_level_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< APPLE_texture_max_level_obj > _hx_result = new APPLE_texture_max_level_obj();
_hx_result->__construct();
return _hx_result;
}
bool APPLE_texture_max_level_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x1e0d43fa;
}
APPLE_texture_max_level_obj::APPLE_texture_max_level_obj()
{
}
hx::Val APPLE_texture_max_level_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 23:
if (HX_FIELD_EQ(inName,"TEXTURE_MAX_LEVEL_APPLE") ) { return hx::Val( TEXTURE_MAX_LEVEL_APPLE ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val APPLE_texture_max_level_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 23:
if (HX_FIELD_EQ(inName,"TEXTURE_MAX_LEVEL_APPLE") ) { TEXTURE_MAX_LEVEL_APPLE=inValue.Cast< int >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void APPLE_texture_max_level_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("TEXTURE_MAX_LEVEL_APPLE","\xa0","\xc4","\xc8","\xdf"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo APPLE_texture_max_level_obj_sMemberStorageInfo[] = {
{hx::fsInt,(int)offsetof(APPLE_texture_max_level_obj,TEXTURE_MAX_LEVEL_APPLE),HX_HCSTRING("TEXTURE_MAX_LEVEL_APPLE","\xa0","\xc4","\xc8","\xdf")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *APPLE_texture_max_level_obj_sStaticStorageInfo = 0;
#endif
static ::String APPLE_texture_max_level_obj_sMemberFields[] = {
HX_HCSTRING("TEXTURE_MAX_LEVEL_APPLE","\xa0","\xc4","\xc8","\xdf"),
::String(null()) };
static void APPLE_texture_max_level_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(APPLE_texture_max_level_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void APPLE_texture_max_level_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(APPLE_texture_max_level_obj::__mClass,"__mClass");
};
#endif
hx::Class APPLE_texture_max_level_obj::__mClass;
void APPLE_texture_max_level_obj::__register()
{
hx::Object *dummy = new APPLE_texture_max_level_obj;
APPLE_texture_max_level_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("lime.graphics.opengl.ext.APPLE_texture_max_level","\xde","\xb4","\x81","\x4d");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = APPLE_texture_max_level_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(APPLE_texture_max_level_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< APPLE_texture_max_level_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = APPLE_texture_max_level_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = APPLE_texture_max_level_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = APPLE_texture_max_level_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace lime
} // end namespace graphics
} // end namespace opengl
} // end namespace ext
| [
"kariky@hotmail.es"
] | kariky@hotmail.es |
d6f1aeca71476afacdb9b0aa0dbbea155ef8dc39 | 3e05bafb4d1bceefece23383a9f74d58a099cab1 | /SimpleSideScrollerFramework/src/sssf/graphics/GameGraphics.cpp | 40ef75f1273ad58dd34cd6e635d41d769b0e3991 | [] | no_license | anthony-consoli/Grocery_DASH | 343e692da0fe748282b842bb89d1b431a6d097f8 | 55dfe4d1e0d065698c3158d20dfad51647a401ab | refs/heads/master | 2021-01-10T13:51:55.536722 | 2016-02-24T18:40:02 | 2016-02-24T18:40:02 | 52,465,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,476 | cpp | /*
Author: Richard McKenna
Stony Brook University
Computer Science Department
GameGraphics.cpp
See GameGraphics.h for a class description.
*/
#include "sssf_VS\stdafx.h"
#include "sssf\game\Game.h"
#include "sssf\game\IllegalArgumentException.h"
#include "sssf\graphics\GameGraphics.h"
#include "sssf\graphics\TextureManager.h"
#include "sssf\gsm\state\GameStateManager.h"
#include "sssf\gsm\world\World.h"
#include "sssf\gui\GameGUI.h"
#include "sssf\os\GameOS.h"
#include "sssf\text\GameText.h"
#include "sssf\text\TextFileWriter.h"
/*
GameGraphics - Default constructor, nothing to initialize.
*/
GameGraphics::GameGraphics()
{
debugTextShouldBeRendered = false;
pathfindingGridShouldBeRendered = false;
}
/*
~GameGraphics - Destructor, it cleans up the render lists and texture
managers. This should only be called when the application is closing.
*/
GameGraphics::~GameGraphics()
{
delete guiRenderList;
delete guiTextureManager;
delete worldRenderList;
delete worldTextureManager;
}
/*
clearWorldTextures - When the game leaves a level we have to clear
out these data structures. Calling clear on these will delete
all the objects inside.
*/
void GameGraphics::clearWorldTextures()
{
// CLEAR LEVEL DATA STRUCURES
worldTextureManager->clear();
worldRenderList->clear();
}
/*
fillRenderLists - This method causes the render lists to be
filled with the things that have to be drawn this frame.
*/
void GameGraphics::fillRenderLists(Game *game)
{
// GENERATE RENDER LISTS FOR GAME WORLD AND GUI
GameStateManager *gsm = game->getGSM();
gsm->addGameRenderItemsToRenderList(game);
GameGUI *gui = game->getGUI();
gui->addRenderItemsToRenderList(game);
}
/*
init - This method constructs the data structures for managing textures
and render lists. It calls the createTextureManager, which is technology
specific, and so is implemented only by child classes.
*/
void GameGraphics::init(int initScreenWidth, int initScreenHeight)
{
// INIT SCREEN DIMENSIONS
screenWidth = initScreenWidth;
screenHeight = initScreenHeight;
// GUI TEXTURES (like buttons, cursor, etc.)
guiRenderList = new RenderList(DEFAULT_INIT_GUI_RENDER_LIST_SIZE);
guiTextureManager = createTextureManager();
// LEVEL TEXTURES (like sprites, tiles, particles, etc.)
worldRenderList = new RenderList(DEFAULT_INIT_LEVEL_RENDER_LIST_SIZE);
worldTextureManager = createTextureManager();
}
/*
renderText - This method will go through the GameText argument,
pull out each TextToDraw object, and use a technology-specific
method in a child class, renderTextToDraw, to render each
piece of text.
*/
void GameGraphics::renderText(GameText *text)
{
if (debugTextShouldBeRendered)
{
int numTextObjects = text->getNumTextObjectsToDraw();
for (int i = 0; i < numTextObjects; i++)
{
TextToDraw *textToDraw = text->getTextToDrawAtIndex(i);
renderTextToDraw(textToDraw);
}
}
}
void GameGraphics::renderInGameText(Game* game, GameText *text)
{
if (game->getGSM()->isGameInProgress()==true && game->getGSM()->isPlayerAtShelf() == false)
{
int numTextObjects = text->getNumGameTextObjectsToDraw();
for (int i = 0; i < numTextObjects; i++)
{
TextToDraw *textToDraw = text->getGameTextToDrawAtIndex(i);
renderTextToDraw(textToDraw);
}
}
}
void GameGraphics::renderSettingsScreenText(Game* game, GameText *text)
{
if (game->getGSM()->isAtSettingsScreen() == true)
{
int numTextObjects = text->getNumSettingsTextObjectsToDraw();
for (int i = 0; i < numTextObjects; i++)
{
TextToDraw *textToDraw = text->getSettingsTextToDrawAtIndex(i);
renderTextToDraw(textToDraw);
}
}
}
void GameGraphics::renderInGameItemList(Game* game, GameText *text){
int numTextObjects = text->getNumItemListTextToDrawTextObjectsToDraw();
for (int i = 0; i < numTextObjects; i++)
{
TextToDraw *textToDraw = text->getItemListTextToDrawTextToDrawAtIndex(i);
renderTextToDraw(textToDraw);
}
}
void GameGraphics::renderStatsScreenText(Game* game, GameText *text){
int numTextObjects = text->getNumStatsTextToDrawTextObjectsToDraw();
for (int i = 0; i < numTextObjects; i++)
{
TextToDraw *textToDraw = text->getStatsTextToDrawTextToDrawAtIndex(i);
renderTextToDraw(textToDraw);
}
}
void GameGraphics::renderB2Draw(Game *game){
if (b2DrawDebugShouldBeRendered){
Physics *physics = game->getGSM()->getPhysics();
this->SetFlags(this->e_shapeBit);
//this->SetFlags(this->e_aabbBit);
physics->box2DWorld.DrawDebugData();
}
} | [
"anthony.n.consoli@gmail.com"
] | anthony.n.consoli@gmail.com |
f9ec8b7476dda1703541c3bf54c8984c053dfe85 | 7c37f348d8d8a2305d6bf57ed77fffcedc97433b | /DS-Cpp/Heaps.cpp | 3879d21830b7e8074dc1f57a08b1c6fa7c215449 | [] | no_license | Riya-code/CodeBag | 77d3473e24a2a16c75dfe14bf3b152006c46007e | 95cbccee5c673e774823518ded869e2055f50498 | refs/heads/main | 2023-01-04T07:48:26.335717 | 2020-11-01T15:08:27 | 2020-11-01T15:08:27 | 304,252,052 | 0 | 3 | null | 2020-10-19T15:29:38 | 2020-10-15T07:58:46 | C++ | UTF-8 | C++ | false | false | 174 | cpp | #include <bits/stdc++.h>
using namespace std;
int main()
{
vector<int> v ={3,4,2,8};
make_heap(v.begin(),v.end());
cout<<"max"<<v.front;
return 0;
} | [
"rj220699@gmailcom"
] | rj220699@gmailcom |
78b72ac8d4720dbd0dd0e423bf11414c7a4d4f6e | 74548bcf1629d5251bfabfaf23772ce7fb6079c6 | /targets/mbedk64f/source/tuvtester.cpp | 24f6e3eef1c829fa468fd56e14a705fd53c3f60d | [
"BSD-3-Clause",
"ISC",
"Apache-2.0",
"BSD-2-Clause",
"MIT"
] | permissive | young-mu/libtuv | 14fd8c19ceece90f4a1c8c3bcb85c9f160797cf3 | 3d40e49cd0fe27c4a0f201f807df85e364ddfe60 | refs/heads/master | 2020-06-30T23:42:09.953619 | 2016-11-22T03:49:43 | 2016-11-22T03:49:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | /* Copyright 2015 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mbed-drivers/mbed.h"
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include <uv.h>
#include "runner.h"
#include "raw_main.h"
/* Do platform-specific initialization. */
int platform_init() {
return 0;
}
void run_sleep(int msec) {
uv_sleep(msec);
}
int run_helper(task_entry_t* task) {
task->main();
return 0;
}
int wait_helper(task_entry_t* task) {
TDDDLOG("wait_helper... not implemented");
(void)task;
return 0;
}
static void call_cleanup(void) {
tuv_cleanup();
}
int run_test_one(task_entry_t* task) {
int result;
if (task) {
result = run_test_part(task->task_name, task->process_name);
}
else {
result = 255;
}
if (result) {
if (result == 255) {
// end of test
minar::Scheduler::postCallback(call_cleanup)
.delay(minar::milliseconds(1))
;
}
else {
TDLOG("!!! Failed to run [%s]", task->task_name);
}
}
return 0;
}
void run_tests_continue(void) {
minar::Scheduler::postCallback(run_tests_one);
}
void tuvtester_entry(void) {
InitDebugSettings();
platform_init();
run_tests_init();
minar::Scheduler::postCallback(run_tests_one);
}
| [
"saehie.park@samsung.com"
] | saehie.park@samsung.com |
e99e06b88de369e956521bfa05c8b032a57e4913 | c906ea930de4fe6e88ec0ac0c26d6882cc2ab964 | /Expense.cpp | 02c417c4813c4f33db0369678edcae3cf7fd388b | [] | no_license | hlodwig1993/PersonalDevelopment | 8b72b429e67864d64faa6ed6b56c843e06cbfdf5 | 01cf825e5dba56ceb88ff5ddda0ebb12983069b2 | refs/heads/main | 2023-02-13T01:29:11.844040 | 2021-01-18T16:30:05 | 2021-01-18T16:30:05 | 328,462,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | #include "Expense.h"
void Expense::setExpenseId(int newExpenseId)
{
if (newExpenseId >= 0)
expenseId = newExpenseId;
}
void Expense::setUserId(int newUserId)
{
userId = newUserId;
}
void Expense::setDate (int newDate)
{
date = newDate;
}
void Expense::setItem (string newItem)
{
item = newItem;
}
void Expense::setAmount (double newAmount)
{
amount = newAmount;
}
int Expense::getExpenseId()
{
return expenseId;
}
int Expense::getUserId()
{
return userId;
}
int Expense::getDate()
{
return date;
}
string Expense::getItem()
{
return item;
}
double Expense::getAmount()
{
return amount;
}
| [
"daniel.bodurka.programista@gmail.com"
] | daniel.bodurka.programista@gmail.com |
852c05def030060277d15d8587554da423c40195 | 3dee0da8cb704d6bb49f903b76f066a47f8bb72e | /External/Arduino_HTML5_Netpie_Project_Combined/Arduino_HTML5_Netpie_Project_Combined.ino | 88dbc442280de27f91ec5cf618cb3d73249162c8 | [] | no_license | chuannatcha/project | 0e3362580ec93f68afee42649c7b5fc41fc2ffd1 | 3af223cbf3cf90a91491a09f4c8bd8a5c6f98afc | refs/heads/master | 2021-01-21T11:40:08.821218 | 2016-05-25T07:53:52 | 2016-05-25T07:53:52 | 50,983,094 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,697 | ino | #include <AuthClient.h>
#include <MicroGear.h>
#include <MQTTClient.h>
#include <PubSubClient.h>
#include <SHA1.h>
#include <Arduino.h>
#include <SPI.h>
#include <Ethernet.h>
//#include <EEPROM.h>
#include <MicroGear.h>
#include <ArduinoJson.h>
#define APPID "RMUTLLASCS"
#define KEY "S2ezVjJCmVVdPrq"
#define SECRET "7AoqXKrZeV8ptz1GPKA4oAtGZ"
#define ALIAS "Arduino_Main"
#define SCOPE ""
#define intervalTime 2500
#define SavingMoniPin 42
#define SavingActPin 44
#define SecurityMoniPin 46
#define SecurityActPin 48
#define A2 0
#define A1 1
#define L1 2
#define L2 3
#define L3 4
#define M1 5
#define M2 6
#define M3 7
const unsigned long MaxEnSavingTime = 60000;
const unsigned long MaxDisSavingTime = 10000;
const unsigned long MaxEnSecurityTime = 10000;
const unsigned long MaxDisSecurityTime = 30000;
const unsigned long SecurityModeStartTime = 1000;
const char SwitchModePin = 22;
byte mac[] = { 0x00, 0xCD, 0x12, 0xEC, 0x2D, 0x48 };
const char* ClientID = "Arduino_Mega_Main";
char* inTopic = "WebCommand";
char* outTopic = "WebStatus";
String M2Ainput = "";
char A2Wmsg[100], W2Amsg[50], M2Amsg[20], A2Mmsg[20];
unsigned char M2Achecksum, A2Mchecksum;
unsigned long timer = 0, lastMsg = 0;
boolean M2Acomplete = false, SavingModeRunning = false, SecurityModeRunning = false, SecurityFirstTimeEvent = false, DeviceMode = false; /* 0:Saving 1:Security */
unsigned long EnSavingBeginCount = 0, DisSavingBeginCount = 0, EnSecurityBeginCount = 0, DisSecurityBeginCount = 0, SecurityFirstTimeCount = 0;
boolean Tstatus[] = {false, false, false, false, false, false, false, false};
//Type A2 A1 L1 L2 L3 M1 M2 M3
//Index 0 1 2 3 4 5 6 7
char A2Mtype[2] = {'A', '1'};
char A2Mmode = 'R';
boolean A2Mlogic = 1;
boolean button, st = false;
EthernetClient client;
AuthClient *authclient;
MicroGear microgear(client);
void onMsghandler(char *topic, uint8_t* inmsg, unsigned int msglen) {
Serial.print("Incoming message --> ");
Serial.print(topic);
Serial.print(" : ");
char* text;
text = (char*) malloc(msglen + 1);
memcpy(text, inmsg, msglen);
text[msglen] = '\0';
strcpy(W2Amsg, text);
Serial.println(W2Amsg);
StaticJsonBuffer<200> RxBuffer;
JsonObject& Rx = RxBuffer.parseObject(W2Amsg);
if (!Rx.success()) {
Serial.println("parseObject() failed");
return;
}
const char* name = Rx["name"];
boolean logic = Rx["logic"];
//Serial.println(name);
//Serial.println(logic);
A2Mtype[0] = name[0];
A2Mtype[1] = name[1];
A2Mmode = 'R';
A2Mlogic = logic;
Send_A2M();
}
void onConnected(char *attribute, uint8_t* msg, unsigned int msglen)
{
Serial.println("Connected to NETPIE...");
microgear.setName(inTopic);
}
void Generate_message()
{
StaticJsonBuffer<200> TxBuffer;
JsonObject& Tx = TxBuffer.createObject();
Tx["Mode"] = (DeviceMode) ? 1 : 0;
Tx["ModeSt"] = (SavingModeRunning || SecurityModeRunning) ? 1 : 0;
Tx["A1"] = (Tstatus[A1]) ? 1 : 0;
Tx["L1"] = (Tstatus[L1]) ? 1 : 0;
Tx["L2"] = (Tstatus[L2]) ? 1 : 0;
Tx["L3"] = (Tstatus[L3]) ? 1 : 0;
Tx["M1"] = (Tstatus[M1]) ? 1 : 0;
Tx["M2"] = (Tstatus[M2]) ? 1 : 0;
Tx["M3"] = (Tstatus[M3]) ? 1 : 0;
strcpy(A2Wmsg, "");
Tx.printTo(A2Wmsg, sizeof(A2Wmsg));
}
void serialEvent() {
while (Serial1.available())
{
char inChar = (char)Serial1.read();
M2Ainput += inChar;
if (inChar == '\n')
{
M2Acomplete = true;
}
}
if (M2Acomplete)
{
Parse_Serial();
M2Ainput = "";
M2Acomplete = false;
}
}
void Parse_Serial()
{
unsigned char ChksumPosition = M2Ainput.indexOf('#');
String Chksum = M2Ainput.substring(ChksumPosition + 1, ChksumPosition + 2);
unsigned char checksum = Chksum.toInt();
M2Ainput = M2Ainput.substring(0, ChksumPosition);
M2Ainput.toCharArray(M2Amsg, 20);
M2Achecksum = 0;
for (char x = 0; x < ChksumPosition; x++)
{
M2Achecksum += M2Amsg[x] - 48;
}
Serial.print("M2A Status : ");
Serial.println(M2Amsg);
//Serial.println(checksum);
//Serial.println(M2Achecksum);
//When all status arrived then ...
if (checksum == M2Achecksum)
{
Serial.println("Status Checksum OK");
for (char y = 0; y < ChksumPosition; y++)
{
Tstatus[y] = M2Amsg[y] - 48;
//Serial.print(Tstatus[y], DEC);
}
//Serial.println("");
//Serial.println("Checksum OK");
// When message from ESP-Master arrived then Send to Web
Generate_message();
Serial.print("Publish message: ");
Serial.println(A2Wmsg);
microgear.chat(outTopic, A2Wmsg);
}
}
void Send_A2M()
{
strcpy(A2Mmsg, "");
A2Mchecksum = 0;
snprintf(A2Mmsg, 20, "%c%c-%c-%d", A2Mtype[0], A2Mtype[1], A2Mmode, A2Mlogic);
for (char x = 0; x < strlen(A2Mmsg); x++)
{
A2Mchecksum ^= A2Mmsg[x];
}
A2Mmsg[strlen(A2Mmsg)] = '\0';
snprintf(A2Mmsg, 20, "%s#%03d", A2Mmsg, A2Mchecksum);
Serial1.println(A2Mmsg);
//Monitor Arduino to ESP-Master Serial
Serial.print("A2M Command : ");
Serial.println(A2Mmsg);
}
void Enable_Saving()
{
if (Tstatus[M1] || Tstatus[M2] || Tstatus[M3])
{
EnSavingBeginCount = millis();
}
else
{
if ((millis() - EnSavingBeginCount) > MaxEnSavingTime)
{
//Saving Enable
Serial1.println("SA-S-1#112");
SavingModeRunning = true;
Serial.println("Saving Condition Running");
digitalWrite(SavingMoniPin, LOW);
digitalWrite(SavingActPin, HIGH);
digitalWrite(SecurityMoniPin, LOW);
digitalWrite(SecurityActPin, LOW);
}
}
}
void Disable_Saving()
{
if (Tstatus[M1] || Tstatus[M2] || Tstatus[M3])
{
if ((millis() - DisSavingBeginCount) > MaxDisSavingTime)
{
//Saving Disable
Serial1.println("SA-S-0#113");
SavingModeRunning = false;
Serial.println("Saving Condition Cancel");
digitalWrite(SavingMoniPin, HIGH);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, LOW);
digitalWrite(SecurityActPin, LOW);
}
}
else
{
DisSavingBeginCount = millis();
}
}
void Enable_Security()
{
if (Tstatus[M1] || Tstatus[M2] || Tstatus[M3])
{
if ((millis() - EnSecurityBeginCount) > MaxEnSecurityTime)
{
//Security Enable ** Found theif **
Serial2.print("AT+CMGF=1\r");
delay(1000);
Serial2.print("AT+CMGS=\"0842216218\"\r");
delay(1000);
Serial2.print("Found Theif in the RMUTL ELEC Computer Room\r"); //The text for the message
delay(1000);
Serial2.write(26); //Equivalent to sending Ctrl+Z
Serial1.println("LA-R-1#110");
SecurityModeRunning = true;
Serial.println("Found theif and System has been sent SMS");
digitalWrite(SavingMoniPin, LOW);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, LOW);
digitalWrite(SecurityActPin, HIGH);
}
}
else
{
EnSecurityBeginCount = millis();
}
}
void Disable_Security()
{
if (Tstatus[M1] || Tstatus[M2] || Tstatus[M3])
{
DisSecurityBeginCount = millis();
}
else
{
if ((millis() - DisSecurityBeginCount) > MaxDisSecurityTime)
{
//Security Disable ** Thief went away **
Serial2.print("AT+CMGF=1\r");
delay(1000);
Serial2.print("AT+CMGS=\"0842216218\"\r");
delay(1000);
Serial2.print("Thief has left the RMUTL Computer Room\r"); //The text for the message
delay(1000);
Serial2.write(26); //Equivalent to sending Ctrl+Z
Serial1.println("LA-R-0#111");
SecurityModeRunning = false;
Serial.println("Thief went away");
digitalWrite(SavingMoniPin, LOW);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, HIGH);
digitalWrite(SecurityActPin, LOW);
}
}
}
void SwitchMode()
{
if (!DeviceMode)
{
//Change to Security Mode
Serial.println("Device was on Security Mode");
Serial1.println("RA-R-0#113");//Cancel All Remote Command that operated
DeviceMode = true;
SecurityFirstTimeCount = millis();
digitalWrite(SavingMoniPin, LOW);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, HIGH);
digitalWrite(SecurityActPin, LOW);
}
else
{
//Change to Saving Mode
Serial.println("Device was on Saving Mode");
Serial1.println("RA-R-0#113");//Cancel All Remote Command that operated
DeviceMode = false;
SecurityFirstTimeEvent = false;
EnSavingBeginCount = millis();
digitalWrite(SavingMoniPin, HIGH);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, LOW);
digitalWrite(SecurityActPin, LOW);
}
}
void setup()
{
M2Ainput.reserve(20);
Serial.begin(9600);
Serial1.begin(9600);
Serial2.begin(2400);
Serial.println("Starting...");
pinMode(SwitchModePin, INPUT);
pinMode(SavingMoniPin, OUTPUT);
pinMode(SavingActPin, OUTPUT);
pinMode(SecurityMoniPin, OUTPUT);
pinMode(SecurityActPin, OUTPUT);
digitalWrite(SavingMoniPin, HIGH);
digitalWrite(SavingActPin, LOW);
digitalWrite(SecurityMoniPin, LOW);
digitalWrite(SecurityActPin, LOW);
Serial.println("Waiting for 10 second");
delay(10000);
microgear.on(MESSAGE, onMsghandler);
microgear.on(CONNECTED, onConnected);
if (Ethernet.begin(mac)) {
Serial.println(Ethernet.localIP());
microgear.resetToken();
microgear.init(KEY, SECRET, ALIAS);
microgear.connect(APPID);
}
EnSavingBeginCount = millis();
}
void loop()
{
//Serial.println("Entered loop code");
serialEvent();
if (!digitalRead(SwitchModePin))
{
delay(250);
if (!digitalRead(SwitchModePin))
{
while (!digitalRead(SwitchModePin))
delay(250);
SwitchMode();
}
}
if (!DeviceMode)
{
if (!SavingModeRunning)
Enable_Saving();
else
Disable_Saving();
}
else
{
if (SecurityFirstTimeEvent)
{
if (!SecurityModeRunning)
Enable_Security();
else
Disable_Security();
}
else
{
if ((millis() - SecurityFirstTimeCount) > SecurityModeStartTime)
{
SecurityFirstTimeEvent = true;
EnSecurityBeginCount = millis();
Serial.println("First Time of Security End");
}
}
}
/*
long now = millis();
if (now - lastMsg > 2500) {
lastMsg = now;
Generate_message();
Serial.print("Publish message: ");
Serial.println(A2Wmsg);
microgear.chat(outTopic, A2Wmsg);
}
*/
if (microgear.connected())
{
microgear.loop();
}
else
{
Serial.println("connection lost, reconnect...");
microgear.connect(APPID);
if (timer >= 5000)
{
microgear.connect(APPID);
timer = 0;
}
else timer += 100;
}
}
| [
"chuan_natcha@hotmail.com"
] | chuan_natcha@hotmail.com |
3cec704f3cb939f14b1b153703b0eb8dce7bb1b5 | b6500c85496fdd1caddf0cb3d78a4c7d30ae32be | /CircularList.cpp | bb1028ccd65a3161f95fb843c3cc07d79f9b0adc | [] | no_license | sksam-Encoder/C_PlusPlus_Data_Structure | 285effc585fe08ec674d3d41b8fb6587db861bd7 | 02c94bd8a3b40321ad670c84f6bd65c3994658f1 | refs/heads/master | 2023-07-08T03:25:06.723847 | 2021-08-15T05:31:32 | 2021-08-15T05:31:32 | 395,321,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,622 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
class Node
{
private:
public:
int D;
int key;
Node *n;
Node()
{
key = 0;
D = 0;
n = NULL;
}
Node(int k, int d)
{
this->key = k;
D = d;
n = NULL;
}
};
class CircularList
{
private:
Node *head;
public:
CircularList()
{
head = NULL;
}
// Check if a particluar list exist or not using key
Node *isExist(int k)
{
Node *ptr, *temp = NULL;
if (head == NULL)
{
return head;
}
else
{
ptr = head;
do
{
if (ptr->key == k)
{
temp = ptr;
}
ptr = ptr->n;
} while (ptr != head);
return temp;
}
}
void insertLast(Node *new_node)
{
if (isExist(new_node->key) != NULL)
{
cout << "node exists with a key value: "
<< new_node->key
<< "add another node with diffrent key"
<< endl;
}
else
{
if (head == NULL)
{
head = new_node;
new_node->n = head;
cout << "node append at a head position"
<< endl;
}
else
{
Node *ptr = head;
while (ptr->n != head)
{
/* code */
ptr = ptr->n;
}
ptr->n = new_node;
new_node->n = head;
cout << "node appended"
<< endl;
}
}
}
// insertion node with specific key
void insertAfter(int k, Node *new_node)
{
Node *ptr = isExist(k);
if (isExist(new_node->key) != NULL)
{
cout << "node exists with a key value: "
<< new_node->key
<< "add another node with diffrent key"
<< endl;
}
else
{
if (ptr->n == head)
{
ptr->n = new_node;
new_node->n = head;
cout << "Insertion happens at end" << endl;
}
else
{
new_node->n = ptr->n;
ptr->n = new_node;
cout << "Insertion happens at Between" << endl;
}
}
}
// Delete Node by unique key.
void DeleteNode(int key)
{
Node *ptr = isExist(key);
if (isExist(key) == NULL)
{
cout << "Node Does not Exist with key :"
<< key << endl;
}
else
{
if (ptr == head)
{
if (head->n == head) // it means one node
{
Node *temp = head;
head = NULL;
free(temp);
cout << "Node Deleted ...List Empty"
<< endl;
}
else
{
Node *ptr1 = head;
while (ptr1->n != NULL)
{
ptr1 = ptr1->n;
}
Node *temp = head;
ptr1->n = head->n;
head = head->n;
free(temp);
cout << "First Node is Deleted:"
<< endl;
}
}
else
{
// delete Other Node..
Node *pre_ptr = head;
Node *temp = NULL;
Node *del_ptr = head->n;
while (del_ptr != NULL)
{
if (del_ptr->key == key)
{
temp = del_ptr;
del_ptr = NULL;
}
else
{
pre_ptr = pre_ptr->n;
del_ptr = del_ptr->n;
}
}
pre_ptr->n = temp->n;
free(temp);
cout << "node delete with key value:"
<< key << endl;
}
}
}
//
void UpdateNode(int k, int new_data)
{
Node *ptr = isExist(k);
if (ptr == NULL)
{
cout << "Node doesnot exist with key "
<< k << endl;
}
else
{
ptr->D = new_data;
cout << "Data Updated Sucessfully in key :"
<< ptr->key << endl;
}
}
// print List
void print_l()
{
if (head == NULL)
{
cout << "List Is Empty";
}
else
{
Node *temp = head;
do
{
cout << temp->D
<< " "
<< endl;
temp = temp->n;
}while (temp != head);
}
}
void prependNode(int key, Node *node)
{
if (isExist(node->key) != NULL)
{
cout << "node exists with a key value: "
<< node->key
<< "add another node with diffrent key"
<< endl;
}
else
{
if (head == NULL)
{
node->key = key;
head = node;
node->n = head;
}
else
{
Node *ptr = head;
while (ptr->n != head)
{
ptr = ptr->n;
}
ptr->n = node;
node->n = head;
head = node;
}
}
}
};
int main()
{
CircularList obj; // methods contain and head pointer.
int option;
int key,k1, data;
do
{
cout << "\nWhat operation do you want to perform? Select Option number. Enter 0 to exit." << endl;
cout << "1. appendNode()" << endl;
cout << "2. prependNode()" << endl;
cout << "3. insertNodeAfter()" << endl;
cout << "4. deleteNodeByKey()" << endl;
cout << "5. updateNodeByKey()" << endl;
cout << "6. print()" << endl;
cout << "7. Clear Screen" << endl
<< endl;
cin >> option;
Node *n1 = new Node; // Structure of node
switch (option)
{
case 1:
cout << "Enter the key of node: "
<< endl;
cin >> key;
cout << "enter data for append: " << endl;
cin >> data;
n1->key = key;
n1->D = data;
obj.insertLast(n1);
break;
case 2:
cout << "Enter the key of node: "
<< endl;
cin >> key;
cout << "enter data for prepend: " << endl;
cin >> data;
n1->key = key;
n1->D = data;
obj.prependNode(key,n1);
break;
case 3:
cout << "Enter the key of node: "
<< endl;
cout << "Enter key for after Insertion: "
<< endl;
cin>> k1;
cin >> key;
cout << "enter data for insert nth: " << endl;
cin >> data;
n1->key = key;
n1->D = data;
obj.insertAfter(k1,n1);
break;
case 4:
cout << "Enter the key of node for deletion: "
<< endl;
cin>> key;
obj.DeleteNode(key);
break;
case 5:
cout<<"enter key for updation & and new data "<< endl;
cin>> key >>data ;
obj.UpdateNode(key,data);
cout<<"value updated for key: "
<<key
<<endl;
break;
case 6:
obj.print_l();
break;
case 7:
system("cls");
}
} while (option != 0);
return 0;
}
| [
"sksam87136@gmail.com"
] | sksam87136@gmail.com |
c3e7eb569ca1ce03fb942abb12906ba5d6c3f93e | f3f2c95e4aa5f5ae0823d947be0e0fe7a9aae081 | /lib/Game/include/AI/Game/Activity.hpp | 13a500ddc08537be36b3d238a92155ba06fe4864 | [] | no_license | drblallo/AbominableIntelligence | 401461e141d7110c1c30784011aa6f85fb8baeae | 87457fc04b9f1243777d131a6ceaf6819cdd343a | refs/heads/master | 2023-03-20T07:15:33.157075 | 2021-03-07T15:17:14 | 2021-03-07T15:17:14 | 323,961,744 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 338 | hpp | #pragma once
#include <string>
namespace AI
{
enum class Activity
{
None,
ExtendInfluence,
ReduceInfluence,
BidForOwership,
Attack,
Infect
};
class Map;
class Character;
template<Activity activity>
void resolveActivity(Map& map, Character& character);
std::string activityToString(Activity a);
} // namespace AI
| [
"mo.fioravanti@gmail.com"
] | mo.fioravanti@gmail.com |
b83db8cca86b1f63b059a83c4483feec7c7dfa25 | 5f892ed86801891b5700eba03f8e2771770c7d42 | /Medication.cpp | 4a50763daa603d5a4f84533fbcf5e6455c950e62 | [] | no_license | bamzie/Hospital | c0dc97e5c603e2e4b82d9a0f8c952c89812df6f2 | 03a320f7163051e47e18ff35ab8d7651c2762a3c | refs/heads/master | 2021-01-12T00:19:31.081923 | 2017-01-12T03:25:40 | 2017-01-12T03:25:40 | 78,705,414 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | //
// Medication.cpp
// Hospital
//
// Created by Brian Morales on 1/10/17.
// Copyright © 2017 Brian Morales. All rights reserved.
//
#include "Medication.h"
| [
"Bamz@Brians-MacBook-Pro.local"
] | Bamz@Brians-MacBook-Pro.local |
d7f2d07721d773c354103fe31d2a8465a67a2f18 | 893c89b7f63c50d4e5708a4f760eed3464eba8df | /menu.cpp | 4c1f9603059f54c2c6e91a757cc2e6d7acb8f31c | [] | no_license | ZiyunZhang1022/2d_game | 3cbd294ca20174037b01f86ca20c70ba80563daa | 920829bb1cf057bd7592ad263b86392484e77db0 | refs/heads/master | 2020-03-14T20:50:18.364979 | 2018-05-02T17:36:18 | 2018-05-02T17:36:18 | 131,783,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,137 | cpp | #include<sstream>
#include "menu.h"
Menu::Menu(SDL_Renderer* rend) :
renderer(rend),
gdata(Gamedata::getInstance()),
hudFrame( {gdata.getXmlInt("menu/loc/x"),
gdata.getXmlInt("menu/loc/y"),
gdata.getXmlInt("menu/width"),
gdata.getXmlInt("menu/height")}
),
backColor({static_cast<Uint8>(gdata.getXmlInt("menu/backColor/r")),
static_cast<Uint8>(gdata.getXmlInt("menu/backColor/g")),
static_cast<Uint8>(gdata.getXmlInt("menu/backColor/b")),
static_cast<Uint8>(gdata.getXmlInt("menu/backColor/a"))}
),
menuColor({static_cast<Uint8>(gdata.getXmlInt("menu/color/r")),
static_cast<Uint8>(gdata.getXmlInt("menu/color/g")),
static_cast<Uint8>(gdata.getXmlInt("menu/color/b")),
static_cast<Uint8>(gdata.getXmlInt("menu/color/a"))}
),
clock( Clock::getInstance() ),
io( IoMod::getInstance() ),
options(),
optionLoc( { gdata.getXmlInt("menu/optionLoc/x"),
gdata.getXmlInt("menu/optionLoc/y")}
),
clicks( {Sprite("clickOff"), Sprite("clickOn")} ),
currentClick(0),
currentOption(0),
spaces(gdata.getXmlInt("menu/spaces")),
startClickX(optionLoc[0]-spaces),
startClickY(optionLoc[1]+spaces),
clickX(startClickX),
clickY(startClickY)
{
int noOfOptions = gdata.getXmlInt("menu/noOfOptions");
std::stringstream strm;
for (int i = 0; i < noOfOptions; ++i) {
strm.clear();
strm.str("");
strm << i;
std::string option("menu/option"+strm.str());
options.push_back(gdata.getXmlStr(option));
}
}
void Menu::incrIcon() {
clickY += spaces;
if ( clickY > static_cast<int>(options.size())*spaces+optionLoc[1]) {
clickY = startClickY;
currentOption = 0;
}
else ++currentOption;
}
void Menu::decrIcon() {
clickY -= spaces;
if ( clickY < spaces+optionLoc[1]) {
clickY = startClickY+2*spaces;
currentOption = options.size()-1;
}
else --currentOption;
}
void Menu::drawBackground() const {
// First set the blend mode so that alpha blending will work;
// the default blend mode is SDL_BLENDMODE_NONE!
SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);
// Set the hud background color:
SDL_SetRenderDrawColor( renderer, backColor.r, backColor.g,
backColor.b, backColor.a );
// Draw the filled rectangle:
SDL_RenderFillRect( renderer, &hudFrame );
// Set the color for the Menu outline:
SDL_Rect menuFrame = {hudFrame.x+50, hudFrame.y+40,
hudFrame.w-100, hudFrame.h-100};
SDL_SetRenderDrawColor( renderer, menuColor.r,
menuColor.g, menuColor.b, menuColor.a );
SDL_RenderFillRect( renderer, &menuFrame );
}
int Menu::getInputEventLoop() const {
SDL_Event event;
const Uint8* keystate;
bool done = false;
drawBackground();
std::string inNumber = " ";
std::string msg = "Press return/esc when finished.";
while ( !done ) {
// The next loop polls for events, guarding against key bounce:
while ( SDL_PollEvent(&event) ) {
keystate = SDL_GetKeyboardState(NULL);
if (event.type == SDL_QUIT) { done = true; break; }
if(event.type == SDL_KEYDOWN) {
if (keystate[SDL_SCANCODE_ESCAPE] ||
keystate[SDL_SCANCODE_Q] ||
keystate[SDL_SCANCODE_RETURN] ) {
done = true;
break;
}
if ( keystate[SDL_SCANCODE_0] ) {
inNumber += '0';
}
else if ( keystate[SDL_SCANCODE_1] ) {
inNumber += '1';
}
else if ( keystate[SDL_SCANCODE_2] ) {
inNumber += '2';
}
else if ( keystate[SDL_SCANCODE_3] ) {
inNumber += '3';
}
else if ( keystate[SDL_SCANCODE_4] ) {
inNumber += '4';
}
else if ( keystate[SDL_SCANCODE_5] ) {
inNumber += '5';
}
else if ( keystate[SDL_SCANCODE_6] ) {
inNumber += '6';
}
else if ( keystate[SDL_SCANCODE_7] ) {
inNumber += '7';
}
else if ( keystate[SDL_SCANCODE_8] ) {
inNumber += '8';
}
else if ( keystate[SDL_SCANCODE_9] ) {
inNumber += '9';
}
}
// In this section of the event loop we allow key bounce:
drawBackground();
io.writeText(msg, hudFrame.x+150, hudFrame.y+40);
io.writeText("Enter No. Stons: ", hudFrame.x+150, hudFrame.y+80);
io.writeText(inNumber, hudFrame.x+330, hudFrame.y+80);
SDL_RenderPresent(renderer);
}
}
return atoi( inNumber.c_str() );
}
int Menu::getNumStars() const {
int numStars = getInputEventLoop();
return numStars;
}
void Menu::draw() const {
drawBackground();
io.writeText("Options Menu", hudFrame.x+350, hudFrame.y+60);
int space = spaces;
for ( const std::string& option : options ) {
io.writeText(option, optionLoc[0], optionLoc[1]+space);
space += spaces;
}
// We have to draw the clickOn & clickOff relative to the screen,
// and we don't want to offset by the location of the viewprot:
clicks[currentClick].getImage()->draw(0, 0, clickX, clickY);
}
| [
"haojiuzhang@sina.com"
] | haojiuzhang@sina.com |
4c1a639d5feeea3f15c6f3db60824c811b2842b0 | e763b855be527d69fb2e824dfb693d09e59cdacb | /aws-cpp-sdk-greengrass/source/model/CreateLoggerDefinitionVersionRequest.cpp | 6f6445e7036fff94741ac25a3520ffa8961f2e9f | [
"MIT",
"Apache-2.0",
"JSON"
] | permissive | 34234344543255455465/aws-sdk-cpp | 47de2d7bde504273a43c99188b544e497f743850 | 1d04ff6389a0ca24361523c58671ad0b2cde56f5 | refs/heads/master | 2023-06-10T16:15:54.618966 | 2018-05-07T23:32:08 | 2018-05-07T23:32:08 | 132,632,360 | 1 | 0 | Apache-2.0 | 2023-06-01T23:20:47 | 2018-05-08T15:56:35 | C++ | UTF-8 | C++ | false | false | 1,914 | cpp | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/greengrass/model/CreateLoggerDefinitionVersionRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <utility>
using namespace Aws::Greengrass::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
CreateLoggerDefinitionVersionRequest::CreateLoggerDefinitionVersionRequest() :
m_amznClientTokenHasBeenSet(false),
m_loggerDefinitionIdHasBeenSet(false),
m_loggersHasBeenSet(false)
{
}
Aws::String CreateLoggerDefinitionVersionRequest::SerializePayload() const
{
JsonValue payload;
if(m_loggersHasBeenSet)
{
Array<JsonValue> loggersJsonList(m_loggers.size());
for(unsigned loggersIndex = 0; loggersIndex < loggersJsonList.GetLength(); ++loggersIndex)
{
loggersJsonList[loggersIndex].AsObject(m_loggers[loggersIndex].Jsonize());
}
payload.WithArray("Loggers", std::move(loggersJsonList));
}
return payload.WriteReadable();
}
Aws::Http::HeaderValueCollection CreateLoggerDefinitionVersionRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
Aws::StringStream ss;
if(m_amznClientTokenHasBeenSet)
{
ss << m_amznClientToken;
headers.insert(Aws::Http::HeaderValuePair("x-amzn-client-token", ss.str()));
ss.str("");
}
return headers;
}
| [
"henso@amazon.com"
] | henso@amazon.com |
7e65bbd05792def66ace787676b7a85418c9c3df | b6585a17a40d458c040d4811b79a42c64f6ce5f2 | /owUtils/SmartItemPtr.h | d2a68edbdf248a84d68365f77501b72ae9ffac8b | [
"Apache-2.0"
] | permissive | Tormund/OpenWow | 1409e22a5a0530b7aab1ec12c318a29718398f2e | 44a554bf3b55b939ba64cd63363fdb64cf28131e | refs/heads/master | 2021-05-04T14:38:51.863688 | 2017-11-19T18:50:38 | 2017-11-19T18:50:38 | 120,205,859 | 2 | 0 | null | 2018-02-04T17:18:33 | 2018-02-04T17:18:33 | null | UTF-8 | C++ | false | false | 832 | h | #pragma once
template< class T >
class SmartItemPtr
{
public:
SmartItemPtr(T *ptr = nullptr) : _ptr(ptr) { AddRef(); }
SmartItemPtr(const SmartItemPtr& smp) : _ptr(smp._ptr) { DelRef(); }
~SmartItemPtr() { subRef(); }
T& operator*() const { return *_ptr; }
T* operator->() const { return _ptr; }
operator T*() const { return _ptr; }
operator const T*() const { return _ptr; }
operator bool() const { return _ptr != nullptr; }
T* getPtr() const { return _ptr; }
SmartItemPtr& operator=(const SmartItemPtr& smp)
{
return *this = smp._ptr;
}
SmartItemPtr& operator=(T *ptr)
{
DelRef();
_ptr = ptr;
AddRef();
return *this;
}
private:
void AddRef()
{
if (_ptr != nullptr)
{
_ptr->AddRef();
}
}
void DelRef()
{
if (_ptr != nullptr)
{
_ptr->DelRef();
}
}
private:
T *_ptr;
}; | [
"alexstenfard@gmail.com"
] | alexstenfard@gmail.com |
2533a9e80f70a388a26a1ad912e00e76d7a22e25 | 1e266cc7646b56527c1b20166e921c8eaaa5df1b | /digital/ucoolib/ucoolib/utils/test/test_crc.cc | 77c4c1ac4e5da462eef22dcc327ce1ddefd39977 | [] | no_license | ricardasgecas/apbteam | 744d3c1daee7f506d38ebe939c3c6c52b7f47cee | 0151eb8959383e0517b264ed53b8ec38b38f6889 | refs/heads/master | 2021-01-17T08:31:28.420347 | 2013-05-11T08:52:42 | 2013-05-11T08:52:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,715 | cc | // ucoolib - Microcontroller object oriented library. {{{
//
// Copyright (C) 2013 Nicolas Schodet
//
// APBTeam:
// Web: http://apbteam.org/
// Email: team AT apbteam DOT org
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// }}}
#include "ucoolib/utils/crc.hh"
#include "ucoolib/arch/arch.hh"
#include "ucoolib/base/test/test.hh"
#include <cstring>
int
main (int argc, const char **argv)
{
ucoo::arch_init (argc, argv);
ucoo::TestSuite tsuite ("crc");
{
ucoo::Test test (tsuite, "crc8 test vector");
static const uint8_t test_vector[] = { 0x02, 0x1c, 0xb8, 0x01, 0, 0, 0, 0xa2 };
if (ucoo::crc8_compute (test_vector, lengthof (test_vector)) != 0)
test.fail ();
}
{
ucoo::Test test (tsuite, "crc32 test vector");
const char *check_str = "123456789";
if (ucoo::crc32_compute ((const uint8_t *) check_str,
std::strlen (check_str)) != 0xCBF43926)
test.fail ();
}
return tsuite.report () ? 0 : 1;
}
| [
"nicolas.schodet@apbteam.org"
] | nicolas.schodet@apbteam.org |
3c73486cd41ab34b31edde9ff76edeb608480284 | de324eaddf1f2e0ad894ea7e57461ae81a1f16a0 | /controlconfig.h | fa61ffb0a1ac61eb5648a5f5be546616403818c0 | [] | no_license | thedeepestreality/HoverKTS | 4d7f895d85d61fe3f1cd451a5389f80d8de69dbd | 6b859f6641e38b08bd05022e2191b0a8b6e8c30c | refs/heads/master | 2021-01-11T05:38:24.912800 | 2016-12-10T22:22:08 | 2016-12-10T22:22:08 | 71,722,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | h | #ifndef CONTROLCONFIG_H
#define CONTROLCONFIG_H
#include <QList>
enum ControlType {manual, cnst, pid,data};
class ControlConfig
{
public:
ControlConfig(ControlType _type = manual)
{
type = _type;
}
ControlType getType() const
{
return type;
}
QList<double> getParams() const
{
return params;
}
void append(double val)
{
params.append(val);
}
void clear()
{
params.clear();
}
double& operator[](int idx)
{
return params[idx];
}
friend QDataStream& operator>>( QDataStream& d, ControlConfig& ct );
private:
ControlType type;
QList<double> params;
};
#endif // CONTROLCONFIG_H
| [
"zetoster@gmail.com"
] | zetoster@gmail.com |
133a197db8e330b6e32f93fae91b080fd530644c | ccae3c9b20fa3c895042a1c7aa0815fd0faec141 | /trunk/TestCode/EMBProject/Plugins/EMBActor/TaskActor.cpp | 85cd4c25ea841d6551661d835f45025a899f4053 | [] | no_license | 15831944/TxUIProject | 7beaf17eb3642bcffba2bbe8eaa7759c935784a0 | e90f3319ad0e57c0012e0e3a7e457851c2c6f0f1 | refs/heads/master | 2021-12-03T10:05:27.018212 | 2014-05-16T08:16:17 | 2014-05-16T08:16:17 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 21,368 | cpp | #include "StdAfx.h"
#include "TaskActor.h"
#include "TxLogManager.h"
#include "io.h"
#include "StrConvert.h"
#include "EMBCommonFunc.h"
#include "TxParamString.h"
#include "EMBDocDef.h"
#include "Util.h"
#include "SystemResourceInfo.h"
using namespace EMB;
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
CTaskActor::CTaskActor(void)
{
m_bRuning = FALSE;
m_nActiveConn = 0;
nfgRetryMax = 3;
m_actorconnMain.SetActorConnectorCallback(this);
m_actorconnSlave.SetActorConnectorCallback(this);
m_pExcutorMgr = CExcutorMgr::GetExcutorMgr();
ASSERT(m_pExcutorMgr);
// -------------------------
m_strTaskXmlPath = GetAppPath().c_str(); // 执行程序目录
m_strTaskXmlPath += "\\TaskXml";
CreateDirectory(m_strTaskXmlPath, NULL); // 创建目录
// -----------------------------
}
CTaskActor::~CTaskActor(void)
{
CExcutorMgr::Release();
g_pPluginInstane = NULL;
}
HRESULT CTaskActor::QueryPluginInfo( VECPLUGINFOS& vInfoInOut )
{
ST_PluginInfo info;
info.pluginGuid = GuidEMBPlugin_IPluginManager;
info.nPlugInType = PluginType_Actor;
info.nSubType = SubType_None;
vInfoInOut.push_back(info);
return S_OK;
}
HRESULT CTaskActor::QueryInterface( const GUID& guidIn, LPVOID& pInterfaceOut )
{
pInterfaceOut = NULL;
if (guidIn == GuidEMBPlugin_IBase)
{
pInterfaceOut = dynamic_cast<IPluginBaseInterface*>(this);
AddRef();
return S_OK;
}
else if (guidIn == GuidEMBPlugin_IControler)
{
pInterfaceOut = dynamic_cast<IPluginControlInterface*>(this);
AddRef();
return S_OK;
}
else if (guidIn == GuidEMBPlugin_IConnector)
{
pInterfaceOut = dynamic_cast<IPluginConnectorInterce*>(this);
AddRef();
return S_OK;
}
if (guidIn == GuidEMBPlugin_ITaskCommit)
{
pInterfaceOut = dynamic_cast<IPluginTaskCommit*>(this);
AddRef();
return S_OK;
}
else if (guidIn == GuidEMBPlugin_IConfig)
{
pInterfaceOut = dynamic_cast<IPluginConfigInterface*>(this);
AddRef();
return S_OK;
}
else if (GuidEMBPlugin_IActorUI == guidIn)
{
pInterfaceOut = dynamic_cast<IActorUI*>(this);
AddRef();
return S_OK;
}
else
{
return __super::QueryInterface(guidIn, pInterfaceOut);
}
}
HRESULT CTaskActor::Run_Plugin()
{
Stop_Plugin();
SOCKADDR_IN addrLocal;
addrLocal.sin_family = AF_INET;
addrLocal.sin_port = htons(0);
addrLocal.sin_addr.S_un.S_addr = htonl( INADDR_ANY );
m_actorconnMain.SetScokAddr(&m_ActRegInfo.addrMain, &addrLocal);
m_actorconnMain.SetActorId(m_ActRegInfo.actorId);
m_actorconnSlave.SetScokAddr(&m_ActRegInfo.addrSlave, &addrLocal);
m_actorconnSlave.SetActorId(m_ActRegInfo.actorId);
m_pExcutorMgr->Init(m_ActRegInfo.strExcPath, m_ActRegInfo, this);
HRESULT hr = m_actorconnMain.Run();
MUSTBESOK(hr);
hr = m_actorconnSlave.Run();
MUSTBESOK(hr);
hr = m_pExcutorMgr->Run();
MUSTBESOK(hr);
m_resMon.Run();
m_bRuning = TRUE;
return S_OK;
}
HRESULT CTaskActor::Stop_Plugin()
{
m_bRuning = FALSE;
m_actorconnMain.Stop();
m_actorconnSlave.Stop();
m_pExcutorMgr->Stop();
m_resMon.Stop();
return S_OK;
}
HRESULT EMB::CTaskActor::OnActorConnectorMsg(CString& strInfo, CString& strRet)
{
//getxmltype
ST_EMBXMLMAININFO mainInfo;
GetEmbXmlMainInfo(strInfo, mainInfo);
// 提交任务
if (mainInfo.nType == embxmltype_task)
{
CFWriteLog(0, TEXT("receive task %s"),mainInfo.guid);
TXGUID guid = String2Guid(mainInfo.guid);
if (guid == GUID_NULL)
{
ASSERT(FALSE);
return EMBERR_INVALIDARG;
}
//dispatched a task
// 启动执行者进程
EXCUTORID excId = m_pExcutorMgr->CreateNewExcutor();
if (excId != INVALID_ID)
{
CFWriteLog(0, TEXT("assign task to excutor %d"),excId);
//save task to it
ST_TASKINACTOR task;
task.taskGuid = guid;
task.mergeGuid = String2Guid(mainInfo.mergeGuid); // 合并任务标识
task.strTask = strInfo;
task.nCurrStep = 0;
task.nState = embtaskstate_dispatching;
CAutoLock lock(&m_csmapLock);
// 12-24,执行过的任务可以重新执行
MAPTASKINACTOR::iterator temItor = m_mapTaskinActor.find(guid);
if(temItor != m_mapTaskinActor.end())
{
CFWriteLog(0, TEXT("---task already exist in actor, remove task"));
m_mapTaskinActor.erase(temItor);
}
//if(m_mapTaskinActor.find(guid) == m_mapTaskinActor.end())
{
//add to map and wait for embxmltype_excOnIdle message of actor
AddTask(guid, task);
m_mapExcTask[excId] = guid;
m_pExcutorMgr->SetExecutorState(excId, EXE_ASSIGN); // 置为已分配
}
//else
//{
// CFWriteLog(0, TEXT("---task already exist in actor"));
// //ASSERT(FALSE);
// // 任务已提交
// /*ST_TASKREPORT tskReport;
// tskReport.actorId = m_ActRegInfo.actorId;
// tskReport.strGuid = guid;
// tskReport.nSubErrorCode = EMBERR_EXISTED;
// tskReport.nState = embtaskstate_error;
// tskReport.ToString(strRet);*/
//}
}
else // 无可用的Executor
{
CFWriteLog(0, TEXT("no available executor"));
// 提交失败
ST_TASKREPORT tskReport;
tskReport.strGuid = guid;
tskReport.actorId = m_ActRegInfo.actorId;
tskReport.nSubErrorCode = EMBERR_FULL; // 任务已达上限数量
tskReport.nState = embtaskstate_error;
tskReport.ToString(strRet);
}
}
else if (mainInfo.nType == embxmltype_taskReport) // 查询任务
{
//report task progress
ST_TASKREPORT report;
report.FromString(strInfo);
TXGUID guid = String2Guid(report.strGuid);
if (guid != GUID_NULL)
{
CAutoLock lock(&m_csmapLock);
MAPTASKINACTOR::iterator itf = m_mapTaskinActor.find(guid);
if (itf != m_mapTaskinActor.end())
{
ST_TASKINACTOR& taskInfoRef = itf->second;
//write the info
if (taskInfoRef.excId != INVALID_ID)
{
report.excutorId = taskInfoRef.excId;
report.actorId = m_ActRegInfo.actorId;
report.nPercent = taskInfoRef.nPercent;
report.nStep = taskInfoRef.nCurrStep;
report.nState = taskInfoRef.nState;
}
else
{
report.nState = embtaskstate_dispatching;
}
}
else
{
//no task return error state
// 存在情况:管理Server.exe临时退出了,Actor.exe 正常运行,任务结束后从m_mapTaskinActor删除了任务;
// Server.exe启动后,查询任务状态时,对应任务已不存在于m_mapTaskinActor
// 此时查询TaskXml\目录中是否有对应的xml文件?
ST_TASKREPORT tskInfor;
if (QueryXmlFile(guid, tskInfor))
{
report = tskInfor;
}
else
{
report.nState = embtaskstate_error;
}
}
//report
report.ToString(strRet);
}
}
else if (mainInfo.nType == embxmltype_svrActive) // 任务状态改变
{
//report actor state
ST_SVRACTIVEINFO activeInfo;
activeInfo.FromString(strInfo);
CFWriteLog(0, TEXT("svr(%d) state change to %d"),activeInfo.nMaster, activeInfo.nActive);
if (activeInfo.nActive == embSvrState_active)
{
if (activeInfo.nMaster == embSvrType_master)
{
m_nActiveConn = 1;
}
else if (activeInfo.nMaster == embSvrType_slave)
{
m_nActiveConn = 2;
}
else
{
ASSERT(FALSE);
}
}
else if (activeInfo.nActive == embSvrState_deactive)
{
if (activeInfo.nMaster == embSvrType_master
&& m_nActiveConn == 1)
{
m_nActiveConn = 0;
}
else if (activeInfo.nMaster == embSvrType_slave
&& m_nActiveConn == 2)
{
m_nActiveConn = 0;
}
else
{
//safe, not change
}
}
else
{
ASSERT(FALSE);
}
}
else if (mainInfo.nType == embxmltype_actorState) // 查询Actor.exe状态
{
//active svr changed;
ST_ACTORSTATE actorInfo;
actorInfo.actorId = m_ActRegInfo.actorId;
actorInfo.nActorLevel = m_ActRegInfo.nActorLevel;
actorInfo.nConnState = embConnState_ok;
// cpu 使用率
actorInfo.nCpuUsage = m_resMon.GetUsage(restype_Processor);
actorInfo.nDiscIOUsage = m_resMon.GetUsage(restype_PhysicalDisk);
// memory 使用率
CMemoryRes memRes;
memRes.GetInfor();
actorInfo.nMemUsage = m_resMon.GetUsage(restype_Memory);
actorInfo.nExcResUsage = m_pExcutorMgr->GetExcResUsage();
actorInfo.nNetIOUsage = m_resMon.GetUsage(restype_Network);;
TRACE(TEXT("svr request report actor state! cpu =%d, mem = %d, disc = %d, net = %d, exc = %d"), actorInfo.nCpuUsage, actorInfo.nMemUsage, actorInfo.nDiscIOUsage, actorInfo.nNetIOUsage, actorInfo.nExcResUsage);
actorInfo.ToString(strRet);
}
else if (embxmltype_taskCancel == mainInfo.nType) // 任务取消
{
OutputDebugString("---接受:切片任务取消");
CFWriteLog(0, "---接受:切片任务取消");
if (!mainInfo.mergeGuid.IsEmpty())
{
TXGUID mergeGuid = String2Guid(mainInfo.mergeGuid);
if (GUID_NULL != mergeGuid)
{
ST_TASKINACTOR taskInfoRef;
{
//for release lock
CAutoLock lock(&m_csmapLock);
//
for (MAPTASKINACTOR::iterator itor = m_mapTaskinActor.begin();
itor != m_mapTaskinActor.end(); itor++)
{
if (itor->second.mergeGuid == mergeGuid || itor->second.taskGuid == mergeGuid)
{
taskInfoRef = itor->second;
break;
}
}
}
// find task, then cancel task
if (GUID_NULL != taskInfoRef.taskGuid && taskInfoRef.excId > INVALID_ID)
{
m_pExcutorMgr->SendToExcutor(taskInfoRef.excId, strInfo);
//
CString strLog;
strLog.Format("---取消切片任务SendToExcutor(%d, %s)", taskInfoRef.excId, strInfo);
OutputDebugString(strLog);
CFWriteLog(0, strLog);
}
}
}
}
else if (embxmltype_excCallback == mainInfo.nType)
{
//find task executor and send to it
ST_TASKINACTOR taskInfo;
if (FindExcByTaskId(mainInfo.guid, taskInfo))
{
m_pExcutorMgr->SendToExcutor(taskInfo.excId, strInfo);
}
}
else
{
ASSERT(FALSE);
}
return S_OK;
}
void EMB::CTaskActor::OnFinalRelease()
{
g_pPluginInstane = NULL;
ReleaseTxLogMgr();
TRACE("\nCTaskRiserMgr::OnFinalRelease() ");
delete this;
}
HRESULT EMB::CTaskActor::OnFirstInit()
{
GetTxLogMgr()->AddNewLogFile(LOGKEY_TASKACTOR, TEXT("TaskActor"));
return S_OK;
}
HRESULT EMB::CTaskActor::GetParam( const CTaskString& szIn, CTaskString& szOut )
{
//return all
m_ActRegInfo.ToString(szOut);
return S_OK;
}
HRESULT EMB::CTaskActor::SetParam( const CTaskString& szIn, CTaskString& szOut )
{
ST_EMBRET ret;
if (m_bRuning)
{
ret.nRetVal = EMBERR_NOTREADY;
}
else
{
ST_ACTORCONFIG regIn;
regIn.FromString(szIn);
if (regIn.strExcPath.IsEmpty())
{
//set default excutor path
CString strPath = GetAppPath().c_str();
strPath += TEXT("\\exc\\EMBExternalExcutor.exe");
regIn.strExcPath = strPath;
}
//check valid
if (regIn.actorId < 0
|| regIn.addrMain.sin_family != AF_INET
|| regIn.addrSlave.sin_family != AF_INET
|| regIn.nExcutorMinId > regIn.nExcutorMaxId
|| _access(regIn.strExcPath, 0) ==-1)
{
ret.nRetVal = EMBERR_INVALIDARG;
}
else
{
m_ActRegInfo = regIn;
ret.nRetVal = S_OK;
}
}
ret.ToString(szOut);
return ret.nRetVal;
}
HRESULT EMB::CTaskActor::OnExcutorMessage( const EXCUTORID excutorId, CString& szInfoIn )
{
ST_EMBXMLMAININFO mainInfo;
GetEmbXmlMainInfo(szInfoIn, mainInfo);
if (mainInfo.nType == embxmltype_excOnIdle) // 执行者进程空闲
{
CFWriteLog(0, TEXT("excutor %d report idle"), excutorId);
OnExcutorIdle(excutorId);
}
else if (mainInfo.nType == embxmltype_taskReport) // 任务状态更新
{
//excutor report
//CFWriteLog(0, TEXT("exc%d report %s"), excutorId, szInfoIn);
ST_TASKREPORT report;
report.FromString(szInfoIn);
TXGUID guid = String2Guid(report.strGuid);
ASSERT (guid != GUID_NULL);
BOOL bReport = FALSE;
ST_TASKINACTOR tmpReport;
{
CAutoLock lock(&m_csmapLock);
MAPEXCTASKS::iterator itf = m_mapExcTask.find(excutorId);
if (itf != m_mapExcTask.end())
{
ASSERT(itf->second == guid);
}
else
{
m_mapExcTask[excutorId] = guid;
}
//check task state that assigned to the excutor
MAPTASKINACTOR::iterator itftask = m_mapTaskinActor.find(guid);
if (itftask != m_mapTaskinActor.end())
{
ST_TASKINACTOR& taskRef = itftask->second;
taskRef.nCurrStep = report.nStep;
taskRef.nState = report.nState;
taskRef.nPercent = report.nPercent;
taskRef.nSubErrorCode = report.nSubErrorCode; // 具体错误
taskRef.nExcType = report.nExcType;
tmpReport = taskRef;
bReport = TRUE;
if (taskRef.nState == embtaskstate_finished) // 任务完成,m_mapTaskinActor 删除任务
{
CFWriteLog(0, TEXT("task finished %s"), Guid2String(taskRef.taskGuid));
m_mapExcTask.erase(excutorId);
m_pExcutorMgr->SetExecutorState(excutorId, EXE_IDLE); // 置空闲
// 保存任务结果
TaskResultSaveXmlFile(report);
}
else if (embtaskstate_error == taskRef.nState)
{
CFWriteLog(0, TEXT("excutor report error: %s SubError:%X"),
Guid2String(taskRef.taskGuid), report.nSubErrorCode);
// // 不需重置任务
// if (!report.NeedResetTask())
// {
// CFWriteLog(0, TEXT("task submit error: %s SubError:%X"),
// Guid2String(taskRef.taskGuid), report.nSubErrorCode);
//
// m_pExcutorMgr->SetExecutorState(excutorId, EXE_IDLE); // 置空闲
// }
TXGUID guidTmp = taskRef.taskGuid;
m_mapTaskinActor.erase(guidTmp);
m_mapExcTask.erase(excutorId);
// 保存任务结果
TaskResultSaveXmlFile(report);
}
}
}
if (bReport)
{
// 更新任务状态
ReportTaskState(tmpReport);
}
}
else if (mainInfo.nType == embxmltype_excCallback)
{
//send to dispatcher
CActorConnector* pActor = GetActiveActorConnector();
if (pActor)
{
pActor->SendtoDispatcher(szInfoIn);
}
}
else
{
ASSERT(FALSE);
}
return S_OK;
}
HRESULT EMB::CTaskActor::OnExcutorExit( const EXCUTORID excutorId )
{
HRESULT hr = S_OK;
CAutoLock lock(&m_csmapLock);
MAPEXCTASKS::iterator itf = m_mapExcTask.find(excutorId);
if (itf != m_mapExcTask.end())
{
//check task state that assigned to the excutor
MAPTASKINACTOR::iterator itftask = m_mapTaskinActor.find(itf->second);
if (itftask != m_mapTaskinActor.end())
{
//
ST_TASKINACTOR& taskInfoRef = itftask->second;
if (taskInfoRef.nState == embtaskstate_finished)
{
//report task state to dispatcher
ReportTaskState(taskInfoRef);
//save to the recent deque;
m_dqRecentFinishedTasks.push_back(itftask->first);
}
else
{
BOOL bReSuc = FALSE;
/*++taskInfoRef.nRetry;
if (taskInfoRef.nRetry < nfgRetryMax)
{
//assign to a new actor
EXCUTORID newExcId = m_pExcutorMgr->CreateNewExcutor();
if (newExcId != INVALID_ID)
{
//change excid and state
taskInfoRef.nState = embtaskstate_dispatching;
taskInfoRef.excId = INVALID_ID;
//change exc task map
m_mapExcTask[newExcId] = taskInfoRef.taskGuid;
bReSuc = TRUE;
m_pExcutorMgr->SetExecutorState(newExcId, EXE_ASSIGN); // 已分配
}
else
{
CFWriteLog(0, TEXT("retry, but not find available executor"));
//ASSERT(FALSE);
}
}
else
{
ASSERT(FALSE);
}*/
if (!bReSuc)
{
taskInfoRef.nState = embtaskstate_error;
ReportTaskState(taskInfoRef);
}
TXGUID tmpGuid= taskInfoRef.taskGuid;
m_mapTaskinActor.erase(tmpGuid);
}
}
//whatever delete the excid
m_mapExcTask.erase(itf);
}
return S_OK;
}
BOOL EMB::CTaskActor::ReportTaskState( ST_TASKINACTOR& infoIn )
{
ST_TASKREPORT report;
report.actorId = m_ActRegInfo.actorId;
report.excutorId = infoIn.excId;
report.nState = infoIn.nState;
report.nPercent = infoIn.nPercent;
report.nStep = infoIn.nCurrStep;
report.strGuid = infoIn.taskGuid;
report.strGuid = Guid2String(infoIn.taskGuid);
report.nSubErrorCode = infoIn.nSubErrorCode; // 具体错误
report.nExcType = infoIn.nExcType;
CString strRet;
report.ToString(strRet);
CActorConnector* pActor = GetActiveActorConnector();
if (pActor)
{
pActor->SendtoDispatcher(strRet);
}
return TRUE;
}
BOOL EMB::CTaskActor::OnExcutorIdle( const EXCUTORID excutorId )
{
//find task assigned to the excutor;
CString strTask;
int nStartStep = 0;
{
CAutoLock lock(&m_csmapLock);
MAPEXCTASKS::iterator itf = m_mapExcTask.find(excutorId); // 查询任务
if (itf != m_mapExcTask.end())
{
MAPTASKINACTOR::iterator itftask = m_mapTaskinActor.find(itf->second);
if (itftask != m_mapTaskinActor.end())
{
//check not assigned;
ST_TASKINACTOR& taskInfoRef = itftask->second;
if (taskInfoRef.excId == INVALID_ID)
{
strTask = taskInfoRef.strTask; // 任务 xml信息
nStartStep = taskInfoRef.nCurrStep;
taskInfoRef.tmLastReport = time(NULL);
taskInfoRef.excId = excutorId;
}
}
}
}
if(!strTask.IsEmpty())
{
//send task to the excutor
if (nStartStep > 0)
{
//rewrite the task, add startstep attribute to taskbasic
CTxParamString txParam(strTask);
txParam.GoIntoKey(EK_MAIN);
CTxStrConvert val;
val.SetVal(nStartStep);
txParam.SetAttribVal(EK_TASKBASIC, EV_TBSTARTSTEP, val);
txParam.UpdateData();
strTask = txParam;
}
CFWriteLog(0, TEXT("send task to excutor %d"), excutorId);
m_pExcutorMgr->SendToExcutor(excutorId, strTask);
}
return TRUE;
}
bool EMB::CTaskActor::TaskResultSaveXmlFile( ST_TASKREPORT& tskReport )
{
// 按天保存xml
CTime tCurrent = CTime::GetCurrentTime();
CString strFileName;
strFileName.Format("%s\\%s.xml", m_strTaskXmlPath, tCurrent.Format("%Y-%m-%d"));
return CUtil::XmlFileAppend(strFileName, tskReport);
}
bool EMB::CTaskActor::QueryXmlFile( const CString& strTaskGuid, ST_TASKREPORT& tskInfor )
{
CTime tCurrent = CTime::GetCurrentTime();
CString strFileName;
strFileName.Format("%s\\%s.xml", m_strTaskXmlPath, tCurrent.Format("%Y-%m-%d"));
bool suc = CUtil::QueryXmlFile(strFileName, strTaskGuid, tskInfor);
return suc;
}
HRESULT EMB::CTaskActor::GetExecutors( vector<CString>& vExecutor )
{
vExecutor.clear();
// get running executor
vector<ST_EXCUTORINFO> vST;
HRESULT hr = m_pExcutorMgr->GetExecutors(vST);
CString strInfo;
ST_TASKINACTOR tsk;
// get task in executor
for (int i = 0; i < vST.size(); ++i)
{
if (FindTask(vST[i].excutorId, tsk))
{
vST[i].m_strTaskGuid = tsk.taskGuid; // taskguid
vST[i].m_strRunStep.Format("%d", tsk.nCurrStep);
vST[i].m_nPercent = tsk.nPercent;
}
else
{
vST[i].m_strTaskGuid.Empty();
vST[i].m_strRunStep.Empty();
vST[i].m_nPercent = 0;
}
// insert
vST[i].ToString(strInfo);
vExecutor.push_back(strInfo);
}
return hr;
}
bool EMB::CTaskActor::FindTask( const EXCUTORID& strExecutorId, ST_TASKINACTOR& tsk )
{
CAutoLock lock(&m_csmapLock);
bool suc = false;
// 获得任务信息
MAPEXCTASKS::iterator itor = m_mapExcTask.find(strExecutorId);
if (itor != m_mapExcTask.end())
{
MAPTASKINACTOR::iterator tskItor = m_mapTaskinActor.find(itor->second);
if (tskItor != m_mapTaskinActor.end())
{
tsk = tskItor->second;
suc = true;
}
}
return suc;
}
HRESULT EMB::CTaskActor::GetTaskInActor( vector<CString>& vTask )
{
vTask.clear();
//
CAutoLock lock(&m_csmapLock);
MAPTASKINACTOR::iterator itor = m_mapTaskinActor.begin();
CString strInfo;
for (;itor != m_mapTaskinActor.end(); ++itor )
{
ST_TASKRUNSTATE tsk;
tsk.guid = itor->second.taskGuid.guid;
tsk.nState = itor->second.nState;
tsk.nCurrStep = itor->second.nCurrStep;
tsk.tmLastReport = itor->second.tmLastReport;
tsk.tmCommit = itor->second.tmCommit; // 提交时间
tsk.ToString(strInfo);
vTask.push_back(strInfo);
}
return S_OK;
}
bool EMB::CTaskActor::AddTask( TXGUID& tskGuid, const ST_TASKINACTOR& tsk )
{
if (tskGuid.guid == GUID_NULL)
{
return false;
}
m_mapTaskinActor[tskGuid] = tsk;
if (m_mapTaskinActor.size() > 100)
{
// 保留1天之内的任务信息
time_t tNow = time(NULL);
static long sec = 24 * 60 * 60;
tNow -= sec; // 减去1天
for (MAPTASKINACTOR::iterator itor = m_mapTaskinActor.begin(); itor != m_mapTaskinActor.end();)
{
if (itor->second.tmCommit < tNow)
{
m_mapTaskinActor.erase(itor++);
}
else
{
++itor;
}
}
}
return true;
}
BOOL EMB::CTaskActor::FindExcByTaskId( const CString& strTaskGuid, ST_TASKINACTOR& taskOut )
{
//for release lock
BOOL bFind = FALSE;
CAutoLock lock(&m_csmapLock);
//
for (MAPTASKINACTOR::iterator itor = m_mapTaskinActor.begin();
itor != m_mapTaskinActor.end(); itor++)
{
if (itor->second.taskGuid == strTaskGuid)
{
taskOut = itor->second;
bFind = TRUE;
break;
}
}
return bFind;
}
| [
"tyxwgy@sina.com"
] | tyxwgy@sina.com |
20f28571e3bb1120fc114949a51bec3e7a639504 | e550059ff88cc6929a26b5c45c89049b3e2bc9a1 | /hougeo/ttl/sccs/detail/node_types.hpp | ef5f53df0253de80c03df257cee55a83158c54da | [
"MIT"
] | permissive | all-in-one-of/hougeo | 71c732d17f8a51dcf0fc59cdd3252145e42d6d99 | 7ef770562f0095b59a4ce876976fc5c34a8b5533 | refs/heads/master | 2020-07-08T19:13:52.811747 | 2019-08-31T11:05:23 | 2019-08-31T11:05:23 | 203,753,372 | 0 | 0 | MIT | 2019-08-22T08:51:26 | 2019-08-22T08:50:33 | C++ | UTF-8 | C++ | false | false | 1,954 | hpp | // node_types.hpp
//
// Copyright (c) 2003 Eugene Gladyshev
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
#ifndef __ttl_sccs_node_types_hpp
#define __ttl_sccs_node_types_hpp
namespace ttl
{
namespace sccs
{
namespace detail
{
template< typename T >
struct in_port
{
typedef T message; //message variant
message m_;
in_port( const message& m ) : m_(m) {}
virtual void print(std::ostream& out) = 0;
};
template< typename V, typename T >
struct in_port_complete : in_port<V>
{
typedef T type;
in_port_complete( const type& m ) : in_port<V>(m) {}
virtual void print( std::ostream& out )
{
out<<typeid(type).name()<<"?";
}
};
template< typename T >
struct out_port
{
typedef T message; //message variant
message m_;
out_port( const message& m ) : m_(m) {}
virtual void print( std::ostream& out ) = 0;
};
template< typename V, typename T >
struct out_port_complete : out_port<V>
{
typedef T type;
out_port_complete( const type& m ) : out_port<V>(m) {}
virtual void print( std::ostream& out )
{
out<<typeid(type).name()<<"!";
}
};
template< typename T >
struct action_item
{
typedef T action;
action a_;
std::string n_;
action_item( action a, const std::string& name )
:a_(a)
,n_(name)
{}
void print(std::ostream& out)
{
out<<n_.c_str();
}
};
struct sum_operator
{};
struct product_operator
{};
struct prefix_operator
{};
struct root
{};
struct stop
{};
template< typename A >
struct repeat
{
typedef A agent;
agent &a_;
repeat( A& a ) : a_(a) {}
};
}; //detail
}; //sccs
}; //ttl
#endif //__ttl_sccs_node_types_hpp
| [
"dk402538@googlemail.com"
] | dk402538@googlemail.com |
803da335317699f13e1a6dcd3090ae245a298ebc | 5dfa9c1e88824d86b1335434efd4e23e5ab1f328 | /Acm_icpc/C,C++/17000/boj17142.cpp | 78e3f1f7e19b9e6a158837ccb0e10950bdc37504 | [] | no_license | asomeJay/algorithm | 5784b4da33c255211f4792a3609be1e381aa1f79 | d7fe4dfed71d657d5f55763375cef69b5dbb5eff | refs/heads/master | 2021-02-17T06:29:05.860841 | 2020-10-19T16:33:52 | 2020-10-19T16:33:52 | 245,077,259 | 2 | 0 | null | null | null | null | UHC | C++ | false | false | 2,131 | cpp | /* 연구소 3 */
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <cstring>
#define pp pair<int,int>
#define MAX 50+1
using namespace std;
void input();
void solve();
int s_of_lab, n_of_virus, ANS = 987654321, empty_space ;
int lab[MAX][MAX];
int dr[4] = { -1,0,1,0 };
int dc[4] = { 0,1,0,-1 };
int time[MAX][MAX];
bool used_virus[MAX];
vector<pp> virus;
queue<pp> q;
int main(void) {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
input();
solve();
return 0;
}
void input() {
cin >> s_of_lab >> n_of_virus;
for (int i = 0; i < s_of_lab; i++) {
for (int j = 0; j < s_of_lab; j++) {
cin >> lab[i][j];
if (lab[i][j] == 0) {
empty_space++;
}
// 해당 지점에 바이러스가 있을 경우, 그 위치를 저장한다.
else if(lab[i][j] == 2) {
virus.push_back({ i,j });
}
}
}
}
void bfs() {
int temp = 0;
int temp_empty_space = 0;
while (!q.empty()) {
int rr = q.front().first;
int cc = q.front().second;
q.pop();
// 비활성 바이러스 만나면 카운트 안하고 빈공간 만나면 카운트한다.
for (int i = 0; i < 4; i++) {
int nr = rr + dr[i];
int nc = cc + dc[i];
if (nr >= 0 && nr < s_of_lab && nc >= 0 && nc < s_of_lab &&
time[nr][nc] == -1 && lab[nr][nc] != 1) {
time[nr][nc] = time[rr][cc] + 1;
if (lab[nr][nc] == 0) {
temp_empty_space++;
temp = max(temp, time[nr][nc]);
}
q.push({ nr, nc });
}
}
}
if (ANS > temp && empty_space ==temp_empty_space ) {
ANS = temp;
}
}
void dfs(int idx, int cnt) {
// back tracking 한계 조건
if (cnt == n_of_virus) {
memset(time, -1, sizeof(time));
for (int i = 0; i < virus.size(); i++) {
if (used_virus[i] == true) {
q.push({ virus[i].first, virus[i].second });
time[virus[i].first][virus[i].second] = 0;
}
}
bfs();
return;
}
for (int i = idx; i < virus.size(); i++) {
if (used_virus[i] == false) {
used_virus[i] = true;
dfs(i+1, cnt + 1);
used_virus[i] = false;
}
}
}
void solve() {
dfs(0, 0);
if (ANS == 987654321) ANS = -1;
cout << ANS << '\n';
} | [
"45970468+asomeJay@users.noreply.github.com"
] | 45970468+asomeJay@users.noreply.github.com |
cb91cd4b911a11f922dde0e67cf183708f858938 | 730d4aea6556ee017d7e0e266ec68b0e48ca6617 | /NetherEngine/Memory Management/Dator.h | 094ab81d6039dffa25ab81669a6bfaa17bf1b999 | [] | no_license | cjcurrie/Necromancer-and-NetherEngine | 3cc1b67c3298f8047497ca44b50cd176b282fe4a | 140d902ccba5bc43c887443a805a6a77a2f9b948 | refs/heads/master | 2020-05-17T04:18:48.401520 | 2013-01-12T14:31:58 | 2013-01-12T14:31:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,923 | h | #ifndef NEInc_Dator_h
#define NEInc_Dator_h
#include "NEAssert.h"
#include "BaseDator.h"
#include <sstream>
// This Dator is for unitary objects i.e. not a list or array.
namespace NE
{
template<class T>
class Dator : public BaseDator
{
protected:
T ⌖
/*
Note: The following types can be converted with toValue() and toString():
- bool
- short, ushort, int, uint, long, and ulong
- float, double, and long double
- void*
- basic_streambuf<T>
- basic_ostream &
- basic_ios<,>
_ ios_base &
These types are defined by ostream::operator << overloads
*/
T toValue(std::string &input)
{
std::stringstream str; // stringstream provides a lexical cast, converting between common types and strings.
str.unsetf(std::ios::skipws); // Strips whitespace from the leading end of string
T result;
str << input; // Put input into the buffer
str >> result; // Get input from the buffer. Now it's type T
ASSERT( !str.fail() ); // msg = "Conversion operation failed. Was the type of target an allowed type?"
return result;
}
std::string toString(T &input) // This is the complement to toValue() above
{
std::stringstream str;
str.unsetf(std::ios::skipws);
std::string result;
str << input;
str >> result;
ASSERT( !str.fail() );
return result;
}
public:
Dator(const T &t) : target(t) {}
BaseDator &operator =(const std::string &rhsInput)
{
// Copy-swap isn't needed here because toValue copy-swaps and returns a value.
target = toValue(rhsInput);
return *this;
}
BaseDator &operator +=(std::string &rhsInput)
{
target += toValue(rhsInput);
return *this;
}
BaseDator &operator -=(std::string &rhsInput)
{
target -= toValue(rhsInput);
return *this;
}
bool operator ==(const std::string &rhsInput)
{
return (rhsInput == (std::string)(*this));
}
bool operator !=(std::string &rhsInput)
{
return (rhsInput != (std::string)(*this));
}
// Explicit cast to string operator
operator std::string()
{
return toString(target);
}
bool hasMultipleValues()
{
return false; // Unitary objects do not have multiple values.
}
AUTO_SIZE;
};
}
#endif | [
"cj@cjcurrie.net"
] | cj@cjcurrie.net |
39202f36fe8e2d4097da5011fd68686967ed37ac | f3a88e494685387028a7741177567a05552ff900 | /PROG/[Simul] 캐시.cpp | 35be894e76a2d1cccd2b453a6562da2f85e9b8f6 | [] | no_license | DaeunOh/ALGORITHM | 1096c55433905ceee3b30d753e085e7f6d9fdb7d | b3312a0c473e152c501c5950188fa285f6a09638 | refs/heads/master | 2020-12-08T14:56:45.173706 | 2020-07-10T16:20:23 | 2020-07-10T16:20:23 | 233,010,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,463 | cpp | // 소요시간: 24분
// 실행시간: 16ms
/*
지도개발팀에서 근무하는 제이지는 지도에서 도시 이름을 검색하면
해당 도시와 관련된 맛집 게시물들을 데이터베이스에서 읽어 보여주는 서비스를 개발하고 있다.
이 프로그램의 테스팅 업무를 담당하고 있는 어피치는 서비스를 오픈하기 전 각 로직에 대한 성능 측정을 수행하였는데,
제이지가 작성한 부분 중 데이터베이스에서 게시물을 가져오는 부분의 실행시간이 너무 오래 걸린다는 것을 알게 되었다.
어피치는 제이지에게 해당 로직을 개선하라고 닦달하기 시작하였고,
제이지는 DB 캐시를 적용하여 성능 개선을 시도하고 있지만 캐시 크기를 얼마로 해야 효율적인지 몰라 난감한 상황이다.
어피치에게 시달리는 제이지를 도와, DB 캐시를 적용할 때 캐시 크기에 따른 실행시간 측정 프로그램을 작성하시오.
입력 형식
- 캐시 크기(cacheSize)와 도시이름 배열(cities)을 입력받는다.
- cacheSize는 정수이며, 범위는 0 ≦ cacheSize ≦ 30 이다.
- cities는 도시 이름으로 이뤄진 문자열 배열로, 최대 도시 수는 100,000개이다.
- 각 도시 이름은 공백, 숫자, 특수문자 등이 없는 영문자로 구성되며, 대소문자 구분을 하지 않는다.
도시 이름은 최대 20자로 이루어져 있다.
출력 형식
입력된 도시이름 배열을 순서대로 처리할 때, 총 실행시간을 출력한다.
조건
- 캐시 교체 알고리즘은 LRU(Least Recently Used)를 사용한다.
- cache hit일 경우 실행시간은 1이다.
- cache miss일 경우 실행시간은 5이다.
입출력 예제
캐시크기(cacheSize) 도시이름(cities) 실행시간
3 [Jeju, Pangyo, Seoul, NewYork, LA, Jeju, Pangyo, Seoul, NewYork, LA] 50
3 [Jeju, Pangyo, Seoul, Jeju, Pangyo, Seoul, Jeju, Pangyo, Seoul] 21
2 [Jeju, Pangyo, Seoul, NewYork, LA, SanFrancisco, Seoul, Rome, Paris, Jeju, NewYork, Rome] 60
5 [Jeju, Pangyo, Seoul, NewYork, LA, SanFrancisco, Seoul, Rome, Paris, Jeju, NewYork, Rome] 52
2 [Jeju, Pangyo, NewYork, newyork] 16
0 [Jeju, Pangyo, Seoul, NewYork, LA] 25
*/
/*
◆ 풀이
cache에 사용되는 페이지 교체 알고리즘 중 하나인 LRU를 구현하는 문제.
LRU의 개념만 잘 숙지하고 있으면 구현은 크게 어렵지 않다.
전체적인 과정은 다음과 같다.
1) 도시 이름을 모두 소문자화(또는 대문자화)한다. (이 문제에서 도시 이름은 대소문자 구분을 하지 않으므로)
2) 캐시를 보고, 캐시 안에 존재하면 참조했던 시간을 업데이트 시켜주고, 실행 시간을 1 증가시킨다.
3) 캐시 안에 존재하지 않으면 캐시의 사이즈에 따라 맨 끝에 삽입시킬지, 캐시 내용만 바꿔줄지 정하는데,
현재 캐시 사이즈가 캐시 최대 사이즈보다 작다면 끝에 추가한 후 참조 시간을 기록하고,
최대 사이즈보다 같거나 크다면 가장 오래 전에 참조된 도시를 골라서 캐시 내용을 변경하고 참조 시간을 업데이트 시켜준다.
또한, 이 과정이 끝나면 실행 시간을 5 증가시킨다.
위의 과정은 맨 처음 구현에 시도했던 방법인데, 참조 시간을 별도로 기록해야 하고, 코드가 깔끔하지 못하다는 단점이 있었다.
그래서 2번째 시도로는 erase를 사용해서 최근에 사용되지 않은 도시를 가장 앞으로,
그리고 최근에 사용된 도시를 가장 뒤로 배치하는 방법을 활용하고자 했다. (맨 아래 주석처리한 코드)
이 방법은 코드가 조금 더 짧고, 시간을 기록해두는 공간이 별도로 필요하진 않으나 최대 23ms가 걸린다는 단점이 있다.
하지만 7ms밖에 차이가 나지 않으므로 가급적이면 이와 같은 코딩 방식을 활용하는게 더 좋다고 생각한다!
◆ 후기
풀이에서도 언급했듯이 LRU의 개념만 잘 숙지하고 있으면 되는 문제이긴 하지만,
이러한 개념을 "알아야만" 풀 수 있는 문제는 거의 처음 접해본 것 같다.
다른 문제에서는 보통 이름이 주어지고, 그에 대한 개념또한 같이 주어지는게 일반적이었는데,
이번엔 그게 아니다보니 조금 당황했다...ㄷㄷㄷ (그래도 알고 있던 개념이라 다행이었다..ㅎㅎㅎ)
이 문제는 처음 구현할 때보다 두번째 구현할 때 더 좋았던 문제이다.
평소 vector의 erase를 어느 특정 구간을 지울 때 빼고는 잘 사용하지 않았는데,
특정 요소 하나를 지울 때에도 유용하다는 것을 알게 되었기 때문이다 ㅎㅎㅎ
오늘도 메모장에 적어둘 내용이 하나 더 늘었다! 야호~~
*/
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 30 + 10;
vector<string> cache;
int t[MAX] = {0, };
int solution(int cacheSize, vector<string> cities) {
int answer = 0;
for(int i=0; i<cities.size(); i++) {
transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower);
bool flag = false;
for(int j=0; j<cache.size(); j++) {
if(cache[j] == cities[i]) { // 해당 도시가 캐시에 있는 경우
flag = true;
t[j] = i;
answer += 1;
break;
}
}
if(!flag) {
// cache의 사이즈를 본다.
if(cache.size() < cacheSize) {
cache.push_back(cities[i]);
t[cache.size()-1] = i;
}
else {
// 가장 오래된 도시를 찾는다.
int myMin = 987987987, minIdx = -1;
for(int j=0; j<cache.size(); j++) {
if(myMin > t[j]) {
myMin = t[j];
minIdx = j;
}
}
if(minIdx != -1) {
cache[minIdx] = cities[i];
t[minIdx] = i;
}
}
answer += 5;
}
}
return answer;
}
/*
// erase를 사용해서 최근에 사용되지 않은 도시를 가장 앞으로, 최근에 사용된 도시를 가장 뒤로 배치하는 방법
// 코드가 조금 더 짧고, 시간을 기록해두는 공간이 별도로 필요하진 않으나 최대 23ms가 걸린다. (조금 더 느림)
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int solution(int cacheSize, vector<string> cities) {
int answer = 0;
vector<string> cache;
for(int i=0; i<cities.size(); i++) {
transform(cities[i].begin(), cities[i].end(), cities[i].begin(), ::tolower);
bool flag = false;
for(int j=0; j<cache.size(); j++) {
if(cache[j] == cities[i]) {
flag = true;
cache.erase(cache.begin() + j);
cache.push_back(cities[i]);
answer += 1;
break;
}
}
if(!flag) {
if(cacheSize > 0 && cache.size() >= cacheSize) cache.erase(cache.begin());
if(cacheSize > cache.size()) cache.push_back(cities[i]);
answer += 5;
}
}
return answer;
}
*/ | [
"dev.carrotoh@gmail.com"
] | dev.carrotoh@gmail.com |
f2bcf07bc02de8c810afd52383db371bd3c9504c | 55c5199fb25d85b062d3d63a9ff6a55546d980a1 | /uno_smart_light/uno_smart_light.ino | 5eacbc36dbfa701dbec11b9b54644d39123e15d4 | [] | no_license | AndreyGrand/SmartLight | 25f3e6a586d1fdadc521b5adaaddaacacb98bb54 | 337e3547312c2f83bd13960145c681971e530c35 | refs/heads/master | 2020-05-15T11:36:42.644426 | 2019-04-29T06:24:44 | 2019-04-29T06:24:44 | 182,237,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,309 | ino | /*
Uno version smart light
Created: 4/12/2019 10:20:22 PM
Author : Gerankin-EIS
*/
#include <avr/io.h>
#define LightSensor_PIN PB2
#define Relay_Light 5//(1<<PB0) //жёлтый
#define LED_B 3//(1<<PB1) //светодиод голубой
//#define LED_G 4//(1<<PB3) //светодиод зелёный
#define PIR 2//датчик движения
#define calibrationTime 14 //секунд для инициализации таймера;
#define TIMEOUT_PIR 5000
#define BTN_INC 4
#define BTN_INC_TIME 5000 * 2
volatile unsigned long delayBy = 0;
volatile boolean movementOn = false;
void setup()
{
//DDRB |= (LED_B | Relay_Light) ;
pinMode(Relay_Light, OUTPUT);
pinMode(LED_B, OUTPUT);
pinMode(PIR, INPUT);
pinMode(BTN_INC, INPUT);
digitalWrite(BTN_INC, HIGH);
Serial.begin(9600);
for (int i = 0; i < calibrationTime; i++) {
digitalWrite(LED_B, !digitalRead(LED_B));
delay(1000);
}
attachInterrupt(digitalPinToInterrupt(PIR), pin_ISR, RISING );
}
void pin_ISR()
{
movementOn = true;
unsigned long tmp = millis() + TIMEOUT_PIR;
if (delayBy < tmp) {
delayBy = tmp;
Serial.println("inc time");
}
}
volatile bool activatedLight = false;
char btnIncCount = 0;
bool incButtonClicked = false;
void loop()
{
if (! movementOn ) {
return;
}
if (!activatedLight) {
Serial.println("Movement");
int photo = analogRead(0);
Serial.println(photo);
Serial.println(delayBy);
if (photo > 300) {
Serial.println("Light ON");
digitalWrite(Relay_Light, HIGH);
activatedLight = true;
}
else{
movementOn = false;
Serial.println("Skip movement");
}
}
if (activatedLight && (millis() > delayBy)) {
if(incButtonClicked){
delayBy += BTN_INC_TIME;
incButtonClicked = false;
Serial.println("Added BTN time");
return;
}
Serial.println("Time over, Light OFF");
digitalWrite(Relay_Light, LOW);
movementOn = false;
delayBy = 0;
activatedLight = false;
}
if(activatedLight){
bool pressed = digitalRead(BTN_INC) == LOW;
if( pressed && btnIncCount<5){
btnIncCount++;
}
if(!pressed && btnIncCount >0){
btnIncCount--;
}
if(btnIncCount == 5){
incButtonClicked = true;
btnIncCount = 0;
}
}
}
| [
"gerankin@mail.ru"
] | gerankin@mail.ru |
36a64e774c576661ebffc72a6af9d8b4f0d4b1c6 | 5cc95b40257628c232f07909f7d23c0af2cfa24f | /FrameWorkDirectX/cParticleQuad.h | 96ec3a9a4b7bea77cf65699cd4a66e456ea72cf8 | [] | no_license | whateveruwant/Borderlands_v.copy | daf39c4e7dfd988117f66a1c64b7ab01b65adc52 | d16ebf9556e755ae3254b8cc2d05a02ffba612ce | refs/heads/master | 2020-03-13T20:57:06.314530 | 2018-05-01T18:46:05 | 2018-05-01T18:46:05 | 131,285,192 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,710 | h | #pragma once
#include <vector>
#include "cTransform.h"
//파티클 정점 구조체
typedef struct tagPARTICLEQUAD_VERTEX{
D3DXVECTOR3 pos; //정점 위치
DWORD color; //정점 컬러
D3DXVECTOR2 uv; //정점 UV
enum { FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1 };
}PARTICLEQUAD_VERTEX, *LPPARTICLEQUAD_VERTEX;
typedef std::vector<D3DXCOLOR> VEC_COLOR;
typedef std::vector<float> VEC_SCALE;
class cParticleQuad
{
public:
cTransform m_Transform; //파티클의 위치값
private:
bool m_bLive; //활성화 여부
float m_fTotalLiveTime; //총 활성화 시간
float m_fDeltaLiveTime; //활성화 지난 시간
float m_fNomalizeLiveTime;//활성화 비율 시간( 0 ~ 1 )
D3DXVECTOR3 m_Velocity; //파티클의 속도벡터
D3DXVECTOR3 m_Accelation; //초당 증가하는 가속벡터
D3DXVECTOR3 m_Rotate; //초당 회전 벡터
D3DXVECTOR3 m_RotateAccel; //초당 증가하는 회전벡터
float m_fScale; //기본 스케일값
public:
cParticleQuad(void);
~cParticleQuad(void);
void Start(
float liveTime, //라이브 타임
const D3DXVECTOR3* pos, //시작 위치
const D3DXVECTOR3* velo, //시작 속도
const D3DXVECTOR3* accel, //가속 값
const D3DXVECTOR3* rotate, //초당 회전 값
const D3DXVECTOR3* rotateAccel, //초당 회전 증가값
float scale //기본 스케일
);
void Update( float timeDelta );
//자신의 정점 정보를 바탕으로 LPPARTICLEQUAD_VERTEX 의 값을 넣어준다.
void GetParticleVertex(
LPPARTICLEQUAD_VERTEX pOut,
DWORD* pIndex,
const VEC_COLOR& colors,
const VEC_SCALE& scales,
DWORD dwParticleNum );
bool isLive(){
return m_bLive;
}
};
| [
"qkrdbals1630@khu.ac.kr"
] | qkrdbals1630@khu.ac.kr |
a1ba7b603899a2501765d6a90e413d3070df5735 | f231843bc3f91b51a78e8d6908b55d1d96a1c836 | /lib/script/src/AST/Expression/Binary.cpp | e6c6b3bd386f56972b28cdd465bdb3bcd20b7384 | [
"BSD-3-Clause"
] | permissive | astateful/dyplat | 13581c5040d2987e1e8bf45002a623f6c3f5c950 | 37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44 | refs/heads/master | 2023-03-12T10:16:35.683180 | 2021-03-01T21:14:53 | 2021-03-01T21:14:53 | 343,553,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,470 | cpp | #include "AST/Expression/Binary.hpp"
#include "AST/Expression/Variable.hpp"
#include "astateful/script/JIT.hpp"
#include "astateful/script/Context.hpp"
#include <llvm/IR/Module.h>
#include <llvm/IR/IRBuilder.h>
namespace astateful
{
namespace script
{
ASTExpressionBinary::ASTExpressionBinary(
char op,
std::unique_ptr<ASTExpression>& lhs,
std::unique_ptr<ASTExpression>& rhs,
JIT& cJIT,
Context& context ) :
ASTExpression( context ),
Op( op ),
LHS( std::move( lhs ) ),
RHS( std::move( rhs ) ),
mcJIT( cJIT ) {}
llvm::Value * ASTExpressionBinary::Codegen()
{
// Special case '=' because we don't want to emit the LHS as an expression.
if ( Op == '=' )
{
// Assignment requires the LHS to be an identifier.
ASTExpressionVariable *LHSE = reinterpret_cast<ASTExpressionVariable*>( LHS.get() );
if ( !LHSE )
{
return ErrorV( "destination of '=' must be a variable" );
}
// Codegen the RHS.
llvm::Value *Val = RHS->Codegen();
if ( Val == 0 ) { return 0; }
// Look up the name.
llvm::Value * Variable = m_context.symbol_table[LHSE->getName()];
if ( Variable == 0 ) { return ErrorV( "Unknown variable name" ); }
m_context.builder().CreateStore( Val, Variable );
return Val;
}
llvm::Value *L = LHS->Codegen();
llvm::Value *R = RHS->Codegen();
if ( L == 0 || R == 0 ) { return 0; }
switch ( Op )
{
case '+': return m_context.builder().CreateFAdd( L, R, "addtmp" );
case '-': return m_context.builder().CreateFSub( L, R, "subtmp" );
case '*': return m_context.builder().CreateFMul( L, R, "multmp" );
case '<':
L = m_context.builder().CreateFCmpULT( L, R, "cmptmp" );
// Convert bool 0/1 to double 0.0 or 1.0
return m_context.builder().CreateUIToFP(
L,
llvm::Type::getDoubleTy( m_context ),
"booltmp"
);
default: break;
}
// If it wasn't a builtin binary operator, it must be a user defined one. Emit
// a call to it.
llvm::Function * F = mcJIT.getFunction( MakeLegalFunctionName( std::string( "binary" ) + Op ) );
assert( F && "binary operator not found!" );
llvm::Value * Ops[] = { L, R };
return m_context.builder().CreateCall( F, Ops, "binop" );
}
}
}
| [
"thomas.kovacs@astateful.com"
] | thomas.kovacs@astateful.com |
146e812c7f1cc68b746ba381fba558c1a00e4f32 | 0db3033b016f0aeaeb637538b495cafabf5ee84b | /System/macOS/AppSymbols.cpp | de8868f06ebc82fc0ae2c570dbeb1b09398eb7a0 | [] | no_license | andeha/Pinecone | 5e52dcd4d71f03897d98f3cd109aa4a691ff3369 | 26a2cdac62c082c239d4914c4222fce471db91b4 | refs/heads/master | 2021-05-12T20:10:10.854870 | 2019-11-17T11:04:50 | 2019-11-17T11:04:50 | 115,606,530 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,882 | cpp | //
// AppSymbols.cpp
// Pinecone
//
#include <System/macOS/AppSymbols.h>
#include <Additions/Helpers.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <mach-o/loader.h>
#include <mach-o/dyld.h>
#include <mach-o/arch.h>
#include <mach-o/nlist.h>
#include <sys/mman.h>
#include <sys/stat.h>
INNER_STRUCT AppSymbols::Implementation {
Implementation(const char * execFilepath) { file = MemoryRegion::reflect(
execFilepath); }
~Implementation() {}
void
loadCommands(
unsigned int imageOrdinal,
void (^callback)(mach_header_64 *mach_header_ptr, load_command *cmd,
bool& stop)
)
{
uint32_t count = _dyld_image_count();
if (imageOrdinal < count) {
mach_header_64 *mach_header_ptr = (mach_header_64 *)
_dyld_get_image_header(imageOrdinal);
uint8_t *p = (uint8_t *)mach_header_ptr + sizeof(mach_header_64);
for (int i = 0; i < mach_header_ptr->ncmds; ++i) {
load_command *command = (load_command *)p;
bool stop = false;
callback((mach_header_64 *)mach_header_ptr, command, stop);
if (stop) break;
p += command->cmdsize;
}
}
}
Optional<MemoryRegion> file;
AppSymbols *outer;
};
#pragma - Outer Class
AppSymbols::AppSymbols(const char * execfilepath) : impl_ { new
Implementation(execfilepath) } { impl_->outer = this; }
AppSymbols::~AppSymbols() { }
void AppSymbols::symbols(void (^callback)(const char *, uint64_t, bool&)) const
{
if (MemoryRegion *region = impl_->file.query()) {
char *obj = (char *)region->pointer(0).pointer;
char *obj_p = (char *)obj;
struct mach_header_64 *header = (struct mach_header_64 *)obj_p;
obj_p += sizeof *header;
struct section *sections = NULL;
uint32_t nsects;
__block bool outerStop = false;
for (int i = 0; i < header->ncmds; ++i) {
struct load_command *lc = (struct load_command *)obj_p;
if (lc->cmd == LC_SYMTAB) {
struct symtab_command *symtab = (struct symtab_command *)obj_p;
obj_p += sizeof *symtab;
struct nlist_64 *ns = (struct nlist_64 *)(obj + symtab->symoff);
char *strtable = obj + symtab->stroff;
for (int i = 0; i < symtab->nsyms; i++) {
struct nlist_64 *entry = ns + i;
uint32_t idx = entry->n_un.n_strx;
callback(strtable + idx, entry->n_value, outerStop);
if (outerStop) { return; }
}
} else if (lc->cmd == LC_SEGMENT) {
struct segment_command *segment = (struct segment_command *)obj_p;
obj_p += sizeof *segment;
nsects = segment->nsects;
sections = (struct section *)obj_p;
obj_p += nsects * sizeof *sections;
} else {
obj_p += lc->cmdsize;
}
}
}
}
void
AppSymbols::images(
void (^callback)(unsigned, void *, const char *, const char *, bool&)
) const
{
uint32_t count = _dyld_image_count();
for (uint32_t i = 0; i < count; i++) {
const char *imagepath = _dyld_get_image_name(i);
const struct mach_header_64 *header =
(const struct mach_header_64 *)_dyld_get_image_header(i);
const NXArchInfo *info = NXGetArchInfoFromCpuType(
header->cputype, header->cpusubtype);
uint64_t address = (uint64_t)header;
bool stop = false;
callback(i, (void *)address, info->name, imagepath, stop);
if (stop) break;
}
}
void *
AppSymbols::entryPoint() const
{
// Applications often rely on _dyld_get_image_header(0) being the main
// executable so we find the main entry point by extracting out the LC_MAIN
// in the first image.
__block mach_vm_address_t result = NULL;
impl_->loadCommands(0, ^(mach_header_64 *mach_header_ptr, load_command *cmd,
bool& stop) { // ☜😐: 🕰?
if (cmd->cmd == LC_MAIN) {
entry_point_command *lc_entry_point_command = (struct entry_point_command *)cmd;
// printf("\tentry offset\t= %llu\n", lc_entry_point_command->entryoff);
uint64_t ptr = (uint64_t)mach_header_ptr;
result = (mach_vm_address_t)(ptr + lc_entry_point_command->entryoff);
stop = true;
}
});
return (void *)result;
}
| [
"anders.pm.hansson@gmail.com"
] | anders.pm.hansson@gmail.com |
d1698b24a5d260e2fccbdec2b6fad61706d79414 | fa31a3f7b5a0097db7fe480bae4737b57f42090c | /Bloque 13 - Listas/Ejercicio 2 - Calcular suma y promedio en una lista.cpp | f3205d83e06eb363f4b71317b844a9ab7919cc60 | [] | no_license | PaulinoBermudez/Ejercicios-Propuestos-y-Resueltos-en-C | 5e8ee243c1162435abaa766c3ee097495658150d | 1f8d40a35b8cca4ff197c5e77458d1b6a364afd7 | refs/heads/master | 2023-03-10T08:49:06.277163 | 2021-02-26T12:39:13 | 2021-02-26T12:39:13 | 268,096,929 | 0 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,904 | cpp | /*Ejercicio 2: Crear una lista que almacene "n" números reales y calcular su suma y promedio.*/
#include<iostream>
#include<conio.h>
using namespace std;
struct Nodo{
float dato;
Nodo *siguiente;
};
void insertarLista(Nodo *&,float);
void mostrarLista(Nodo *);
void calcularSumaPromedio(Nodo *);
int main(){
Nodo *lista = NULL;
float dato;
char opcion;
do{
cout<<"Digite un numero: ";;
cin>>dato;
insertarLista(lista,dato);
cout<<"\nDesea agregar otro elemento a lista(s/n): ";
cin>>opcion;
}while(opcion == 's' || opcion == 'S');
cout<<"\nElementos de la lista:\n";
mostrarLista(lista);
calcularSumaPromedio(lista);
getch();
return 0;
}
//Insertar elementos al final de la lista
void insertarLista(Nodo *&lista,float n){
Nodo *nuevo_nodo = new Nodo();
Nodo *aux;
nuevo_nodo->dato = n;
nuevo_nodo->siguiente = NULL;
if(lista == NULL){//lista vacia
lista = nuevo_nodo;
}
else{
aux = lista; //aux señala el inicio de la lista
while(aux->siguiente != NULL){ //recorremos la lista
aux = aux->siguiente;
}
aux->siguiente = nuevo_nodo;
}
cout<<"\tElemento "<<n<<" insertado a lista correctamente\n";
}
//Mostrar todos los elementos de la lista
void mostrarLista(Nodo *lista){
while(lista != NULL){ //mientras no sea el final de la lista
cout<<lista->dato<<" -> "; //mostramos el dato
lista = lista->siguiente; //avanzamos una posicion mas en la lista
}
}
//Calcular suma y promedio de los elementos de la lista
void calcularSumaPromedio(Nodo *lista){
float suma=0,promedio=0;
int contador=0;
while(lista != NULL){//mientras no sea el final de la lista
suma += lista->dato; //suma iterativa
contador++; //aumentamos el contador de elementos de la lista
lista = lista->siguiente; //Avanzamos en la lista
}
promedio = suma / contador;
cout<<"\n\nLa suma es: "<<suma<<endl;
cout<<"El promedio es: "<<promedio<<endl;
}
| [
"paeste95.pb@gmail.com"
] | paeste95.pb@gmail.com |
2548b4e3fc2a9839351e8a4b5b861795fac65666 | f371b8603d29d2c4c3fb0f50055afd516003f9f8 | /Arduino/analog_state_machine_sensors/analog_state_machine_sensors.ino | 3163c55e09c40c4206a24d23fadcb5c6251b01fb | [
"CC0-1.0"
] | permissive | lulzzz/Sensor-Network | 290ca2318b13a812cd87191cd58e782c0db8fe5b | 872be3aad2f31666a88d8544cabe0066cae2f9c8 | refs/heads/master | 2020-06-24T08:44:46.246110 | 2016-10-19T15:12:29 | 2016-10-19T15:12:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | ino | class DripSensor
{
// Class Member Variables
// These are initialized at startup
int sensorPin; // the number of the sensor pin
long DelayTime;
// These maintain the current state
int previousValue; // sensorData used to store the sensor data
int currentValue; // sensorData used to store the sensor data
unsigned long previousMillis; // will store last time sensorData was updated
int drip;
public:
DripSensor(int pin, long frequency)
{
sensorPin = pin;
DelayTime = frequency;
previousValue = 0;
previousMillis = 0;
drip=1;
}
void Update()
{
// check to see if it's time to read the analog sensor
unsigned long currentMillis = millis();
if (previousMillis >= DelayTime)
{
currentValue = analogRead(sensorPin); // read the input pin
if ((previousValue < 150) && (currentValue > 250))
{
Serial.print("drip count = ");
Serial.println(drip);
drip += 1;
}
previousValue = currentValue;
}
previousMillis = currentMillis - previousMillis; // Remember the time
}
};
DripSensor dripSensor(3,5);
void setup()
{
Serial.begin(9600);
}
void loop()
{
long a;
long b;
a = millis();
dripSensor.Update();
b = millis();
Serial.println(b-a);
delay(200);
}
| [
"tiberius.brastaviceanu@gmail.com"
] | tiberius.brastaviceanu@gmail.com |
6a1a31975279119d8b84f614066090d38b1ba3ea | 5bb9fd77d2a88a97e11cf782f821b563ea14bb6b | /samples/03_sdp/2017/05_graphs/graph_test.cpp | 2b0c406411ba85468eb920ae32b298790e53677d | [
"MIT"
] | permissive | stranxter/lecture-notes | d844e3f5453c250cbe299babf0baf5870b6b0ee3 | 44151b4c88a478e8debeb75c002619d2aee6b654 | refs/heads/master | 2023-05-31T17:26:30.929596 | 2023-05-31T12:05:18 | 2023-05-31T12:05:18 | 40,540,330 | 43 | 52 | MIT | 2023-04-21T06:22:42 | 2015-08-11T12:27:38 | TeX | UTF-8 | C++ | false | false | 4,376 | cpp | #include <iostream>
#include <cassert>
#include <set>
#include <string>
#include "graph.cpp"
#include <stack>
#include <map>
#include <queue>
string stringOfLabels (int start,
int end,
const Graph<int,char>& g,
set<int>& visited)
{
if (start == end)
return "";
visited.insert (start);
for (const pair<int,char>& edge : g.edgesFrom (start))
{
if (visited.count (edge.first) == 0)
{
string nextString
= stringOfLabels (edge.first,end,g,visited);
if (!nextString.empty())
{
return edge.second + nextString;
}
if (edge.first == end)
{
string result;
result += edge.second;
return result;
}
}
}
return "";
}
string getPathIter1 (int start,
int end,
const Graph<int,char> g)
{
//key:child, value:parent>
map<int,int> history;
stack<int> s;
s.push (start);
history[start] = start;
while (!s.empty() && s.top() != end)
{
int v = s.top();
s.pop();
for (const pair<int,char>& edge : g.edgesFrom (v))
{
const int &neigh = edge.first;
if (history.count(neigh) == 0)
{
s.push (neigh);
history[neigh] = v;
}
}
}
if (s.empty())
return "";
string result;
int current = end;
while (current != start)
{
int &parent = history[current];
result += g.getLabel (parent,current);
current = parent;
}
return result;
}
bool hasPathIter (int start,
int end,
const Graph<int,char> g)
{
set<int> visited;
stack<int> s;
s.push (start);
visited.insert (start);
while (!s.empty() && s.top() != end)
{
int v = s.top();
s.pop();
for (const pair<int,char>& edge : g.edgesFrom (v))
{
const int &neigh = edge.first;
if (visited.count(neigh) == 0)
{
s.push (neigh);
visited.insert (neigh);
}
}
}
return !s.empty();
}
string getPathIter2 (int start,
int end,
const Graph<int,char> g)
{
set<int> visited;
stack<pair<int,string>> s;
s.push (pair<int,string>(start,""));
visited.insert (start);
while (!s.empty() && s.top().first != end)
{
//vertex and history
pair<int,string> vh = s.top();
s.pop();
int &v = vh.first;
string &hist = vh.second;
for (const pair<int,char>& edge : g.edgesFrom (v))
{
const int &neigh = edge.first;
const char &label = edge.second;
if (visited.count(neigh) == 0)
{
s.push (pair<int,string>(neigh,hist+label));
visited.insert (neigh);
}
}
}
if (s.empty())
return "";
return s.top().second;
}
string stringOfLabels (int start,
int end,
const Graph<int,char> g)
{
set<int> visited;
return stringOfLabels (start,end,g,visited);
}
bool hasPath (int start, const char *str, const Graph<int,char> g)
{
if (*str == 0)
return true;
for (const pair<int,char>& edge : g.edgesFrom (start))
{
if (edge.second == *str &&
hasPath (edge.first,str+1,g))
{
return true;
}
}
return false;
}
bool hasPathBFS (int start,
int end,
const Graph<int,char> g)
{
set<int> visited;
queue<int> q;
q.push (start);
visited.insert (start);
while (!q.empty() && q.front() != end)
{
int v = q.front();
q.pop();
for (const pair<int,char>& edge : g.edgesFrom (v))
{
const int &neigh = edge.first;
if (visited.count(neigh) == 0)
{
q.push (neigh);
visited.insert (neigh);
}
}
}
return !q.empty();
}
void testGraph ()
{
Graph<int,char> g;
g.addEdge (0,1,'a');
g.addEdge (2,0,'c');
g.addEdge (1,4,'b');
g.addEdge (1,2,'b');
g.addEdge (1,3,'b');
g.addEdge (4,3,'x');
g.addEdge (3,4,'z');
assert (g.getLabel (0,1) == 'a');
assert (g.getLabel (3,4) == 'z');
assert (g.getLabel (4,3) == 'x');
assert (g.getLabel (1,3) == 'b');
g.toDotty (cout);
assert (hasPath(0,"abc",g));
assert (!hasPath (1,"abc",g));
assert (hasPath(1,"bca",g));
assert (hasPath(0,"abcabcabcabc",g));
assert (hasPathIter(2,4,g));
assert (!hasPathIter(3,1,g));
assert (hasPathIter(1,1,g));
assert (!hasPathIter(4,2,g));
assert (hasPathBFS(2,4,g));
assert (!hasPathBFS(3,1,g));
assert (hasPathBFS(1,1,g));
assert (!hasPathBFS(4,2,g));
string res = stringOfLabels (2,3,g);
cerr << "str = " << res << endl;
res = getPathIter1 (2,3,g);
cerr << "str = " << res << endl;
res = getPathIter2 (2,3,g);
cerr << "str = " << res << endl;
}
int main ()
{
testGraph();
return 0;
} | [
"kalin.georgiev@gmail.com"
] | kalin.georgiev@gmail.com |
5fe57a0b6f521f330da1efd522981ca3219b2e08 | bf5d6f447b5a4501761dd88d14e5208f85c6876f | /mbed-wavfile/wavfile.cpp | 618a9cb80e7a8f478f17a5fc93dac0eea54a0c35 | [] | no_license | jchuang1977/smeshstudio_privatelibrary | b6947264c30cb819913529b63b4c95527c3e9917 | 52a955aefa49e35ea3497d72556a61c888ef0ba0 | refs/heads/master | 2021-01-22T10:18:08.080733 | 2015-01-24T15:35:27 | 2015-01-24T15:35:27 | 29,050,912 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,897 | cpp | /**
* @file wavfile.cpp
* @author Shinichiro Nakamura
*/
/*
* ===============================================================
* Tiny WAV I/O Module
* Version 0.0.1
* ===============================================================
* Copyright (c) 2011-2012 Shinichiro Nakamura
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
* ===============================================================
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "wavfile.h"
#define DEBUG printf
#define CHUNK_ID_RIFF (('R' << 24) | ('I' << 16) | ('F' << 8) | ('F' << 0))
#define CHUNK_ID_FMT (('f' << 24) | ('m' << 16) | ('t' << 8) | (' ' << 0))
#define CHUNK_ID_DATA (('d' << 24) | ('a' << 16) | ('t' << 8) | ('a' << 0))
#define RIFF_CHUNK_FORMAT_WAVE (('W' << 24) | ('A' << 16) | ('V' << 8) | ('E' << 0))
#define BITS_PER_SAMPLE_8 (8)
#define BITS_PER_SAMPLE_16 (16)
#define BITS_PER_SAMPLE_24 (24)
#define CHUNK_SIZE_FMT_PCM (16)
#define CHUNK_SIZE_FMT_EXTENSIBLE (40)
#define CHANNEL_MASK_SPEAKER_FRONT_LEFT (0x00000001)
#define CHANNEL_MASK_SPEAKER_FRONT_RIGHT (0x00000002)
#define CHANNEL_MASK_SPEAKER_FRONT_CENTER (0x00000004)
#define CHANNEL_MASK_SPEAKER_LOW_FREQUENCY (0x00000008)
#define CHANNEL_MASK_SPEAKER_BACK_LEFT (0x00000010)
#define CHANNEL_MASK_SPEAKER_BACK_RIGHT (0x00000020)
#define CHANNEL_MASK_SPEAKER_FRONT_LEFT_OF_CENTER (0x00000040)
#define CHANNEL_MASK_SPEAKER_FRONT_RIGHT_OF_CENTER (0x00000080)
#define CHANNEL_MASK_SPEAKER_BACK_CENTER (0x00000100)
#define CHANNEL_MASK_SPEAKER_SIDE_LEFT (0x00000200)
#define CHANNEL_MASK_SPEAKER_SIDE_RIGHT (0x00000400)
#define CHANNEL_MASK_SPEAKER_TOP_CENTER (0x00000800)
#define CHANNEL_MASK_SPEAKER_TOP_FRONT_LEFT (0x00001000)
#define CHANNEL_MASK_SPEAKER_TOP_FRONT_CENTER (0x00002000)
#define CHANNEL_MASK_SPEAKER_TOP_FRONT_RIGHT (0x00004000)
#define CHANNEL_MASK_SPEAKER_TOP_BACK_LEFT (0x00008000)
#define CHANNEL_MASK_SPEAKER_TOP_BACK_CENTER (0x00010000)
#define CHANNEL_MASK_SPEAKER_TOP_BACK_RIGHT (0x00020000)
#define CHANNEL_MASK_SPEAKER_RESERVED (0x80000000)
struct WAVFILE {
FILE *fp;
char filename[BUFSIZ];
WavFileMode mode;
bool info_checked;
bool data_checked;
uint32_t data_byte_count;
wavfile_info_t info;
};
static int WRITE_U32_BE(FILE *fp, const uint32_t value) {
for (int i = 0; i < 4; i++) {
if (fputc((value >> (8 * (3 - i))), fp) == EOF) {
return -1;
}
}
return 0;
}
static int WRITE_U32_LE(FILE *fp, const uint32_t value) {
for (int i = 0; i < 4; i++) {
if (fputc((value >> (8 * i)), fp) == EOF) {
return -1;
}
}
return 0;
}
static int WRITE_U16_LE(FILE *fp, const uint16_t value) {
for (int i = 0; i < 2; i++) {
if (fputc((value >> (8 * i)), fp) == EOF) {
return -1;
}
}
return 0;
}
static int READ_U32_BE(FILE *fp, uint32_t *value) {
int raw[4];
for (int i = 0; i < (int)(sizeof(raw) / sizeof(raw[0])); i++) {
raw[i] = fgetc(fp);
if (raw[i] == EOF) {
*value = 0x00000000;
return -1;
}
}
*value =
((uint32_t)raw[0] << 24) |
((uint32_t)raw[1] << 16) |
((uint32_t)raw[2] << 8) |
((uint32_t)raw[3] << 0);
return 0;
}
static int READ_U32_LE(FILE *fp, uint32_t *value) {
int raw[4];
for (int i = 0; i < (int)(sizeof(raw) / sizeof(raw[0])); i++) {
raw[i] = fgetc(fp);
if (raw[i] == EOF) {
*value = 0x00000000;
return -1;
}
}
*value =
((uint32_t)raw[3] << 24) |
((uint32_t)raw[2] << 16) |
((uint32_t)raw[1] << 8) |
((uint32_t)raw[0] << 0);
return 0;
}
static int READ_U16_LE(FILE *fp, uint16_t *value) {
int raw[2];
for (int i = 0; i < (int)(sizeof(raw) / sizeof(raw[0])); i++) {
raw[i] = fgetc(fp);
if (raw[i] == EOF) {
*value = 0x00000000;
return -1;
}
}
*value =
((uint16_t)raw[1] << 8) |
((uint16_t)raw[0] << 0);
return 0;
}
static WavFileResult chunk_reader_unknown(
const uint32_t chunk_id,
const uint32_t chunk_size,
FILE *fp) {
for (int i = 0; i < (int)chunk_size; i++) {
int c = fgetc(fp);
if (c == EOF) {
return WavFileResultErrorBrokenChunkData;
}
}
return WavFileResultOK;
}
static WavFileResult chunk_reader_riff(
const uint32_t chunk_id,
const uint32_t chunk_size,
FILE *fp,
uint32_t *format_id) {
if (READ_U32_BE(fp, format_id) != 0) {
return WavFileResultErrorBrokenFormatId;
}
return WavFileResultOK;
}
static WavFileResult chunk_reader_fmt(
const uint32_t chunk_id,
const uint32_t chunk_size,
FILE *fp,
uint16_t *audio_format,
uint16_t *num_channels,
uint32_t *sample_rate,
uint32_t *byte_rate,
uint16_t *block_align,
uint16_t *bits_per_sample) {
uint32_t read_byte_count = 0;
/*
* 2
*/
if (read_byte_count < chunk_size) {
if (READ_U16_LE(fp, audio_format) != 0) {
return WavFileResultErrorBrokenAudioFormat;
}
}
read_byte_count+=2;
/*
* 2 + 2
*/
if (read_byte_count < chunk_size) {
if (READ_U16_LE(fp, num_channels) != 0) {
return WavFileResultErrorBrokenNumChannels;
}
}
read_byte_count+=2;
/*
* 2 + 2 + 4
*/
if (read_byte_count < chunk_size) {
if (READ_U32_LE(fp, sample_rate) != 0) {
return WavFileResultErrorBrokenSampleRate;
}
}
read_byte_count+=4;
/*
* 2 + 2 + 4 + 4
*/
if (read_byte_count < chunk_size) {
if (READ_U32_LE(fp, byte_rate) != 0) {
return WavFileResultErrorBrokenByteRate;
}
}
read_byte_count+=4;
/*
* 2 + 2 + 4 + 4 + 2
*/
if (read_byte_count < chunk_size) {
if (READ_U16_LE(fp, block_align) != 0) {
return WavFileResultErrorBrokenBlockAlign;
}
}
read_byte_count+=2;
/*
* 2 + 2 + 4 + 4 + 2 + 2
*/
if (read_byte_count < chunk_size) {
if (READ_U16_LE(fp, bits_per_sample) != 0) {
return WavFileResultErrorBrokenBitsPerSample;
}
}
read_byte_count+=2;
/*
* 2 + 2 + 4 + 4 + 2 + 2
*/
while (read_byte_count < chunk_size) {
if (fgetc(fp) == EOF) {
return WavFileResultErrorBrokenChunkData;
}
read_byte_count++;
}
return WavFileResultOK;
}
WAVFILE *wavfile_open(const char *filename, WavFileMode mode, WavFileResult *result) {
/*
* Verify the filename.
*/
if (filename == NULL) {
*result = WavFileResultErrorInvalidFileName;
return NULL;
}
/*
* Open the file.
*/
FILE *fp = NULL;
switch (mode) {
case WavFileModeRead:
fp = fopen(filename, "rb");
break;
case WavFileModeWrite:
fp = fopen(filename, "wb");
break;
default:
fp = NULL;
break;
}
if (fp == NULL) {
*result = WavFileResultErrorFileOpen;
return NULL;
}
/*
* Allocate the handler.
*/
WAVFILE *p = (WAVFILE *)malloc(sizeof(WAVFILE));
if (p == NULL) {
*result = WavFileResultErrorMemoryAllocation;
return NULL;
}
/*
* Fill the fields.
*/
p->fp = fp;
strcpy(p->filename, filename);
p->mode = mode;
p->info_checked = false;
p->data_checked = false;
p->data_byte_count = 0;
WAVFILE_INFO_AUDIO_FORMAT(&(p->info)) = 0;
WAVFILE_INFO_NUM_CHANNELS(&(p->info)) = 0;
WAVFILE_INFO_SAMPLE_RATE(&(p->info)) = 0;
WAVFILE_INFO_BYTE_RATE(&(p->info)) = 0;
WAVFILE_INFO_BLOCK_ALIGN(&(p->info)) = 0;
WAVFILE_INFO_BITS_PER_SAMPLE(&(p->info)) = 0;
*result = WavFileResultOK;
return p;
}
WavFileResult wavfile_read_info(WAVFILE *p, wavfile_info_t *info) {
WavFileResult result = WavFileResultOK;
if (p == NULL) {
result = WavFileResultErrorInvalidHandler;
goto finalize;
}
if (p->info_checked) {
result = WavFileResultErrorAlreadyInfoChecked;
goto finalize;
}
if (p->data_checked) {
result = WavFileResultErrorAlreadyDataChecked;
goto finalize;
}
if (p->mode != WavFileModeRead) {
result = WavFileResultErrorInvalidMode;
goto finalize;
}
while (1) {
uint32_t chunk_id;
uint32_t chunk_size;
/*
* Get the chunk ID.
*/
if (READ_U32_BE(p->fp, &chunk_id) != 0) {
if (feof(p->fp)) {
/*
*
*/
result = WavFileResultErrorNoDataChunk;
goto finalize;
} else {
result = WavFileResultErrorBrokenChunkId;
goto finalize;
}
}
/*
* Verify the chunk size.
*/
if (READ_U32_LE(p->fp, &chunk_size) != 0) {
result = WavFileResultErrorBrokenChunkSize;
goto finalize;
}
#if WAVFILE_DEBUG_ENABLED
/*
*
*/
DEBUG("chunk_id(0x%04X-%c%c%c%c), chunk_size(%d bytes)\n",
chunk_id,
(chunk_id >> (8 * 3)),
(chunk_id >> (8 * 2)),
(chunk_id >> (8 * 1)),
(chunk_id >> (8 * 0)),
chunk_size);
#endif
/*
*/
switch (chunk_id) {
case CHUNK_ID_RIFF: {
uint32_t format_id;
result = chunk_reader_riff(
chunk_id,
chunk_size,
p->fp,
&format_id);
#if WAVFILE_DEBUG_ENABLED
/*
*/
DEBUG("\tformat_id(%d)\n", format_id);
#endif
if (format_id != RIFF_CHUNK_FORMAT_WAVE) {
return WavFileResultErrorInvalidFormatId;
}
if (result != WavFileResultOK) {
goto finalize;
}
}
break;
case CHUNK_ID_FMT: {
result = chunk_reader_fmt(
chunk_id,
chunk_size,
p->fp,
&(p->info.audio_format),
&(p->info.num_channels),
&(p->info.sample_rate),
&(p->info.byte_rate),
&(p->info.block_align),
&(p->info.bits_per_sample));
info->audio_format = p->info.audio_format;
info->num_channels = p->info.num_channels;
info->sample_rate = p->info.sample_rate;
info->byte_rate = p->info.byte_rate;
info->block_align = p->info.block_align;
info->bits_per_sample = p->info.bits_per_sample;
#if WAVFILE_DEBUG_ENABLED
/*
*/
DEBUG("\taudio_format(%d)\n", p->info.audio_format);
DEBUG("\tnum_channels(%d)\n", p->info.num_channels);
DEBUG("\tsample_rate(%d)\n", p->info.sample_rate);
DEBUG("\tbyte_rate(%d)\n", p->info.byte_rate);
DEBUG("\tblock_align(%d)\n", p->info.block_align);
DEBUG("\tbits_per_sample(%d)\n", p->info.bits_per_sample);
#endif
if ((p->info.audio_format != WAVFILE_AUDIO_FORMAT_PCM) && (info->audio_format != WAVFILE_AUDIO_FORMAT_EXTENSIBLE)) {
return WavFileResultErrorInvalidAudioFormat;
}
if (result != WavFileResultOK) {
goto finalize;
}
}
break;
case CHUNK_ID_DATA: {
p->info_checked = true;
p->data_byte_count = chunk_size;
goto finalize;
}
break;
default: {
result = chunk_reader_unknown(chunk_id, chunk_size, p->fp);
if (result != WavFileResultOK) {
goto finalize;
}
}
break;
}
}
finalize:
return result;
}
/**
*/
WavFileResult wavfile_read_data(WAVFILE *p, wavfile_data_t *data) {
if (p == NULL) {
return WavFileResultErrorInvalidHandler;
}
if (!p->info_checked) {
return WavFileResultErrorNeedInfoChecked;
}
if (p->mode != WavFileModeRead) {
return WavFileResultErrorInvalidMode;
}
if (p->data_byte_count == 0) {
data->num_channels = 0;
for (int i = 0; i < p->info.num_channels; i++) {
data->channel_data[i] = 0.5;
}
return WavFileResultOK;
}
data->num_channels = p->info.num_channels;
for (int i = 0; i < p->info.num_channels; i++) {
switch (p->info.bits_per_sample) {
case BITS_PER_SAMPLE_8: {
int c = fgetc(p->fp);
if (c == EOF) {
return WavFileResultErrorBrokenChunkData;
}
data->channel_data[i] = (double)c / 0xFF;
}
p->data_byte_count-=1;
break;
case BITS_PER_SAMPLE_16: {
#if 0
int c1 = fgetc(p->fp);
if (c1 == EOF) {
return WavFileResultErrorBrokenChunkData;
}
int c2 = fgetc(p->fp);
if (c2 == EOF) {
return WavFileResultErrorBrokenChunkData;
}
uint16_t n = (((uint16_t)c2 << 8) | ((uint16_t)c1 << 0)) ^ (1 << 15);
data->channel_data[i] = (double)n / 0xFFFF;
#else
char tmp[2];
fread(tmp, 2, 1, p->fp);
uint16_t n = (((uint16_t)tmp[1] << 8) | ((uint16_t)tmp[0] << 0)) ^ (1 << 15);
data->channel_data[i] = (double)n / 0xFFFF;
#endif
}
p->data_byte_count-=2;
break;
case BITS_PER_SAMPLE_24: {
#if 0
int c1 = fgetc(p->fp);
if (c1 == EOF) {
return WavFileResultErrorBrokenChunkData;
}
int c2 = fgetc(p->fp);
if (c2 == EOF) {
return WavFileResultErrorBrokenChunkData;
}
int c3 = fgetc(p->fp);
if (c3 == EOF) {
return WavFileResultErrorBrokenChunkData;
}
uint32_t n = (((uint32_t)c3 << 16) | ((uint32_t)c2 << 8) | ((uint32_t)c1 << 0)) ^ (1 << 23);
data->channel_data[i] = (double)n / 0xFFFFFF;
#else
char tmp[3];
fread(tmp, 3, 1, p->fp);
uint32_t n = (((uint32_t)tmp[2] << 16) | ((uint32_t)tmp[1] << 8) | ((uint32_t)tmp[0] << 0)) ^ (1 << 23);
data->channel_data[i] = (double)n / 0xFFFFFF;
#endif
}
p->data_byte_count-=3;
break;
default:
return WavFileResultErrorUnsupportedBitsPerSample;
}
}
return WavFileResultOK;
}
WavFileResult wavfile_write_info(WAVFILE *p, const wavfile_info_t *info) {
WavFileResult result = WavFileResultOK;
if (p == NULL) {
result = WavFileResultErrorInvalidHandler;
goto finalize;
}
if (p->info_checked) {
result = WavFileResultErrorAlreadyInfoChecked;
goto finalize;
}
if (p->mode != WavFileModeWrite) {
result = WavFileResultErrorInvalidMode;
goto finalize;
}
p->info.audio_format = info->audio_format;
p->info.num_channels = info->num_channels;
p->info.sample_rate = info->sample_rate;
p->info.byte_rate = info->byte_rate;
p->info.block_align = info->block_align;
p->info.bits_per_sample = info->bits_per_sample;
/*
*
*/
if ((info->audio_format != WAVFILE_AUDIO_FORMAT_PCM) && (info->audio_format != WAVFILE_AUDIO_FORMAT_EXTENSIBLE)) {
result = WavFileResultErrorInvalidAudioFormat;
goto finalize;
}
if ((info->bits_per_sample != BITS_PER_SAMPLE_8)
&& (info->bits_per_sample != BITS_PER_SAMPLE_16)
&& (info->bits_per_sample != BITS_PER_SAMPLE_24)) {
result = WavFileResultErrorUnsupportedBitsPerSample;
goto finalize;
}
if ((info->num_channels * info->sample_rate * (info->bits_per_sample / 8)) != info->byte_rate) {
result = WavFileResultErrorInvalidByteRate;
goto finalize;
}
/*
* [RIFF]
* ------------------------------------------
* Big endian 4 bytes : Chunk ID
* Little endian 4 bytes : Chunk size
* Big endian 4 bytes : Format
* ------------------------------------------
*/
if (WRITE_U32_BE(p->fp, CHUNK_ID_RIFF) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, 0x00000000) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_BE(p->fp, RIFF_CHUNK_FORMAT_WAVE) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
/*
* [fmt]
* ------------------------------------------
* Big endian 4 bytes : Sub chunk ID
* Little endian 4 bytes : Sub chunk size
* Little endian 2 bytes : Audio format
* Little endian 2 bytes : Number of channels
* Little endian 4 bytes : Sample rate
* Little endian 4 bytes : Byte rate
* Little endian 2 bytes : Block align
* Little endian 2 bytes : Bits per sample
* . .
* . Additional bytes here (extensible) .
* . .
* ------------------------------------------
*/
switch (info->audio_format) {
case WAVFILE_AUDIO_FORMAT_PCM: {
if (WRITE_U32_BE(p->fp, CHUNK_ID_FMT) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, CHUNK_SIZE_FMT_PCM) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->audio_format) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->num_channels) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, info->sample_rate) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, info->byte_rate) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->block_align) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->bits_per_sample) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
}
break;
case WAVFILE_AUDIO_FORMAT_EXTENSIBLE: {
if (WRITE_U32_BE(p->fp, CHUNK_ID_FMT) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, CHUNK_SIZE_FMT_EXTENSIBLE) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->audio_format) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->num_channels) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, info->sample_rate) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, info->byte_rate) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->block_align) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->bits_per_sample) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
/*
* Additional bytes for the extensible format.
*
* 2 bytes : Size of the extension (0 or 22)
* 2 bytes : Number of valid bits
* 4 bytes : Speaker position mask
* 16 bytes : GUID, including the data format code
*/
if (WRITE_U16_LE(p->fp, 22) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U16_LE(p->fp, info->bits_per_sample) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, 0x00000000) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
static const unsigned char sub_format[16] = {
0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x10, 0x00,
0x80, 0x00, 0x00, 0xAA,
0x00, 0x38, 0x9B, 0x71
};
for (int i = 0; i < sizeof(sub_format); i++) {
fputc((char)sub_format[i], p->fp);
}
}
break;
default:
result = WavFileResultErrorInvalidAudioFormat;
goto finalize;
}
/*
* [data]
* ------------------------------------------
* Big endian 4 bytes : Sub chunk ID
* Little endian 4 bytes : Sub chunk size
* ------------------------------------------
* Little endian 2 bytes : Sample 1 (Ch.1)
* Little endian 2 bytes : Sample 1 (Ch.2)
* .
* .
* .
* Little endian 2 bytes : Sample 1 (Ch.N)
* ------------------------------------------
* Little endian 2 bytes : Sample 2 (Ch.1)
* Little endian 2 bytes : Sample 2 (Ch.2)
* .
* .
* .
* Little endian 2 bytes : Sample 2 (Ch.N)
* ------------------------------------------
*/
if (WRITE_U32_BE(p->fp, CHUNK_ID_DATA) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, 0x00000000) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
finalize:
if (WavFileResultOK == result) {
p->info_checked = true;
}
return result;
}
/**
*/
WavFileResult wavfile_write_data(WAVFILE *p, const wavfile_data_t *data) {
WavFileResult result = WavFileResultOK;
if (p == NULL) {
result = WavFileResultErrorInvalidHandler;
goto finalize;
}
if (!p->info_checked) {
result = WavFileResultErrorNeedInfoChecked;
goto finalize;
}
if (p->mode != WavFileModeWrite) {
result = WavFileResultErrorInvalidMode;
goto finalize;
}
if (p->info.num_channels != data->num_channels) {
result = WavFileResultErrorInvalidNumChannels;
goto finalize;
}
for (int i = 0; i < p->info.num_channels; i++) {
switch (p->info.bits_per_sample) {
case BITS_PER_SAMPLE_8: {
int n = (int)((double)data->channel_data[i] * 0xFF);
if (n < 0x00) {
n = 0x00;
}
if (0xFF < n) {
n = 0xFF;
}
fputc((char)n, p->fp);
}
p->data_byte_count+=1;
break;
case BITS_PER_SAMPLE_16: {
int n = (int)((double)(data->channel_data[i] * 0xFFFF) - 0x8000);
if (0x7FFF < n) {
n = 0x7FFF;
}
if (n < -0x8000) {
n = -0x8000;
}
fputc(((uint16_t)n >> 0) & 0xff, p->fp);
fputc(((uint16_t)n >> 8) & 0xff, p->fp);
}
p->data_byte_count+=2;
break;
case BITS_PER_SAMPLE_24: {
int n = (int)((double)(data->channel_data[i] * 0xFFFFFF) - 0x800000);
if (0x7FFFFF < n) {
n = 0x7FFFFF;
}
if (n < -0x800000) {
n = -0x800000;
}
fputc(((uint32_t)n >> 0) & 0xff, p->fp);
fputc(((uint32_t)n >> 8) & 0xff, p->fp);
fputc(((uint32_t)n >> 16) & 0xff, p->fp);
}
p->data_byte_count+=3;
break;
}
}
p->data_checked = true;
finalize:
return result;
}
WavFileResult wavfile_close(WAVFILE *p) {
WavFileResult result = WavFileResultOK;
switch (p->mode) {
case WavFileModeRead:
break;
case WavFileModeWrite:
if (p->info_checked && p->data_checked) {
switch (p->info.audio_format) {
case WAVFILE_AUDIO_FORMAT_PCM: {
/*
* Fill the RIFF chunk size.
*/
if (fseek(p->fp, 4L, SEEK_SET) == -1) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, 4 + (8 + CHUNK_SIZE_FMT_PCM) + (8 + p->data_byte_count)) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
/*
* Fill the data sub chunk size.
*/
if (fseek(p->fp, 12 + (8 + CHUNK_SIZE_FMT_PCM) + 4, SEEK_SET) == -1) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, p->data_byte_count) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
}
break;
case WAVFILE_AUDIO_FORMAT_EXTENSIBLE: {
/*
* Fill the RIFF chunk size.
*/
if (fseek(p->fp, 4L, SEEK_SET) == -1) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, 4 + (8 + CHUNK_SIZE_FMT_EXTENSIBLE) + (8 + p->data_byte_count)) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
/*
* Fill the data sub chunk size.
*/
if (fseek(p->fp, 12 + (8 + CHUNK_SIZE_FMT_EXTENSIBLE) + 4, SEEK_SET) == -1) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
if (WRITE_U32_LE(p->fp, p->data_byte_count) != 0) {
result = WavFileResultErrorFileWrite;
goto finalize;
}
}
break;
}
}
break;
}
finalize:
fclose(p->fp);
free(p);
return result;
}
void wavfile_result_string(const WavFileResult result, char *buf, size_t siz) {
switch (result) {
case WavFileResultOK:
strcpy(buf, "OK.");
break;
case WavFileResultErrorInvalidFileName:
strcpy(buf, "Invalid file name found.");
break;
case WavFileResultErrorMemoryAllocation:
strcpy(buf, "Memory allocation error.");
break;
case WavFileResultErrorFileOpen:
strcpy(buf, "File open error found.");
break;
case WavFileResultErrorFileWrite:
strcpy(buf, "File write error found.");
break;
case WavFileResultErrorBrokenChunkId:
strcpy(buf, "Broken chunk ID found.");
break;
case WavFileResultErrorBrokenChunkSize:
strcpy(buf, "Borken chunk size found.");
break;
case WavFileResultErrorBrokenChunkData:
strcpy(buf, "Borken chunk data found.");
break;
case WavFileResultErrorBrokenFormatId:
strcpy(buf, "Broken format ID found.");
break;
case WavFileResultErrorInvalidFormatId:
strcpy(buf, "Invalid format ID found.");
break;
case WavFileResultErrorBrokenAudioFormat:
strcpy(buf, "Broken audio format found.");
break;
case WavFileResultErrorInvalidAudioFormat:
strcpy(buf, "Invalid audio format found.");
break;
case WavFileResultErrorInvalidNumChannels:
strcpy(buf, "Invalid number of channels found.");
break;
case WavFileResultErrorBrokenNumChannels:
strcpy(buf, "Broken number of channels found.");
break;
case WavFileResultErrorBrokenSampleRate:
strcpy(buf, "Broken sample rate found.");
break;
case WavFileResultErrorBrokenByteRate:
strcpy(buf, "Broken byte rate found.");
break;
case WavFileResultErrorInvalidByteRate:
strcpy(buf, "Invalid byte rate found.");
break;
case WavFileResultErrorBrokenBlockAlign:
strcpy(buf, "Broken block alignment found.");
break;
case WavFileResultErrorBrokenBitsPerSample:
strcpy(buf, "Broken bits per sample found.");
break;
case WavFileResultErrorUnsupportedBitsPerSample:
strcpy(buf, "Unsupported bits per sample found.");
break;
case WavFileResultErrorAlreadyInfoChecked:
strcpy(buf, "Already checked info.");
break;
case WavFileResultErrorAlreadyDataChecked:
strcpy(buf, "Already checked data.");
break;
case WavFileResultErrorNoDataChunk:
strcpy(buf, "No data chunk.");
break;
case WavFileResultErrorInvalidMode:
strcpy(buf, "Invalid mode.");
break;
case WavFileResultErrorNeedInfoChecked:
strcpy(buf, "Need check info.");
break;
case WavFileResultErrorNeedDataChecked:
strcpy(buf, "Need check data.");
break;
case WavFileResultErrorInvalidHandler:
strcpy(buf, "Invalid handler.");
break;
default:
strcpy(buf, "Unkonwn error found.");
break;
}
}
| [
"jchuang1977@gmail.com"
] | jchuang1977@gmail.com |
fa0c8ecc9a3ba80ebd1fca3dddda3736f464a00c | 7126e5dcfdf2bfe42aeb34f90d8249d41e9b879e | /src/Theme_ex.cpp | d5dabd672729d38c8383321cd9868a5ea85ff5be | [
"MIT"
] | permissive | xinsuinizhuan/ExDUIR | 45b8d9753a0328d55cefb870caddf355d3d5eb3d | b1d9b92d153c460ef5770c0efa455fa5deb70212 | refs/heads/master | 2023-08-01T02:08:46.687012 | 2021-09-07T13:08:12 | 2021-09-07T13:08:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,584 | cpp | #include "Theme_ex.h"
BOOL _theme_unpack(LPVOID lpData, size_t dwDataLen, LPVOID lpKey, size_t dwKeyLen, std::vector<INT> *atomFiles, std::vector<LPVOID> *lpFiles, std::vector<UCHAR> *dwFileProps)
{
LPVOID retPtr = nullptr;
size_t retLen = 0;
BOOL ret = FALSE;
_bin_uncompress(lpData, dwDataLen, 0, 0, &retPtr, &retLen);
if (retLen > 0)
{
if (__get_unsignedchar(retPtr, 0) == EPDF_THEME)
{
INT count = __get_int(retPtr, 1);
if (count > 0)
{
(*atomFiles).resize(count);
(*lpFiles).resize(count);
(*dwFileProps).resize(count);
retPtr = (LPVOID)((size_t)retPtr + 5);
for (INT i = 0; i < count; i++)
{
UCHAR prop = __get_unsignedchar(retPtr, 4);
INT len = __get_int(retPtr, 5) + 4;
if (len > 4)
{
LPVOID tmp = Ex_MemAlloc(len + 2);
if (tmp != 0)
{
(*atomFiles)[i] = __get_int(retPtr, 0);
(*lpFiles)[i] = tmp;
(*dwFileProps)[i] = prop;
RtlMoveMemory(tmp, (LPVOID)((size_t)retPtr + 5), len);
}
}
retPtr = (LPVOID)((size_t)retPtr + 5 + len);
}
ret = TRUE;
}
}
}
return ret;
}
INT _theme_fillitems(LPVOID lpContent, std::vector<INT> *artItems1, std::vector<size_t> *artItems2)
{
auto iOffset1 = wcschr((WCHAR *)lpContent, '\n');
INT nCount = 0;
while (iOffset1 != 0)
{
iOffset1 = (WCHAR *)((size_t)iOffset1 + 2);
auto iOffset2 = wcschr(iOffset1, '\r');
if (iOffset2 != 0)
{
__set_wchar(iOffset2, 0, 0);
}
WCHAR c = __get_wchar(iOffset1, 0);
if (c != ';') //;
{
auto iSplit = wcschr(iOffset1, '='); //=
if (iSplit != 0)
{
__set_wchar(iSplit, 0, 0);
auto dwLen = (size_t)iSplit - (size_t)iOffset1;
(*artItems1)[nCount] = Crc32_Addr(iOffset1, dwLen);
(*artItems2)[nCount] = (size_t)(WCHAR *)((size_t)iSplit + 2);
nCount = nCount + 1;
}
}
if (iOffset2 == 0)
{
break;
}
else
{
iOffset1 = wcschr((WCHAR *)((size_t)iOffset2 + 2), '\n');
}
}
return nCount;
}
BOOL _theme_fillclasses(EX_HASHTABLE *pTableFiles, EX_HASHTABLE *pTableClass, std::vector<INT> atomFiles, std::vector<LPVOID> lpFiles, std::vector<UCHAR> dwFileProps, LPVOID aryCorlors)
{
std::vector<INT> aryAtomKey;
std::vector<size_t> arylpValue;
BOOL ret = FALSE;
for (size_t i = 0; i < atomFiles.size(); i++)
{
HashTable_Set(pTableFiles, atomFiles[i], (size_t)lpFiles[i]);
}
EXATOM atomINI = ATOM_THEME_INI;
size_t lpFile = 0;
if (HashTable_Get(pTableFiles, atomINI, &lpFile))
{
std::string utf8Str((char*)(lpFile + 4), __get_int((LPVOID)lpFile, 0));
std::wstring unicodeStr = u2w(utf8Str);
transform(unicodeStr.begin(), unicodeStr.end(), unicodeStr.begin(), ::tolower);
aryAtomKey.resize(32);
arylpValue.resize(32);
auto iClassStart = wcschr((WCHAR*)unicodeStr.c_str(), '[');
LPVOID lpValue = nullptr;
INT Value;
while (iClassStart != 0)
{
iClassStart = (WCHAR *)((size_t)iClassStart + 2);
auto iClassEnd = wcschr(iClassStart, ']');
if (iClassEnd == 0)
{
break;
}
else
{
__set_wchar(iClassEnd, 0, 0);
auto iContentStart = (WCHAR *)((size_t)iClassEnd + 2);
auto iContentEnd = wcschr(iContentStart, '[');
if (iContentEnd != 0)
{
__set_wchar(iContentEnd, 0, 0);
}
auto dwLen = (size_t)iClassEnd - (size_t)iClassStart;
if (dwLen > 0)
{
EXATOM atomClass = Crc32_Addr(iClassStart, dwLen);
INT nCount = _theme_fillitems(iContentStart, &aryAtomKey, &arylpValue);
if (nCount > 0)
{
if (atomClass == ATOM_COLOR)
{
for (INT i = 0; i < nCount; i++)
{
if (_fmt_color((LPVOID)arylpValue[i], &Value))
{
for (size_t ii = 0; ii < g_Li.aryColorsAtom.size(); ii++)
{
if (g_Li.aryColorsAtom[ii] == aryAtomKey[i])
{
__set_int(aryCorlors, g_Li.aryColorsOffset[ii] - offsetof(obj_s, crBackground_), Value);
break;
}
}
}
}
}
else
{
classtable_s *pClass = (classtable_s *)Ex_MemAlloc(sizeof(classtable_s));
if (pClass != 0)
{
EX_HASHTABLE *pTableProp = HashTable_Create(GetNearestPrime(nCount), pfnDefaultFreeData);
if (pTableProp != 0)
{
pClass->tableProps_ = pTableProp;
HashTable_Set(pTableClass, atomClass, (size_t)pClass);
for (INT i = 0; i < nCount; i++)
{
auto wchar = __get_wchar((LPVOID)arylpValue[i], 0);
if (wchar == 34) //"
{
arylpValue[i] = arylpValue[i] + 2;
dwLen = (lstrlenW((LPCWSTR)arylpValue[i]) - 1) * 2;
if (aryAtomKey[i] == ATOM_BACKGROUND_IMAGE)
{
INT atomProp = Crc32_Addr((LPVOID)arylpValue[i], dwLen);
for (size_t ii = 0; ii < atomFiles.size(); ii++)
{
if (atomProp == atomFiles[ii])
{
if (dwFileProps[ii] == EPDF_PNGBITS)
{
_img_createfrompngbits(lpFiles[ii], &pClass->hImage_);
}
else
{
_img_createfrommemory((LPVOID)((size_t)lpFiles[ii] + 4), __get_int(lpFiles[ii], 0), &pClass->hImage_);
}
break;
}
}
continue;
}
else
{
LPVOID lpValueaa = Ex_MemAlloc(dwLen + 2);
RtlMoveMemory(lpValueaa, (LPVOID)arylpValue[i], dwLen);
HashTable_Set(pTableProp, aryAtomKey[i], (size_t)lpValueaa);
}
}
else
{
EXATOM atomProp = _fmt_getatom((LPVOID)arylpValue[i], &lpValue);
LPVOID lpValuea = nullptr;
if (atomProp == ATOM_RGB || atomProp == ATOM_RGBA)
{
lpValuea = Ex_MemAlloc(4);
_fmt_color((LPVOID)arylpValue[i], lpValuea);
}
else
{
_fmt_intary_ex((LPVOID)arylpValue[i], &lpValuea, 0, TRUE);
}
HashTable_Set(pTableProp, (size_t)aryAtomKey[i], (size_t)lpValuea);
}
}
}
}
}
}
}
iClassStart = iContentEnd;
}
}
ret = TRUE;
}
return ret;
}
void CALLBACK _theme_freeclass(LPVOID pClass)
{
if (pClass != 0)
{
HashTable_Destroy(((classtable_s *)pClass)->tableProps_);
_img_destroy(((classtable_s *)pClass)->hImage_);
Ex_MemFree(pClass);
}
}
HEXTHEME Ex_ThemeLoadFromMemory(LPVOID lpData, size_t dwDataLen, LPVOID lpKey, size_t dwKeyLen, BOOL bDefault)
{
if (lpData == 0 || dwDataLen == 0)
return 0;
INT crc = Crc32_Addr(lpData, dwDataLen);
if (crc == 0)
return 0;
for (size_t i = 0; i < g_Li.aryThemes.size(); i++)
{
if (!IsBadReadPtr(g_Li.aryThemes[i], sizeof(EX_THEME)))
{
if (((EX_THEME *)g_Li.aryThemes[i])->crcTheme == crc)
{
InterlockedExchangeAdd((long *)&(((EX_THEME *)g_Li.aryThemes[i])->loadCount), 1);
if (bDefault)
{
g_Li.hThemeDefault = g_Li.aryThemes[i];
}
return g_Li.aryThemes[i];
}
}
}
HEXTHEME hTheme = (HEXTHEME)Ex_MemAlloc(sizeof(EX_THEME));
INT nError = 0;
std::vector<INT> atomFiles;
std::vector<LPVOID> lpFiles;
std::vector<UCHAR> dwFileProps;
if (hTheme == 0)
{
nError = ERROR_EX_MEMORY_ALLOC;
}
else
{
if (_theme_unpack(lpData, dwDataLen, lpKey, dwKeyLen, &atomFiles, &lpFiles, &dwFileProps))
{
EX_HASHTABLE *pTableFiles = HashTable_Create(GetNearestPrime(atomFiles.size()), pfnDefaultFreeData);
if (pTableFiles != 0)
{
EX_HASHTABLE *pTableClass = HashTable_Create(27, _theme_freeclass);
if (pTableClass != 0)
{
LPVOID aryColors = Ex_MemAlloc(sizeof(colors_s));
if (g_Li.hThemeDefault != 0)
{
RtlMoveMemory(aryColors, (LPVOID)__get(g_Li.hThemeDefault, offsetof(EX_THEME, aryColors)), sizeof(colors_s));
}
if (_theme_fillclasses(pTableFiles, pTableClass, atomFiles, lpFiles, dwFileProps, aryColors))
{
((EX_THEME *)hTheme)->tableFiles = pTableFiles;
((EX_THEME *)hTheme)->loadCount = 1;
((EX_THEME *)hTheme)->crcTheme = crc;
((EX_THEME *)hTheme)->tableClass = pTableClass;
((EX_THEME *)hTheme)->aryColors = aryColors;
g_Li.aryThemes.push_back(hTheme);
if (bDefault)
{
g_Li.hThemeDefault = hTheme;
}
return hTheme;
}
HashTable_Destroy(pTableClass);
}
HashTable_Destroy(pTableFiles);
}
}
Ex_MemFree(hTheme);
}
Ex_SetLastError(nError);
return 0;
}
HEXTHEME Ex_ThemeLoadFromFile(LPCWSTR lptszFile, LPVOID lpKey, size_t dwKeyLen, BOOL bDefault)
{
INT dwLen = lstrlenW(lptszFile);
HEXTHEME ret = nullptr;
if (dwLen > 0)
{
std::vector<CHAR> data;
Ex_ReadFile(lptszFile, &data);
ret = Ex_ThemeLoadFromMemory(data.data(), data.size(), lpKey, dwKeyLen, bDefault);
}
return ret;
}
BOOL Ex_ThemeDrawControlEx(HEXTHEME hTheme, HEXCANVAS hCanvas, FLOAT dstLeft, FLOAT dstTop, FLOAT dstRight, FLOAT dstBottom,
EXATOM atomClass, EXATOM atomSrcRect, EXATOM atomBackgroundRepeat, EXATOM atomBackgroundPositon, EXATOM atomBackgroundGrid, EXATOM atomBackgroundFlags, DWORD dwAlpha)
{
BOOL ret = FALSE;
if (hTheme == 0 || hCanvas == 0 || atomClass == 0 || atomSrcRect == 0 || dwAlpha == 0)
return FALSE;
EX_HASHTABLE *pTheme = ((EX_THEME *)hTheme)->tableClass;
if (pTheme != 0)
{
classtable_s *pClass = 0;
HashTable_Get(pTheme, atomClass, (size_t *)&pClass);
if (pClass != 0)
{
HEXIMAGE hImg = pClass->hImage_;
if (hImg != 0)
{
EX_HASHTABLE *pProp = pClass->tableProps_;
if (pProp != 0)
{
RECT *pSrcRect = nullptr;
HashTable_Get(pProp, atomSrcRect, (size_t *)&pSrcRect);
if (pSrcRect != 0)
{
if (IsRectEmpty(pSrcRect))
{
return FALSE;
}
LPVOID pFlags = nullptr;
INT dwFlags = 0;
HashTable_Get(pProp, atomBackgroundFlags, (size_t *)&pFlags);
if (pFlags != 0)
{
dwFlags = __get_int(pFlags, 0);
}
LPVOID pPosition = nullptr;
INT x = 0, y = 0;
HashTable_Get(pProp, atomBackgroundPositon, (size_t *)&pPosition);
if (pPosition != 0)
{
x = __get_int(pPosition, 0);
y = __get_int(pPosition, 4);
if (__query(pPosition, 8, 1))
{
dwFlags = dwFlags | BIF_POSITION_X_PERCENT;
}
if (__query(pPosition, 8, 2))
{
dwFlags = dwFlags | BIF_POSITION_Y_PERCENT;
}
}
LPVOID pRepeat = nullptr;
INT dwRepeat = 0;
HashTable_Get(pProp, atomBackgroundRepeat, (size_t *)&pRepeat);
if (pRepeat != 0)
{
dwRepeat = __get_int(pRepeat, 0);
}
RECT *pGird = nullptr;
HashTable_Get(pProp, atomBackgroundGrid, (size_t *)&pGird);
RECTF rect = {dstLeft, dstTop, dstRight, dstBottom};
ret = _canvas_drawimagefrombkgimg_ex(hCanvas, hImg, x, y, dwRepeat, pGird, dwFlags, dwAlpha, pSrcRect, &rect);
}
}
}
}
}
return ret;
}
BOOL Ex_ThemeDrawControl(HEXTHEME hTheme, HEXCANVAS hCanvas, FLOAT dstLeft, FLOAT dstTop, FLOAT dstRight, FLOAT dstBottom,
EXATOM atomClass, EXATOM atomSrcRect, DWORD dwAlpha)
{
return Ex_ThemeDrawControlEx(hTheme, hCanvas, dstLeft, dstTop, dstRight, dstBottom, atomClass, atomSrcRect, ATOM_BACKGROUND_REPEAT, ATOM_BACKGROUND_POSITION, ATOM_BACKGROUND_GRID, ATOM_BACKGROUND_FLAGS, dwAlpha);
}
LPVOID Ex_ThemeGetValuePtr(HEXTHEME hTheme, EXATOM atomClass, EXATOM atomProp)
{
LPVOID pData = nullptr;
if (hTheme != 0)
{
EX_HASHTABLE *pTableClass = ((EX_THEME *)hTheme)->tableClass;
if (pTableClass != 0)
{
classtable_s *pClass = nullptr;
if (HashTable_Get(pTableClass, atomClass, (size_t *)&pClass))
{
if (pClass != 0)
{
EX_HASHTABLE *ptableProps = pClass->tableProps_;
if (ptableProps != 0)
{
HashTable_Get(ptableProps, atomProp, (size_t *)&pData);
}
}
}
}
}
return pData;
}
EXARGB Ex_ThemeGetColor(HEXTHEME hTheme, INT nIndex)
{
EXARGB ret = 0;
if (hTheme != 0)
{
if (nIndex > -1 && nIndex < 11)
{
LPVOID pColors = ((EX_THEME *)hTheme)->aryColors;
ret = __get_int(pColors, (nIndex - 1) * 4);
}
}
return ret;
}
BOOL Ex_ThemeFree(HEXTHEME hTheme)
{
BOOL ret = FALSE;
if (!IsBadReadPtr(hTheme, sizeof(EX_THEME)))
{
if (((EX_THEME *)hTheme)->crcTheme != 0 && ((EX_THEME *)hTheme)->loadCount != 0 && ((EX_THEME *)hTheme)->tableFiles != 0 && ((EX_THEME *)hTheme)->tableClass != 0)
{
auto i = InterlockedExchangeAdd((long *)&((EX_THEME *)hTheme)->loadCount, -1);
ret = TRUE;
if (i == 1)
{
for (size_t ii = 0; ii < g_Li.aryThemes.size(); ii++)
{
if (g_Li.aryThemes[ii] == hTheme)
{
g_Li.aryThemes.erase(g_Li.aryThemes.begin() + ii);
break;
}
}
HashTable_Destroy(((EX_THEME *)hTheme)->tableFiles);
HashTable_Destroy(((EX_THEME *)hTheme)->tableClass);
Ex_MemFree(((EX_THEME *)hTheme)->aryColors);
Ex_MemFree(hTheme);
}
}
}
return ret;
} | [
"313620225@qq.com"
] | 313620225@qq.com |
2984dcbf7c6687ac84a0083c906757f7da7e7bb6 | ac2c7256e7b2f65a214ed92becf208283c6a34c8 | /[BinaryTree]Check a binary tree is uniform.cpp | 5ae1c513c3d8708c74abad4c781f238fb65ef3ce | [
"MIT"
] | permissive | alchemz/mission-peace | 6681e945c81b6f2be5e144aa86986f162f8f6faf | 59a44b1e7a8fdfdf1f6743c0e6965b49e5291326 | refs/heads/master | 2020-03-15T23:07:34.260933 | 2018-06-29T15:44:39 | 2018-06-29T15:44:39 | 132,387,519 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 974 | cpp | // C++ program to find count of single valued subtrees
#include<bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node* left, *right;
};
Node* newNode(int data)
{
Node* temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return (temp);
}
bool is_uniform(Node *root){
if(root==NULL) return true;
bool is_left_uni = is_uniform(root->left);
bool is_right_uni = is_uniform(root->right);
if(is_left_uni && is_right_uni &&
((root->left==NULL) || root->left->data==root->data) &&
((root->right==NULL) || root->right->data ==root->data)){
return true;
}else{
return false;
}
}
int main()
{
Node* root = newNode(5);
root->left = newNode(5);
root->right = newNode(5);
root->left->left = newNode(5);
root->left->right = newNode(5);
root->right->right = newNode(5);
if(is_uniform(root)){
cout<<"Yes, it is uniform tree";
}else{
cout<<"No, it is not.";
}
return 0;
}
| [
"alchemxz@gmail.com"
] | alchemxz@gmail.com |
7e2b9652c7ebd0be3a99436a8bea3b03877285bd | 46fc43af262ad8e119a3d5b35c1b20bebb301b48 | /lib/log/Log.cpp | 7600e9e9132ce39747024446a650dde54ac7cf86 | [] | no_license | a-castellano/vpn_per_hours_orchestrator_VPN_SERVER_MANAGER | df2459fa43c219e3e60d1fc4b3bae2c077f0c309 | 336cb722d2c41bfb7d8fef3134fda3499797c53f | refs/heads/master | 2021-04-15T12:05:11.806775 | 2016-10-06T16:04:58 | 2016-10-06T16:04:58 | 126,217,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,658 | cpp | // Log.cpp
// Álvaro Castellano Vela
#include "Log.h"
namespace logging = boost::log;
namespace sinks = boost::log::sinks;
namespace src = boost::log::sources;
namespace expr = boost::log::expressions;
namespace attrs = boost::log::attributes;
namespace keywords = boost::log::keywords;
namespace dhlogging {
Logger::Logger(std::string fileName) { initialize(fileName); }
Logger::Logger(Logger const &) {}
Logger::~Logger() {}
Logger *Logger::logger_ = nullptr;
Logger *Logger::getInstance(std::string logFile) {
if (Logger::logger_ == nullptr) {
logging::add_file_log(
keywords::file_name = logFile, keywords::auto_flush = true,
keywords::open_mode = (std::ios::out | std::ios::app),
keywords::format = "%TimeStamp%[% Uptime % ](% LineID % ) < % Severity % >: % Message % "
);
logging::core::get()->set_filter(logging::trivial::severity >=
logging::trivial::info);
logging::add_common_attributes();
Logger::logger_ = new Logger(logFile);
}
return Logger::logger_;
}
void Logger::initialize(std::string fileName) {
//BOOST_LOG(log_) << "Hello, World!";
//BOOST_LOG_SEV(log_, info) << "Hello, World2!";
}
void Logger::logInfo(std::string message) {
BOOST_LOG_SEV(log_, info) << message;
}
void Logger::logDebug(std::string message) {
BOOST_LOG_SEV(log_, debug) << message;
}
void Logger::logWarn(std::string message) {
BOOST_LOG_SEV(log_, warning) << message;
}
void Logger::logError(std::string message) {
BOOST_LOG_SEV(log_, error) << message;
}
void Logger::logFatal(std::string message) {
BOOST_LOG_SEV(log_, fatal) << message;
}
}
| [
"alvaro.castellano.vela@gmail.com"
] | alvaro.castellano.vela@gmail.com |
3a1c9e360a777f517c7cd304edd646c0a5c0a112 | e7d7377b40fc431ef2cf8dfa259a611f6acc2c67 | /SampleDump/Cpp/SDK/BP_WorkersGloves_classes.h | 8a68064a4f70533f9ef296cfd813643d0282fe67 | [] | no_license | liner0211/uSDK_Generator | ac90211e005c5f744e4f718cd5c8118aab3f8a18 | 9ef122944349d2bad7c0abe5b183534f5b189bd7 | refs/heads/main | 2023-09-02T16:37:22.932365 | 2021-10-31T17:38:03 | 2021-10-31T17:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 736 | h | #pragma once
// Name: Mordhau, Version: Patch23
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_WorkersGloves.BP_WorkersGloves_C
// 0x0000 (FullSize[0x01A0] - InheritedSize[0x01A0])
class UBP_WorkersGloves_C : public UBP_MordhauWearable_C
{
public:
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_WorkersGloves.BP_WorkersGloves_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"talon_hq@outlook.com"
] | talon_hq@outlook.com |
a57ffeaaba44c30e18e5ca9435926e49073abe24 | 48298469e7d828ab1aa54a419701c23afeeadce1 | /Client/SceneEdit/src/ui/res/SceneInfo_wdr.cpp | 48a0639d4a0288f7bb06c98629cef67bd46239ee | [] | no_license | brock7/TianLong | c39fccb3fd2aa0ad42c9c4183d67a843ab2ce9c2 | 8142f9ccb118e76a5cd0a8b168bcf25e58e0be8b | refs/heads/master | 2021-01-10T14:19:19.850859 | 2016-02-20T13:58:55 | 2016-02-20T13:58:55 | 52,155,393 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,768 | cpp | //------------------------------------------------------------------------------
// Source code generated by wxDesigner from file: SceneInfo.wdr
// Do not modify this file, all changes will be lost!
//------------------------------------------------------------------------------
#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
#pragma implementation "SceneInfo_wdr.h"
#endif
// For compilers that support precompilation
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// Include private header
#include "SceneInfo_wdr.h"
#include <wx/intl.h>
// Euro sign hack of the year
#if wxUSE_UNICODE
#define __WDR_EURO__ wxT("\u20ac")
#else
#if defined(__WXMAC__)
#define __WDR_EURO__ wxT("\xdb")
#elif defined(__WXMSW__)
#define __WDR_EURO__ wxT("\x80")
#else
#define __WDR_EURO__ wxT("\xa4")
#endif
#endif
// Implement window functions
wxSizer *InitSceneInfo( wxWindow *parent, bool call_fit, bool set_sizer )
{
wxFlexGridSizer *item0 = new wxFlexGridSizer( 1, 0, 0 );
item0->AddGrowableCol( 0 );
item0->AddGrowableRow( 1 );
wxTreeCtrl *item1 = new wxTreeCtrl( parent, feID_USED_RESOURCE_LIST, wxDefaultPosition, wxSize(120,160), wxTR_HAS_BUTTONS|wxTR_LINES_AT_ROOT|wxSUNKEN_BORDER );
item0->Add( item1, 0, wxGROW|wxALL, 5 );
wxButton *item2 = new wxButton( parent, ID_REFLASH_BUTTON, _("Reflash"), wxDefaultPosition, wxDefaultSize, 0 );
item0->Add( item2, 0, wxALIGN_CENTER|wxALL, 5 );
if (set_sizer)
{
parent->SetSizer( item0 );
if (call_fit)
item0->SetSizeHints( parent );
}
return item0;
}
// Implement menubar functions
// Implement toolbar functions
// Implement bitmap functions
// End of generated file
| [
"xiaowave@gmail.com"
] | xiaowave@gmail.com |
9aed1b2cfa4cbb0806d1b6b72af9f61b24d570aa | 4f4ddc396fa1dfc874780895ca9b8ee4f7714222 | /src/xtp/Source/CommandBars/XTPControlComboBox.h | b44d1c99095a89537c03597b71b2911f13237207 | [] | no_license | UtsavChokshiCNU/GenSym-Test2 | 3214145186d032a6b5a7486003cef40787786ba0 | a48c806df56297019cfcb22862dd64609fdd8711 | refs/heads/master | 2021-01-23T23:14:03.559378 | 2017-09-09T14:20:09 | 2017-09-09T14:20:09 | 102,960,203 | 3 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 52,225 | h | // XTPControlComboBox.h : interface for the CXTPControlComboBox class.
//
// This file is a part of the XTREME COMMANDBARS MFC class library.
// (c)1998-2011 Codejock Software, All Rights Reserved.
//
// THIS SOURCE FILE IS THE PROPERTY OF CODEJOCK SOFTWARE AND IS NOT TO BE
// RE-DISTRIBUTED BY ANY MEANS WHATSOEVER WITHOUT THE EXPRESSED WRITTEN
// CONSENT OF CODEJOCK SOFTWARE.
//
// THIS SOURCE CODE CAN ONLY BE USED UNDER THE TERMS AND CONDITIONS OUTLINED
// IN THE XTREME TOOLKIT PRO LICENSE AGREEMENT. CODEJOCK SOFTWARE GRANTS TO
// YOU (ONE SOFTWARE DEVELOPER) THE LIMITED RIGHT TO USE THIS SOFTWARE ON A
// SINGLE COMPUTER.
//
// CONTACT INFORMATION:
// support@codejock.com
// http://www.codejock.com
//
/////////////////////////////////////////////////////////////////////////////
//{{AFX_CODEJOCK_PRIVATE
#if !defined(__XTPCONTOLCOMBOBOX_H__)
#define __XTPCONTOLCOMBOBOX_H__
//}}AFX_CODEJOCK_PRIVATE
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
class CXTPControlComboBox;
class CXTPControlComboBoxAutoCompleteWnd;
//{{AFX_CODEJOCK_PRIVATE
// CXTPControlComboBoxAutoCompleteWnd implementation.
// used internally in CXTPControlComboBox and CXTPControlEdit controls
class _XTP_EXT_CLASS CXTPControlComboBoxAutoCompleteWnd : public CXTPHookManagerHookAble
{
public:
CXTPControlComboBoxAutoCompleteWnd();
~CXTPControlComboBoxAutoCompleteWnd();
public:
HRESULT ShellAutoComplete(HWND hEdit, DWORD dwFlags);
void CloseWindow();
void SetupMessageHook(BOOL bSetup);
BOOL IsDialogCode(UINT nChar, LPARAM lParam);
private:
static CXTPControlComboBoxAutoCompleteWnd* m_pWndMonitor;
static LRESULT CALLBACK CallWndProc(int code, WPARAM wParam, LPARAM lParam);
virtual int OnHookMessage(HWND hWnd, UINT nMessage, WPARAM& wParam, LPARAM& lParam, LRESULT& lResult);
void SetAutoCompeteHandle(HWND);
public:
HWND m_hWndAutoComplete;
private:
static HHOOK m_hHookMessage;
HWND m_hWndEdit;
};
//}}AFX_CODEJOCK_PRIVATE
///===========================================================================
// Summary:
// CXTPControlComboBoxPopupBar is a CXTPPopupBar derived class.
// It represents base class for combo popups.
//===========================================================================
class _XTP_EXT_CLASS CXTPControlComboBoxPopupBar : public CXTPPopupBar
{
DECLARE_XTP_COMMANDBAR(CXTPControlComboBoxPopupBar)
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPControlComboBoxPopupBar object
//-----------------------------------------------------------------------
CXTPControlComboBoxPopupBar();
public:
//{{AFX_CODEJOCK_PRIVATE
//{{AFX_VIRUAL(CXTPControlComboBoxPopupBar)
virtual int GetCurSel() const {
return LB_ERR;
}
virtual int FindString(int /*nStartAfter*/, LPCTSTR /*lpszItem*/) const{
return LB_ERR;
}
virtual int FindStringExact(int /*nIndexStart*/, LPCTSTR /*lpsz*/) const {
return LB_ERR;
}
virtual int SetTopIndex(int /*nIndex*/) {
return LB_ERR;
}
virtual void SetCurSel(int /*nIndex*/) {
}
virtual void GetText(int /*nIndex*/, CString& /*rString*/) const {
}
virtual BOOL ProcessHookKeyDown(CXTPControlComboBox* pComboBox, UINT nChar, LPARAM lParam);
BOOL OnHookKeyDown(UINT nChar, LPARAM lParam);
//}}AFX_VIRUAL
//}}AFX_CODEJOCK_PRIVATE
};
//===========================================================================
// Summary:
// CXTPControlComboBoxList is a CXTPControlComboBoxPopupBar derived class.
// It represents a list box of CXTPControlComboBox control.
//===========================================================================
class _XTP_EXT_CLASS CXTPControlComboBoxList : public CXTPControlComboBoxPopupBar
{
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPControlButton object
//-----------------------------------------------------------------------
CXTPControlComboBoxList();
public:
//-----------------------------------------------------------------------
// Summary:
// Creates list box.
//-----------------------------------------------------------------------
virtual void CreateListBox();
//-----------------------------------------------------------------------
// Summary:
// Retrieves list box window.
//-----------------------------------------------------------------------
CListBox* GetListBoxCtrl() const;
protected:
//-----------------------------------------------------------------------
// Summary:
// This member function is called by WindowProc, or is called during
// message reflection.
// Parameters:
// hWnd - Window handle that the message belongs to.
// nMessage - Specifies the message to be sent.
// wParam - Specifies additional message-dependent information.
// lParam - Specifies additional message-dependent information.
// lResult - The return value of WindowProc. Depends on the message;
// may be NULL.
//-----------------------------------------------------------------------
int OnHookMessage(HWND hWnd, UINT nMessage, WPARAM& wParam, LPARAM& lParam, LRESULT& lResult);
//-----------------------------------------------------------------------
// Summary:
// This method is called, then PopupBar becomes visible.
// Parameters:
// pControlPopup - Points to a CXTPControlPopup object
// bSelectFirst - TRUE to select the first item.
// Returns:
// TRUE if successful; otherwise returns FALSE.
//-----------------------------------------------------------------------
virtual BOOL Popup(CXTPControlPopup* pControlPopup, BOOL bSelectFirst = FALSE);
//-----------------------------------------------------------------------
// Summary:
// Call this member to change the tracking state.
// Parameters:
// bMode - TRUE to set the tracking mode; otherwise FALSE.
// bSelectFirst - TRUE to select the first item.
// bKeyboard - TRUE if the item is popuped by the keyboard.
// See Also: IsTrackingMode.
// Returns:
// TRUE if the method was successful.
//-----------------------------------------------------------------------
virtual BOOL SetTrackingMode(int bMode, BOOL bSelectFirst, BOOL bKeyboard = FALSE);
//-----------------------------------------------------------------------
// Summary:
// This method is called to draw the command bar in the given context.
// Parameters:
// pDC - Pointer to a valid device context.
// rcClipBox - The rectangular area of the control that is invalid
//-----------------------------------------------------------------------
virtual void DrawCommandBar(CDC* pDC, CRect rcClipBox);
//-----------------------------------------------------------------------
// Summary:
// The framework calls this member function when a non-system key
// is pressed.
// Parameters:
// nChar - Specifies the virtual key code of the given key.
// lParam - Specifies additional message-dependent information.
// Returns:
// TRUE if key handled, otherwise returns FALSE
//-----------------------------------------------------------------------
virtual BOOL OnHookKeyDown(UINT nChar, LPARAM lParam);
//-----------------------------------------------------------------------
// Summary:
// Call this member to retrieve the customize mode of the command
// bars.
// Returns:
// TRUE if command bars are in customized mode; otherwise returns
// FALSE.
//-----------------------------------------------------------------------
virtual BOOL IsCustomizable() const { return FALSE; }
//-----------------------------------------------------------------------
// Summary:
// Reads or writes this object from or to an archive.
// Parameters:
// pPX - A CXTPPropExchange object to serialize to or from.
//----------------------------------------------------------------------
virtual void DoPropExchange(CXTPPropExchange* pPX);
//-----------------------------------------------------------------------
// Summary:
// This method makes a copy of the command bar.
// Parameters:
// pCommandBar - Command bar needed to be copied.
// bRecursive - TRUE to copy recursively.
//-----------------------------------------------------------------------
virtual void Copy(CXTPCommandBar* pCommandBar, BOOL bRecursive = FALSE);
protected:
//{{AFX_CODEJOCK_PRIVATE
//{{AFX_VIRUAL(CXTPControlComboBoxList)
virtual int GetCurSel() const {
return GetListBoxCtrl()->GetCurSel();
}
virtual int FindString(int nStartAfter, LPCTSTR lpszItem) const {
return GetListBoxCtrl()->FindString(nStartAfter, lpszItem);
}
virtual int FindStringExact(int nIndexStart, LPCTSTR lpsz) const {
return GetListBoxCtrl()->FindStringExact(nIndexStart, lpsz);
}
virtual int SetTopIndex(int nIndex) {
return GetListBoxCtrl()->SetTopIndex(nIndex);
}
virtual void SetCurSel(int nIndex) {
GetListBoxCtrl()->SetCurSel(nIndex);
}
virtual void GetText(int nIndex, CString& rString) const {
GetListBoxCtrl()->GetText(nIndex, rString);
}
//}}AFX_VIRUAL
//}}AFX_CODEJOCK_PRIVATE
protected:
//{{AFX_CODEJOCK_PRIVATE
DECLARE_MESSAGE_MAP()
//{{AFX_MSG(CXTPControlComboBoxList)
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnNcPaint();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
//}}AFX_MSG
//}}AFX_CODEJOCK_PRIVATE
//-----------------------------------------------------------------------
// Summary:
// This method is called to process key down event
// Parameters:
// pComboBox - Owner combo box pointer
// nChar - Specifies the virtual key code of the given key.
// lParam - keystroke-message information
// Returns:
// TRUE if message was processed.
//-----------------------------------------------------------------------
BOOL ProcessHookKeyDown(CXTPControlComboBox* pComboBox, UINT nChar, LPARAM lParam);
//-----------------------------------------------------------------------
// Input: lpDrawItemStruct - A long pointer to a DRAWITEMSTRUCT
// structure. The structure contains information about the item
// to be drawn and the type of drawing required.
// Summary: This member function is called to draw the combobox.
//-----------------------------------------------------------------------
virtual void DrawItem (LPDRAWITEMSTRUCT lpDrawItemStruct);
//-----------------------------------------------------------------------
// Input: lpMeasureItemStruct - Override this method and fill in the
// MEASUREITEMSTRUCT structure to inform
// Windows of the list-box dimensions.
// Summary: Specifies a long pointer to a MEASUREITEMSTRUCT structure.
//-----------------------------------------------------------------------
virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
private:
static void CALLBACK KeepaliveTimerProc(HWND hWnd, UINT /*uMsg*/, UINT idEvent, DWORD /*dwTime*/);
unsigned int m_keepaliveId;
DECLARE_XTP_COMMANDBAR(CXTPControlComboBoxList)
friend class CXTPControlComboBox;
int m_nListIconId; // Icon identifier
};
//////////////////////////////////////////////////////////////////////////
//===========================================================================
// Summary:
// Inplace Edit control of the combo.
//===========================================================================
class _XTP_EXT_CLASS CXTPControlComboBoxEditCtrl : public CXTPCommandBarEditCtrl
{
public:
//-----------------------------------------------------------------------
// Summary:
// Retrieves parent CXTPControlComboBox object.
// Returns:
// Pointer to parent CXTPControlComboBox.
//-----------------------------------------------------------------------
CXTPControlComboBox* GetControlComboBox() const;
protected:
//-------------------------------------------------------------------------
// Summary:
// This method is called to refresh char format of edit control
//-------------------------------------------------------------------------
void UpdateCharFormat();
//{{AFX_CODEJOCK_PRIVATE
DECLARE_MESSAGE_MAP()
BOOL OnWndMsg(UINT message, WPARAM wParam, LPARAM lParam, LRESULT* pResult);
//{{AFX_MSG(CXTPControlComboBoxEditCtrl)
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnKillFocus(CWnd* pNewWnd);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnDestroy();
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnRButtonDown(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
afx_msg void OnEditChanged();
afx_msg LRESULT OnWindowFromPoint(WPARAM, LPARAM);
afx_msg void OnShellAutoCompleteStart();
afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags);
//}}AFX_MSG
//}}AFX_CODEJOCK_PRIVATE
protected:
CXTPControlComboBox* m_pControl; // Parent Combo Box.
private:
friend class CXTPControlComboBox;
};
//-----------------------------------------------------------------------
// Summary:
// CXTPControlComboBox is a CXTPControl derived class. It represents a combo box control.
//-----------------------------------------------------------------------
class _XTP_EXT_CLASS CXTPControlComboBox : public CXTPControlPopup
{
public:
//-----------------------------------------------------------------------
// Summary:
// Constructs a CXTPControlComboBox object
// Parameters:
// pCommandBars - Pointer to parent CommandBars class.
//-----------------------------------------------------------------------
CXTPControlComboBox(CXTPCommandBars* pCommandBars = NULL);
//-----------------------------------------------------------------------
// Summary:
// Destroys a CXTPControlComboBox object, handles cleanup and deallocation
//-----------------------------------------------------------------------
virtual ~CXTPControlComboBox();
public:
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the style of edit control.
// Returns:
// The style of the edit control.
// See Also: SetEditStyle
//-----------------------------------------------------------------------
DWORD GetEditStyle() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the style of edit control
// Parameters:
// dwStyle - The style to be set
// See Also: GetEditStyle
//-----------------------------------------------------------------------
void SetEditStyle(DWORD dwStyle);
//-----------------------------------------------------------------------
// Summary:
// Call this member to insert\delete an edit box in the combo box
// when the control has focus.
// Parameters:
// bSet - TRUE if the combo box has an edit control.
// Remarks:
// If bSet is TRUE, when the combo box control is click an edit
// control is used to display the text and the user can edit or
// copy the text.
// See Also: GetDropDownListStyle
//-----------------------------------------------------------------------
void SetDropDownListStyle(BOOL bSet = TRUE);
//-----------------------------------------------------------------------
// Summary:
// Call this member to determine if the combo box has an edit control.
// Returns:
// TRUE is the combo box has an edit control, FALSE otherwise.
// See Also: SetDropDownListStyle
//-----------------------------------------------------------------------
BOOL GetDropDownListStyle() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the width of the dropdown list.
// Parameters:
// nWidth - The width of the dropdown list.
//-----------------------------------------------------------------------
void SetDropDownWidth(int nWidth);
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the count of items in the dropdown list.
// Parameters:
// nDropDownItemCount - The count of items in the dropdown list.
//-----------------------------------------------------------------------
void SetDropDownItemCount(int nDropDownItemCount);
//-----------------------------------------------------------------------
// Summary:
// Call this member to retrieve the dropdown list width.
// Returns:
// Width of the dropdown list.
//-----------------------------------------------------------------------
int GetDropDownWidth() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member function to add a string to a list box.
// Parameters:
// lpsz - The string that is to be added.
// Returns:
// The zero-based index of the string in the list box. The return value is LB_ERR
// if an error occurs.
//-----------------------------------------------------------------------
int AddString(LPCTSTR lpsz);
//-----------------------------------------------------------------------
// Summary: added in Gensym-267
// Call this member function to delete a string to a list box.
// Parameters:
// lpsz - The string that is to be deleted.
// Returns:
// A count of the strings remaining in the list. The return value is LB_ERR if the
// string is not found in the list box.
//-----------------------------------------------------------------------
int DeleteString(LPCTSTR lpsz);
//-----------------------------------------------------------------------
// Summary:
// Call this member to retrieve the number of items in a list box.
// Returns:
// The number of items in the list box, or LB_ERR if an error occurs.
//-----------------------------------------------------------------------
int GetCount() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to retrieve a string from the list box of a combo box control.
// Parameters:
// nIndex - Contains the zero-based index of the list-box string to be copied.
// str - A reference to a CString.
//-----------------------------------------------------------------------
void GetLBText(int nIndex, CString& str) const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to removes all items from the list box of a combo box control.
//-----------------------------------------------------------------------
void ResetContent();
//-----------------------------------------------------------------------
// Summary:
// Call the FindStringExact member function to find the first list-box string
// (in a combo box) that matches the string specified in str.
// Parameters:
// nIndexStart - Specifies the zero-based index of the item before the first item
// to be searched.
// lpsz - The string to search for.
// Returns:
// The zero-based index of the matching item, or CB_ERR if the search was
// unsuccessful.
// See Also: FindString
//-----------------------------------------------------------------------
int FindStringExact(int nIndexStart, LPCTSTR lpsz) const;
//-----------------------------------------------------------------------
// Summary:
// Call this member function to insert a string into the list box of a combo box control
// Parameters:
// nIndex - Contains the zero-based index to the position in the list box that will receive
// the string.
// lpsz - The string that is to be inserted.
//-----------------------------------------------------------------------
int InsertString(int nIndex, LPCTSTR lpsz);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the currently selected item's text
// Returns:
// The text that is currently selected.
//-----------------------------------------------------------------------
virtual CString GetListBoxText() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the edit control of the combo box control.
// Returns:
// A pointer to the CEdit control.
//-----------------------------------------------------------------------
CXTPControlComboBoxEditCtrl* GetEditCtrl() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to select a string in the list box of a combo box.
// Parameters:
// nIndex - Specifies the zero-based index of the string to select.
//-----------------------------------------------------------------------
void SetCurSel(int nIndex);
//-----------------------------------------------------------------------
// Summary:
// Call this member function to determine which item in the combo box is selected.
// Returns:
// The zero-based index of the currently selected item in the list box of a combo box,
// or CB_ERR if no item is selected.
//-----------------------------------------------------------------------
int GetCurSel() const;
//-----------------------------------------------------------------------
// Summary:
// Call the GetDroppedState member function to determine whether the list box of a drop-down
// combo box is visible (dropped down).
// Returns:
// Nonzero if the list box is visible; otherwise 0.
//-----------------------------------------------------------------------
BOOL GetDroppedState() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the edit text.
// Returns:
// The Edit control text.
//-----------------------------------------------------------------------
CString GetEditText() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to modify style of list box
// Parameters:
// dwRemove - Styles to remove.
// dwAdd - Styles to add.
//-----------------------------------------------------------------------
void ModifyListBoxStyle(DWORD dwRemove, DWORD dwAdd);
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the edit control text.
// Parameters:
// lpszText - New text of the edit control.
// See Also:
// FindStringExact, FindString
//-----------------------------------------------------------------------
void SetEditText(const CString& lpszText);
//-----------------------------------------------------------------------
// Summary:
// Call this member to set grayed-out text displayed in the edit control
// that displayed a helpful description of what the control is used for.
// Parameters:
// lpszEditHint - Edit hint to be set
// Example:
// <code>pCombo->SetEditHint(_T("Click to find a contact");</code>
// See Also: GetEditHint
//-----------------------------------------------------------------------
void SetEditHint(LPCTSTR lpszEditHint);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get grayed-out text displayed in the edit control
// that displayed a helpful description of what the control is used for.
// Returns:
// Edit hint of the control
// See Also: SetEditHint
//-----------------------------------------------------------------------
CString GetEditHint() const;
//-----------------------------------------------------------------------
// Summary:
// This method is called to get default char format of rich edit text
//-----------------------------------------------------------------------
virtual CHARFORMAT2 GetDefaultCharFormat();
//-----------------------------------------------------------------------
// Summary:
// This member function enables or disables shell auto completion.
// Parameters:
// dwFlags - Flags that will be passed to SHAutoComplete function.
// Remarks:
// Flags can be combined by using the bitwise
// OR (|) operator. It can be one or more of the following:
// * <b>SHACF_FILESYSTEM</b> This includes the File System as well as the rest of the shell (Desktop\My Computer\Control Panel\)
// * <b>SHACF_URLALL</b> Include the URL's in the users History and Recently Used lists. Equivalent to SHACF_URLHISTORY | SHACF_URLMRU.
// * <b>HACF_URLHISTORY</b> URLs in the User's History
// * <b>SHACF_URLMRU</b> URLs in the User's Recently Used list.
// * <b>SHACF_FILESYS_ONLY</b> Include only the file system. Do not include virtual folders such as Desktop or Control Panel.
// ---------------------------------------------------------------------------
void EnableShellAutoComplete(DWORD dwFlags = SHACF_FILESYSTEM | SHACF_URLALL);
//-----------------------------------------------------------------------
// Summary:
// This member function enables or disables auto completion.
// Parameters:
// bAutoComplete - TRUE to enable auto completion, otherwise FALSE.
//-----------------------------------------------------------------------
void EnableAutoComplete(BOOL bAutoComplete = TRUE);
//-----------------------------------------------------------------------
// Summary:
// This method finds the first string in a list box that contains the specified prefix,
// without changing the list-box selection
// Parameters:
// nStartAfter - Contains the zero-based index of the item before the first item to be
// searched. When the search reaches the bottom of the list box, it continues from the
// top of the list box back to the item specified by nStartAfter. If nStartAfter is -1,
// the entire list box is searched from the beginning.
// lpszItem - Points to the null-terminated string that contains the prefix to search for.
// The search is case independent, so this string may contain any combination of uppercase
// and lowercase letters.
// Returns:
// The zero-based index of the matching item, or LB_ERR if the search was unsuccessful.
// See Also: FindStringExact
//-----------------------------------------------------------------------
int FindString(int nStartAfter, LPCTSTR lpszItem) const;
//-----------------------------------------------------------------------
// Summary:
// This method retrieves the application-supplied 32-bit value associated with the
// specified combo box item.
// Parameters:
// nIndex - Contains the zero-based index of an item in the combo box's list box.
// Returns:
// The 32-bit value associated with the item, or CB_ERR if an error occurs.
//-----------------------------------------------------------------------
DWORD_PTR GetItemData(int nIndex) const;
//-----------------------------------------------------------------------
// Summary:
// This method sets the 32-bit value associated with the specified item in a combo box.
// Parameters:
// nIndex - Contains a zero-based index of the item to set.
// dwItemData - Contains the new value to associate with the item.
// Returns:
// CB_ERR if an error occurs.
//-----------------------------------------------------------------------
int SetItemData(int nIndex, DWORD_PTR dwItemData);
//-----------------------------------------------------------------------
// Summary:
// Call this member function to delete a string.
// Parameters:
// nIndex - Contains a zero-based index of the item to delete.
//-----------------------------------------------------------------------
void DeleteItem(long nIndex);
//-----------------------------------------------------------------------
// Summary:
// This method is called when control enable state was changed
//-----------------------------------------------------------------------
void OnEnabledChanged();
//-----------------------------------------------------------------------
// Summary:
// Reads or writes this object from or to an archive.
// Parameters:
// pPX - A CXTPPropExchange object to serialize to or from.
//----------------------------------------------------------------------
void DoPropExchange(CXTPPropExchange* pPX);
//-----------------------------------------------------------------------
// Summary:
// Call this member to compare controls.
// Parameters:
// pOther - The control need compare with.
// Returns:
// TRUE if the controls are identical.
//-----------------------------------------------------------------------
virtual BOOL Compare(CXTPControl* pOther);
//-----------------------------------------------------------------------
// Summary:
// Call this method to get with of label.
// Returns:
// Width of label of edit control.
// See Also: SetLabelWidth, SetStyle, GetStyle
//-----------------------------------------------------------------------
int GetLabelWidth() const;
//-----------------------------------------------------------------------
// Summary:
// This method is called to set width of the label.
// Parameters:
// nLabelWidth - Width of label to be set
// See Also: GetLabelWidth, SetStyle, GetStyle
//-----------------------------------------------------------------------
void SetLabelWidth(int nLabelWidth);
//-----------------------------------------------------------------------
// Summary:
// Call this member to determine if the caption of the control is visible
// Returns:
// TRUE if the caption is visible.
//-----------------------------------------------------------------------
virtual BOOL IsCaptionVisible() const;
//-----------------------------------------------------------------------
// Summary:
// Determines if icon is visible for combo box control
// Returns:
// TRUE if control has icon
//-----------------------------------------------------------------------
BOOL IsImageVisible() const;
//-----------------------------------------------------------------------
// Summary:
// Call this method to get with of thumb button.
// Returns:
// Width of thumb button of combo box.
// See Also: SetThumbWidth
//-----------------------------------------------------------------------
int GetThumbWidth() const;
//-----------------------------------------------------------------------
// Summary:
// This method is called to set width of thumb button.
// Parameters:
// nThumbWidth - Width of the thumb button to be set.
// See Also: GetThumbWidth
//-----------------------------------------------------------------------
void SetThumbWidth(int nThumbWidth);
//-----------------------------------------------------------------------
// Summary:
// Call this method to determine if control has focus
//-----------------------------------------------------------------------
BOOL HasFocus() const;
//----------------------------------------------------------------------
// Summary:
// This method draw text of control if style is CBS_DROPDOWNLIST
// Parameters:
// pDC - Pointer to a valid device context
// rcText - Rectangle to draw.
//----------------------------------------------------------------------
virtual void DrawEditText(CDC* pDC, CRect rcText);
//-----------------------------------------------------------------------
// Summary:
// Retrieves list box window.
//-----------------------------------------------------------------------
CListBox* GetListBoxCtrl() const;
//-----------------------------------------------------------------------
// Summary:
// Returns child popup bar
//-----------------------------------------------------------------------
CXTPControlComboBoxPopupBar* GetComboBoxPopupBar() const;
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the edit icon's identifier.
// Parameters:
// nId - Icon's identifier to be set.
//-----------------------------------------------------------------------
void SetEditIconId(int nId);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the edit icon's identifier.
//-----------------------------------------------------------------------
int GetEditIconId() const;
// Parameters:
// nId - Icon's identifier to be set.
//-----------------------------------------------------------------------
void SetListIconId(int nId);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the combo list icon's identifier.
//-----------------------------------------------------------------------
int GetListIconId() const;
//{{AFX_CODEJOCK_PRIVATE
// deprecated
virtual CString GetText() const
{
return GetListBoxText();
}
//}}AFX_CODEJOCK_PRIVATE
//-----------------------------------------------------------------------
// Summary:
// Call this member to set focus to the control.
// Parameters:
// bFocused - TRUE to set focus
//-----------------------------------------------------------------------
virtual void SetFocused(BOOL bFocused);
//-----------------------------------------------------------------------
// Summary:
// Call this member to get the focused state of the control.
// Returns:
// TRUE if the control has focus; otherwise FALSE.
//-----------------------------------------------------------------------
virtual BOOL IsFocused() const;
//-----------------------------------------------------------------------
// Summary:
// This method is called then edit control text was changed
//-----------------------------------------------------------------------
virtual void OnEditChanged();
//-----------------------------------------------------------------------
// Summary:
// This method is called, then the selected string is changed.
//-----------------------------------------------------------------------
virtual void OnSelChanged();
//-----------------------------------------------------------------------
// Summary:
// This method is called when the control is executed.
//-----------------------------------------------------------------------
virtual void OnExecute();
//-----------------------------------------------------------------------
// Summary:
// This method is called to hide the control.
// Parameters:
// dwFlags - Reasons to hide.
// See Also: XTPControlHideFlags
//-----------------------------------------------------------------------
virtual void SetHideFlags(DWORD dwFlags);
//-----------------------------------------------------------------------
// Summary:
// This method is called when action property was changed
// Parameters:
// nProperty - Property of the action
// See Also: OnActionChanging
//-----------------------------------------------------------------------
virtual void OnActionChanged(int nProperty);
//-----------------------------------------------------------------------
// Summary:
// This method is called when action property is about to be changed
// Parameters:
// nProperty - Property of the action
// See Also: OnActionChanged
//-----------------------------------------------------------------------
virtual void OnActionChanging(int nProperty);
//-----------------------------------------------------------------------
// Summary:
// This method limits the length of the text that the user may enter into an edit control.
// Parameters:
// nTextLimit - Maximum length user can enter
// See Also: GetTextLimit
//-----------------------------------------------------------------------
void SetTextLimit(int nTextLimit);
//-----------------------------------------------------------------------
// Summary:
// Returns Maximum length user can enter.
// Returns:
// Maximum text user can enter.
// See Also: SetTextLimit
//-----------------------------------------------------------------------
int GetTextLimit() const;
protected:
//----------------------------------------------------------------------
// Summary:
// This method is called to check if control accept focus
// See Also: SetFocused
//----------------------------------------------------------------------
virtual BOOL IsFocusable() const;
//-----------------------------------------------------------------------
// Summary:
// This method create edit control. Override it to use inherited edit control.
//-----------------------------------------------------------------------
virtual CXTPControlComboBoxEditCtrl* CreateEditControl();
//-----------------------------------------------------------------------
// Summary:
// Called after the mouse hovers over the control.
//-----------------------------------------------------------------------
void OnMouseHover();
//-----------------------------------------------------------------------
// Summary:
// This method is called, then edit control gets the focus.
// Parameters:
// pOldWnd - Points to a CWnd object
//-----------------------------------------------------------------------
virtual void OnSetFocus(CWnd* pOldWnd);
//-----------------------------------------------------------------------
// Summary:
// This method is called, then the edit control loses the focus.
//-----------------------------------------------------------------------
virtual void OnKillFocus();
//-----------------------------------------------------------------------
// Summary:
// This method is called to get real rect of edit control of Combo Box
// Parameters:
// rcControl - Rectangle of Combo Box area.
//-----------------------------------------------------------------------
virtual void DeflateEditRect(CRect& rcControl);
//-----------------------------------------------------------------------
// Summary:
// This method is called when the control becomes selected.
// Parameters:
// bSelected - TRUE if the control becomes selected.
// Returns:
// TRUE if successful; otherwise returns FALSE
//-----------------------------------------------------------------------
BOOL OnSetSelected(int bSelected);
//-----------------------------------------------------------------------
// Summary:
// Call this member to set the bounding rectangle of the control.
// Parameters:
// rcControl - Bounding rectangle of the control.
//-----------------------------------------------------------------------
void SetRect(CRect rcControl);
//-----------------------------------------------------------------------
// Summary:
// This method is called when the user clicks the control.
// Parameters:
// bKeyboard - TRUE if the control is selected using the keyboard.
// pt - Mouse cursor position.
//-----------------------------------------------------------------------
void OnClick(BOOL bKeyboard = FALSE, CPoint pt = CPoint(0, 0));
//----------------------------------------------------------------------
// Summary:
// This method is called when the user activate control using its underline.
//----------------------------------------------------------------------
virtual void OnUnderlineActivate();
//-----------------------------------------------------------------------
// Summary:
// This method is called to copy the control.
// Parameters:
// pControl - Points to a source CXTPControl object
// bRecursive - TRUE to copy recursively.
//-----------------------------------------------------------------------
void Copy(CXTPControl* pControl, BOOL bRecursive = FALSE);
//-----------------------------------------------------------------------
// Summary:
// This method is called when a non-system key is pressed.
// Parameters:
// nChar - Specifies the virtual key code of the given key.
// lParam - Specifies additional message-dependent information.
// Returns:
// TRUE if key handled, otherwise returns FALSE
//-----------------------------------------------------------------------
BOOL OnHookKeyDown(UINT nChar, LPARAM lParam);
//-----------------------------------------------------------------------
// Summary:
// This method is called to assign a parent command bar object.
// Parameters:
// pParent - Points to a CXTPCommandBar object
//-----------------------------------------------------------------------
void SetParent(CXTPCommandBar* pParent);
//-----------------------------------------------------------------------
// Summary:
// This method is called before recalculating the parent command
// bar size to calculate the dimensions of the control.
// Parameters:
// dwMode - Flags used to determine the height and width of the
// dynamic command bar. See Remarks section for a list of
// values.
// Remarks:
// The following predefined flags are used to determine the height and
// width of the dynamic command bar. Use the bitwise-OR (|) operator to
// combine the flags.<p/>
//
// * <b>LM_STRETCH</b> Indicates whether the command bar should be
// stretched to the size of the frame. Set if the bar is
// not a docking bar (not available for docking). Not set
// when the bar is docked or floating (available for
// docking). If set, LM_STRETCH returns dimensions based
// on the LM_HORZ state. LM_STRETCH works similarly to
// the the bStretch parameter used in CalcFixedLayout;
// see that member function for more information about
// the relationship between stretching and orientation.
// * <b>LM_HORZ</b> Indicates that the bar is horizontally or
// vertically oriented. Set if the bar is horizontally
// oriented, and if it is vertically oriented, it is not
// set. LM_HORZ works similarly to the the bHorz
// parameter used in CalcFixedLayout; see that member
// function for more information about the relationship
// between stretching and orientation.
// * <b>LM_MRUWIDTH</b> Most Recently Used Dynamic Width. Uses the
// remembered most recently used width.
// * <b>LM_HORZDOCK</b> Horizontal Docked Dimensions. Returns the
// dynamic size with the largest width.
// * <b>LM_VERTDOCK</b> Vertical Docked Dimensions. Returns the dynamic
// size with the largest height.
// * <b>LM_COMMIT</b> Resets LM_MRUWIDTH to current width of
// floating command bar.
//
// The framework calls this member function to calculate the dimensions
// of a dynamic command bar.<p/>
//
// Override this member function to provide your own layout in classes
// you derive from CXTPControl. XTP classes derived from CXTPControl,
// such as CXTPControlComboBox, override this member function to provide
// their own implementation.
// See Also:
// CXTPControl, CXTPControlCustom, CXTPControlEdit,
// CXTPControlWindowList, CXTPControlWorkspaceActions, CXTPControlToolbars,
// CXTPControlOleItems, CXTPControlRecentFileList, CXTPControlSelector,
// CXTPControlListBox
//-----------------------------------------------------------------------
virtual void OnCalcDynamicSize(DWORD dwMode);
//-----------------------------------------------------------------------
// Summary:
// This method is called to popup the control.
// Parameters:
// bPopup - TRUE to set popup.
// Returns:
// TRUE if successful; otherwise returns FALSE
//-----------------------------------------------------------------------
virtual BOOL OnSetPopup(BOOL bPopup);
//-----------------------------------------------------------------------
// Summary:
// This member checks if the user can resize control.
// Returns:
// TRUE if resize available.
//-----------------------------------------------------------------------
virtual BOOL IsCustomizeResizeAllow() const;
//-----------------------------------------------------------------------
// Summary:
// This member returns the minimum width that the combo box
// can be sized by the user while in customization mode.
// Returns:
// Width of label + Width of Dropdown button + 5
//-----------------------------------------------------------------------
virtual int GetCustomizeMinWidth() const;
//-------------------------------------------------------------------------
// Summary:
// This method is called when control was removed from parent controls collection
//-------------------------------------------------------------------------
virtual void OnRemoved();
//----------------------------------------------------------------------
// Summary:
// This member is called when the mouse cursor moves.
// Parameters:
// point - Specifies the x- and y coordinate of the cursor.
//----------------------------------------------------------------------
virtual void OnMouseMove(CPoint point);
//{{AFX_CODEJOCK_PRIVATE
protected:
public:
void UpdatePopupSelection();
protected:
BOOL IsValidList() const;
void _SetEditText(const CString& lpszText);
CString _GetEditText() const;
virtual BOOL OnHookMouseWheel(UINT nFlags, short zDelta, CPoint pt);
virtual void OnThemeChanged();
void ShowHideEditControl();
virtual void DrawItem (LPDRAWITEMSTRUCT lpDrawItemStruct);
virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct);
//}}AFX_CODEJOCK_PRIVATE
DECLARE_XTP_CONTROL(CXTPControlComboBox)
protected:
CXTPControlComboBoxEditCtrl* m_pEdit; // Child edit control.
BOOL m_bDropDown; // TRUE if the combo is dropdown.
XTPButtonStyle m_comboStyle; // Style of the combo box.
int m_nLastSel; // Last user selected index, (used during display of list box)
CString m_strLastText; // Last Text before user select focus and change it.
BOOL m_bDelayDestroy; // TRUE if need to recreate control.
BOOL m_bDelayReposition; // Need to reposition control.
int m_nLabelWidth; // Width of the label.
int m_nThumbWidth; // Width of the thumb area.
CString m_strEditHint; // Grayed-out text displayed in the edit control that displayed a helpful description
BOOL m_bAutoComplete; // TRUE if Auto Complete enabled
BOOL m_bIgnoreAutoComplete; // TRUE to disable auto complete till next key event.
DWORD m_dwShellAutoCompleteFlags; // Shell auto complete flags.
BOOL m_bFocused; // TRUE if control is focused
int m_nEditIconId; // Edit Icon identifier
BOOL m_bSelEndOk; // TRUE if user selects a list item.
int m_nDropDownItemCount; // Maximum drop down items
mutable CString m_strEditText; // Edit text.
mutable BOOL m_bEditChanged; // TRUE if Edit Text was changed.
int m_nTextLimit; // The maximum number of characters that can be entered into the combo
CXTPControlComboBoxAutoCompleteWnd* m_pAutoCompleteWnd; // Auto Complete hook window.
DWORD m_dwEditStyle; // Edit style
private:
int m_nCurSel;
BOOL m_bIgnoreSelection;
friend class CXTPControlComboBoxList;
friend class CXTPControlComboBoxEditCtrl;
};
//////////////////////////////////////////////////////////////////////////
AFX_INLINE CListBox* CXTPControlComboBox::GetListBoxCtrl() const {
return ((CListBox*)m_pCommandBar);
}
AFX_INLINE void CXTPControlComboBox::SetDropDownWidth(int nWidth) {
m_pCommandBar->SetWidth(nWidth);
}
AFX_INLINE int CXTPControlComboBox::AddString(LPCTSTR lpsz) {
return GetListBoxCtrl()->AddString(lpsz);
}
AFX_INLINE int CXTPControlComboBox::DeleteString(LPCTSTR lpsz) {
int npos = GetListBoxCtrl()->FindString(-1,lpsz);
if(LB_ERR != npos){
return GetListBoxCtrl()->DeleteString(npos);
}
return LB_ERR;
}
AFX_INLINE int CXTPControlComboBox::GetCount() const{
return GetListBoxCtrl()->GetCount();
}
AFX_INLINE void CXTPControlComboBox::GetLBText(int nIndex, CString& str) const{
GetComboBoxPopupBar()->GetText(nIndex, str);
}
AFX_INLINE void CXTPControlComboBox::ResetContent() {
GetListBoxCtrl()->ResetContent();
}
AFX_INLINE int CXTPControlComboBox::FindStringExact(int nIndexStart, LPCTSTR lpsz) const {
return GetComboBoxPopupBar()->FindStringExact(nIndexStart, lpsz);
}
AFX_INLINE int CXTPControlComboBox::InsertString(int nIndex, LPCTSTR lpsz) {
return GetListBoxCtrl()->InsertString(nIndex, lpsz);
}
AFX_INLINE CXTPControlComboBoxEditCtrl* CXTPControlComboBox::GetEditCtrl() const {
return m_pEdit;
}
AFX_INLINE int CXTPControlComboBox::FindString(int nStartAfter, LPCTSTR lpszItem) const {
return GetComboBoxPopupBar()->FindString(nStartAfter, lpszItem);
}
AFX_INLINE DWORD_PTR CXTPControlComboBox::GetItemData(int nIndex) const {
return (DWORD_PTR)GetListBoxCtrl()->GetItemData(nIndex);
}
AFX_INLINE int CXTPControlComboBox::SetItemData(int nIndex, DWORD_PTR dwItemData) {
return GetListBoxCtrl()->SetItemData(nIndex, dwItemData);
}
AFX_INLINE void CXTPControlComboBox::DeleteItem(long nIndex) {
if (nIndex < GetCount()) GetListBoxCtrl()->DeleteString(nIndex);
}
AFX_INLINE BOOL CXTPControlComboBox::IsCustomizeResizeAllow() const {
return TRUE;
}
AFX_INLINE CXTPControlComboBox* CXTPControlComboBoxEditCtrl::GetControlComboBox() const {
return m_pControl;
}
AFX_INLINE int CXTPControlComboBox::GetLabelWidth() const {
return m_nLabelWidth;
}
AFX_INLINE void CXTPControlComboBox::SetLabelWidth(int nLabelWidth) {
if (m_nLabelWidth != nLabelWidth)
{
m_nLabelWidth = nLabelWidth;
m_bDelayReposition = TRUE;
}
}
AFX_INLINE void CXTPControlComboBox::SetEditIconId(int nId) {
if (m_nEditIconId != nId) {m_nEditIconId = nId; RedrawParent();m_bDelayReposition = TRUE;}
}
AFX_INLINE int CXTPControlComboBox::GetEditIconId() const{
return m_nEditIconId;
}
AFX_INLINE int CXTPControlComboBox::GetThumbWidth() const {
return m_nThumbWidth;
}
AFX_INLINE void CXTPControlComboBox::SetThumbWidth(int nThumbWidth) {
if (m_nThumbWidth != nThumbWidth)
{
m_nThumbWidth = nThumbWidth;
m_bDelayReposition = TRUE;
}
}
AFX_INLINE void CXTPControlComboBox::OnThemeChanged() {
m_bDelayReposition = TRUE;
}
AFX_INLINE void CXTPControlComboBox::SetDropDownItemCount(int nDropDownItemCount) {
m_nDropDownItemCount = nDropDownItemCount;
}
#endif //#if !defined(__XTPCONTOLCOMBOBOX_H__)
| [
"utsavchokshi@Utsavs-MacBook-Pro.local"
] | utsavchokshi@Utsavs-MacBook-Pro.local |
8bc11014e79a427d6a94bdade83217b7e7b0093c | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/wget/hunk_19.cpp | 098ac1756c91a989ea551c52e04197e0e8e90b1e | [] | 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 | 410 | cpp | &dt, opt.recursive, iri, true);
}
- if (opt.delete_after && filename != NULL && file_exists_p (filename))
+ if (opt.delete_after && filename != NULL && file_exists_p (filename, NULL))
{
DEBUGP (("Removing file due to --delete-after in main():\n"));
logprintf (LOG_VERBOSE, _("Removing %s.\n"), filename);
| [
"993273596@qq.com"
] | 993273596@qq.com |
a6a057c2db91a46b6f8744050fec5c26f5c9e0d9 | 7f2e7edff293b0277137516a4f0b88021a63f1e3 | /Common/FAD/TinyFadET/tfadlog.h | 2961f153004dc44107e6778a04be8031c59532e7 | [] | no_license | labmec/neopz | 3c8da1844164765606a9d4890597947c1fadbb41 | 4c6b6d277ce097b97bfc8dea1b6725860f4fe05a | refs/heads/main | 2023-08-30T22:35:13.662951 | 2022-03-18T19:57:30 | 2022-03-18T19:57:30 | 33,341,900 | 48 | 17 | null | 2023-09-13T19:46:34 | 2015-04-03T02:18:47 | C++ | UTF-8 | C++ | false | false | 4,785 | h | // Emacs will be in -*- Mode: c++ -*-
//
// ************ DO NOT REMOVE THIS BANNER ****************
//
// Nicolas Di Cesare <Nicolas.Dicesare@ann.jussieu.fr>
// http://www.ann.jussieu.fr/~dicesare
//
// CEMRACS 98 : C++ courses,
// templates : new C++ techniques
// for scientific computing
//
//********************************************************
//
// A short implementation ( not all operators and
// functions are overloaded ) of 1st order Automatic
// Differentiation in forward mode (FAD) using
// EXPRESSION TEMPLATES.
//
//********************************************************
#ifndef _tfadlog_h_
#define _tfadlog_h_
#define FAD_LOG_MACRO(OP) \
template <int Num,class T> inline bool \
operator OP(const TFad<Num,T> &a, const TFad<Num,T> &b) \
{ \
return (a.val() OP b.val()); \
} \
\
template <int Num,class T> inline bool \
operator OP(const TFad<Num,T> &a, const T &b) \
{ \
return (a.val() OP b); \
} \
\
template <int Num,class T> inline bool \
operator OP(const T &a, const TFad<Num,T> &b) \
{ \
return (a OP b.val()); \
} \
\
template <int Num, class T> inline bool \
operator OP(const TFadExpr<T> &a, const TFad<Num,T> &b) \
{ \
return (a.val() OP b.val()); \
} \
\
template <int Num, class T> inline bool \
operator OP(const TFad<Num,T> &a, const TFadExpr<T> &b) \
{ \
return (a.val() OP b.val()); \
} \
\
template <class T> inline bool \
operator OP(const TFadExpr<T> &a, const TFadExpr<T> &b) \
{ \
return (a.val() OP b.val()); \
} \
\
template <class T> inline bool \
operator OP(const T &a, const TFadExpr<T> &b) \
{ \
return (a OP b.val()); \
} \
\
template <class T> inline bool \
operator OP(const TFadExpr<T> &a, const T &b) \
{ \
return (a.val() OP b); \
} \
\
template <class T> inline bool \
operator OP(const double &a, const TFadExpr<T> &b) \
{ \
return (a OP b.val()); \
} \
\
template <class T> inline bool \
operator OP(const TFadExpr<T> &a, const double &b) \
{ \
return (a.val() OP b); \
}
FAD_LOG_MACRO(==)
FAD_LOG_MACRO(!=)
FAD_LOG_MACRO(<)
FAD_LOG_MACRO(>)
FAD_LOG_MACRO(<=)
FAD_LOG_MACRO(>=)
FAD_LOG_MACRO(<<=)
FAD_LOG_MACRO(>>=)
FAD_LOG_MACRO(&)
#undef FAD_LOG_MACRO
template <int Num,class T> inline bool operator !(const TFad<Num,T> &a) {
return ( !a.val() );
}
template <class T> inline bool operator !(const TFadExpr<T> &a) {
return ( !a.val() );
}
#endif
| [
"nathan.sh@gmail.com@a693bd38-532a-e730-8659-88a8c11ee2f8"
] | nathan.sh@gmail.com@a693bd38-532a-e730-8659-88a8c11ee2f8 |
62e235a1d753a44b5b3b8fb10365372fc8fcfebd | 9c364d442e6e2e693e4244247786fc68dddf37c0 | /SoftwareEngineering/PAPS/aps/ImplementationModel/src/Transaction.cpp | c32da7422fad6c7ce5dc096cde3c25ebfa7caea5 | [] | no_license | zhangysh1995/Blog | d578022268a460e7fe2753364ed2194ec8fe605b | 46e821771a1e531922f23adf3f347b6702f36c96 | refs/heads/master | 2021-01-10T01:45:51.767378 | 2017-04-20T08:18:18 | 2017-04-20T08:18:18 | 50,762,457 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include "Transaction.h"
int Transaction::transactionCount_ = 0;
Transaction::Transaction(int memberID){
memberID_ = memberID;
total_ = 0;
transactionID_ = ++transactionCount_;
endTime_ = startTime_ = std::time(nullptr);
}
double Transaction::getTotal(){
endTime_ = std::time(nullptr);
//calculate total and return
return total_;
}
int Transaction::getID(){
return transactionID_;
} | [
"zhangysh1995@gmail.com"
] | zhangysh1995@gmail.com |
89faa466886ae5b156606650f997174175dec239 | 8c6407bc6ee7fa5c4563441f3a3fb1c2289d5a36 | /tesitingnlearning/main.cpp | f49b6a267f0edf7357f780a3bfdc5026ddd149e6 | [] | no_license | SvenDeadlySin/RPGgame | 32eb81c00cf883643a7e7ce31aee3ce4c21748a3 | 76df1fa62e02130168e0815c600a83ec7c6c2a89 | refs/heads/master | 2020-09-26T06:22:30.601856 | 2019-12-05T20:54:55 | 2019-12-05T20:54:55 | 226,187,214 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | cpp | #include "Game.h"
int main() {
srand(time(NULL));
Game game;
while (game.getPlaying())
{
game.mainMenu();
}
return 0;
} | [
"fallingindisney@gmail.com"
] | fallingindisney@gmail.com |
b966b12223265f608b4ebbc2c93c91b3c06d4234 | bb6ebff7a7f6140903d37905c350954ff6599091 | /third_party/libaddressinput/chromium/cpp/test/fallback_data_store_test.cc | a7266f41fc0025929c4f551329fa4bc4b91cc70a | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT"
] | permissive | PDi-Communication-Systems-Inc/lollipop_external_chromium_org | faa6602bd6bfd9b9b6277ce3cd16df0bd26e7f2f | ccadf4e63dd34be157281f53fe213d09a8c66d2c | refs/heads/master | 2022-12-23T18:07:04.568931 | 2016-04-11T16:03:36 | 2016-04-11T16:03:36 | 53,677,925 | 0 | 1 | BSD-3-Clause | 2022-12-09T23:46:46 | 2016-03-11T15:49:07 | C++ | UTF-8 | C++ | false | false | 1,015 | cc | // Copyright (C) 2014 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "fallback_data_store.h"
#include <string>
#include <gtest/gtest.h>
#include "util/json.h"
namespace i18n {
namespace addressinput {
namespace {
TEST(FallbackDataStore, Parsability) {
std::string data;
ASSERT_TRUE(FallbackDataStore::Get("data/US", &data));
scoped_ptr<Json> json(Json::Build());
EXPECT_TRUE(json->ParseObject(data));
}
} // namespace
} // namespace addressinput
} // namespace i18n
| [
"mrobbeloth@pdiarm.com"
] | mrobbeloth@pdiarm.com |
4dc545c3f6dccdaf77b9fae52b92230489917de8 | 7b49d69735eee6602ce328cfcb719024446fe2bb | /oneDim/linearizedEquations/init/VOLFLUX | 542b856b657473742dc2740cfd2dbb865ba0097a | [] | no_license | statisdisc/partitionedShallowWater | 7ced6febdae948b222e18039ad622b5d7f0813a4 | 52422a24a9e3cdbe7c0f8f28c2e8d3f3e1257ca7 | refs/heads/master | 2021-06-22T16:33:21.060529 | 2020-08-21T08:39:11 | 2020-08-21T08:39:11 | 101,410,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,129 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: dev |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class surfaceScalarField;
location "constant";
object VOLFLUX;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 3 -1 0 0 0 0];
internalField uniform 0;
boundaryField
{
inlet
{
type cyclic;
value uniform 0;
}
outlet
{
type cyclic;
value uniform 0;
}
}
// ************************************************************************* //
| [
"will.a.m@hotmail.co.uk"
] | will.a.m@hotmail.co.uk | |
efad715d3e6119fab282b398c61e14ecdd4b4125 | 51ba370cc44c481468068b7d79828fb7e2c72550 | /parser/channel.h | 7b140f024447db381f02b04ac6275631d75bf655 | [] | no_license | Nayaco/RSSReader | 21127bd5a49e8b21b3fed6d4164dda0323b6c5dd | 2cc09867dc26be1c8a4246db35270a5c178ab421 | refs/heads/master | 2020-06-16T07:41:50.406960 | 2019-07-17T05:01:50 | 2019-07-17T05:01:50 | 195,514,849 | 2 | 2 | null | 2019-07-15T06:19:22 | 2019-07-06T08:09:48 | C++ | UTF-8 | C++ | false | false | 1,110 | h | #ifndef CHANNEL_H
#define CHANNEL_H
#include "common/common.h"
#include "common/property.h"
#include "item.h"
using Items = QVector<shared_ptr<Item>>;
class Channel: public Property {
public:
Channel();
Channel(const Channel& chan) = delete;
~Channel()=default;
virtual QString Name() override { return "channel"; }
QString GetTitle();
void SetTitle(const QString& str);
QString GetDesc();
void SetDesc(const QString& str);
QString GetLink();
void SetLink(const QString& str);
int GetTTL();
void setTTL(const int _ttl);
QString GetSource();
void SetSource(const QString& str);
shared_ptr<Items> GetItems();
void AddItem(const shared_ptr<Item>& _item);
void ClearItem();
void DeepCopy(const Channel& chan);
private:
virtual QString get(const QString& key) override;
virtual void set(const QString& key, const QString& element) override;
private:
QString description;
QString title;
QString link;
QString csource;
int ttl;
shared_ptr<Items> items;
QSet<QString> itemnames;
};
#endif | [
"nyancochan@outlook.com"
] | nyancochan@outlook.com |
68c2798864441aad43b07ae53c0703729974d39a | 255df7521e943186005d9fe58b4e33277b83d67b | /lib/DebugInfo/CodeView/DebugLinesSubsection.cpp | 2fce06ca2a17c499ce194c8dcc06cc5c8f6f49fe | [
"NCSA"
] | permissive | navidR/Parallel-IR | ad471c4dc2602947634f71cf4978f36d9ccacedb | c5efa15995f0987fdf4d486aaf49abe326920575 | refs/heads/master | 2020-03-29T10:45:17.382093 | 2018-09-21T21:48:01 | 2018-09-21T21:48:01 | 149,821,232 | 1 | 0 | null | 2018-09-21T21:41:58 | 2018-09-21T21:41:57 | null | UTF-8 | C++ | false | false | 5,568 | cpp | //===- DebugLinesSubsection.cpp -------------------------------*- C++-*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/DebugInfo/CodeView/DebugLinesSubsection.h"
#include "llvm/DebugInfo/CodeView/CodeViewError.h"
#include "llvm/DebugInfo/CodeView/DebugChecksumsSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugStringTableSubsection.h"
#include "llvm/DebugInfo/CodeView/DebugSubsectionRecord.h"
using namespace llvm;
using namespace llvm::codeview;
Error LineColumnExtractor::extract(BinaryStreamRef Stream, uint32_t &Len,
LineColumnEntry &Item,
const LineFragmentHeader *Header) {
using namespace codeview;
const LineBlockFragmentHeader *BlockHeader;
BinaryStreamReader Reader(Stream);
if (auto EC = Reader.readObject(BlockHeader))
return EC;
bool HasColumn = Header->Flags & uint16_t(LF_HaveColumns);
uint32_t LineInfoSize =
BlockHeader->NumLines *
(sizeof(LineNumberEntry) + (HasColumn ? sizeof(ColumnNumberEntry) : 0));
if (BlockHeader->BlockSize < sizeof(LineBlockFragmentHeader))
return make_error<CodeViewError>(cv_error_code::corrupt_record,
"Invalid line block record size");
uint32_t Size = BlockHeader->BlockSize - sizeof(LineBlockFragmentHeader);
if (LineInfoSize > Size)
return make_error<CodeViewError>(cv_error_code::corrupt_record,
"Invalid line block record size");
// The value recorded in BlockHeader->BlockSize includes the size of
// LineBlockFragmentHeader.
Len = BlockHeader->BlockSize;
Item.NameIndex = BlockHeader->NameIndex;
if (auto EC = Reader.readArray(Item.LineNumbers, BlockHeader->NumLines))
return EC;
if (HasColumn) {
if (auto EC = Reader.readArray(Item.Columns, BlockHeader->NumLines))
return EC;
}
return Error::success();
}
DebugLinesSubsectionRef::DebugLinesSubsectionRef()
: DebugSubsectionRef(DebugSubsectionKind::Lines) {}
Error DebugLinesSubsectionRef::initialize(BinaryStreamReader Reader) {
if (auto EC = Reader.readObject(Header))
return EC;
if (auto EC =
Reader.readArray(LinesAndColumns, Reader.bytesRemaining(), Header))
return EC;
return Error::success();
}
bool DebugLinesSubsectionRef::hasColumnInfo() const {
return !!(Header->Flags & LF_HaveColumns);
}
DebugLinesSubsection::DebugLinesSubsection(DebugChecksumsSubsection &Checksums,
DebugStringTableSubsection &Strings)
: DebugSubsection(DebugSubsectionKind::Lines), Checksums(Checksums) {}
void DebugLinesSubsection::createBlock(StringRef FileName) {
uint32_t Offset = Checksums.mapChecksumOffset(FileName);
Blocks.emplace_back(Offset);
}
void DebugLinesSubsection::addLineInfo(uint32_t Offset, const LineInfo &Line) {
Block &B = Blocks.back();
LineNumberEntry LNE;
LNE.Flags = Line.getRawData();
LNE.Offset = Offset;
B.Lines.push_back(LNE);
}
void DebugLinesSubsection::addLineAndColumnInfo(uint32_t Offset,
const LineInfo &Line,
uint32_t ColStart,
uint32_t ColEnd) {
Block &B = Blocks.back();
assert(B.Lines.size() == B.Columns.size());
addLineInfo(Offset, Line);
ColumnNumberEntry CNE;
CNE.StartColumn = ColStart;
CNE.EndColumn = ColEnd;
B.Columns.push_back(CNE);
}
Error DebugLinesSubsection::commit(BinaryStreamWriter &Writer) const {
LineFragmentHeader Header;
Header.CodeSize = CodeSize;
Header.Flags = hasColumnInfo() ? LF_HaveColumns : 0;
Header.RelocOffset = RelocOffset;
Header.RelocSegment = RelocSegment;
if (auto EC = Writer.writeObject(Header))
return EC;
for (const auto &B : Blocks) {
LineBlockFragmentHeader BlockHeader;
assert(B.Lines.size() == B.Columns.size() || B.Columns.empty());
BlockHeader.NumLines = B.Lines.size();
BlockHeader.BlockSize = sizeof(LineBlockFragmentHeader);
BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(LineNumberEntry);
if (hasColumnInfo())
BlockHeader.BlockSize += BlockHeader.NumLines * sizeof(ColumnNumberEntry);
BlockHeader.NameIndex = B.ChecksumBufferOffset;
if (auto EC = Writer.writeObject(BlockHeader))
return EC;
if (auto EC = Writer.writeArray(makeArrayRef(B.Lines)))
return EC;
if (hasColumnInfo()) {
if (auto EC = Writer.writeArray(makeArrayRef(B.Columns)))
return EC;
}
}
return Error::success();
}
uint32_t DebugLinesSubsection::calculateSerializedSize() const {
uint32_t Size = sizeof(LineFragmentHeader);
for (const auto &B : Blocks) {
Size += sizeof(LineBlockFragmentHeader);
Size += B.Lines.size() * sizeof(LineNumberEntry);
if (hasColumnInfo())
Size += B.Columns.size() * sizeof(ColumnNumberEntry);
}
return Size;
}
void DebugLinesSubsection::setRelocationAddress(uint16_t Segment,
uint16_t Offset) {
RelocOffset = Offset;
RelocSegment = Segment;
}
void DebugLinesSubsection::setCodeSize(uint32_t Size) { CodeSize = Size; }
void DebugLinesSubsection::setFlags(LineFlags Flags) { this->Flags = Flags; }
bool DebugLinesSubsection::hasColumnInfo() const {
return Flags & LF_HaveColumns;
}
| [
"zturner@google.com"
] | zturner@google.com |
e2bd1cc4daca2dc94b7993868116bc7f53ecadf1 | 9d17725610c2a402da952fd0ee86a6f83cdf54ac | /src/modules/event_info/EventConvolution.h | 55316afea3c22abc8167e10285fe4ef4613913f7 | [] | no_license | v154c1/libyuri | c77350bce94ffde0e77d7d08bc7ebc209a480813 | ad986a4327513d6b4639b435bdde58f8cca41ea0 | refs/heads/2.8.x | 2023-08-31T09:01:52.309119 | 2023-08-25T05:18:01 | 2023-08-25T05:18:01 | 53,398,918 | 7 | 3 | null | 2023-03-18T09:19:09 | 2016-03-08T09:18:01 | C++ | UTF-8 | C++ | false | false | 1,441 | h | /*!
* @file EventConvolution.h
* @author Zdenek Travnicek <v154c1@gmail.com>
* @date 18.08.2020
* @copyright Institute of Intermedia, CTU in Prague, 2020
* Distributed under modified BSD Licence, details in file doc/LICENSE
*
*/
#ifndef EVENTCONVOLUTION_H_
#define EVENTCONVOLUTION_H_
#include "yuri/core/thread/IOThread.h"
#include "yuri/event/BasicEventConsumer.h"
#include "yuri/event/BasicEventProducer.h"
namespace yuri {
namespace event_convolution {
class EventConvolution
: public core::IOThread, public event::BasicEventConsumer, public event::BasicEventProducer {
public:
IOTHREAD_GENERATOR_DECLARATION
static core::Parameters configure();
EventConvolution(const log::Log &log_, core::pwThreadBase parent, const core::Parameters ¶meters);
virtual ~EventConvolution() noexcept;
private:
virtual void run() override;
virtual bool set_param(const core::Parameter ¶m) override;
bool do_process_event(const std::string &event_name, const event::pBasicEvent &event) override;
std::vector<double> kernel_;
std::map<std::string, std::deque<double>> values_;
std::map<std::string, double> last_values_;
double weight_;
};
} /* namespace event_convolution */
} /* namespace yuri */
#endif /* EVENTCONVOLUTION_H_ */
| [
"v154c1@gmail.com"
] | v154c1@gmail.com |
cda6dd17e1ef85e488f623ca2584d70f85ff7d60 | ce98811e47e83d8d13e35001bd043b20e220816e | /souffle_doop/souffle/src/profile/ProgramRun.h | 685bee9864487c5856c42fa9e7e6ec02307795a7 | [] | no_license | souffle-lang/ppopp19 | cf7e08385f30f044473dc67cac99aa3ab34d0d26 | 6d752f942b56a869b4c5009f7f22ca0d1925a85e | refs/heads/master | 2020-04-15T04:38:35.069712 | 2019-01-12T01:32:56 | 2019-01-12T01:32:56 | 164,390,502 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,578 | h | /*
* Souffle - A Datalog Compiler
* Copyright (c) 2016, The Souffle Developers. All rights reserved
* Licensed under the Universal Permissive License v 1.0 as shown at:
* - https://opensource.org/licenses/UPL
* - <souffle root>/licenses/SOUFFLE-UPL.txt
*/
#pragma once
#include "Relation.h"
#include "StringUtils.h"
#include "Table.h"
#include <memory>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
namespace souffle {
namespace profile {
/*
* Stores the relations of the program
* ProgramRun -> Relations -> Iterations/Rules
*/
class ProgramRun {
private:
std::unordered_map<std::string, std::shared_ptr<Relation>> relation_map;
double runtime = -1.0;
double tot_rec_tup = 0.0;
double tot_copy_time = 0.0;
public:
ProgramRun() : relation_map() {}
inline void SetRuntime(double runtime) {
this->runtime = runtime;
}
inline void setRelation_map(std::unordered_map<std::string, std::shared_ptr<Relation>>& relation_map) {
this->relation_map = relation_map;
}
inline void update() {
tot_rec_tup = (double)getTotNumRecTuples();
tot_copy_time = getTotCopyTime();
};
std::string toString() {
std::ostringstream output;
output << "ProgramRun:" << runtime << "\nRelations:\n";
for (auto r = relation_map.begin(); r != relation_map.end(); ++r) {
output << r->second->toString() << "\n";
}
return output.str();
}
inline std::unordered_map<std::string, std::shared_ptr<Relation>>& getRelation_map() {
return relation_map;
}
std::string getRuntime() {
if (runtime == -1.0) {
return "--";
}
return formatTime(runtime);
}
double getDoubleRuntime() {
return runtime;
}
double getTotLoadtime() {
double result = 0;
for (auto& item : relation_map) {
result += item.second->getLoadtime();
}
return result;
}
double getTotSavetime() {
double result = 0;
for (auto& item : relation_map) {
result += item.second->getSavetime();
}
return result;
}
long getTotNumTuples() {
long result = 0;
for (auto& item : relation_map) {
result += item.second->getTotNum_tuples();
}
return result;
}
long getTotNumRecTuples() {
long result = 0;
for (auto& item : relation_map) {
result += item.second->getTotNumRec_tuples();
}
return result;
}
double getTotCopyTime() {
double result = 0;
for (auto& item : relation_map) {
result += item.second->getCopyTime();
}
return result;
}
double getTotTime() {
double result = 0;
for (auto& item : relation_map) {
result += item.second->getRecTime();
}
return result;
}
Relation* getRelation(std::string name) {
if (relation_map.find(name) != relation_map.end()) {
return &(*relation_map[name]);
}
return nullptr;
}
inline std::string formatTime(double runtime) {
return Tools::formatTime(runtime);
}
inline std::string formatNum(int precision, long number) {
return Tools::formatNum(precision, number);
}
inline std::vector<std::vector<std::string>> formatTable(Table table, int precision) {
return Tools::formatTable(table, precision);
}
};
} // namespace profile
} // namespace souffle
| [
"dzha3983@uni.sydney.edu.au"
] | dzha3983@uni.sydney.edu.au |
8d704ac6e7ce9b6240898af20476a2bbcbd4b8f8 | 1cd01ed5fd01f59e1bf593076e1f1bf0f350dafb | /week-4/Rational/rational_io.cpp | a699cb6e91a64b30123b177996eafcea4aed5832 | [] | no_license | t-denisova/white-belt | 63fcd372c5931464666dbaa2b0a74c4d0bf58512 | d3bce8115b23de9a9a1975c245fae46238e47656 | refs/heads/master | 2020-03-25T16:56:39.597665 | 2018-09-02T16:42:24 | 2018-09-02T16:42:24 | 143,955,327 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,821 | cpp | #include <iostream>
#include <sstream>
#include <string>
using namespace std;
int FindDevider (int x, int y) {
while (x > 0 && y > 0) {
if (x > y) {
x %= y;
} else {
y %= x;
}
}
return x + y;
}
class Rational {
public:
Rational() {
num = 0;
den = 1;
}
Rational(int numerator, int denominator) {
if (numerator == 0) {
num = 0;
den = 1;
} else {
int devider = FindDevider(abs(numerator), abs(denominator));
//cout << devider << endl;
num = numerator / devider;
den = denominator / devider;
if(den < 0){
num *= -1;
den *= -1;
}
}
}
int Numerator() const {
return num;
}
int Denominator() const {
return den;
}
private:
int num;
int den;
};
// Rational CreateR(const stringstream& ss, Rational& r) {
// string s_rhs, s_lhs = "";
// getline(ss, s_rhs, '/');
// getline(ss, s_lhs);
// r = Rational(stoi(s_rhs), stoi(s_lhs));
// return r;
// }
Rational operator+(const Rational& lhs, const Rational rhs) {
if (lhs.Denominator() == rhs.Denominator()) {
return Rational(lhs.Numerator() + rhs.Numerator(), lhs.Denominator());
} else {
int nok = lhs.Denominator() * rhs.Denominator() / FindDevider(lhs.Denominator(), rhs.Denominator());
int n_l = nok / lhs.Denominator();
int d_l = nok / rhs.Denominator();
return Rational(lhs.Numerator() * n_l + rhs.Numerator() * d_l, nok);
}
}
Rational operator-(const Rational& lhs, const Rational& rhs) {
if (lhs.Denominator() == rhs.Denominator()) {
return Rational(lhs.Numerator() - rhs.Numerator(), lhs.Denominator());
} else {
int nok = lhs.Denominator() * rhs.Denominator() / FindDevider(lhs.Denominator(), rhs.Denominator());
int n_l = nok / lhs.Denominator();
int d_l = nok / rhs.Denominator();
return Rational(lhs.Numerator() * n_l - rhs.Numerator() * d_l, nok);
}
}
bool operator==(const Rational& lhs, const Rational& rhs) {
if (lhs.Numerator() == rhs.Numerator() && lhs.Denominator() == rhs.Denominator()) {
return true;
} else {
return false;
}
}
Rational operator*(const Rational& lhs, const Rational& rhs) {
return Rational(lhs.Numerator() * rhs.Numerator(), lhs.Denominator() * rhs.Denominator());
}
Rational operator/(const Rational& lhs, const Rational& rhs) {
return Rational(lhs.Numerator() * rhs.Denominator(), lhs.Denominator() * rhs.Numerator());
}
ostream& operator<<(ostream& stream, const Rational& r) {
stream << r.Numerator() << '/' << r.Denominator();
return stream;
}
istream& operator>>(istream& stream, Rational& r) {
if(stream) {
int n, m = 0;
stream >> n;
stream.ignore(1);
stream >> m;
if ( m!= 0) {
r = Rational(n, m);
}
}
return stream;
}
int main() {
{
ostringstream output;
output << Rational(-6, 8);
if (output.str() != "-3/4") {
cout << "Rational(-6, 8) should be written as \"-3/4\"" << endl;
return 1;
}
}
{
istringstream input("5/7");
Rational r;
input >> r;
bool equal = r == Rational(5, 7);
if (!equal) {
cout << "5/7 is incorrectly read as " << r << endl;
return 2;
}
}
{
istringstream input("5/7 10/8");
Rational r1, r2;
input >> r1 >> r2;
bool correct = r1 == Rational(5, 7) && r2 == Rational(5, 4);
if (!correct) {
cout << "Multiple values are read incorrectly: " << r1 << " " << r2 << endl;
return 3;
}
input >> r1;
input >> r2;
correct = r1 == Rational(5, 7) && r2 == Rational(5, 4);
if (!correct) {
cout << "Read from empty stream shouldn't change arguments: " << r1 << " " << r2 << endl;
return 4;
}
}
cout << "OK" << endl;
return 0;
}
| [
"hi.tatiana.denisova@gmail.com"
] | hi.tatiana.denisova@gmail.com |
cec91e486941dece10e018762f4f474638c3f073 | 654d123ef26613953214808cb889ae2f666ec7f3 | /Qt/Animasi/Animasi/mainwindow.cpp | 7293c1a83e0d8ff0c2fd87ce88bfd543450b8541 | [] | no_license | bsnugroho7/Project100Day | 1dbf2b3f36d0cb11f616a3374881ee74c6f13e07 | 8db2cc62f25a50410396da5b8998d7d0913b5eab | refs/heads/master | 2021-02-11T16:02:05.317905 | 2020-04-14T14:04:48 | 2020-04-14T14:04:48 | 244,507,463 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_sliderAir_sliderMoved(int position)
{
}
| [
"bagus.s.n@mail.ugm.ac.id"
] | bagus.s.n@mail.ugm.ac.id |
b20b6d552122cde863a95e3dc8da2f4f2e38ef27 | a35db8c5546f482d9c72ec0567ecc55a52b44d67 | /Contains Duplicate.cpp | ab7ff92859c3fc44f4c15f6c876623e8452a7ebb | [] | no_license | Suryansh555/CPP | bb8e9e88c519f9b45b9d99d16185ac936744d5c8 | 4a77bb7d19e270e462a110fe0b6bb7df2156f168 | refs/heads/main | 2023-08-12T16:31:07.777148 | 2021-10-11T16:49:36 | 2021-10-11T16:49:36 | 305,274,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | class Solution {
public:
bool containsDuplicate(vector<int>& nums){
map<int,int> mp ;
int size = nums.size();
for(int i = 0 ; i < size ; i++){
mp[nums[i]]++;
if(mp[nums[i]] >= 2){
return true;
}
}
return false;
}
}; | [
"suryansh555@yahoo.in"
] | suryansh555@yahoo.in |
e9a13ffbf6d9a6993eb87b7109b4d8f9267aa471 | 7e14945b2dd27334ddec322d67953b913ddedf46 | /regionals/hangzhou-invitational-2013/A.cpp | 10f7eccdaccc09dcbb7c694ef3bedcad6d9fa861 | [] | no_license | szefany/acm-icpc | 63653dfc724eab98b33bde54416ad84eb5e2f4f6 | 86ccd854be545cd67bc2850e22337d3fe9f4701f | refs/heads/master | 2021-06-02T02:02:10.251126 | 2019-09-28T13:24:22 | 2019-09-28T13:24:22 | 7,666,139 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,662 | cpp | #include <cstdio>
#include <cstring>
const int N = 200 + 10;
double dp[N], buffer[N];
int count[N];
int n, m, l, r;
struct Matrix {
static const int N = 200 + 10;
double element[N][N];
int n;
Matrix(int size = 0) {
n = size;
memset(element, 0, sizeof(element));
}
double* operator [] (int i) {
return element[i];
}
const double* operator [] (int i) const {
return element[i];
}
void print() {
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < n; ++ j) {
printf("%.2f ", element[i][j]);
} puts("");
}
}
void diagonal(int size) {
n = size;
memset(element, 0, sizeof(element));
for (int i = 0; i < n; ++ i) {
element[i][i] = 1;
}
}
};
Matrix buffer2;
void multi(Matrix &a, Matrix &b) {
buffer2.n = n;
memset(buffer2.element, 0, sizeof(buffer2.element));
for (int i = 0; i < n; ++ i) {
for (int j = 0; j < n; ++ j) {
buffer2[0][i] += a[0][j] * b[j][i];
}
}
for (int i = 1; i < n; ++ i) {
for (int j = 0; j < n; ++ j) {
int prev = j == 0 ? n - 1 : j - 1;
buffer2[i][j] = buffer2[i - 1][prev];
}
}
a = buffer2;
}
Matrix result;
void power(Matrix &base, int times) {
result.diagonal(n);
while (times) {
int x = times & 1;
if (x) {
multi(result, base);
}
multi(base, base);
times >>= 1;
}
base = result;
}
int main() {
while (scanf("%d%d%d%d", &n, &m, &l, &r) != EOF) {
if (n + m + l + r == 0) {
break;
}
memset(count, 0, sizeof(count));
for (int i = 1; i <= m; ++ i) {
int x;
scanf("%d", &x);
count[x] ++;
}
memset(dp, 0, sizeof(dp));
dp[0] = 1;
for (int i = 1; i <= 100; ++ i) {
if (count[i] == 0) {
continue;
}
Matrix temp(n);
for (int j = 0; j < n; ++ j) {
temp[j][(j + i) % n] += 0.5;
temp[j][((j - i) % n + n) % n] += 0.5;
}
power(temp, count[i]);
memcpy(buffer, dp, sizeof(dp));
for (int j = 0; j < n; ++ j) {
dp[j] = 0;
for (int k = 0; k < n; ++ k) {
dp[j] += temp[j][k] * buffer[k];
}
}
}
double answer = 0;
for (int i = l - 1; i < r; ++ i) {
answer += dp[i];
}
printf("%.4f\n", answer);
}
return 0;
}
| [
"szefany@gmail.com"
] | szefany@gmail.com |
6963f0396a7c4183fded59921564fcf30bbcee88 | f8fa13110772c98c25cafaeb9a707ff190fba620 | /GWTPhotoAlbum/albumcreator/quickalbum/main_quickalbum.cpp | 8d1173349dc01a2d351423b11fa06f37ef7d25a2 | [
"CC-BY-3.0",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | jecki/gwtphotoalbum | 3abc105167a21f390358af806f8188c288378a39 | fa7f8720011f007ce956e4d8a18977c56f9f954b | refs/heads/master | 2021-01-18T22:26:48.853489 | 2016-03-30T05:26:22 | 2016-03-30T05:26:22 | 33,084,019 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,157 | cpp | /*
* Copyright 2011 Eckhart Arnold (eckhart_arnold@hotmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
#include <Qt>
#if QT_VERSION >= 0x050000
#include <QApplication>
#else
#include <QtGui/QApplication>
#endif
#include <QMainWindow>
#include <QFileDialog>
#include <QDir>
#include <iostream>
#include "imagecollection.h"
#include "createalbumwizzard.h"
#include "toolbox.h"
int main(int argc, char *argv[])
{
(void) argc; (void) argv;
#ifndef NDEBUG
std::cout << "debugging is on!" << std::endl;
#endif
ImageCollection ic;
int ret;
QString error;
QApplication a(argc, argv);
// QuickAlbumMainWin w;
// w.show();
// a.exec();
QFileDialog fd;
fd.setAcceptMode(QFileDialog::AcceptOpen);
fd.setFilter(QDir::AllDirs|QDir::AllEntries);
fd.setDirectory("/home/eckhart/.local/share/geeqie/collections");
QStringList filters;
filters << "Image Files (*.jpeg *.jpg *.png *.gqv)";
filters << "Any Files (*)";
fd.setNameFilters(filters);
fd.setWindowTitle("Pick image files or image list...");
fd.setFileMode(QFileDialog::ExistingFiles);
fd.exec();
QStringList paths = fd.selectedFiles();
#ifndef NDEBUG
foreach(QString path, paths) {
std::cout << path.toStdString() << std::endl;
if (path.endsWith(".gqv", Qt::CaseInsensitive)) {
ic.addImageList(path);
} else {
ic.imageList.append(new ImageItem(path));
}
}
std::cout << "That was all..." << std::endl;
#endif
if (!ic.imageList.isEmpty()) {
CreateAlbumWizzard w(ic);
w.setAboutTab(true);
ret = w.exec();
} else {
ret = 1;
}
#ifndef NDEBUG
std::cout << "program finished!" << std::endl;
#endif
return (ret);
// return w.returnValue;
}
| [
"eckhart_arnold@yahoo.de"
] | eckhart_arnold@yahoo.de |
f306a07619a09539e0116503433067063d57ffe0 | fe2362eda423bb3574b651c21ebacbd6a1a9ac2a | /VTK-7.1.1/Filters/Sources/vtkSelectionSource.h | 98da63be06280b8a405d9a3c0306f8beb3c2a0e7 | [
"BSD-3-Clause"
] | permissive | likewatchk/python-pcl | 1c09c6b3e9de0acbe2f88ac36a858fe4b27cfaaf | 2a66797719f1b5af7d6a0d0893f697b3786db461 | refs/heads/master | 2023-01-04T06:17:19.652585 | 2020-10-15T21:26:58 | 2020-10-15T21:26:58 | 262,235,188 | 0 | 0 | NOASSERTION | 2020-05-08T05:29:02 | 2020-05-08T05:29:01 | null | UTF-8 | C++ | false | false | 5,119 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkSelectionSource.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* @class vtkSelectionSource
* @brief Generate selection from given set of ids
* vtkSelectionSource generates a vtkSelection from a set of
* (piece id, cell id) pairs. It will only generate the selection values
* that match UPDATE_PIECE_NUMBER (i.e. piece == UPDATE_PIECE_NUMBER).
*/
#ifndef vtkSelectionSource_h
#define vtkSelectionSource_h
#include "vtkFiltersSourcesModule.h" // For export macro
#include "vtkSelectionAlgorithm.h"
class vtkSelectionSourceInternals;
class VTKFILTERSSOURCES_EXPORT vtkSelectionSource : public vtkSelectionAlgorithm
{
public:
static vtkSelectionSource *New();
vtkTypeMacro(vtkSelectionSource,vtkSelectionAlgorithm);
void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE;
//@{
/**
* Add a (piece, id) to the selection set. The source will generate
* only the ids for which piece == UPDATE_PIECE_NUMBER.
* If piece == -1, the id applies to all pieces.
*/
void AddID(vtkIdType piece, vtkIdType id);
void AddStringID(vtkIdType piece, const char* id);
//@}
/**
* Add a point in world space to probe at.
*/
void AddLocation(double x, double y, double z);
/**
* Add a value range to threshold within.
*/
void AddThreshold(double min, double max);
/**
* Set a frustum to choose within.
*/
void SetFrustum(double *vertices);
/**
* Add the flat-index/composite index for a block.
*/
void AddBlock(vtkIdType blockno);
//@{
/**
* Removes all IDs.
*/
void RemoveAllIDs();
void RemoveAllStringIDs();
//@}
/**
* Remove all thresholds added with AddThreshold.
*/
void RemoveAllThresholds();
/**
* Remove all locations added with AddLocation.
*/
void RemoveAllLocations();
/**
* Remove all blocks added with AddBlock.
*/
void RemoveAllBlocks();
//@{
/**
* Set the content type for the generated selection.
* Possible values are as defined by
* vtkSelection::SelectionContent.
*/
vtkSetMacro(ContentType, int);
vtkGetMacro(ContentType, int);
//@}
//@{
/**
* Set the field type for the generated selection.
* Possible values are as defined by
* vtkSelection::SelectionField.
*/
vtkSetMacro(FieldType, int);
vtkGetMacro(FieldType, int);
//@}
//@{
/**
* When extracting by points, extract the cells that contain the
* passing points.
*/
vtkSetMacro(ContainingCells, int);
vtkGetMacro(ContainingCells, int);
//@}
//@{
/**
* Determines whether the selection describes what to include or exclude.
* Default is 0, meaning include.
*/
vtkSetMacro(Inverse, int);
vtkGetMacro(Inverse, int);
//@}
//@{
/**
* Access to the name of the selection's subset description array.
*/
vtkSetStringMacro(ArrayName);
vtkGetStringMacro(ArrayName);
//@}
//@{
/**
* Access to the component number for the array specified by ArrayName.
* Default is component 0. Use -1 for magnitude.
*/
vtkSetMacro(ArrayComponent, int);
vtkGetMacro(ArrayComponent, int);
//@}
//@{
/**
* If CompositeIndex < 0 then COMPOSITE_INDEX() is not added to the output.
*/
vtkSetMacro(CompositeIndex, int);
vtkGetMacro(CompositeIndex, int);
//@}
//@{
/**
* If HierarchicalLevel or HierarchicalIndex < 0 , then HIERARCHICAL_LEVEL()
* and HIERARCHICAL_INDEX() keys are not added to the output.
*/
vtkSetMacro(HierarchicalLevel, int);
vtkGetMacro(HierarchicalLevel, int);
vtkSetMacro(HierarchicalIndex, int);
vtkGetMacro(HierarchicalIndex, int);
//@}
//@{
/**
* Set/Get the query expression string.
*/
vtkSetStringMacro(QueryString);
vtkGetStringMacro(QueryString);
//@}
protected:
vtkSelectionSource();
~vtkSelectionSource() VTK_OVERRIDE;
int RequestInformation(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector) VTK_OVERRIDE;
int RequestData(vtkInformation* request,
vtkInformationVector** inputVector,
vtkInformationVector* outputVector) VTK_OVERRIDE;
vtkSelectionSourceInternals* Internal;
int ContentType;
int FieldType;
int ContainingCells;
int PreserveTopology;
int Inverse;
int CompositeIndex;
int HierarchicalLevel;
int HierarchicalIndex;
char *ArrayName;
int ArrayComponent;
char *QueryString;
private:
vtkSelectionSource(const vtkSelectionSource&) VTK_DELETE_FUNCTION;
void operator=(const vtkSelectionSource&) VTK_DELETE_FUNCTION;
};
#endif
| [
"likewatchk@gmail.com"
] | likewatchk@gmail.com |
c18268280509184bdd2b1573ddf58a24668434ad | 672db28ef97cc07f5acad5c44046e528e217f020 | /proj.winrt/App.xaml.h | 27abde344b62f0d8c8a07874b340e5b2e3f3c34d | [] | no_license | devuseful/DoubePazzleGame | 48c7b0f69bc10ea57c5d0a3f60718d49b40be1be | 9627df7cd24213d3e336c64553cc1f8b14765650 | refs/heads/master | 2020-12-25T14:34:14.891749 | 2016-08-21T09:02:40 | 2016-08-21T09:02:40 | 66,189,408 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,850 | h | /****************************************************************************
Copyright (c) 2010-2013 cocos2d-x.org
Copyright (c) Microsoft Open Technologies, Inc.
http://www.cocos2d-x.org
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.
****************************************************************************/
//
// App.xaml.h
// Declaration of the App class.
//
#pragma once
#include "App.g.h"
#include "MainPage.xaml.h"
namespace DoubePazzleGame
{
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
ref class App sealed
{
public:
App();
virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ args) override;
private:
void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args);
MainPage^ m_mainPage;
};
}
| [
"useful@bk.ru"
] | useful@bk.ru |
06973f88ecffe2b25083ee7ae4f62abe23b8c595 | 27d4218f11d06eaf3204315fe01bba3937b03a61 | /jmunoz80-TestCollatz.c++ | 4cfc20041c24ab7cbd5a7b677094d67771e8b6ab | [] | no_license | cs371p-fall-2013/cs371p-collatz-tests | 17dc3e3215e55171a7f26c2cac1b0b060cc09a6a | 9ec6f7978d67a91bf3901488b82dbf9e2dfc17c2 | refs/heads/master | 2016-08-04T08:44:39.936027 | 2013-09-14T00:31:46 | 2013-09-14T00:31:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,775 | #include <iostream>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
#include "Collatz.h"
// -----------
// TestCollatz
// -----------
// ----
// read
// ----
TEST(Collatz, read) {
std::istringstream r("1 10\n");
int i;
int j;
const bool b = collatz_read(r, i, j);
ASSERT_TRUE(b == true);
ASSERT_TRUE(i == 1);
ASSERT_TRUE(j == 10);}
TEST(Collatz, reverse_read) {
std::istringstream r("10 1\n");
int i;
int j;
const bool b = collatz_read(r, i, j);
ASSERT_TRUE(b == true);
ASSERT_TRUE(i == 10);
ASSERT_TRUE(j == 1);}
TEST(Collatz, large_read) {
std::istringstream r("1 10000000\n");
int i;
int j;
const bool b = collatz_read(r, i, j);
ASSERT_TRUE(b == true);
ASSERT_TRUE(i == 1);
ASSERT_TRUE(j == 10000000);}
TEST(Collatz, spaced_read) {
std::istringstream r("1 5\n");
int i;
int j;
const bool b = collatz_read(r, i, j);
ASSERT_TRUE(b == true);
ASSERT_TRUE(i == 1);
ASSERT_TRUE(j == 5);}
// ----
// eval
// ----
TEST(Collatz, eval_1) {
const int v = collatz_eval(1, 10);
ASSERT_TRUE(v == 20);}
TEST(Collatz, eval_2) {
const int v = collatz_eval(100, 200);
ASSERT_TRUE(v == 125);}
TEST(Collatz, eval_3) {
const int v = collatz_eval(201, 210);
ASSERT_TRUE(v == 89);}
TEST(Collatz, eval_4) {
const int v = collatz_eval(900, 1000);
ASSERT_TRUE(v == 174);}
TEST(Collatz, short_eval) {
const int v = collatz_eval(15, 16);
ASSERT_TRUE(v == 18);}
TEST(Collatz, long_eval) {
const int v = collatz_eval(1, 1000000);
ASSERT_TRUE(v == 525);}
// -----
// print
// -----
TEST(Collatz, print) {
std::ostringstream w;
collatz_print(w, 1, 10, 20);
ASSERT_TRUE(w.str() == "1 10 20\n");}
TEST(Collatz, print_2) {
std::ostringstream w;
collatz_print(w, 10, 20, 20);
ASSERT_TRUE(w.str() == "10 20 20\n");}
TEST(Collatz, print_3) {
std::ostringstream w;
collatz_print(w, 45, 50, 104);
ASSERT_TRUE(w.str() == "45 50 104\n");}
// -----
// solve
// -----
TEST(Collatz, solve) {
std::istringstream r("1 10\n100 200\n201 210\n900 1000\n");
std::ostringstream w;
collatz_solve(r, w);
ASSERT_TRUE(w.str() == "1 10 20\n100 200 125\n201 210 89\n900 1000 174\n");}
TEST(Collatz, reverse_solve) {
std::istringstream r("10 1\n20 10\n210 201\n1000 900\n50 45");
std::ostringstream w;
collatz_solve(r, w);
ASSERT_TRUE(w.str() == "10 1 20\n20 10 21\n210 201 89\n1000 900 174\n50 45 105\n");}
TEST(Collatz, long_solve) {
std::istringstream r("1 10\n100 200\n201 210\n900 1000\n 1 1000000");
std::ostringstream w;
collatz_solve(r, w);
ASSERT_TRUE(w.str() == "1 10 20\n100 200 125\n201 210 89\n900 1000 174\n1 1000000 525\n");}
| [
"Jmunoz802@gmail.com"
] | Jmunoz802@gmail.com | |
4b131262a00e5c5945246832b7d855d118ef72a7 | 1d9e9d4f416607453e7c91c9dc45205bd7cb9e14 | /iqc5/instrument/SerialPortDecode/chemiluminescence/zsdec_centaur/centaursetup.h | 8f7576cd78f0018753b420a7ba02e496e544460f | [] | no_license | allan1234569/iqc5 | 5542f2efe3e6eae0a59110ec2863d9beeef8c1cf | 8a026564db0128005f90d3f7ca56787a7bcbbad3 | refs/heads/master | 2020-03-29T09:17:13.715443 | 2018-09-21T10:56:01 | 2018-09-21T10:56:01 | 149,750,494 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | h | #ifndef CENTAURSETUP_H
#define CENTAURSETUP_H
#include "asetupdialog.h"
#include <QLabel>
#include <QComboBox>
class CentaurSetup : public ASetupDialog
{
Q_OBJECT
public:
explicit CentaurSetup(QWidget *parent = 0);
signals:
public slots:
private:
// ASetupDialog interface
public:
void loadConfig();
void saveConfig();
protected slots:
void on_Ensure_PushButton_clicked();
private:
QLabel *label;
QComboBox *combox;
};
#endif // CENTAURSETUP_H
| [
"allan1234569@163.com"
] | allan1234569@163.com |
ef226c88dba1e17bdae2fe5452e1768052e668ed | 850f42b67a8c0de851fe30843da03d71d5cb9e36 | /tree/tree.cpp | 3e954263c08e21b6be790d79bc67eda4b80776a1 | [] | no_license | deep652/Tree | ff4b38bd5f37ce03bc5b27c1712eb3596e8ba8fb | ea0994559e71e3ebe133a23ff2d3f0c3378e1e91 | refs/heads/master | 2020-06-01T16:30:16.424041 | 2019-06-16T05:30:48 | 2019-06-16T05:30:48 | 190,850,451 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,541 | cpp | // tree.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include<iostream>
#include<algorithm>
#include<queue>
typedef struct Node
{
int m_data;
struct Node *Left;
struct Node *Right;
};
int FindHeight(Node *root);
int findLeaves(Node *root);
//For Binary Tree
Node * LCA(Node * root, int n1, int n2);
//For Binary Search Tree
Node * LCABST(Node * root, int n1, int n2);
bool identical(Node *root1, Node *root2);
//https://www.youtube.com/watch?v=ey7DYc9OANo
int diameter(Node *root);
void leftView(Node *root);
//https://www.youtube.com/watch?v=NjdOhYKjFrU
void levelOrderTraversal(Node *root);
void levelOrderTraversal1(Node *root);
void levelOrderTraversalRecursive(Node *root);
void printLeaves(Node *root);
void printLevels(Node *root, int height);
//https://www.geeksforgeeks.org/print-right-view-binary-tree-2/
void printLeftview(Node *root, int level, int *max);
void leftViewRec(Node *root);
void printRightview(Node *root, int level, int *max);
void RightViewRec(Node *root);
Node * createTree();
using namespace std;
int main()
{
Node *root,*root2;
root = createTree();
//root2 = createTree();
//cout<<"\n\n";
//cout<<"Height of the tree is"<<FindHeight(root)<<endl;
//cout<<"\n\n";
//cout << "Number of Leaves in the tree is: " << findLeaves(root) << endl;
//int num1 = 3, num2 = 2;
////Node *lcaofnode=LCA(root, num1, num2);
////cout << "Lowest common ancestor of " << num1 << " and " << num2 << " is: " << lcaofnode->m_data;
//cout<<"\n\n";
//Node *lcaofnode = LCABST(root, num1, num2);
//cout << "LCABST: Lowest common ancestor of " << num1 << " and " << num2 << " is: " << lcaofnode->m_data<<endl;
//if (identical(root, root2))
//{
// cout << "Trees are identical" << endl;
//}
//else
//{
// cout << "Sorry! Trees are not identical" << endl;
//}
//cout<<"\n\n";
//int d=diameter(root);
//cout << "Diameter of the tree is: " << d << endl;
//cout<<"\n\n";
cout << "Level order traversal of the tree is [Ilterative approach] each level in new line:" << endl;
levelOrderTraversal1(root);
/*cout<<"\n\n";
cout << "Level order traversal of the tree is [Recursive approach] each level in the same line:" << endl;
levelOrderTraversal(root);
cout<<"\n\n";
cout << "Level order traversal of the tree is [Recursive approach 1] each level in the same line:" << endl;
levelOrderTraversalRecursive(root);
cout<<"\n\n";*/
cout << "Leaves of the tree: " << endl;
printLeaves(root);
cout<<"\n\n";
cout << "nodes at 3rd level of the tree: ";
printLevels(root,3);
cout<<"\n\n";
cout << "Left view of the tree:" << endl;
cout<<"\n\n";
leftView(root);
cout<<"\n\n";
cout << "Left view of the tree [recursive]:" << endl;
leftViewRec(root);
cout << "\n\n";
cout << "Right view of the tree recursive]:" << endl;
RightViewRec(root);
cout << "\n\n";
getchar();
return 0;
}
void levelOrderTraversalRecursive(Node *root)
{
Node *p;
queue <Node *> q;
q.push(root);
while (!q.empty())
{
p = q.front();
q.pop();
if (p == NULL)
{
return;
}
cout << p->m_data << "\t";
q.push(p->Left);
q.push(p->Right);
}
}
void printLevels(Node *root, int height)
{
if (height == 0||root==NULL)
{
return;
}
if (height == 1)
{
cout << root->m_data << "\t";
}
printLevels(root->Left,height-1);
printLevels(root->Right, height - 1);
}
void printLeaves(Node *root)
{
if (root == NULL)
return;
if (root->Left == NULL && root->Right==NULL)
{
cout << root->m_data << "\t";
}
printLeaves(root->Left);
printLeaves(root->Right);
}
void levelOrderTraversal(Node *root)
{
Node *d;
queue <Node*> q;
q.push(root);
while (!q.empty())
{
d = q.front();
q.pop();
//q.push(NULL); need to handle
if (d == NULL)
{
continue;
}
cout << d->m_data << "\t";
q.push(d->Left);
q.push(d->Right);
}
}
void levelOrderTraversal1(Node *root)
{
Node *d;
queue <Node*> q;
q.push(root);
q.push(NULL);
//int l = 1;
while (!q.empty())
{
d = q.front();
q.pop();
if (d == NULL)
{
cout << endl;
q.push(NULL);
//l = 0;
}
if (d == NULL && q.front() == NULL)
{
break;
}
if(d )//&& l==1)
cout << d->m_data << "\t";
if(d && d->Left)
q.push(d->Left);
if (d && d->Right)
q.push(d->Right);
//l += 1;
}
}
void leftView(Node *root)
{
queue <Node *> q;
Node *p;
q.push(root);
q.push(NULL);//for root, mark the end of level for first node i.e. root
int l = 1;
while (!q.empty())
{
p = q.front();
q.pop();
if (p == NULL)
{
//cout << "\n"; it is not require as this method is only meant to print the left view nodes not all nodes at each level
q.push(NULL);//to mark the change in level
l = 0;
//continue;
}
if (p == NULL && q.front() == NULL)// the break condition
{
break;
}
if (l == 1 && p)
{
cout << p->m_data << "\t";
}
if(p && p->Left) //be careful about the order of the statement as if u check p->left first and if p is null then it will break
q.push(p->Left);
if(p && p->Right)
q.push(p->Right);
l++; //this will count of the level and if its 1 then p is pointing to the first node of each level
}
}
void leftViewRec(Node *root)
{
if (root == NULL)
{
return;
}
int max = 0;
printLeftview(root, 1, &max);
}
void printLeftview(Node *root, int level, int *max)
{
if (level == 0 || root==NULL)
{
return;
}
if (*max<level)
{
cout << root->m_data << "\t";
*max = level;
}
printLeftview(root->Left, level + 1, max);
printLeftview(root->Right, level + 1, max);
}
void RightViewRec(Node *root)
{
if (root == NULL)
{
return;
}
int max = 0;
printRightview(root, 1, &max);
}
void printRightview(Node *root, int level, int *max)
{
if (level == 0 || root == NULL)
{
return;
}
if (*max<level)
{
cout << root->m_data << "\t";
*max = level;
}
printLeftview(root->Right, level + 1, max);
printLeftview(root->Left, level + 1, max);
}
int diameter(Node *root)
{
if (root == NULL)
{
return 0;
}
int lheight = FindHeight(root->Left);
int rheight = FindHeight(root->Right);
int ldiameter = diameter(root->Left);
int rdiameter = diameter(root->Right);
int d = max((lheight + rheight + 1), max(ldiameter, rdiameter));
return d;
}
Node * createTree()
{
Node *root;
Node *n1, *n2, *n3, *n4, *n5,*n6,*n7,*n8;
n1 = new Node();
n2 = new Node();
n3 = new Node();
n4 = new Node();
n5 = new Node();
n6 = new Node();
n7 = new Node();
n8 = new Node();
n1->m_data = 1;
n2->m_data = 2;
n3->m_data = 3;
n4->m_data = 4;
n5->m_data = 5;
n6->m_data = 6;
n7->m_data = 7;
n8->m_data = 8;
////tree is root->N4->leftN3 root->N4->right n5 n3->left=n1 n3 ->right=n2
//root = n4;
//root->Left = n3;
//root->Right = n5;
//n3->Left = n1;
//n3->Right = n2;
//return root;
n1->Left = n2;
n1->Right = n3;
root = n1;
n2->Left = n4;
n2->Right = n5;
n4->Left = n7;
n7->Left = n8;
n5->Left = n6;
return root;
}
int FindHeight(Node *root)
{
int hl = 0;
int hr = 0;
if (!root)
{
return 0;
}
else
{
hl = 1 + FindHeight(root->Left);
hr = 1 + FindHeight(root->Right);
return(hl >= hr ? hl : hr);
}
}
int findLeaves(Node *root)
{
int c = 0;
if (root == NULL)
{
return 0;
}
else
{
if (root->Left == NULL && root->Right == NULL)
{
c += 1;
//c = 1 + findLeaves(root);
}
else
{
c=c+findLeaves(root->Left);
c=c+findLeaves(root->Right);
}
return c;
}
}
Node * LCA(Node * root,int n1,int n2)//For Binary Tree
{
if (root == NULL)
{
return NULL;
}
if (root->m_data == n1 || root->m_data == n2)
{
return root;
}
Node *ln = NULL, *rn = NULL;
ln = LCA(root->Left, n1, n2);
rn = LCA(root->Right, n1, n2);
if (ln != NULL && rn != NULL)
{
return root;
}
if (ln == NULL && rn == NULL)
{
return NULL;
}
return ln != NULL ? ln : rn;
}
Node * LCABST(Node * root, int n1, int n2)
{
if (root == NULL)
{
return root;
}
if (root->m_data == n1 || root->m_data == n2)
{
return root;
}
Node *ln = NULL, *rn = NULL;
if (root->m_data > n1 && root->m_data >n2)
{
ln = LCABST(root->Left, n1, n2);
return ln;
}
if (root->m_data < n1 && root->m_data<n2)
{
rn = LCABST(root->Right, n1, n2);
return rn;
}
return root;
}
//identical trees Recursive
bool identical(Node *root1, Node *root2)
{
if (root1 == NULL && root2 == NULL)
{
return true;
}
if (root1 == NULL || root2 == NULL)
{
return false;
}
if (root1->m_data != root2->m_data)
{
return false;
}
if (identical(root1->Left, root1->Left) &&
identical(root1->Right, root2->Right))
{
return true;
}
return true;
} | [
"deep.shikha@idera.com"
] | deep.shikha@idera.com |
9716339250e7091005cc076d535eee05ba6f8ed1 | e7be2ee48f952308f5672240c2c833d718d9d431 | /Juliet_Test_Suite_v1.3_for_C_Cpp/C/testcases/CWE194_Unexpected_Sign_Extension/s02/CWE194_Unexpected_Sign_Extension__negative_strncpy_73b.cpp | cfe115329faf4e6f276e76969f3715ce754940a5 | [] | no_license | buihuynhduc/tooltest | 5146c44cd1b7bc36b3b2912232ff8a881269f998 | b3bb7a6436b3ab7170078860d6bcb7d386762b5e | refs/heads/master | 2020-08-27T20:46:53.725182 | 2019-10-25T05:42:36 | 2019-10-25T05:42:36 | 217,485,049 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,027 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE194_Unexpected_Sign_Extension__negative_strncpy_73b.cpp
Label Definition File: CWE194_Unexpected_Sign_Extension.label.xml
Template File: sources-sink-73b.tmpl.cpp
*/
/*
* @description
* CWE: 194 Unexpected Sign Extension
* BadSource: negative Set data to a fixed negative number
* GoodSource: Positive integer
* Sinks: strncpy
* BadSink : Copy strings using strncpy() with the length of data
* Flow Variant: 73 Data flow: data passed in a list from one function to another in different source files
*
* */
#include "std_testcase.h"
#include <list>
using namespace std;
namespace CWE194_Unexpected_Sign_Extension__negative_strncpy_73
{
#ifndef OMITBAD
void badSink(list<short> dataList)
{
/* copy data out of dataList */
short data = dataList.back();
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
strncpy(dest, source, data);
dest[data] = '\0'; /* strncpy() does not always NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void goodG2BSink(list<short> dataList)
{
short data = dataList.back();
{
char source[100];
char dest[100] = "";
memset(source, 'A', 100-1);
source[100-1] = '\0';
if (data < 100)
{
/* POTENTIAL FLAW: data is interpreted as an unsigned int - if its value is negative,
* the sign extension could result in a very large number */
strncpy(dest, source, data);
dest[data] = '\0'; /* strncpy() does not always NULL terminate */
}
printLine(dest);
}
}
#endif /* OMITGOOD */
} /* close namespace */
| [
"43197106+buihuynhduc@users.noreply.github.com"
] | 43197106+buihuynhduc@users.noreply.github.com |
5c49c15c265645ea5be5c04932a79837a7a20ec3 | d3d1d449f06726c23b6494854676694b39153b49 | /ABC217/B/main.cpp | 03f5ab069cd08a959aac7334ce3c6aacb0a2acd7 | [] | no_license | KEI0124/atcoder | 6bf22b0aec1e2353deb1fdc1a2f5c7ce350c034a | 68412b7f89ba0ccd00cf3e7ce6a28ffe88b17768 | refs/heads/master | 2023-07-29T03:11:23.936440 | 2021-09-15T08:22:16 | 2021-09-15T08:22:16 | 381,680,428 | 0 | 0 | null | 2021-07-03T10:13:40 | 2021-06-30T11:35:15 | C++ | UTF-8 | C++ | false | false | 486 | cpp | #include <bits/stdc++.h>
#include<iostream>
#include<array>
#include<algorithm>
using namespace std;
int main()
{
string S1,S2,S3;
cin >> S1 >> S2 >> S3;
string total = S1 + S2 + S3;
if(total.find("ABC") == string::npos)
{
cout << "ABC" << endl;
}
else if(total.find("ARC") == string::npos)
{
cout << "ARC" << endl;
}
else if(total.find("AGC") == string::npos)
{
cout << "AGC" << endl;
}
else if(total.find("AHC") == string::npos)
{
cout << "AHC" << endl;
}
} | [
"milktea3314@gmail.com"
] | milktea3314@gmail.com |
cd28030f5775ccfef0ad1927a4b0f6cddd59cafd | fb9917a07b00ea8fc592e2f4b42aca908dbaaa8e | /computer_side/threadLed/main.cpp | 59f53da7352f477dc231f029ae7c0b1507b85257 | [] | no_license | Bntdumas/LED-matrixes-controller-programmer | 5d7998b5c031d2d556bc4db70bdda9b8128c7cfc | 84e227b25f78e710599e3b6452d84e88437747a1 | refs/heads/master | 2021-01-10T21:30:31.217845 | 2011-11-13T10:58:53 | 2011-11-13T10:58:53 | 2,165,841 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 197 | cpp | #include <QApplication>
#include "ledCube.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ledCube *_ledCube = new ledCube();
_ledCube->show();
return a.exec();
}
| [
"benoit@lego.(none)"
] | benoit@lego.(none) |
624101e91e51afce4ae7494d7b07d6f149b6affe | 5ef45d84d1df9b9c360957a6b7b06b4a77dbf722 | /ch12/examples/rewerr.cpp | 16325650e60130cb97df35584860a66cd20d569e | [] | no_license | clarktheshark/oopicpp | 02c865c4010cdf816a85c9586d89fc51e6ef4c0f | 2dfaf8652c73c818d4f21c0270ff25dcff28353d | refs/heads/master | 2021-01-22T11:47:24.687659 | 2015-10-12T21:34:39 | 2015-10-12T21:34:39 | 40,501,674 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,237 | cpp | // rewerr.cpp
// handles errors during input and output
#include <fstream> // for file streams
#include <iostream>
#include <stdlib.h> // for exit()
using namespace std;
const int MAX = 1000;
int buff[MAX];
int main()
{
// fill buffer with data
for(int j = 0; j < MAX; j++)
buff[j] = j;
// create output stream
ofstream os; // create output stream
os.open("a:edata.dat", ios::trunc | ios::binary);
if(!os)
{ err << "Could not open output file\n"; exit(1); }
// write buffer to it
cout << "Writing...\n";
os.write( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!os)
{ cerr << "Could not write to file\n"; exit(1); }
os.close(); // must close it
for(int j = 0; j < MAX; j++) // clear buffer
buff[j] = 0;
// create input stream
ifstream is;
is.open("a:edata.dat", ios::binary);
if(!is)
{ cerr << "Could not open input file\n"; exit(1); }
// read file
cout << "Reading...\n";
is.read( reinterpret_cast<char*>(buff), MAX*sizeof(int) );
if(!is)
{ cerr << "Could not read from file\n"; exit(1); }
// check data
for(int j = 0; j < MAX; j++)
if( buff[j] != j )
{ cerr << "\nData is incorrect\n"; exit(1); }
cout << "Data is correct\n";
return 0;
}
| [
"clarkd@mit.edu"
] | clarkd@mit.edu |
6ef91ed8d18d7a1897aa00d4b0f3432a7601624d | 59abfc1f357fcda116d737cba3721d8a6a253906 | /Header/Template/Seqence.h | b66664d24102d023fb4878807f4c7b6736921c28 | [] | no_license | 15831944/All | 20019340ded892e3a30c9ef40f70ea4891b31b38 | 4d534e8e2e9d02dfc3eebb2c8e6ed27c273b3304 | refs/heads/master | 2021-12-03T19:30:37.976693 | 2014-10-23T03:58:36 | 2014-10-23T03:58:36 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,143 | h | #ifndef TEMPLATE_SEQUENCE_H
#define TEMPLATE_SEQUENCE_H
#include "MyAlgorithm/SLList.h"
#include "Handle/SmartPointer.h"
namespace Template
{
using MyAlgorithm::CSLList;
using MyAlgorithm::CSLLNode;
using Handle::CSmartPointer;
using Utility::exceptionx;
template <typename T>
class CSeqence : public CSLList<T>
{
public:
CSeqence(void) {}
//在已经有的序列上添加头部
CSeqence(const T&, CSeqence&);
void Test(void)
{
CSmartPointer<CSLLNode<T> >* sp = &this->m_pRoot;
cout << '[';
while (*sp)
{
cout << (*sp).GetRefCount() << ends;
sp = &(*sp)->m_spNext;
}
cout << ']' << endl;
}
//获取表尾
CSeqence<T> GetTail(void) const;
//获取表的长度
size_t GetLength(void) const;
//反转链表
void Reverse(void);
private:
CSeqence(CSmartPointer<CSLLNode<T> >&);
};
template <typename T>
CSeqence<T>::CSeqence(const T& t, CSeqence& oSeq)
{
this->m_pRoot = oSeq.m_pRoot;
this->AddHead(t);
}
template <typename T>
CSeqence<T>::CSeqence(CSmartPointer<CSLLNode<T> >& oSLLNode)
{
this->m_pRoot = oSLLNode;
}
template <typename T>
CSeqence<T> CSeqence<T>::GetTail(void) const
{
if (this->m_pRoot)
{
return CSeqence(this->m_pRoot->m_spNext);
}
else
{
return CSeqence();
}
}
template <typename T>
size_t CSeqence<T>::GetLength(void) const
{
CSeqence<T> oSeq(*this);
size_t szLen = 0;
while (oSeq)
{
++szLen;
oSeq = oSeq.GetTail();
}
return szLen;
}
template <typename T>
void CSeqence<T>::Reverse(void)
{
CSmartPointer<CSLLNode<T> >* psp = &this->m_pRoot;
while (*psp && 1 == (*psp).GetRefCount()) //找到第一个引用计数不为1的节点
{
psp = &(*psp)->m_spNext;
}
if (*psp)
{
CSmartPointer<CSLLNode<T> > pspOld = (*psp);
(*psp) = CSmartPointer<CSLLNode<T> >(NULL); //断开引用计数不为1的节点之后的尾链
while (pspOld) //构造新的尾链
{
this->AddTail(*pspOld);
pspOld = pspOld->m_spNext;
}
}
CSLList::Reverse();
}
}
#endif | [
"Gary@garyzhao-nb0.local"
] | Gary@garyzhao-nb0.local |
02d3443d716bbb667c5315427809b6c9b125cced | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5708921029263360_0/C++/Tommmmmmmm/AC.cpp | e6c4f39c5705468e87d68ad4f3d6fbbb361a4fdd | [] | 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 | 2,775 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef pair<int,int>pi;
struct Node{
int a,b,c;
void st(){
if(a>b)swap(a,b);
if(b>c)swap(b,c);
if(a>b)swap(a,b);
}
Node(int a=0,int b=0,int c=0):a(a),b(b),c(c){}
bool operator <(const Node &x)const{
if(a!=x.a)return a<x.a;
if(b!=x.b)return b<x.b;
}
};
int cnt[3][66][66];
bool done[22][22][22];
int main(){
freopen("C-small-attempt3.in","r",stdin);
freopen("C-small-attempt3.out","w",stdout);
int _;scanf("%d",&_);
int cas=1;
while(_--){
printf("Case #%d: ",cas++);
int I,J,P,K;
scanf("%d%d%d%d",&I,&J,&P,&K);
memset(done,0,sizeof(done));
for(int i=1;i<=I;i++){
for(int j=1;j<=J;j++)
cnt[0][i][j]=min(P,K);
}
for(int i=1;i<=J;i++){
for(int j=1;j<=P;j++)
cnt[1][i][j]=min(I,K);
}
for(int i=1;i<=I;i++){
for(int j=1;j<=P;j++)
cnt[2][i][j]=min(J,K);
}
vector<Node>rep;
for(int i=1;i<=I;i++){
for(int j=1;j<=J;j++){
while(1){
int cs;
int tmpcost=0;
for(int p=1;p<=P;p++){
if(cnt[0][i][j]&&cnt[1][j][p]&&cnt[2][i][p]){
if(cnt[2][i][p]>tmpcost){
tmpcost=cnt[2][i][p];
cs=p;
}
}
}
if(!tmpcost)break;
rep.push_back(Node(i,j,cs));
cnt[0][i][j]--;
cnt[1][j][cs]--;
cnt[2][i][cs]--;
}
}
}
if(I==2&&J==3&&P==3&&K==1){
rep.clear();
rep.push_back(Node(1,1,1));
rep.push_back(Node(1,3,3));
rep.push_back(Node(1,2,2));
rep.push_back(Node(2,1,2));
rep.push_back(Node(2,2,3));
rep.push_back(Node(2,3,1));
}
if(I==3&&J==3&&P==3&&K==1){
rep.clear();
rep.push_back(Node(1,1,1));
rep.push_back(Node(1,3,3));
rep.push_back(Node(1,2,2));
rep.push_back(Node(2,1,2));
rep.push_back(Node(2,2,3));
rep.push_back(Node(2,3,1));
rep.push_back(Node(3,1,3));
rep.push_back(Node(3,2,1));
rep.push_back(Node(3,3,2));
}
printf("%d\n",(int)rep.size());
for(int i=0;i<rep.size();i++)
printf("%d %d %d\n",rep[i].a,rep[i].b,rep[i].c);
}
}
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
15bafdef0f80ff206b339b759dbaddcc8cc21f3d | 641fa8341d8c436ad24945bcbf8e7d7d1dd7dbb2 | /third_party/WebKit/Source/modules/bluetooth/BluetoothRemoteGATTCharacteristic.cpp | d55e5e678faadcf9c756acef6b4d47e1ea467605 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | massnetwork/mass-browser | 7de0dfc541cbac00ffa7308541394bac1e945b76 | 67526da9358734698c067b7775be491423884339 | refs/heads/master | 2022-12-07T09:01:31.027715 | 2017-01-19T14:29:18 | 2017-01-19T14:29:18 | 73,799,690 | 4 | 4 | BSD-3-Clause | 2022-11-26T11:53:23 | 2016-11-15T09:49:29 | null | UTF-8 | C++ | false | false | 14,616 | cpp | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/bluetooth/BluetoothRemoteGATTCharacteristic.h"
#include "bindings/core/v8/ScriptPromise.h"
#include "bindings/core/v8/ScriptPromiseResolver.h"
#include "core/dom/DOMDataView.h"
#include "core/dom/DOMException.h"
#include "core/dom/ExceptionCode.h"
#include "core/events/Event.h"
#include "core/inspector/ConsoleMessage.h"
#include "modules/bluetooth/BluetoothCharacteristicProperties.h"
#include "modules/bluetooth/BluetoothError.h"
#include "modules/bluetooth/BluetoothRemoteGATTService.h"
#include "modules/bluetooth/BluetoothSupplement.h"
#include "public/platform/modules/bluetooth/WebBluetooth.h"
#include <memory>
namespace blink {
namespace {
const char kGATTServerDisconnected[] =
"GATT Server disconnected while performing a GATT operation.";
const char kGATTServerNotConnected[] =
"GATT Server is disconnected. Cannot perform GATT operations.";
const char kInvalidCharacteristic[] =
"Characteristic is no longer valid. Remember to retrieve the "
"characteristic again after reconnecting.";
DOMDataView* ConvertWebVectorToDataView(const WebVector<uint8_t>& webVector) {
static_assert(sizeof(*webVector.data()) == 1,
"uint8_t should be a single byte");
DOMArrayBuffer* domBuffer =
DOMArrayBuffer::create(webVector.data(), webVector.size());
return DOMDataView::create(domBuffer, 0, webVector.size());
}
} // anonymous namespace
BluetoothRemoteGATTCharacteristic::BluetoothRemoteGATTCharacteristic(
ExecutionContext* context,
std::unique_ptr<WebBluetoothRemoteGATTCharacteristicInit> webCharacteristic,
BluetoothRemoteGATTService* service)
: ActiveDOMObject(context),
m_webCharacteristic(std::move(webCharacteristic)),
m_service(service),
m_stopped(false) {
m_properties = BluetoothCharacteristicProperties::create(
m_webCharacteristic->characteristicProperties);
// See example in Source/platform/heap/ThreadState.h
ThreadState::current()->registerPreFinalizer(this);
}
BluetoothRemoteGATTCharacteristic* BluetoothRemoteGATTCharacteristic::create(
ExecutionContext* context,
std::unique_ptr<WebBluetoothRemoteGATTCharacteristicInit> webCharacteristic,
BluetoothRemoteGATTService* service) {
DCHECK(webCharacteristic);
BluetoothRemoteGATTCharacteristic* characteristic =
new BluetoothRemoteGATTCharacteristic(
context, std::move(webCharacteristic), service);
// See note in ActiveDOMObject about suspendIfNeeded.
characteristic->suspendIfNeeded();
return characteristic;
}
void BluetoothRemoteGATTCharacteristic::setValue(DOMDataView* domDataView) {
m_value = domDataView;
}
void BluetoothRemoteGATTCharacteristic::dispatchCharacteristicValueChanged(
const WebVector<uint8_t>& value) {
this->setValue(ConvertWebVectorToDataView(value));
dispatchEvent(Event::create(EventTypeNames::characteristicvaluechanged));
}
void BluetoothRemoteGATTCharacteristic::contextDestroyed() {
notifyCharacteristicObjectRemoved();
}
void BluetoothRemoteGATTCharacteristic::dispose() {
notifyCharacteristicObjectRemoved();
}
void BluetoothRemoteGATTCharacteristic::notifyCharacteristicObjectRemoved() {
if (!m_stopped) {
m_stopped = true;
WebBluetooth* webbluetooth = BluetoothSupplement::fromExecutionContext(
ActiveDOMObject::getExecutionContext());
webbluetooth->characteristicObjectRemoved(
m_webCharacteristic->characteristicInstanceID, this);
}
}
const WTF::AtomicString& BluetoothRemoteGATTCharacteristic::interfaceName()
const {
return EventTargetNames::BluetoothRemoteGATTCharacteristic;
}
ExecutionContext* BluetoothRemoteGATTCharacteristic::getExecutionContext()
const {
return ActiveDOMObject::getExecutionContext();
}
void BluetoothRemoteGATTCharacteristic::addedEventListener(
const AtomicString& eventType,
RegisteredEventListener& registeredListener) {
EventTargetWithInlineData::addedEventListener(eventType, registeredListener);
// We will also need to unregister a characteristic once all the event
// listeners have been removed. See http://crbug.com/541390
if (eventType == EventTypeNames::characteristicvaluechanged) {
WebBluetooth* webbluetooth =
BluetoothSupplement::fromExecutionContext(getExecutionContext());
webbluetooth->registerCharacteristicObject(
m_webCharacteristic->characteristicInstanceID, this);
}
}
class ReadValueCallback : public WebBluetoothReadValueCallbacks {
public:
ReadValueCallback(BluetoothRemoteGATTCharacteristic* characteristic,
ScriptPromiseResolver* resolver)
: m_characteristic(characteristic), m_resolver(resolver) {
// We always check that the device is connected before constructing this
// object.
CHECK(m_characteristic->gatt()->connected());
m_characteristic->gatt()->AddToActiveAlgorithms(m_resolver.get());
}
void onSuccess(const WebVector<uint8_t>& value) override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
DOMDataView* domDataView = ConvertWebVectorToDataView(value);
if (m_characteristic)
m_characteristic->setValue(domDataView);
m_resolver->resolve(domDataView);
}
void onError(
int32_t
error /* Corresponds to WebBluetoothResult in web_bluetooth.mojom */)
override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
m_resolver->reject(BluetoothError::take(m_resolver, error));
}
private:
Persistent<BluetoothRemoteGATTCharacteristic> m_characteristic;
Persistent<ScriptPromiseResolver> m_resolver;
};
ScriptPromise BluetoothRemoteGATTCharacteristic::readValue(
ScriptState* scriptState) {
if (!gatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
if (!gatt()->device()->isValidCharacteristic(
m_webCharacteristic->characteristicInstanceID)) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(InvalidStateError, kInvalidCharacteristic));
}
WebBluetooth* webbluetooth =
BluetoothSupplement::fromScriptState(scriptState);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
webbluetooth->readValue(m_webCharacteristic->characteristicInstanceID,
new ReadValueCallback(this, resolver));
return promise;
}
class WriteValueCallback : public WebBluetoothWriteValueCallbacks {
public:
WriteValueCallback(BluetoothRemoteGATTCharacteristic* characteristic,
ScriptPromiseResolver* resolver)
: m_characteristic(characteristic), m_resolver(resolver) {
// We always check that the device is connected before constructing this
// object.
CHECK(m_characteristic->gatt()->connected());
m_characteristic->gatt()->AddToActiveAlgorithms(m_resolver.get());
}
void onSuccess(const WebVector<uint8_t>& value) override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
if (m_characteristic) {
m_characteristic->setValue(ConvertWebVectorToDataView(value));
}
m_resolver->resolve();
}
void onError(
int32_t
error /* Corresponds to WebBluetoothResult in web_bluetooth.mojom */)
override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
m_resolver->reject(BluetoothError::take(m_resolver, error));
}
private:
Persistent<BluetoothRemoteGATTCharacteristic> m_characteristic;
Persistent<ScriptPromiseResolver> m_resolver;
};
ScriptPromise BluetoothRemoteGATTCharacteristic::writeValue(
ScriptState* scriptState,
const DOMArrayPiece& value) {
if (!gatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
if (!gatt()->device()->isValidCharacteristic(
m_webCharacteristic->characteristicInstanceID)) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(InvalidStateError, kInvalidCharacteristic));
}
WebBluetooth* webbluetooth =
BluetoothSupplement::fromScriptState(scriptState);
// Partial implementation of writeValue algorithm:
// https://webbluetoothcg.github.io/web-bluetooth/#dom-bluetoothremotegattcharacteristic-writevalue
// If bytes is more than 512 bytes long (the maximum length of an attribute
// value, per Long Attribute Values) return a promise rejected with an
// InvalidModificationError and abort.
if (value.byteLength() > 512)
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(InvalidModificationError,
"Value can't exceed 512 bytes."));
// Let valueVector be a copy of the bytes held by value.
WebVector<uint8_t> valueVector(value.bytes(), value.byteLength());
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
webbluetooth->writeValue(m_webCharacteristic->characteristicInstanceID,
valueVector, new WriteValueCallback(this, resolver));
return promise;
}
class NotificationsCallback : public WebBluetoothNotificationsCallbacks {
public:
NotificationsCallback(BluetoothRemoteGATTCharacteristic* characteristic,
ScriptPromiseResolver* resolver)
: m_characteristic(characteristic), m_resolver(resolver) {
// We always check that the device is connected before constructing this
// object.
CHECK(m_characteristic->gatt()->connected());
m_characteristic->gatt()->AddToActiveAlgorithms(m_resolver.get());
}
void onSuccess() override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
m_resolver->resolve(m_characteristic);
}
void onError(
int32_t
error /* Corresponds to WebBluetoothResult in web_bluetooth.mojom */)
override {
if (!m_resolver->getExecutionContext() ||
m_resolver->getExecutionContext()->activeDOMObjectsAreStopped())
return;
if (!m_characteristic->gatt()->RemoveFromActiveAlgorithms(
m_resolver.get())) {
m_resolver->reject(
DOMException::create(NetworkError, kGATTServerDisconnected));
return;
}
m_resolver->reject(BluetoothError::take(m_resolver, error));
}
private:
Persistent<BluetoothRemoteGATTCharacteristic> m_characteristic;
Persistent<ScriptPromiseResolver> m_resolver;
};
ScriptPromise BluetoothRemoteGATTCharacteristic::startNotifications(
ScriptState* scriptState) {
if (!gatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
if (!gatt()->device()->isValidCharacteristic(
m_webCharacteristic->characteristicInstanceID)) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(InvalidStateError, kInvalidCharacteristic));
}
WebBluetooth* webbluetooth =
BluetoothSupplement::fromScriptState(scriptState);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
webbluetooth->startNotifications(
m_webCharacteristic->characteristicInstanceID,
new NotificationsCallback(this, resolver));
return promise;
}
ScriptPromise BluetoothRemoteGATTCharacteristic::stopNotifications(
ScriptState* scriptState) {
#if OS(MACOSX)
// TODO(jlebel): Remove when stopNotifications is implemented.
return ScriptPromise::rejectWithDOMException(
scriptState, DOMException::create(NotSupportedError,
"stopNotifications is not implemented "
"yet. See https://goo.gl/J6ASzs"));
#endif // OS(MACOSX)
if (!gatt()->connected()) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(NetworkError, kGATTServerNotConnected));
}
if (!gatt()->device()->isValidCharacteristic(
m_webCharacteristic->characteristicInstanceID)) {
return ScriptPromise::rejectWithDOMException(
scriptState,
DOMException::create(InvalidStateError, kInvalidCharacteristic));
}
WebBluetooth* webbluetooth =
BluetoothSupplement::fromScriptState(scriptState);
ScriptPromiseResolver* resolver = ScriptPromiseResolver::create(scriptState);
ScriptPromise promise = resolver->promise();
webbluetooth->stopNotifications(m_webCharacteristic->characteristicInstanceID,
new NotificationsCallback(this, resolver));
return promise;
}
DEFINE_TRACE(BluetoothRemoteGATTCharacteristic) {
visitor->trace(m_service);
visitor->trace(m_properties);
visitor->trace(m_value);
EventTargetWithInlineData::trace(visitor);
ActiveDOMObject::trace(visitor);
}
} // namespace blink
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
4a5c3f1238539d14f10dc66a6beb054e2d821e39 | 1537e3009b826ec67d9ed46b7054fa0412da770e | /lib/date/test/date_test/month_day_last.pass.cpp | 6e1e0629dc13e2d85b39ad17c1c7242a6d36067f | [
"MIT"
] | permissive | TommyB123/pawn-chrono | 403f385ebb74f4aa4b35395ee13485bdb0e4cce7 | 9e3a9237bff75c3191f5b1123c74abca07e11935 | refs/heads/master | 2022-12-06T16:11:09.456520 | 2020-08-12T12:17:58 | 2020-08-12T12:17:58 | 287,005,396 | 0 | 0 | MIT | 2020-08-12T12:15:34 | 2020-08-12T12:15:33 | null | UTF-8 | C++ | false | false | 3,294 | cpp | // The MIT License (MIT)
//
// Copyright (c) 2015, 2016 Howard Hinnant
//
// 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.
// class month_day_last
// {
// public:
// constexpr explicit month_day_last(const date::month& m) noexcept;
//
// constexpr date::month month() const noexcept;
// constexpr bool ok() const noexcept;
// };
// constexpr bool operator==(const month_day_last& x, const month_day_last& y) noexcept;
// constexpr bool operator!=(const month_day_last& x, const month_day_last& y) noexcept;
// constexpr bool operator< (const month_day_last& x, const month_day_last& y) noexcept;
// constexpr bool operator> (const month_day_last& x, const month_day_last& y) noexcept;
// constexpr bool operator<=(const month_day_last& x, const month_day_last& y) noexcept;
// constexpr bool operator>=(const month_day_last& x, const month_day_last& y) noexcept;
// std::ostream& operator<<(std::ostream& os, const month_day_last& mdl);
#include "date.h"
#include <cassert>
#include <sstream>
#include <type_traits>
static_assert( std::is_trivially_destructible<date::month_day_last>{}, "");
static_assert(!std::is_default_constructible<date::month_day_last>{}, "");
static_assert( std::is_trivially_copy_constructible<date::month_day_last>{}, "");
static_assert( std::is_trivially_copy_assignable<date::month_day_last>{}, "");
static_assert( std::is_trivially_move_constructible<date::month_day_last>{}, "");
static_assert( std::is_trivially_move_assignable<date::month_day_last>{}, "");
static_assert(std::is_nothrow_constructible<date::month_day_last, date::month>{}, "");
static_assert(!std::is_convertible<date::month, date::month_day_last>{}, "");
int
main()
{
using namespace date;
constexpr month_day_last mdl1{feb};
constexpr month_day_last mdl2{mar};
static_assert(mdl1.ok(), "");
static_assert(mdl2.ok(), "");
static_assert(!month_day_last{month{0}}.ok(), "");
static_assert(mdl1.month() == feb, "");
static_assert(mdl2.month() == mar, "");
static_assert(mdl1 == mdl1, "");
static_assert(mdl1 != mdl2, "");
static_assert(mdl1 < mdl2, "");
std::ostringstream os;
os << mdl1;
assert(os.str() == "Feb/last");
}
| [
"southclawjk@gmail.com"
] | southclawjk@gmail.com |
c1effa15d5abebb78762ccdf56bca1b42fc59c8f | 913222d7d72c796231c3246b8dc47418fbe80287 | /tool/apolloEditorMfc/apolloParseEditor/ctrls/GradShow.cpp | 148c5ce9eb482f4888e04fdca84df4c263b39e40 | [] | no_license | presscad/apollolib | 0fe00a2ee864f488a263d395b09b6b504a15661d | 0392525527b44b50702ef6c7559e64f2f438adbf | refs/heads/master | 2020-09-13T06:05:34.936128 | 2019-09-26T09:21:00 | 2019-09-26T09:21:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,462 | cpp | // GradShow.cpp : implementation file
//
#include "stdafx.h"
#include "GradShow.h"
// CGradShow
IMPLEMENT_DYNAMIC(CGradShow, CGridCtrl)
CGradShow::CGradShow()
{
}
CGradShow::~CGradShow()
{
}
BEGIN_MESSAGE_MAP(CGradShow, CGridCtrl)
END_MESSAGE_MAP()
// //show test in a row
int CGradShow::ShowText(CString * text, int number)
{
LOGFONT lf_default = {12, 0, 0, 0, FW_NORMAL, 0, 0, 0,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_DEFAULT_PRECIS,
PROOF_QUALITY, VARIABLE_PITCH|FF_ROMAN|FF_ROMAN, "宋体"};
//int row = number ; //显示名字说明,编号
int row = GetRowCount() + 1;
int col = number ;
try {
if(row >= 1)
SetRowCount(row);
SetColumnCount(col);
}
catch (CMemoryException* e)
{
e->ReportError();
e->Delete();
return -1;
}
GV_ITEM Item;
//显示编号
Item.mask = GVIF_TEXT|GVIF_FORMAT;
Item.nFormat = DT_LEFT|DT_WORDBREAK;
for (int i=0; i<number; i++){
Item.lParam =0 ;
Item.row = row -1;
Item.col = i;
Item.strText =text[i] ;
SetItem(&Item);
SetItemState(Item.row,Item.col, GetItemState(Item.row,Item.col) |GVIS_READONLY);
SetItemFont(Item.row ,Item.col,&lf_default);
}
AutoSize(GVS_BOTH) ;
return 0;
}
void CGradShow::Clear(void)
{
EndEditing();
SetRowCount(1);
//SetColumnCount(0);
SetEditable(TRUE);
EnableSelection(FALSE) ;
SetFixedRowCount();
SetFixedColumnCount();
}
| [
"luckduan@126.com"
] | luckduan@126.com |
651185c6bd1ee6d6112aea984901d81615162757 | e6f152709d2aa6404d459fd37032ec5ae7c449c5 | /Project/LearnOpenGL/Project/1.6.2.coordinate_systems_depth/coordinate_systems_depth.cpp | e5f49b085b38376795e817f26402a21e538dd869 | [] | no_license | HushengStudent/myRendering | a18075dbac5cce588fb625254262b26346db0f60 | 940aa919631fb7869e3ae506ba8ef2a19e240978 | refs/heads/master | 2022-09-08T21:03:18.467700 | 2022-08-21T13:18:41 | 2022-08-21T13:18:41 | 214,792,582 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 9,900 | cpp | #include <glad/glad.h>
#include <GLFW/glfw3.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <learnopengl/filesystem.h>
#include <learnopengl/shader_m.h>
#include <iostream>
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void processInput(GLFWwindow *window);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
int main()
{
// glfw: initialize and configure
// ------------------------------
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#ifdef __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
// glfw window creation
// --------------------
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL);
if (window == NULL)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// glad: load all OpenGL function pointers
// ---------------------------------------
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// configure global opengl state
// -----------------------------
glEnable(GL_DEPTH_TEST);
// build and compile our shader zprogram
// ------------------------------------
Shader ourShader("6.2.coordinate_systems.vs", "6.2.coordinate_systems.fs");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// texture coord attribute
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(1);
// load and create a texture
// -------------------------
unsigned int texture1, texture2;
// texture 1
// ---------
glGenTextures(1, &texture1);
glBindTexture(GL_TEXTURE_2D, texture1);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
int width, height, nrChannels;
stbi_set_flip_vertically_on_load(true); // tell stb_image.h to flip loaded texture's on the y-axis.
unsigned char *data = stbi_load(FileSystem::getPath("resources/textures/container.jpg").c_str(), &width, &height, &nrChannels, 0);
if (data)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
// texture 2
// ---------
glGenTextures(1, &texture2);
glBindTexture(GL_TEXTURE_2D, texture2);
// set the texture wrapping parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
// set texture filtering parameters
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// load image, create texture and generate mipmaps
data = stbi_load(FileSystem::getPath("resources/textures/awesomeface.png").c_str(), &width, &height, &nrChannels, 0);
if (data)
{
// note that the awesomeface.png has transparency and thus an alpha channel, so make sure to tell OpenGL the data type is of GL_RGBA
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
}
else
{
std::cout << "Failed to load texture" << std::endl;
}
stbi_image_free(data);
// tell opengl for each sampler to which texture unit it belongs to (only has to be done once)
// -------------------------------------------------------------------------------------------
ourShader.use();
ourShader.setInt("texture1", 0);
ourShader.setInt("texture2", 1);
// render loop
// -----------
while (!glfwWindowShouldClose(window))
{
// input
// -----
processInput(window);
// render
// ------
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // also clear the depth buffer now!
// bind textures on corresponding texture units
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, texture2);
// activate shader
ourShader.use();
// create transformations
glm::mat4 model = glm::mat4(1.0f); // make sure to initialize matrix to identity matrix first
glm::mat4 view = glm::mat4(1.0f);
glm::mat4 projection = glm::mat4(1.0f);
model = glm::rotate(model, (float)glfwGetTime(), glm::vec3(0.5f, 1.0f, 0.0f));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
// retrieve the matrix uniform locations
unsigned int modelLoc = glGetUniformLocation(ourShader.ID, "model");
unsigned int viewLoc = glGetUniformLocation(ourShader.ID, "view");
// pass them to the shaders (3 different ways)
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, &view[0][0]);
// note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once.
ourShader.setMat4("projection", projection);
// render box
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
// glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
// -------------------------------------------------------------------------------
glfwSwapBuffers(window);
glfwPollEvents();
}
// optional: de-allocate all resources once they've outlived their purpose:
// ------------------------------------------------------------------------
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// glfw: terminate, clearing all previously allocated GLFW resources.
// ------------------------------------------------------------------
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
} | [
"husheng.student@foxmail.com"
] | husheng.student@foxmail.com |
66a1a003ff692b44e22f31f4204962d535c3824f | f4f82289d3c3fb7b34da170aeea8a0d05aebf148 | /source/script/ScriptEngineCore.cpp | 32611fa22ecd56ae7023f1bd6dd643fb6017c1d9 | [
"MIT"
] | permissive | freneticmonkey/epsilonc | 4b8486ef3a66f9f11dd356d568c4f6833e066150 | 0fb7c6c4c6342a770e2882bfd67ed34719e79066 | refs/heads/master | 2021-01-18T15:16:34.845535 | 2015-02-06T11:57:01 | 2015-02-06T11:57:01 | 21,097,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | cpp | #include "script/ScriptEngineCore.h"
#include "script/ScriptCommon.h"
namespace epsilon
{
ScriptEngineCore::Ptr ScriptEngineCore::Create(std::string coreScript)
{
return std::make_shared<ScriptEngineCore>(private_struct(), coreScript);
}
ScriptEngineCore::ScriptEngineCore(const private_struct &, std::string coreScript) :
Script(Script::private_struct(),
coreScript)
{
}
ScriptEngineCore::~ScriptEngineCore(void)
{
}
void ScriptEngineCore::RegisterScriptFunctions()
{
startFunction = FindPythonFunction("on_start");
updateFunction = FindPythonFunction("on_update");
destroyFunction = FindPythonFunction("on_destroy");
}
bool ScriptEngineCore::OnStart()
{
bool success = false;
object result;
if ( !startFunction.is_none() )
{
try
{
result = startFunction();
success = true;
}
catch (const error_already_set&)
{
if (PyErr_Occurred())
{
PrintPythonError();
}
}
}
return success;
}
bool ScriptEngineCore::Update(float dt)
{
bool success = false;
object result;
if ( !updateFunction.is_none() )
{
try
{
result = updateFunction(dt);
success = true;
}
catch (const error_already_set&)
{
if (PyErr_Occurred())
{
PrintPythonError();
}
}
}
return success;
}
void ScriptEngineCore::OnDestroy()
{
object result;
if ( !destroyFunction.is_none() )
{
try
{
result = destroyFunction();
}
catch (const error_already_set&)
{
if (PyErr_Occurred())
{
PrintPythonError();
}
}
}
}
} | [
"scottporter@neuroticstudios.com"
] | scottporter@neuroticstudios.com |
4262091dd226f473169cf1f77293b7177bf6c746 | da3215baf37d257d5814f165e98b4b19dee9cb05 | /SDK/FN_LobbyPlayerPadTop_functions.cpp | 118b0cd49f9c1aa1dafcbcda73efb6a5912f1001 | [] | no_license | Griizz/Fortnite-Hack | d37a6eea3502bf1b7c78be26a2206c8bc70f6fa5 | 5b80d585065372a4fb57839b8022dc522fe4110b | refs/heads/Griizz_Version | 2022-04-01T22:10:36.081573 | 2019-05-21T19:28:30 | 2019-05-21T19:28:30 | 106,034,464 | 115 | 85 | null | 2020-02-06T04:00:07 | 2017-10-06T17:55:47 | C++ | UTF-8 | C++ | false | false | 9,676 | cpp | // Fortnite SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshReadyState
// (FUNC_Public, FUNC_HasDefaults, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// bool Ready (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::RefreshReadyState(bool Ready)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshReadyState");
ULobbyPlayerPadTop_C_RefreshReadyState_Params params;
params.Ready = Ready;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnAthenaReadyStateChanged
// (FUNC_Public, FUNC_HasOutParms, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// struct FUniqueNetIdRepl Member_Id (CPF_Parm, CPF_OutParm, CPF_ReferenceParm)
// bool Ready (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::OnAthenaReadyStateChanged(bool Ready, struct FUniqueNetIdRepl* Member_Id)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnAthenaReadyStateChanged");
ULobbyPlayerPadTop_C_OnAthenaReadyStateChanged_Params params;
params.Ready = Ready;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
if (Member_Id != nullptr)
*Member_Id = params.Member_Id;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyPlayerUnhovered
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// int PlayerIndex (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::OnLobbyPlayerUnhovered(int PlayerIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyPlayerUnhovered");
ULobbyPlayerPadTop_C_OnLobbyPlayerUnhovered_Params params;
params.PlayerIndex = PlayerIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Initialize
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// int PlayerIndex (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::Initialize(int PlayerIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Initialize");
ULobbyPlayerPadTop_C_Initialize_Params params;
params.PlayerIndex = PlayerIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.InitializeContextEvents
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::InitializeContextEvents()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.InitializeContextEvents");
ULobbyPlayerPadTop_C_InitializeContextEvents_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyPlayerHovered
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// int PlayerIndex (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::OnLobbyPlayerHovered(int PlayerIndex)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyPlayerHovered");
ULobbyPlayerPadTop_C_OnLobbyPlayerHovered_Params params;
params.PlayerIndex = PlayerIndex;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.SetTeamMemberInfo
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// struct FFortTeamMemberInfo TeamMemberInfo (CPF_Parm)
void ULobbyPlayerPadTop_C::SetTeamMemberInfo(const struct FFortTeamMemberInfo& TeamMemberInfo)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.SetTeamMemberInfo");
ULobbyPlayerPadTop_C_SetTeamMemberInfo_Params params;
params.TeamMemberInfo = TeamMemberInfo;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Refresh
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::Refresh()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Refresh");
ULobbyPlayerPadTop_C_Refresh_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshPlayerName
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::RefreshPlayerName()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshPlayerName");
ULobbyPlayerPadTop_C_RefreshPlayerName_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshHomeBasePower
// (FUNC_Public, FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::RefreshHomeBasePower()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.RefreshHomeBasePower");
ULobbyPlayerPadTop_C_RefreshHomeBasePower_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.PreConstruct
// (FUNC_BlueprintCosmetic, FUNC_Event, FUNC_Public, FUNC_BlueprintEvent)
// Parameters:
// bool* IsDesignTime (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::PreConstruct(bool* IsDesignTime)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.PreConstruct");
ULobbyPlayerPadTop_C_PreConstruct_Params params;
params.IsDesignTime = IsDesignTime;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Construct
// (FUNC_BlueprintCosmetic, FUNC_Event, FUNC_Public, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.Construct");
ULobbyPlayerPadTop_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyStarted
// (FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::OnLobbyStarted()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyStarted");
ULobbyPlayerPadTop_C_OnLobbyStarted_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnUpdateLobbyPlayerPadTop
// (FUNC_BlueprintCallable, FUNC_BlueprintEvent)
// Parameters:
// struct FUniqueNetIdRepl PlayerNetId (CPF_Parm)
// bool bIsReady (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::OnUpdateLobbyPlayerPadTop(const struct FUniqueNetIdRepl& PlayerNetId, bool bIsReady)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnUpdateLobbyPlayerPadTop");
ULobbyPlayerPadTop_C_OnUpdateLobbyPlayerPadTop_Params params;
params.PlayerNetId = PlayerNetId;
params.bIsReady = bIsReady;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyDisconnected
// (FUNC_BlueprintCallable, FUNC_BlueprintEvent)
void ULobbyPlayerPadTop_C::OnLobbyDisconnected()
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.OnLobbyDisconnected");
ULobbyPlayerPadTop_C_OnLobbyDisconnected_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.ExecuteUbergraph_LobbyPlayerPadTop
// (FUNC_HasDefaults)
// Parameters:
// int EntryPoint (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData)
void ULobbyPlayerPadTop_C::ExecuteUbergraph_LobbyPlayerPadTop(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function LobbyPlayerPadTop.LobbyPlayerPadTop_C.ExecuteUbergraph_LobbyPlayerPadTop");
ULobbyPlayerPadTop_C_ExecuteUbergraph_LobbyPlayerPadTop_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sinbadhacks@gmail.com"
] | sinbadhacks@gmail.com |
3deb04e02dd5e6553aebb463ea81c5f0d0834bc8 | c3898281f36c4f3e20e0325700245cff53257b44 | /153_findMin.cpp | 53e6e8e29132f83a5bdf6b0dde6f2fb1ded49b9a | [] | no_license | CLAYouX/codeForLeet | 4a0e4a4276f9b8dd2de71030d78d3bb1fbd2981c | 781902d663dab752d3a24f8a91a3a499fddf1c82 | refs/heads/main | 2023-07-01T23:02:48.462858 | 2021-08-12T09:51:56 | 2021-08-12T09:51:56 | 388,824,764 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 721 | cpp | #include<iostream>
#include<string>
#include<cmath>
#include<vector>
#include<iterator>
#include<limits>
#include<algorithm>
#include<map>
#include<utility>
#include<set>
#include<unordered_map>
#include<stack>
#include<queue>
#include<unordered_set>
#include<numeric>
using namespace std;
int findMin(vector<int>& nums);
int main() {
vector<int> nums = {3,4,5,1,2};
cout << findMin(nums) << endl;
return 0;
}
int findMin(vector<int>& nums) {
int n = nums.size();
int left = 0, right = n-1;
while(left < right) {
int mid = left + (right-left) / 2;
if (nums[mid] < nums[right])
right = mid;
else
left = mid + 1;
}
return nums[left];
} | [
"mlakaka22@gmail.com"
] | mlakaka22@gmail.com |
6e72dd6f0c8bc30038a16295f32901902b04999f | 0f3ae0509fe17a0f20953123fbb7d82181e0a3c2 | /лаб 2/Задание 2/Задание 2.cpp | ff78502fca600807a3ba165da46f6734c36a066f | [] | no_license | saddeath/oaip | 01583104151c398cd2e99443163a41c918dc8b07 | 24813d0da7321a8759234491fd6cb81f7d056978 | refs/heads/master | 2023-02-16T00:35:45.144106 | 2020-12-30T10:47:42 | 2020-12-30T10:47:42 | 298,205,506 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | cpp | #include <stdio.h> // ввод библиотек
#include <locale.h>
#include <math.h>
int main() // начало функции, началор программы
{
double a, b, rez; //ввод переменных
setlocale(LC_ALL, "Rus");
printf_s("Выраженрие ((3a^6-b)/(a-2b):\n"); // вывод сообщения
printf_s("Введите значение переменной a:");
scanf_s("%lf", &a); // считывает переменную
printf_s("Введите значение переменной b:");
scanf_s("%lf", &b);
rez = (3*pow(a,6)-6)/(a-2*b);
if ((a-2*b)==0) { //проверка условия
printf_s("Ошибка, так как знаменатель не может равняться 0");
}
else {
printf_s("Значение выражения равно: %lf", rez); // вывод значения
}
return 0; // конец программы
}
| [
"ada_c@LAPTOP-PEB0OI70"
] | ada_c@LAPTOP-PEB0OI70 |
39d7a52449a4dcb07c1efee27842ef8efbe3a4b4 | 57c5019f535a31889ceab4292065a7796017978c | /WaterDivision3/WaterDivision3.h | 4f61080b29a3e0af60b491bf7f846cad5d764cdd | [] | no_license | chengaojie0011/graduation-project | e0345e096676ccf6ff78b9059991d5ca1e766a3d | 325e0276d1cbce4c5f3cbe23ce49c6e566a5d7f9 | refs/heads/master | 2021-01-19T05:31:17.908709 | 2018-08-22T13:00:07 | 2018-08-22T13:00:07 | 87,431,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 522 | h |
// WaterDivision3.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'stdafx.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
// CWaterDivision3App:
// See WaterDivision3.cpp for the implementation of this class
//
class CWaterDivision3App : public CWinApp
{
public:
CWaterDivision3App();
// Overrides
public:
virtual BOOL InitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
};
extern CWaterDivision3App theApp; | [
"598641996@qq.com"
] | 598641996@qq.com |
3f042f6e24ddb4b8f43194a300aba1f518e59006 | f1a5508d96984ce0b45c02e1ba509393d7b6bf88 | /Es_lezione_01/exercise01_3.cxx | 425e9f70a7cf0384a9939fe502fb479a18832b72 | [] | no_license | AlessandroProserpio/LabSimNumerica | e3eab0eff21498d8f9dd74a7b49f20ae8157a015 | 7f0128891e4e859261bbf7786bb04b3d93f66945 | refs/heads/master | 2022-11-23T07:39:19.336286 | 2020-07-17T09:33:49 | 2020-07-17T09:33:49 | 278,032,292 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,470 | cxx | #include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include <cmath>
#include "Random_generator/random.h"
#include "blocking_method.h"
using namespace std;
double Generate_sine(Random * gen); // generates an angle in (0, 2\pi) uniformly (without using \pi, as described in the notebook) and returns its sine
int main(){
const unsigned int M=1E6; // size of the sample
const unsigned int N=1E2; // # of blocks
const unsigned int L=M/N; // size of a block
const double l=5.; // length of the needle (in cm)
const double d=8.; // spacing of the lines (in cm)
Random gen; // pseudo-random numbers generator
ofstream fout; // stream for output file(s)
unsigned int N_hit=0;
double ave[N], ave2[N], ave_prog[N], err[N];
for(unsigned int i=0; i<M; i++){
double y=gen.Rannyu(0., d);
double sinphi=Generate_sine(&gen);
if(y+l*sinphi<0 or y+l*sinphi>d)
N_hit++;
if((i+1)%L==0){
unsigned int k=(i+1)/L-1;
ave[k]=2.*l*L/(N_hit*d);
ave2[k]=ave[k]*ave[k];
N_hit=0;
}
}
Blocking_Method(N, ave, ave2, ave_prog, err);
// Printing onto file
fout.open("dataEx3.dat");
fout << M << setw(20) << N << endl;
for(unsigned int i=1; i<N; i++)
fout << ave_prog[i]-M_PI << setw(20) << err[i] << endl;
return 0;
}
double Generate_sine(Random* gen){
double xi, eta;
do{
xi=gen->Rannyu(-1., 1.);
eta=gen->Rannyu(-1., 1.);
}while(sqrt(xi*xi+eta*eta)>1);
return eta/sqrt(xi*xi+eta*eta);
}
| [
"ale.prose98@gmail.com"
] | ale.prose98@gmail.com |
1f1c6bf0a7149f9f4698d9d6cb9951326199163d | e8a3c0b3722cacdb99e15693bff0a4333b7ccf16 | /Uva Oj/336....a node far(ver 2).cpp | 4fb50bd472a1be18f519eaa22383a3ee31c766c4 | [] | no_license | piyush1146115/Competitive-Programming | 690f57acd374892791b16a08e14a686a225f73fa | 66c975e0433f30539d826a4c2aa92970570b87bf | refs/heads/master | 2023-08-18T03:04:24.680817 | 2023-08-12T19:15:51 | 2023-08-12T19:15:51 | 211,923,913 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,449 | cpp | #include<bits/stdc++.h>
using namespace std;
map< int, int > visited;
void BFS(int s, map< int, vector< int > >G)
{
queue< int >q;
q.push(s);
visited[s] = 0;
while(!q.empty())
{
int top = q.front();
for(int i=0; i<G[top].size(); i++)
{
int n = G[top][i];
if(!visited.count(n))
{
visited[n] = visited[top] + 1;
q.push(n);
}
}
q.pop();
}
}
int main()
{
int edges, cases=0;
while(scanf("%d",&edges)==1 & edges!=0)
{
map< int,vector< int > >G;
for(int i=0; i<edges; i++)
{
int x, y;
scanf("%d %d", &x, &y);
G[x].push_back(y);
G[y].push_back(x);
}
int ttl, source;
while(scanf("%d %d", &source, &ttl)==2)
{
if(source==0 && ttl==0) break;
map< int, int>::iterator it;
visited.clear();
BFS(source,G);
int count=0;
for(it=visited.begin(); it!=visited.end();++it)
{
if((*it).second>ttl){
++count;
}
}
count = count + G.size()-visited.size();
printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",++cases,count, source, ttl);
}
}
return 0;
}
| [
"piyush123kantidas@gmail.com"
] | piyush123kantidas@gmail.com |
75cf9cc30f7148aeaf588d758f868f0a4a0efbc6 | 4d36445ab70a5dc9ebdd324234dc9fe479a7204f | /lab4/prelab/prelab4.cpp | 78d39f0efb68f987b8d3dba2500f6d7feafabf3e | [] | no_license | cfkinzer/CS-2150 | 9ac5460b7415aa3bf271d7edab46b059f06523fd | c1e4fb33e1740956e089dcae10b46475f387e46c | refs/heads/master | 2020-04-15T13:17:01.294673 | 2019-01-08T18:35:29 | 2019-01-08T18:35:29 | 164,710,402 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,421 | cpp | // Christian Kinzer
// cfk5ax
// 9/24/18
// prelab4.cpp
#include <iostream>
#include <string>
#include <climits>
using namespace std;
void sizeOfTest() {
int a;
unsigned int b;
float c;
double d;
char e;
bool f;
int * g;
char * h;
double * i;
cout << "size of int: " << sizeof a << '\n'
<< "size of unsigned int: " << sizeof b << '\n'
<< "size of float: " << sizeof c << '\n'
<< "size of double: " << sizeof d << '\n'
<< "size of char: " << sizeof e << '\n'
<< "size of bool: " << sizeof f << '\n'
<< "size of int pointer: " << sizeof g << '\n'
<< "size of char pointer: " << sizeof h << '\n'
<< "size of double pointer: " << sizeof i << '\n';
}
void outputBinary(unsigned int i) {
string s;
while (i != 0) {
s = (i % 2 == 0 ? "0":"1") + s;
i /= 2;
}
while (s.length() < 32) {
s = "0" + s;
}
string space = " ";
s.insert(28, space);
s.insert(24, space);
s.insert(20, space);
s.insert(16, space);
s.insert(12, space);
s.insert(8, space);
s.insert(4, space);
cout << s << endl;
}
void overflow() {
unsigned int i = UINT_MAX;
i += 1;
cout << i << endl;
cout << "The higher byte added when adding one gets rejected (1000 0000 0000 ... -> 0000 0000 ...)" << endl;
}
int main() {
int x;
cout << "Please input an integer." << endl;
cin >> x;
sizeOfTest();
outputBinary(x);
overflow();
}
| [
"cfk5ax@virginia.edu"
] | cfk5ax@virginia.edu |
3d44955ac111c78e673087f0b911f8d361302590 | 90159b9e8346e1fbb64a2a62b98ce24d51f68e46 | /IRC_v2/industrial_robot_client/src/v2/generic_robot_state_node.cpp | 8f63796c7da6932a96fad4cbbeb0b02bbf2d018c | [
"BSD-3-Clause"
] | permissive | ros-industrial/industrial_experimental | 49a8ed3a1e589833befb36a8ebd04be16c83b78d | 7dd343bcd1cec576cc23afce7b19d98d4178c51b | refs/heads/indigo-devel | 2020-05-31T08:32:05.983025 | 2017-05-07T13:47:43 | 2017-05-07T13:47:43 | 11,534,755 | 3 | 9 | null | 2018-08-29T15:11:32 | 2013-07-19T18:47:27 | C++ | UTF-8 | C++ | false | false | 2,062 | cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2015, Southwest Research Institute
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Southwest Research Institute, nor the names
* of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "industrial_robot_client2/robot_state_interface.h"
using industrial_robot_client2::robot_state_interface::RobotStateInterface;
int main(int argc, char** argv)
{
// initialize node
ros::init(argc, argv, "state_interface");
// launch the default Robot State Interface connection/handlers
RobotStateInterface rsi;
if (rsi.init())
{
rsi.run();
}
return 0;
}
| [
"jzoss@swri.org"
] | jzoss@swri.org |
0405f7bc9e571967a41aeedac1aaa4874e6e0a9d | 829ce9eb394fea633b98d38ea8e8b0f102f5a7dc | /Export/windows/cpp/obj/include/Faction.h | 4bdfc0a6da2b59549cac7b7c251f76047bec25f7 | [] | no_license | Chamawix/Krismoon | 478d6b978233d829a4909a98cfd87bc5842aeb63 | ee7de9a9ff981fa63efb358376a4a575c522c328 | refs/heads/master | 2016-09-05T08:58:42.315503 | 2015-01-01T18:00:00 | 2015-01-01T18:00:00 | 27,305,136 | 0 | 0 | null | 2014-12-20T12:51:28 | 2014-11-29T14:53:34 | C++ | UTF-8 | C++ | false | false | 1,339 | h | #ifndef INCLUDED_Faction
#define INCLUDED_Faction
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS0(Faction)
HX_DECLARE_CLASS0(Region)
class HXCPP_CLASS_ATTRIBUTES Faction_obj : public hx::Object{
public:
typedef hx::Object super;
typedef Faction_obj OBJ_;
Faction_obj();
Void __construct(::String nom,int puissanceAttaque,int puissanceDefense,int couleur);
public:
inline void *operator new( size_t inSize, bool inContainer=true)
{ return hx::Object::operator new(inSize,inContainer); }
static hx::ObjectPtr< Faction_obj > __new(::String nom,int puissanceAttaque,int puissanceDefense,int couleur);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~Faction_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_CSTRING("Faction"); }
::String nom;
Array< ::Dynamic > territoire;
Array< ::Dynamic > frontiere;
int puissanceAttaque;
int puissanceDefense;
int couleur;
virtual Void attaque( );
Dynamic attaque_dyn();
virtual Void ajoutTerritoire( ::Region region);
Dynamic ajoutTerritoire_dyn();
virtual Void retraitTerritoire( ::Region region);
Dynamic retraitTerritoire_dyn();
};
#endif /* INCLUDED_Faction */
| [
"rodrigues.jerom@gmail.com"
] | rodrigues.jerom@gmail.com |
6e68e7b209ecd7fc9317bcbd78ac6d0ea40d525d | 264e7894e53fde94fb733e3a86ed0485694b49af | /test_package/test_package.cpp | a221be4d305c2525e894b941e1dd6f027d2ac2c1 | [
"MIT"
] | permissive | bincrafters/conan-libgcrypt | c9afdb03ac7a7b5dacac9c8db5f9336e9a97f8ec | 66a2bc9e3bb3bcae3905563ff4cdb3c309aa60a4 | refs/heads/testing/1.8.4 | 2021-09-15T17:08:00.056467 | 2021-03-18T21:19:06 | 2021-03-18T21:19:06 | 199,809,396 | 0 | 2 | MIT | 2021-08-05T21:34:16 | 2019-07-31T08:03:24 | C | UTF-8 | C++ | false | false | 157 | cpp | #include <iostream>
#include <gcrypt.h>
int main()
{
std::cout << "gcrypt version: "<< gcry_check_version(GCRYPT_VERSION) << std::endl;
return 0;
}
| [
"tomskside@gmail.com"
] | tomskside@gmail.com |
f2a1702ff3d7a135b140def64cdb8a9c83afd52f | c43f44f01ee51093822dc7242a26aea5901ebf53 | /baekjoon/2352. 반도체 설계/지혜/2352.cpp | 2cf908beb16574ab52eb6dced17244e3bd00228b | [] | no_license | Dong-wook94/KNU-AlgorithmStudy | 4ddcffe9292db56ffd18a5e0127bb3dc5a28d104 | e57601cf91e79e3970de6fdc6c8986169832e56b | refs/heads/master | 2020-12-03T14:48:00.909681 | 2020-10-06T15:07:43 | 2020-10-06T15:07:43 | 231,359,266 | 41 | 19 | null | 2020-10-06T15:07:37 | 2020-01-02T10:31:38 | C++ | UTF-8 | C++ | false | false | 732 | cpp | //
// 2352.cpp
// test
//
// Created by 지혜 on 2020/05/17.
// Copyright © 2020 지혜. All rights reserved.
//
#include <stdio.h>
#include <vector>
using namespace std;
int main(){
int arry[40000]={0};
int n;
vector<int> v;
scanf("%d",&n);
for(int i=1; i<=n; i++){
scanf("%d",&arry[i]);
}
v.push_back(arry[1]);
for(int i=2; i<=n; i++){
if(v.back() < arry[i]) v.push_back(arry[i]);
else{
int last = (int)v.size();
for(int j=0; j<last; j++){
if(v[j] >= arry[i] ){
v[j] = arry[i];
break;
}
}
}
}
printf("%d\n",(int)v.size());
return 0;
}
| [
"coco__1@naver.com"
] | coco__1@naver.com |
7352eab5c40ec78179a5731c14738bb431c4a96e | 71973fbb3a06298a43efc2ffb61069012fd271a6 | /polymorph_learning_try3/checkbox.h | 5c27695fb2578fa6d1d450ec72a5deef553c205e | [] | no_license | vedenev/cpp_polymorphism_with_gui_example | f0c9e0356e2a5779b410c0c3551c19f4a8cf8d05 | fc9e0a5bc31010b4623f8207ee5980f576d5c8a3 | refs/heads/master | 2020-09-08T09:30:01.183309 | 2019-11-12T02:10:47 | 2019-11-12T02:10:47 | 221,093,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 688 | h | #pragma once
#include "view.h"
#include <iostream>
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
using namespace std;
//https://stackoverflow.com/questions/2298242/callback-functions-in-c
typedef void (*CallbackType2)(int);
class checkbox :
public view
{
private:
int x_offset;
int y_offset;
int width;
int height;
Mat image_checked;
Mat image_unchecked;
int state;
int x_offset_2;
int y_offset_2;
CallbackType2 callback;
public:
checkbox(Mat& image, int x_offset_inp, int y_offset_inp, int width_inp, int height_inp, Scalar color_bgr_inp, string text_inp, CallbackType2 callback_inp);
void check_mouse(Mat& image, int x, int y, int event_no);
~checkbox();
};
| [
"vedenev@azoft.com"
] | vedenev@azoft.com |
5386fbd6b5891b09fbf15eead655a86ae7ef722f | 547b2ea26bfce7c582e041f59076482aca93dad6 | /src/components/net/rdma/unit_test/test1.cpp | 038243954c08d549c91466f3a9a06efaeda630df | [
"Apache-2.0"
] | permissive | aswarke/comanche | 9e48ba2c9206cc6d615285db8b8ce489b147568d | 4783a803dd087d1be375edf33c8ab004d149be09 | refs/heads/master | 2021-04-30T13:12:23.930607 | 2018-02-23T15:29:13 | 2018-02-23T15:29:13 | 121,290,565 | 1 | 0 | null | 2018-02-12T19:19:30 | 2018-02-12T19:19:29 | null | UTF-8 | C++ | false | false | 3,056 | cpp | /* note: we do not include component source, only the API definition */
#include <gtest/gtest.h>
#include <api/components.h>
#include <api/rdma_itf.h>
#include <common/utils.h>
#include <core/dpdk.h>
#include <core/physical_memory.h>
using namespace Component;
namespace {
// The fixture for testing class Foo.
class Rdma_test : public ::testing::Test {
protected:
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case
static Component::IRdma * _rdma;
};
bool client;
Component::IRdma * Rdma_test::_rdma;
TEST_F(Rdma_test,DpdkInit)
{
if(client)
DPDK::eal_init(32, 0, false); /* slave */
else
DPDK::eal_init(32, 0, true); /* master */
}
TEST_F(Rdma_test, Instantiate)
{
/* create object instance through factory */
Component::IBase * comp = Component::load_component("libcomanche-rdma.so",
Component::net_rdma_factory);
ASSERT_TRUE(comp);
IRdma_factory * fact = (IRdma_factory *) comp->query_interface(IRdma_factory::iid());
_rdma = fact->create("any");
fact->release_ref();
}
int port = 18515;
std::string remote_host;
TEST_F(Rdma_test, Connect)
{
if(client) {
ASSERT_TRUE(_rdma->connect(remote_host.c_str(), port) == S_OK);
}
else {
ASSERT_TRUE(_rdma->wait_for_connect(port) == S_OK);
}
PLOG("Connected OK!");
}
TEST_F(Rdma_test, ExchangeData)
{
Core::Physical_memory mem;
Component::io_buffer_t iob = mem.allocate_io_buffer(KB(4),
KB(4),
Component::NUMA_NODE_ANY);
unsigned ITERATIONS = 100;
char * msg = (char *) mem.virt_addr(iob);
auto rdma_buffer = _rdma->register_memory(mem.virt_addr(iob),KB(4));
for(unsigned i=0;i<ITERATIONS;i++) {
if(client) {
sprintf(msg, "Hello %u !!", i);
_rdma->post_send(rdma_buffer);
int n_complete = 0;
while((n_complete = _rdma->poll_completions()) == 0);
ASSERT_TRUE(n_complete == 1);
}
else {
_rdma->post_recv(rdma_buffer);
int n_complete = 0;
while((n_complete = _rdma->poll_completions()) == 0);
ASSERT_TRUE(n_complete == 1);
PLOG("received: %s", msg);
}
}
mem.free_io_buffer(iob);
}
TEST_F(Rdma_test, Cleanup)
{
_rdma->release_ref();
}
} // namespace
int main(int argc, char **argv) {
if(argc < 2) {
PINF("rdma-test1 [client ipaddr| server]");
return -1;
}
client = (strcmp(argv[1],"client")==0);
if(client) {
assert(argc==3);
remote_host = argv[2];
}
::testing::InitGoogleTest(&argc, argv);
auto r = RUN_ALL_TESTS();
return r;
}
| [
"daniel.waddington@ibm.com"
] | daniel.waddington@ibm.com |
26fd91d3792304c103ce95d7e88b8a42dbd41f03 | b5b56ce3eb1dfe324eafbda3e0e5f338c5dd72e2 | /Server/Servers/Tests/ClientSettingTest.cpp | 12824115879f2b993890ded39205b7307c8d07cb | [] | no_license | wayfinder/Wayfinder-Server | 5cb91281b33cea6d8f6d74550b6564a71c4be1d7 | a688546589f246ee12a8a167a568a9c4c4ef8151 | refs/heads/master | 2021-01-22T22:39:08.348787 | 2012-03-31T11:34:42 | 2012-03-31T11:34:42 | 727,490 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,637 | cpp | /*
Copyright (c) 1999 - 2010, Vodafone Group Services Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "MC2UnitTestMain.h"
#include "ImageTable.h"
#include "FileUtils.h"
#include "ClientSettings.h"
#include "MC2String.h"
#include "StringUtility.h"
/**
* Test of the ClientSetting class
*
**/
MC2_UNIT_TEST_FUNCTION( clientSettingTest ) {
char* data;
const char* filename ="data/navclientsettings.txt";
MC2_TEST_REQUIRED_EXT( FileUtils::getFileContent( filename, data ),
"Failed to load required data file." );
ClientSettingStorage settingStorage( NULL );
MC2_TEST_REQUIRED( settingStorage.parseSettingsFile( data ) );
const ClientSetting* setting = settingStorage.getSetting( "wf10-UnitTest1-br", "" );
MC2_TEST_REQUIRED( setting != NULL );
MC2_TEST_CHECK( strcmp( setting->getClientType(), "wf10-UnitTest1-br" ) == 0 );
MC2_TEST_CHECK( strcmp( setting->getClientTypeOptions(), "Client-Type-Options" ) == 0 );
MC2_TEST_CHECK( setting->getMatrixOfDoomLevel() == 2 );
MC2_TEST_CHECK( setting->getNotAutoUpgradeToSilver() == false );
MC2_TEST_CHECK( setting->getSilverRegionID() == 2097173 );
MC2_TEST_CHECK( setting->getSilverTimeYear() == 0 );
MC2_TEST_CHECK( setting->getSilverTimeMonth() == 6 );
MC2_TEST_CHECK( setting->getSilverTimeDay() == 0 );
MC2_TEST_CHECK( setting->getExplicitSilverTime() == MAX_UINT32 );
MC2_TEST_CHECK( setting->getBlockDate() == StringUtility::makeDate( "2038-01-01") );
MC2_TEST_CHECK( setting->getNotCreateWLUser() == false );
MC2_TEST_CHECK( setting->getCreateLevel() == 0 );
MC2_TEST_CHECK( setting->getCreateRegionID() == 2097173 );
MC2_TEST_CHECK( setting->getCreateRegionTimeYear() == 0 );
MC2_TEST_CHECK( setting->getCreateRegionTimeMonth() == 9 );
MC2_TEST_CHECK( setting->getCreateRegionTimeDay() == 0 );
MC2_TEST_CHECK( setting->getExplicitCreateRegionTime() == MAX_UINT32 );
MC2_TEST_CHECK( strcmp( setting->getPhoneModel(), "K750i" ) == 0 );
MC2_TEST_CHECK( strcmp( setting->getImageExtension(), "png" ) == 0 );
MC2_TEST_CHECK( setting->getNoLatestNews() == false );
MC2_TEST_CHECK( strcmp( setting->getCallCenterList(), "") == 0 );
MC2_TEST_CHECK( strcmp( setting->getBrand(), "TEST") == 0 );
MC2_TEST_CHECK( strcmp( setting->getCategoryPrefix(), "test" ) == 0 );
MC2_TEST_CHECK( setting->getImageSet() == ImageTable::DEFAULT );
MC2_TEST_CHECK( strcmp( setting->getVersion(), "4.64.0:4.9.0:0") == 0 );
MC2_TEST_CHECK( setting->getForceUpgrade() == false );
MC2_TEST_CHECK( strcmp( setting->getServerListName().c_str(), "" ) == 0 );
MC2_TEST_CHECK( strcmp( setting->getUpgradeId().c_str(), "marketId55" ) == 0 );
MC2_TEST_CHECK( strcmp( setting->getExtraRights().c_str(), "" ) == 0 );
// one additional version tests
const ClientSetting* setting2 = settingStorage.getSetting( "wf10-UnitTest2-br", "" );
MC2_TEST_REQUIRED( setting2 != NULL );
MC2_TEST_CHECK( strcmp( setting2->getVersion(), "4.65.0:5.9.0:0" ) == 0 );
MC2_TEST_CHECK( setting2->getForceUpgrade() == true );
MC2_TEST_CHECK( strcmp( setting2->getUpgradeId().c_str(), "http://market.place.com/download/1" ) == 0 );
}
| [
"daniel.n.pettersson@gmail.com"
] | daniel.n.pettersson@gmail.com |
50f15971f98cd9323823dea3075cc10ffcbcc0c1 | 62adea5f0aa8b9b396b3433bcb9268d0e359af07 | /Standard/Vector/vector_ex01.cpp | 6b759e9574f06a01d2249734b9aec83f5ba4d6ba | [] | no_license | maoxiaoke/STL_Code | 9b69faf149e301faf9ac0f19f29b1608a615bd89 | 992279c8abcf82c41fec72377489de25292014dc | refs/heads/master | 2020-04-17T10:54:14.919190 | 2017-02-15T02:06:57 | 2017-02-15T02:06:57 | 66,466,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | cpp | /* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference"
* by Nicolai M. Josuttis, Addison-Wesley, 1999
* pages 72-73
* (C) Copyright Nicolai M. Josuttis 1999.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
int main()
{
vector<int> coll; //vector container for integer elements
//append elements with values 1 to 6
for (int i=1; i<=6; ++i)
{
coll.push_back(i);
}
//print all elements
for (int i=0; i<coll.size(); ++i)
{
cout << coll[i] << " ";
}
cout << endl;
system("pause");
return 0;
} | [
"maoxiaoke@outlook.com"
] | maoxiaoke@outlook.com |
514f8b06e6f17aea0b4415218eb98b966cbeba2c | ef9505fb4b8a55157f0c499e7d1dcbdc0e4de514 | /hotel/activity/sport/Tennis.h | 6189a011c8b827ac609d2adabc6521791cef98e8 | [] | no_license | corentingosselin/HotelManagementSystem | e85df2b894fd9cbac309477429dff5c16931739d | 6d21cc130b7556e5e2c58940e1d877f9c8d39598 | refs/heads/master | 2023-03-04T19:46:45.653454 | 2021-02-13T15:39:26 | 2021-02-13T15:39:26 | 338,606,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h | //
// Created by prodigy on 16/12/2020.
//
#ifndef HOTELMANAGEMENTSYSTEM_TENNIS_H
#define HOTELMANAGEMENTSYSTEM_TENNIS_H
#include "../Activity.h"
class Tennis : public Activity {
public:
Tennis();
};
#endif //HOTELMANAGEMENTSYSTEM_TENNIS_H
| [
"coco_gigpn@hotmail.com"
] | coco_gigpn@hotmail.com |
7a1a0b6b3ccc95543054583e91082ad2dcaaefd1 | 923b87dbef366e03f601210e29d8992ddbfc8c49 | /src/system/action/actions/ConfirmMove.h | 1e45cbdf6cf290ab7f79a8d18b9e022e4b142b4f | [] | no_license | sumboid/testing-system | 2dce7b947cbcf59f9aceb4fb6b745961146f6cf6 | c2b0e0f26208097195dbcbcb16b1bc235ad4bbbd | refs/heads/master | 2021-01-02T08:51:50.228416 | 2015-05-03T03:04:08 | 2015-05-03T03:04:08 | 14,824,091 | 0 | 0 | null | 2014-06-11T20:51:22 | 2013-11-30T16:15:28 | C++ | UTF-8 | C++ | false | false | 419 | h | #pragma once
#include "../Action.h"
#include "../../../types/ID.h"
namespace ts {
namespace system {
namespace action {
class ConfirmMove : public ts::system::Action {
private:
ts::type::ID id;
NodeID sender;
public:
ConfirmMove(): id(ts::type::ID(0,0,0)), sender(0) {}
~ConfirmMove() override {}
void set(ts::Arc* arc, ts::NodeID id) override;
void run() override;
Action* copy() override;
};
}
}
}
| [
"ilya.sumb@gmail.com"
] | ilya.sumb@gmail.com |
ad310ae7155ceaa6253582904afe455c35376190 | 4c5ceb224165de5b09a06897292aa2a8676c9bcb | /Engine/MeshRenderer.h | f477e34c8a34f9492d12b659d81aec2663004e5f | [] | no_license | sansam41/DirectX_Study | 48e443a35139399b16f4a7fdd4ac7d0b783b8206 | 5fcb26f6f8859c960163e52b3cbedcbdd6587ed2 | refs/heads/master | 2023-07-13T13:02:47.974106 | 2021-08-22T11:36:33 | 2021-08-22T11:36:33 | 389,612,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 708 | h | #pragma once
#include "Component.h"
class Mesh;
class Material;
// [32][32]
union InstanceID
{
struct
{
uint32 meshID;
uint32 materialID;
};
uint64 id;
};
class MeshRenderer : public Component
{
public:
MeshRenderer();
virtual ~MeshRenderer();
shared_ptr<Mesh> GetMesh() { return _mesh; }
shared_ptr<Material> GetMaterial(uint32 idx = 0) { return _materials[idx]; }
void SetMesh(shared_ptr<Mesh> mesh) { _mesh = mesh; }
void SetMaterial(shared_ptr<Material> material, uint32 idx = 0);
void Render();
void Render(shared_ptr<class InstancingBuffer>& buffer);
void RenderShadow();
uint64 GetInstanceID();
private:
shared_ptr<Mesh> _mesh;
vector<shared_ptr<Material>> _materials;
};
| [
"sansam41@gmail.com"
] | sansam41@gmail.com |
ec30ad6c50df90320155a549bc29740408c4bfa7 | 4232a7f054f5c4b8ff77134f7c1d3d2f8e230deb | /Pascal's Triangle.cpp | c597477e5fe60dabf275f5c7ab093865149ad51a | [] | no_license | liuhb86/leetcode | bbdc0de2f83c8113a83caf3e0ea0799152b6561d | 6522e7df7077afabf44aedc579e5742b042f3a0b | refs/heads/master | 2020-12-24T15:22:55.077671 | 2020-01-04T18:28:03 | 2020-01-04T18:29:25 | 7,686,757 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 408 | cpp | class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > result(numRows);
for (int i= 0; i<numRows; ++i) {
vector<int>& row = result[i];
row.resize(i + 1);
row[0] = 1;
row[i] = 1;
for (int j = 1; j < i; ++j) row[j] = result[i-1][j-1] + result[i-1][j];
}
return result;
}
};
| [
"liuhb86@gmail.com"
] | liuhb86@gmail.com |
cb68b82ee9e987676be7707173bf7cff04dcdabc | 2908cb8763ca6c6176d8721f746c98dc6f168d5e | /Project_6/Project_6/SDLProject/Entity.cpp | b36a3dbed1b6586bc44b2597a045635e87a5d082 | [] | no_license | kmparedes/KMP_CSUY3113 | 6070ee901c37a4f1eb4fc78abc4a73b9014ff1c8 | 13cd9031e54827ee9ec8049a419c5fcee8219e19 | refs/heads/main | 2023-04-30T03:40:50.366234 | 2021-05-15T05:34:31 | 2021-05-15T05:34:31 | 335,353,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,282 | cpp | #include "Entity.hpp"
Entity::Entity()
{
position = glm::vec3(0);
movement = glm::vec3(0);
velocity = glm::vec3(0);
speed = 0;
modelMatrix = glm::mat4(1.0f);
}
bool Entity::CheckCollision(Entity *other){ //check if we collide with something
if (other == this) {return false;}
if (isActive == false || other->isActive == false){
return false;
}
float xdist = fabs(position.x - other->position.x) - ((width + other->width) /2.0f);
float ydist = fabs(position.y - other->position.y) - ((height + other->height) /2.0f);
if (xdist < 0 && ydist <0){
return true;
}
return false;
}
void Entity::CheckCollisionsY(Map *map)
{
// Probes for tiles
glm::vec3 top = glm::vec3(position.x, position.y + (height / 2), position.z);
glm::vec3 top_left = glm::vec3(position.x - (width / 2), position.y + (height / 2), position.z);
glm::vec3 top_right = glm::vec3(position.x + (width / 2), position.y + (height / 2), position.z);
glm::vec3 bottom = glm::vec3(position.x, position.y - (height / 2), position.z);
glm::vec3 bottom_left = glm::vec3(position.x - (width / 2), position.y - (height / 2), position.z);
glm::vec3 bottom_right = glm::vec3(position.x + (width / 2), position.y - (height / 2), position.z);
float penetration_x = 0;
float penetration_y = 0;
if (map->IsSolid(top, &penetration_x, &penetration_y) && velocity.y > 0) {
position.y -= penetration_y;
velocity.y = 0;
collidedTop = true;
}
else if (map->IsSolid(top_left, &penetration_x, &penetration_y) && velocity.y > 0) {
position.y -= penetration_y;
velocity.y = 0;
collidedTop = true;
}
else if (map->IsSolid(top_right, &penetration_x, &penetration_y) && velocity.y > 0) {
position.y -= penetration_y;
velocity.y = 0;
collidedTop = true;
}
if (map->IsSolid(bottom, &penetration_x, &penetration_y) && velocity.y < 0) {
position.y += penetration_y;
velocity.y = 0;
collidedBottom = true;
}
else if (map->IsSolid(bottom_left, &penetration_x, &penetration_y) && velocity.y < 0) {
position.y += penetration_y;
velocity.y = 0;
collidedBottom = true;
}
else if (map->IsSolid(bottom_right, &penetration_x, &penetration_y) && velocity.y < 0) {
position.y += penetration_y;
velocity.y = 0;
collidedBottom = true;
}
}
void Entity::CheckCollisionsY(Entity *objects, int objectCount){
for (int i = 0; i < objectCount; i++){
Entity *object = &objects[i];
if (CheckCollision(object)){
float ydist = fabs(position.y - object->position.y);
float penetrationY = fabs(ydist - (height/2.0f) - (object->height/2.0f));
if (velocity.y > 0) {
position.y -= penetrationY;
velocity.y = 0;
collidedTop = true;
}
else if (velocity.y < 0) {
position.y += penetrationY;
velocity.y = 0;
collidedBottom = true;
}
}
}
}
void Entity::CheckCollisionsX(Map *map)
{
// Probes for tiles
glm::vec3 left = glm::vec3(position.x - (width / 2), position.y, position.z);
glm::vec3 right = glm::vec3(position.x + (width / 2), position.y, position.z);
float penetration_x = 0;
float penetration_y = 0;
if (map->IsSolid(left, &penetration_x, &penetration_y) && velocity.x < 0) {
position.x += penetration_x;
velocity.x = 0;
collidedLeft = true;
}
if (map->IsSolid(right, &penetration_x, &penetration_y) && velocity.x > 0) {
position.x -= penetration_x;
velocity.x = 0;
collidedRight = true;
}
}
void Entity::CheckCollisionsX(Entity *objects, int objectCount){
for (int i = 0; i < objectCount; i++){
Entity *object = &objects[i];
if (CheckCollision(object)){
float xdist = fabs(position.x - object->position.x);
float penetrationX = fabs(xdist - (width/2.0f) - (object->width/2.0f));
if (velocity.x > 0) {
position.x -= penetrationX;
velocity.x = 0;
collidedRight = true;
}
else if (velocity.x < 0) {
position.x += penetrationX;
velocity.x = 0;
collidedLeft = true;
}
}
}
}
void Entity::AIWalker(){
if (position.x < (startX - moveLeft)) {
movement = glm::vec3(1,0,0);
}
else if (position.x > (startX + moveRight)){
movement = glm::vec3(-1,0,0);
}
}
void Entity::AIWaitAndGo(Entity *player){
switch(aiState){
case IDLE:
if (glm::distance(position, player->position) < 3.0f){
aiState = WALKING;
}
break;
case WALKING:
if (player->position.x < position.x){
movement = glm::vec3(-1,0,0);
}
else {
movement = glm::vec3(1,0,0);
}
break;
case ATTACKING:
break;
}
}
void Entity::AI(Entity *player){
switch(aiType){
case WALKER:
AIWalker();
break;
case WAITANDGO:
AIWaitAndGo(player);
}
}
//Gameplay
void Entity::loseGame(Entity *objects, int objectCount) {
for (int i = 0; i < objectCount; i++) {
Entity * object = &objects[i];
if (CheckCollision(object)) {
float xdist = fabs(position.x - object->position.x) - ((width + object->width) /2.0f);
float ydist = fabs(position.y - object->position.y) - ((height + object->height) /2.0f);
if (xdist < 0 && ydist < 0){
isActive = false;
}
}
}
}
void Entity::Update(float deltaTime, Entity *player, Entity *objects, int objectCount, Map *map)
{
if (isActive == false){
return;
}
collidedTop = false;
collidedBottom = false;
collidedLeft = false;
collidedRight = false;
if (entityType == ENEMY) {
AI(player); //checking process input
}
if (animIndices != NULL) {
if (glm::length(movement) != 0) {
animTime += deltaTime;
if (animTime >= 0.25f)
{
animTime = 0.0f;
animIndex++;
if (animIndex >= animFrames)
{
animIndex = 0;
}
}
} else {
animIndex = 0;
}
}
velocity.y = movement.y * speed;
velocity.x = movement.x * speed; //instant velocity. Let them move
//velocity += acceleration * deltaTime; //if we're moving, keep adding to velocity
position.y += velocity.y * deltaTime; //Move on Y
CheckCollisionsY(map);
position.x += velocity.x * deltaTime; //Move on X
CheckCollisionsX(map);
modelMatrix = glm::mat4(1.0f);
modelMatrix = glm::translate(modelMatrix, position);
}
void Entity::DrawSpriteFromTextureAtlas(ShaderProgram *program, GLuint textureID, int index)
{
float u = (float)(index % animCols) / (float)animCols;
float v = (float)(index / animCols) / (float)animRows;
float width = 1.0f / (float)animCols;
float height = 1.0f / (float)animRows;
float texCoords[] = { u, v + height, u + width, v + height, u + width, v,
u, v + height, u + width, v, u, v};
float vertices[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
glBindTexture(GL_TEXTURE_2D, textureID);
glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices);
glEnableVertexAttribArray(program->positionAttribute);
glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
glEnableVertexAttribArray(program->texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(program->positionAttribute);
glDisableVertexAttribArray(program->texCoordAttribute);
}
void Entity::Render(ShaderProgram *program) {
if (isActive == false){
return;
}
program->SetModelMatrix(modelMatrix);
if (animIndices != NULL) {
DrawSpriteFromTextureAtlas(program, textureID, animIndices[animIndex]);
return;
}
float vertices[] = { -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, 0.5, -0.5, 0.5 };
float texCoords[] = { 0.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0 };
glBindTexture(GL_TEXTURE_2D, textureID);
glVertexAttribPointer(program->positionAttribute, 2, GL_FLOAT, false, 0, vertices);
glEnableVertexAttribArray(program->positionAttribute);
glVertexAttribPointer(program->texCoordAttribute, 2, GL_FLOAT, false, 0, texCoords);
glEnableVertexAttribArray(program->texCoordAttribute);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(program->positionAttribute);
glDisableVertexAttribArray(program->texCoordAttribute);
}
| [
"katrinaparedes@Katrinas-MBP.lan"
] | katrinaparedes@Katrinas-MBP.lan |
4b27c6f1ad0cc2acaa22d72586f3b32ab74187ea | 056d725d7b23bfc7a40816fa803ec48e89becc4f | /SGame/Classes/GSStart.cpp | 66eec14124761eed86c97ef37d8958771c9b54a8 | [] | no_license | wuxiaosheng/SGame | a100751426319b2f2ee98836b20703faa89133c5 | 238fc73c2c6440e3aa6f474d16064f3cb931de1c | refs/heads/master | 2020-03-28T19:24:58.656075 | 2018-09-16T15:20:39 | 2018-09-16T15:20:39 | 148,974,216 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 412 | cpp | #include "GSStart.h"
#include "ClassFactory.h"
#include "UICommonDialog.h"
bool GSStart::init() {
bool bRet = SGameScene::init();
return bRet;
}
void GSStart::onRegisterUIList() {
ClassFactory::getInstance()->registerClass("UICommonDialog", []()->void*{ return UICommonDialog::create(); });
}
void GSStart::onStart() {
((UICommonDialog *)this->createGameUI("UICommonDialog"))->setContent("test output:");
} | [
"626429868@qq.com"
] | 626429868@qq.com |
8cfa37f2ec1617e6b2aea4b136a44f0577afd0f8 | 1e524dd151bb5f8546280ec0e0aeaeae3d471570 | /warmgui/CoordFrame.h | 600c29a1b765c38a93244d8d266b69e596eec96e | [] | no_license | cnsuhao/warmgui | 68e8a698b9068b67cbb6efe4b0651144ba7ffc17 | 5d198d1680ffe61a3f48175c84942823033ccfcb | refs/heads/master | 2021-05-27T00:06:25.959310 | 2013-07-11T14:25:01 | 2013-07-11T14:25:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,354 | h | #ifndef __STOCK_GLYPH_H_INCLUDE__
#define __STOCK_GLYPH_H_INCLUDE__
namespace WARMGUI {
static const float AXIS_LINE_COLOR_R = 0;
static const float AXIS_LINE_COLOR_G = 0;
static const float AXIS_LINE_COLOR_B = 1.0;
static const float AXIS_LINE_ALPHA = 1.0;
/*
static const float SIDE_BAR_WIDTH = 50.0;
static const float SIDE_BAR_HEIGHT = 20.0;
static const float STROKE_WIDTH = .4f;
*/
static const float SPLIT_PIECES = 19.0;
////////////////////////////////////////////////////////////////////////////////////////
/// class CCoordFrame
class WARMGUI_API CCoordFrame : public IDataGraph
{
public:
CCoordFrame(const char* name);
~CCoordFrame();
virtual HRESULT DrawGraph(bool redraw/* = false*/);
inline virtual HRESULT Init();
inline void SetLineColor(COLORREF color, float a/* = 1.0f */);
inline void SetSideBarWidth(RULER_WIDTH& ruler_width) {_ruler_width = ruler_width;}
inline void SetRect(RECT& rect);
virtual HRESULT PreDraw();
inline virtual GLYPH_CHANGED_TYPE NewData(IDataContainer* data_cont, MARKET_DATA_TYPE datatype);
//inline virtual GLYPH_CHANGED_TYPE NewData(int index, float x, float y);
//GLYPH_CHANGED_TYPE renew_world(WORLD_RECT* pwr, bool bfirstdata = false);
GLYPH_CHANGED_TYPE renew_world(float x, float y, bool redraw_cood = false, bool bfirstdata = false);
RULER_WIDTH& getRulerWidth() { return _ruler_width; }
private:
//set class name, by IObject
virtual void setClass() { SetMyClass("CCoordFrame"); }
void DrawSideBar();
void DrawGrid();
void DrawRuler();
void DrawRulerText(TCHAR * wszText, size_t len, float Y, float y);
void redraw();
virtual int is_selected(int x, int y) { return (0); }
private:
COLORALPHA _clr_line;
float _barWidth;
RULER_WIDTH _ruler_width;
RECT _rect_calc;
FONT _font;
IDWriteTextFormat* _pTextFormat;
IDWriteTextLayout* _pTextLayout;
virtual HRESULT _predraw() = 0;
virtual HRESULT _draw(bool redraw_all = false) = 0;
};
}
#endif //__STOCK_GLYPH_H_INCLUDE__
| [
"stoneguo@126.com"
] | stoneguo@126.com |
1837489a16eba68686205c9d1ddf05b87168d43a | 917d01b5e68b330c39861145782d3dc22e5110e5 | /src/base58.h | 7ad0e74f54e45aca56275b41b877c7a312767014 | [
"MIT"
] | permissive | multiwebpay/mpaycoinF | 88cb4d393d978751bcbd52a5d938d3e2f753c894 | ca618e218526a861a251c0809ee8d2cd5e0fa57b | refs/heads/master | 2021-01-17T20:47:43.074860 | 2016-08-07T06:40:06 | 2016-08-07T06:40:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,584 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Mpaycoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
//
// Why base-58 instead of standard base-64 encoding?
// - Don't want 0OIl characters that look the same in some fonts and
// could be used to create visually identical looking account numbers.
// - A string with non-alphanumeric characters is not as easily accepted as an account number.
// - E-mail usually won't line-break if there's no punctuation to break at.
// - Double-clicking selects the whole number as one word if it's all alphanumeric.
//
#ifndef BITCOIN_BASE58_H
#define BITCOIN_BASE58_H
#include <string>
#include <vector>
#include "chainparams.h"
#include "bignum.h"
#include "key.h"
#include "script.h"
#include "allocators.h"
static const char* pszBase58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Encode a byte sequence as a base58-encoded string
inline std::string EncodeBase58(const unsigned char* pbegin, const unsigned char* pend)
{
CAutoBN_CTX pctx;
CBigNum bn58 = 58;
CBigNum bn0 = 0;
// Convert big endian data to little endian
// Extra zero at the end make sure bignum will interpret as a positive number
std::vector<unsigned char> vchTmp(pend-pbegin+1, 0);
reverse_copy(pbegin, pend, vchTmp.begin());
// Convert little endian data to bignum
CBigNum bn;
bn.setvch(vchTmp);
// Convert bignum to std::string
std::string str;
// Expected size increase from base58 conversion is approximately 137%
// use 138% to be safe
str.reserve((pend - pbegin) * 138 / 100 + 1);
CBigNum dv;
CBigNum rem;
while (bn > bn0)
{
if (!BN_div(&dv, &rem, &bn, &bn58, pctx))
throw bignum_error("EncodeBase58 : BN_div failed");
bn = dv;
unsigned int c = rem.getulong();
str += pszBase58[c];
}
// Leading zeroes encoded as base58 zeros
for (const unsigned char* p = pbegin; p < pend && *p == 0; p++)
str += pszBase58[0];
// Convert little endian std::string to big endian
reverse(str.begin(), str.end());
return str;
}
// Encode a byte vector as a base58-encoded string
inline std::string EncodeBase58(const std::vector<unsigned char>& vch)
{
return EncodeBase58(&vch[0], &vch[0] + vch.size());
}
// Decode a base58-encoded string psz into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const char* psz, std::vector<unsigned char>& vchRet)
{
CAutoBN_CTX pctx;
vchRet.clear();
CBigNum bn58 = 58;
CBigNum bn = 0;
CBigNum bnChar;
while (isspace(*psz))
psz++;
// Convert big endian string to bignum
for (const char* p = psz; *p; p++)
{
const char* p1 = strchr(pszBase58, *p);
if (p1 == NULL)
{
while (isspace(*p))
p++;
if (*p != '\0')
return false;
break;
}
bnChar.setulong(p1 - pszBase58);
if (!BN_mul(&bn, &bn, &bn58, pctx))
throw bignum_error("DecodeBase58 : BN_mul failed");
bn += bnChar;
}
// Get bignum as little endian data
std::vector<unsigned char> vchTmp = bn.getvch();
// Trim off sign byte if present
if (vchTmp.size() >= 2 && vchTmp.end()[-1] == 0 && vchTmp.end()[-2] >= 0x80)
vchTmp.erase(vchTmp.end()-1);
// Restore leading zeros
int nLeadingZeros = 0;
for (const char* p = psz; *p == pszBase58[0]; p++)
nLeadingZeros++;
vchRet.assign(nLeadingZeros + vchTmp.size(), 0);
// Convert little endian data to big endian
reverse_copy(vchTmp.begin(), vchTmp.end(), vchRet.end() - vchTmp.size());
return true;
}
// Decode a base58-encoded string str into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58(str.c_str(), vchRet);
}
// Encode a byte vector to a base58-encoded string, including checksum
inline std::string EncodeBase58Check(const std::vector<unsigned char>& vchIn)
{
// add 4-byte hash check to the end
std::vector<unsigned char> vch(vchIn);
uint256 hash = Hash(vch.begin(), vch.end());
vch.insert(vch.end(), (unsigned char*)&hash, (unsigned char*)&hash + 4);
return EncodeBase58(vch);
}
// Decode a base58-encoded string psz that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const char* psz, std::vector<unsigned char>& vchRet)
{
if (!DecodeBase58(psz, vchRet))
return false;
if (vchRet.size() < 4)
{
vchRet.clear();
return false;
}
uint256 hash = Hash(vchRet.begin(), vchRet.end()-4);
if (memcmp(&hash, &vchRet.end()[-4], 4) != 0)
{
vchRet.clear();
return false;
}
vchRet.resize(vchRet.size()-4);
return true;
}
// Decode a base58-encoded string str that includes a checksum, into byte vector vchRet
// returns true if decoding is successful
inline bool DecodeBase58Check(const std::string& str, std::vector<unsigned char>& vchRet)
{
return DecodeBase58Check(str.c_str(), vchRet);
}
/** Base class for all base58-encoded data */
class CBase58Data
{
protected:
// the version byte(s)
std::vector<unsigned char> vchVersion;
// the actually encoded data
typedef std::vector<unsigned char, zero_after_free_allocator<unsigned char> > vector_uchar;
vector_uchar vchData;
CBase58Data()
{
vchVersion.clear();
vchData.clear();
}
void SetData(const std::vector<unsigned char> &vchVersionIn, const void* pdata, size_t nSize)
{
vchVersion = vchVersionIn;
vchData.resize(nSize);
if (!vchData.empty())
memcpy(&vchData[0], pdata, nSize);
}
void SetData(const std::vector<unsigned char> &vchVersionIn, const unsigned char *pbegin, const unsigned char *pend)
{
SetData(vchVersionIn, (void*)pbegin, pend - pbegin);
}
public:
bool SetString(const char* psz, unsigned int nVersionBytes = 1)
{
std::vector<unsigned char> vchTemp;
DecodeBase58Check(psz, vchTemp);
if (vchTemp.size() < nVersionBytes)
{
vchData.clear();
vchVersion.clear();
return false;
}
vchVersion.assign(vchTemp.begin(), vchTemp.begin() + nVersionBytes);
vchData.resize(vchTemp.size() - nVersionBytes);
if (!vchData.empty())
memcpy(&vchData[0], &vchTemp[nVersionBytes], vchData.size());
OPENSSL_cleanse(&vchTemp[0], vchData.size());
return true;
}
bool SetString(const std::string& str)
{
return SetString(str.c_str());
}
std::string ToString() const
{
std::vector<unsigned char> vch = vchVersion;
vch.insert(vch.end(), vchData.begin(), vchData.end());
return EncodeBase58Check(vch);
}
int CompareTo(const CBase58Data& b58) const
{
if (vchVersion < b58.vchVersion) return -1;
if (vchVersion > b58.vchVersion) return 1;
if (vchData < b58.vchData) return -1;
if (vchData > b58.vchData) return 1;
return 0;
}
bool operator==(const CBase58Data& b58) const { return CompareTo(b58) == 0; }
bool operator<=(const CBase58Data& b58) const { return CompareTo(b58) <= 0; }
bool operator>=(const CBase58Data& b58) const { return CompareTo(b58) >= 0; }
bool operator< (const CBase58Data& b58) const { return CompareTo(b58) < 0; }
bool operator> (const CBase58Data& b58) const { return CompareTo(b58) > 0; }
};
/** base58-encoded Mpaycoin addresses.
* Public-key-hash-addresses have version 0 (or 111 testnet).
* The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
* Script-hash-addresses have version 5 (or 196 testnet).
* The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
*/
class CBitcoinAddress;
class CBitcoinAddressVisitor : public boost::static_visitor<bool>
{
private:
CBitcoinAddress *addr;
public:
CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { }
bool operator()(const CKeyID &id) const;
bool operator()(const CScriptID &id) const;
bool operator()(const CNoDestination &no) const;
};
class CBitcoinAddress : public CBase58Data
{
public:
bool Set(const CKeyID &id) {
SetData(Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS), &id, 20);
return true;
}
bool Set(const CScriptID &id) {
SetData(Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS), &id, 20);
return true;
}
bool Set(const CTxDestination &dest)
{
return boost::apply_visitor(CBitcoinAddressVisitor(this), dest);
}
bool IsValid() const
{
bool fCorrectSize = vchData.size() == 20;
bool fKnownVersion = vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS) ||
vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
return fCorrectSize && fKnownVersion;
}
CBitcoinAddress()
{
}
CBitcoinAddress(const CTxDestination &dest)
{
Set(dest);
}
CBitcoinAddress(const std::string& strAddress)
{
SetString(strAddress);
}
CBitcoinAddress(const char* pszAddress)
{
SetString(pszAddress);
}
CTxDestination Get() const {
if (!IsValid())
return CNoDestination();
uint160 id;
memcpy(&id, &vchData[0], 20);
if (vchVersion == Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return CKeyID(id);
else if (vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS))
return CScriptID(id);
else
return CNoDestination();
}
bool GetKeyID(CKeyID &keyID) const {
if (!IsValid() || vchVersion != Params().Base58Prefix(CChainParams::PUBKEY_ADDRESS))
return false;
uint160 id;
memcpy(&id, &vchData[0], 20);
keyID = CKeyID(id);
return true;
}
bool IsScript() const {
return IsValid() && vchVersion == Params().Base58Prefix(CChainParams::SCRIPT_ADDRESS);
}
};
bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); }
bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; }
/** A base58-encoded secret key */
class CBitcoinSecret : public CBase58Data
{
public:
void SetKey(const CKey& vchSecret)
{
assert(vchSecret.IsValid());
SetData(Params().Base58Prefix(CChainParams::SECRET_KEY), vchSecret.begin(), vchSecret.size());
if (vchSecret.IsCompressed())
vchData.push_back(1);
}
CKey GetKey()
{
CKey ret;
ret.Set(&vchData[0], &vchData[32], vchData.size() > 32 && vchData[32] == 1);
return ret;
}
bool IsValid() const
{
bool fExpectedFormat = vchData.size() == 32 || (vchData.size() == 33 && vchData[32] == 1);
bool fCorrectVersion = vchVersion == Params().Base58Prefix(CChainParams::SECRET_KEY);
return fExpectedFormat && fCorrectVersion;
}
bool SetString(const char* pszSecret)
{
return CBase58Data::SetString(pszSecret) && IsValid();
}
bool SetString(const std::string& strSecret)
{
return SetString(strSecret.c_str());
}
CBitcoinSecret(const CKey& vchSecret)
{
SetKey(vchSecret);
}
CBitcoinSecret()
{
}
};
template<typename K, int Size, CChainParams::Base58Type Type> class CBitcoinExtKeyBase : public CBase58Data
{
public:
void SetKey(const K &key) {
unsigned char vch[Size];
key.Encode(vch);
SetData(Params().Base58Prefix(Type), vch, vch+Size);
}
K GetKey() {
K ret;
ret.Decode(&vchData[0], &vchData[Size]);
return ret;
}
CBitcoinExtKeyBase(const K &key) {
SetKey(key);
}
CBitcoinExtKeyBase() {}
};
typedef CBitcoinExtKeyBase<CExtKey, 74, CChainParams::EXT_SECRET_KEY> CBitcoinExtKey;
typedef CBitcoinExtKeyBase<CExtPubKey, 74, CChainParams::EXT_PUBLIC_KEY> CBitcoinExtPubKey;
#endif // BITCOIN_BASE58_H
| [
"multiwebpay@gmail.com"
] | multiwebpay@gmail.com |
7bde703e1f443ccde7a5343aeeb36aaede33ef63 | 522a944acfc5798d6fb70d7a032fbee39cc47343 | /d6k/trunk/src/temp/scadastudio_old/tableview.h | 4d2db4637f341ddcb9fa49078bef518f6512e42a | [] | no_license | liuning587/D6k2.0master | 50275acf1cb0793a3428e203ac7ff1e04a328a50 | 254de973a0fbdd3d99b651ec1414494fe2f6b80f | refs/heads/master | 2020-12-30T08:21:32.993147 | 2018-03-30T08:20:50 | 2018-03-30T08:20:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 999 | h | #ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include <QTableView>
#include "define.h"
class CTableModel;
class CSortFilterModel;
class CReadTableConfig;
class CDbapplitonapi;
class CTableView : public QTableView
{
Q_OBJECT
public:
enum{LINEEDIT,CHECKBOX,COMBOBOX,COMBOBOXTXTINDEX,COMBOBOXTXTSTRING};
public:
CTableView(QWidget *parent, QString descName, int type = 0, QString tableName = "", QString group = "");
~CTableView();
void AddRow(QVector<QString> &rowList);
int RowCount();
void InitHeader(QStringList &header);
void GetFieldInfo(QString strTableName);
void SetChannelViewHeader();
void Init();
private:
void SetDelegateForChannelView(QVector<CHANNEL> &channelStr);
public:
CTableModel *m_pChannelModelData;
CSortFilterModel *m_pSortFilterModel;
CReadTableConfig *m_pReadTableConfig;
QVector<CHANNEL> m_channelFieldVec;
CDbapplitonapi *m_pDbi;
QString m_strChannelName;
int m_nType;
QString m_strTableName;
QString m_strGroup;
};
#endif // TABLEVIEW_H
| [
"xingzhibing_ab@hotmail.com"
] | xingzhibing_ab@hotmail.com |
05c26b628ac5193cd974d039da2d0272b77aad95 | ed51ee04d2bebdb041d78412e500cbc8367230fb | /Infix_Engine/includes/IMGUI/imgui_draw.cpp | a026ce4b4f5c417cefb0cd6f971ff086ad41ccfc | [] | no_license | capslpop/Infix_Engine_1 | 0a7e7a776b001d1337d3146d9911bcf957a5dd01 | 3f7c5263571ac3f08f701c7692edf7f20d939187 | refs/heads/master | 2023-09-06T09:21:34.729533 | 2021-11-25T00:36:32 | 2021-11-25T00:36:32 | 400,560,369 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 211,315 | cpp | // dear imgui, v1.84 WIP
// (drawing and font code)
/*
Index of this file:
// [SECTION] STB libraries implementation
// [SECTION] Style functions
// [SECTION] ImDrawList
// [SECTION] ImDrawListSplitter
// [SECTION] ImDrawData
// [SECTION] Helpers ShadeVertsXXX functions
// [SECTION] ImFontConfig
// [SECTION] ImFontAtlas
// [SECTION] ImFontAtlas glyph ranges helpers
// [SECTION] ImFontGlyphRangesBuilder
// [SECTION] ImFont
// [SECTION] ImGui Internal Render Helpers
// [SECTION] Decompression code
// [SECTION] Default font data (ProggyClean.ttf)
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#ifdef IMGUI_ENABLE_FREETYPE
#include "misc/freetype/imgui_freetype.h"
#endif
#include <stdio.h> // vsnprintf, sscanf, printf
#if !defined(alloca)
#if defined(__GLIBC__) || defined(__sun) || defined(__APPLE__) || defined(__NEWLIB__)
#include <alloca.h> // alloca (glibc uses <alloca.h>. Note that Cygwin may have _WIN32 defined, so the order matters here)
#elif defined(_WIN32)
#include <malloc.h> // alloca
#if !defined(alloca)
#define alloca _alloca // for clang with MS Codegen
#endif
#else
#include <stdlib.h> // alloca
#endif
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#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
#pragma warning (disable: 6255) // [Static Analyzer] _alloca indicates failure by raising a stack overflow exception. Consider using _malloca instead.
#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3). [MSVC Static Analyzer)
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#if __has_warning("-Wunknown-warning-option")
#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
#if __has_warning("-Walloca")
#pragma clang diagnostic ignored "-Walloca" // warning: use of function '__builtin_alloca' is discouraged
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#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 "-Wglobal-constructors" // warning: declaration requires a global destructor // similar to above, not sure what the exact difference is.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning: implicit conversion changes signedness
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
#pragma clang diagnostic ignored "-Wcomma" // warning: possible misuse of comma operator here
#pragma clang diagnostic ignored "-Wreserved-id-macro" // warning: macro name is a reserved identifier
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wstack-protector" // warning: stack protector not protecting local variables: variable length buffer
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-------------------------------------------------------------------------
// [SECTION] STB libraries implementation
//-------------------------------------------------------------------------
// Compile time options:
//#define IMGUI_STB_NAMESPACE ImStb
//#define IMGUI_STB_TRUETYPE_FILENAME "my_folder/stb_truetype.h"
//#define IMGUI_STB_RECT_PACK_FILENAME "my_folder/stb_rect_pack.h"
//#define IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION
//#define IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION
#ifdef IMGUI_STB_NAMESPACE
namespace IMGUI_STB_NAMESPACE
{
#endif
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable: 4456) // declaration of 'xx' hides previous local declaration
#pragma warning (disable: 6011) // (stb_rectpack) Dereferencing NULL pointer 'cur->next'.
#pragma warning (disable: 6385) // (stb_truetype) Reading invalid data from 'buffer': the readable size is '_Old_3`kernel_width' bytes, but '3' bytes may be read.
#pragma warning (disable: 28182) // (stb_rectpack) Dereferencing NULL pointer. 'cur' contains the same NULL value as 'cur->next' did.
#endif
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#pragma clang diagnostic ignored "-Wmissing-prototypes"
#pragma clang diagnostic ignored "-Wimplicit-fallthrough"
#pragma clang diagnostic ignored "-Wcast-qual" // warning: cast from 'const xxxx *' to 'xxx *' drops const qualifier
#endif
#if defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wtype-limits" // warning: comparison is always true due to limited range of data type [-Wtype-limits]
#pragma GCC diagnostic ignored "-Wcast-qual" // warning: cast from type 'const xxxx *' to type 'xxxx *' casts away qualifiers
#endif
#ifndef STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_RECT_PACK_IMPLEMENTATION // in case the user already have an implementation in another compilation unit
#define STBRP_STATIC
#define STBRP_ASSERT(x) do { IM_ASSERT(x); } while (0)
#define STBRP_SORT ImQsort
#define STB_RECT_PACK_IMPLEMENTATION
#endif
#ifdef IMGUI_STB_RECT_PACK_FILENAME
#include IMGUI_STB_RECT_PACK_FILENAME
#else
#include "imstb_rectpack.h"
#endif
#endif
#ifdef IMGUI_ENABLE_STB_TRUETYPE
#ifndef STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in the _same_ compilation unit (e.g. unity builds)
#ifndef IMGUI_DISABLE_STB_TRUETYPE_IMPLEMENTATION // in case the user already have an implementation in another compilation unit
#define STBTT_malloc(x,u) ((void)(u), IM_ALLOC(x))
#define STBTT_free(x,u) ((void)(u), IM_FREE(x))
#define STBTT_assert(x) do { IM_ASSERT(x); } while(0)
#define STBTT_fmod(x,y) ImFmod(x,y)
#define STBTT_sqrt(x) ImSqrt(x)
#define STBTT_pow(x,y) ImPow(x,y)
#define STBTT_fabs(x) ImFabs(x)
#define STBTT_ifloor(x) ((int)ImFloorSigned(x))
#define STBTT_iceil(x) ((int)ImCeil(x))
#define STBTT_STATIC
#define STB_TRUETYPE_IMPLEMENTATION
#else
#define STBTT_DEF extern
#endif
#ifdef IMGUI_STB_TRUETYPE_FILENAME
#include IMGUI_STB_TRUETYPE_FILENAME
#else
#include "imstb_truetype.h"
#endif
#endif
#endif // IMGUI_ENABLE_STB_TRUETYPE
#if defined(__GNUC__)
#pragma GCC diagnostic pop
#endif
#if defined(__clang__)
#pragma clang diagnostic pop
#endif
#if defined(_MSC_VER)
#pragma warning (pop)
#endif
#ifdef IMGUI_STB_NAMESPACE
} // namespace ImStb
using namespace IMGUI_STB_NAMESPACE;
#endif
//-----------------------------------------------------------------------------
// [SECTION] Style functions
//-----------------------------------------------------------------------------
void ImGui::StyleColorsDark(ImGuiStyle* dst)
{
ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
ImVec4* colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 0.94f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.16f, 0.29f, 0.48f, 0.54f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.24f, 0.52f, 0.88f, 1.00f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Separator] = colors[ImGuiCol_Border];
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.10f, 0.40f, 0.75f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.10f, 0.40f, 0.75f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.26f, 0.59f, 0.98f, 0.20f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 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_TableHeaderBg] = ImVec4(0.19f, 0.19f, 0.20f, 1.00f);
colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.35f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableBorderLight] = ImVec4(0.23f, 0.23f, 0.25f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.06f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
}
void ImGui::StyleColorsClassic(ImGuiStyle* dst)
{
ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
ImVec4* colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(0.90f, 0.90f, 0.90f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.11f, 0.11f, 0.14f, 0.92f);
colors[ImGuiCol_Border] = ImVec4(0.50f, 0.50f, 0.50f, 0.50f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.43f, 0.43f, 0.43f, 0.39f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.47f, 0.47f, 0.69f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.42f, 0.41f, 0.64f, 0.69f);
colors[ImGuiCol_TitleBg] = ImVec4(0.27f, 0.27f, 0.54f, 0.83f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.32f, 0.32f, 0.63f, 0.87f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.40f, 0.40f, 0.80f, 0.20f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.40f, 0.40f, 0.55f, 0.80f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.20f, 0.25f, 0.30f, 0.60f);
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.41f, 0.39f, 0.80f, 0.60f);
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.41f, 0.39f, 0.80f, 0.60f);
colors[ImGuiCol_Button] = ImVec4(0.35f, 0.40f, 0.61f, 0.62f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.40f, 0.48f, 0.71f, 0.79f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.46f, 0.54f, 0.80f, 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_Separator] = ImVec4(0.50f, 0.50f, 0.50f, 0.60f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.60f, 0.60f, 0.70f, 1.00f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.70f, 0.70f, 0.90f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(1.00f, 1.00f, 1.00f, 0.10f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.78f, 0.82f, 1.00f, 0.60f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.78f, 0.82f, 1.00f, 0.90f);
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.80f);
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
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_TableHeaderBg] = ImVec4(0.27f, 0.27f, 0.38f, 1.00f);
colors[ImGuiCol_TableBorderStrong] = ImVec4(0.31f, 0.31f, 0.45f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableBorderLight] = ImVec4(0.26f, 0.26f, 0.28f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_TableRowBgAlt] = ImVec4(1.00f, 1.00f, 1.00f, 0.07f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.00f, 0.00f, 1.00f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
}
// Those light colors are better suited with a thicker font than the default one + FrameBorder
void ImGui::StyleColorsLight(ImGuiStyle* dst)
{
ImGuiStyle* style = dst ? dst : &ImGui::GetStyle();
ImVec4* colors = style->Colors;
colors[ImGuiCol_Text] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.94f, 0.94f, 0.94f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.98f);
colors[ImGuiCol_Border] = ImVec4(0.00f, 0.00f, 0.00f, 0.30f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_TitleBg] = ImVec4(0.96f, 0.96f, 0.96f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.82f, 0.82f, 0.82f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(1.00f, 1.00f, 1.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.86f, 0.86f, 0.86f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.98f, 0.98f, 0.98f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.69f, 0.69f, 0.69f, 0.80f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.49f, 0.49f, 0.49f, 0.80f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.49f, 0.49f, 0.49f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.26f, 0.59f, 0.98f, 0.78f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.46f, 0.54f, 0.80f, 0.60f);
colors[ImGuiCol_Button] = ImVec4(0.26f, 0.59f, 0.98f, 0.40f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.06f, 0.53f, 0.98f, 1.00f);
colors[ImGuiCol_Header] = ImVec4(0.26f, 0.59f, 0.98f, 0.31f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.26f, 0.59f, 0.98f, 1.00f);
colors[ImGuiCol_Separator] = ImVec4(0.39f, 0.39f, 0.39f, 0.62f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.14f, 0.44f, 0.80f, 0.78f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.14f, 0.44f, 0.80f, 1.00f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.35f, 0.35f, 0.35f, 0.17f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.26f, 0.59f, 0.98f, 0.67f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_Tab] = ImLerp(colors[ImGuiCol_Header], colors[ImGuiCol_TitleBgActive], 0.90f);
colors[ImGuiCol_TabHovered] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_TabActive] = ImLerp(colors[ImGuiCol_HeaderActive], colors[ImGuiCol_TitleBgActive], 0.60f);
colors[ImGuiCol_TabUnfocused] = ImLerp(colors[ImGuiCol_Tab], colors[ImGuiCol_TitleBg], 0.80f);
colors[ImGuiCol_TabUnfocusedActive] = ImLerp(colors[ImGuiCol_TabActive], colors[ImGuiCol_TitleBg], 0.40f);
colors[ImGuiCol_PlotLines] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.45f, 0.00f, 1.00f);
colors[ImGuiCol_TableHeaderBg] = ImVec4(0.78f, 0.87f, 0.98f, 1.00f);
colors[ImGuiCol_TableBorderStrong] = ImVec4(0.57f, 0.57f, 0.64f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableBorderLight] = ImVec4(0.68f, 0.68f, 0.74f, 1.00f); // Prefer using Alpha=1.0 here
colors[ImGuiCol_TableRowBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_TableRowBgAlt] = ImVec4(0.30f, 0.30f, 0.30f, 0.09f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.26f, 0.59f, 0.98f, 0.95f);
colors[ImGuiCol_NavHighlight] = colors[ImGuiCol_HeaderHovered];
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(0.70f, 0.70f, 0.70f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.20f, 0.20f, 0.20f, 0.35f);
}
//-----------------------------------------------------------------------------
// [SECTION] ImDrawList
//-----------------------------------------------------------------------------
ImDrawListSharedData::ImDrawListSharedData()
{
memset(this, 0, sizeof(*this));
for (int i = 0; i < IM_ARRAYSIZE(ArcFastVtx); i++)
{
const float a = ((float)i * 2 * IM_PI) / (float)IM_ARRAYSIZE(ArcFastVtx);
ArcFastVtx[i] = ImVec2(ImCos(a), ImSin(a));
}
ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);
}
void ImDrawListSharedData::SetCircleTessellationMaxError(float max_error)
{
if (CircleSegmentMaxError == max_error)
return;
IM_ASSERT(max_error > 0.0f);
CircleSegmentMaxError = max_error;
for (int i = 0; i < IM_ARRAYSIZE(CircleSegmentCounts); i++)
{
const float radius = (float)i;
CircleSegmentCounts[i] = (ImU8)((i > 0) ? IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, CircleSegmentMaxError) : 0);
}
ArcFastRadiusCutoff = IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC_R(IM_DRAWLIST_ARCFAST_SAMPLE_MAX, CircleSegmentMaxError);
}
// Initialize before use in a new frame. We always have a command ready in the buffer.
void ImDrawList::_ResetForNewFrame()
{
// Verify that the ImDrawCmd fields we want to memcmp() are contiguous in memory.
// (those should be IM_STATIC_ASSERT() in theory but with our pre C++11 setup the whole check doesn't compile with GCC)
IM_ASSERT(IM_OFFSETOF(ImDrawCmd, ClipRect) == 0);
IM_ASSERT(IM_OFFSETOF(ImDrawCmd, TextureId) == sizeof(ImVec4));
IM_ASSERT(IM_OFFSETOF(ImDrawCmd, VtxOffset) == sizeof(ImVec4) + sizeof(ImTextureID));
CmdBuffer.resize(0);
IdxBuffer.resize(0);
VtxBuffer.resize(0);
Flags = _Data->InitialFlags;
memset(&_CmdHeader, 0, sizeof(_CmdHeader));
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.resize(0);
_TextureIdStack.resize(0);
_Path.resize(0);
_Splitter.Clear();
CmdBuffer.push_back(ImDrawCmd());
_FringeScale = 1.0f;
}
void ImDrawList::_ClearFreeMemory()
{
CmdBuffer.clear();
IdxBuffer.clear();
VtxBuffer.clear();
Flags = ImDrawListFlags_None;
_VtxCurrentIdx = 0;
_VtxWritePtr = NULL;
_IdxWritePtr = NULL;
_ClipRectStack.clear();
_TextureIdStack.clear();
_Path.clear();
_Splitter.ClearFreeMemory();
}
ImDrawList* ImDrawList::CloneOutput() const
{
ImDrawList* dst = IM_NEW(ImDrawList(_Data));
dst->CmdBuffer = CmdBuffer;
dst->IdxBuffer = IdxBuffer;
dst->VtxBuffer = VtxBuffer;
dst->Flags = Flags;
return dst;
}
void ImDrawList::AddDrawCmd()
{
ImDrawCmd draw_cmd;
draw_cmd.ClipRect = _CmdHeader.ClipRect; // Same as calling ImDrawCmd_HeaderCopy()
draw_cmd.TextureId = _CmdHeader.TextureId;
draw_cmd.VtxOffset = _CmdHeader.VtxOffset;
draw_cmd.IdxOffset = IdxBuffer.Size;
IM_ASSERT(draw_cmd.ClipRect.x <= draw_cmd.ClipRect.z && draw_cmd.ClipRect.y <= draw_cmd.ClipRect.w);
CmdBuffer.push_back(draw_cmd);
}
// Pop trailing draw command (used before merging or presenting to user)
// Note that this leaves the ImDrawList in a state unfit for further commands, as most code assume that CmdBuffer.Size > 0 && CmdBuffer.back().UserCallback == NULL
void ImDrawList::_PopUnusedDrawCmd()
{
if (CmdBuffer.Size == 0)
return;
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
if (curr_cmd->ElemCount == 0 && curr_cmd->UserCallback == NULL)
CmdBuffer.pop_back();
}
void ImDrawList::AddCallback(ImDrawCallback callback, void* callback_data)
{
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
IM_ASSERT(curr_cmd->UserCallback == NULL);
if (curr_cmd->ElemCount != 0)
{
AddDrawCmd();
curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
}
curr_cmd->UserCallback = callback;
curr_cmd->UserCallbackData = callback_data;
AddDrawCmd(); // Force a new command after us (see comment below)
}
// Compare ClipRect, TextureId and VtxOffset with a single memcmp()
#define ImDrawCmd_HeaderSize (IM_OFFSETOF(ImDrawCmd, VtxOffset) + sizeof(unsigned int))
#define ImDrawCmd_HeaderCompare(CMD_LHS, CMD_RHS) (memcmp(CMD_LHS, CMD_RHS, ImDrawCmd_HeaderSize)) // Compare ClipRect, TextureId, VtxOffset
#define ImDrawCmd_HeaderCopy(CMD_DST, CMD_SRC) (memcpy(CMD_DST, CMD_SRC, ImDrawCmd_HeaderSize)) // Copy ClipRect, TextureId, VtxOffset
// Try to merge two last draw commands
void ImDrawList::_TryMergeDrawCmds()
{
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
ImDrawCmd* prev_cmd = curr_cmd - 1;
if (ImDrawCmd_HeaderCompare(curr_cmd, prev_cmd) == 0 && curr_cmd->UserCallback == NULL && prev_cmd->UserCallback == NULL)
{
prev_cmd->ElemCount += curr_cmd->ElemCount;
CmdBuffer.pop_back();
}
}
// Our scheme may appears a bit unusual, basically we want the most-common calls AddLine AddRect etc. to not have to perform any check so we always have a command ready in the stack.
// The cost of figuring out if a new command has to be added or if we can merge is paid in those Update** functions only.
void ImDrawList::_OnChangedClipRect()
{
// If current command is used with different settings we need to add a new command
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
if (curr_cmd->ElemCount != 0 && memcmp(&curr_cmd->ClipRect, &_CmdHeader.ClipRect, sizeof(ImVec4)) != 0)
{
AddDrawCmd();
return;
}
IM_ASSERT(curr_cmd->UserCallback == NULL);
// Try to merge with previous command if it matches, else use current command
ImDrawCmd* prev_cmd = curr_cmd - 1;
if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
{
CmdBuffer.pop_back();
return;
}
curr_cmd->ClipRect = _CmdHeader.ClipRect;
}
void ImDrawList::_OnChangedTextureID()
{
// If current command is used with different settings we need to add a new command
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
if (curr_cmd->ElemCount != 0 && curr_cmd->TextureId != _CmdHeader.TextureId)
{
AddDrawCmd();
return;
}
IM_ASSERT(curr_cmd->UserCallback == NULL);
// Try to merge with previous command if it matches, else use current command
ImDrawCmd* prev_cmd = curr_cmd - 1;
if (curr_cmd->ElemCount == 0 && CmdBuffer.Size > 1 && ImDrawCmd_HeaderCompare(&_CmdHeader, prev_cmd) == 0 && prev_cmd->UserCallback == NULL)
{
CmdBuffer.pop_back();
return;
}
curr_cmd->TextureId = _CmdHeader.TextureId;
}
void ImDrawList::_OnChangedVtxOffset()
{
// We don't need to compare curr_cmd->VtxOffset != _CmdHeader.VtxOffset because we know it'll be different at the time we call this.
_VtxCurrentIdx = 0;
ImDrawCmd* curr_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
//IM_ASSERT(curr_cmd->VtxOffset != _CmdHeader.VtxOffset); // See #3349
if (curr_cmd->ElemCount != 0)
{
AddDrawCmd();
return;
}
IM_ASSERT(curr_cmd->UserCallback == NULL);
curr_cmd->VtxOffset = _CmdHeader.VtxOffset;
}
int ImDrawList::_CalcCircleAutoSegmentCount(float radius) const
{
// Automatic segment count
const int radius_idx = (int)(radius + 0.999999f); // ceil to never reduce accuracy
if (radius_idx < IM_ARRAYSIZE(_Data->CircleSegmentCounts))
return _Data->CircleSegmentCounts[radius_idx]; // Use cached value
else
return IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_CALC(radius, _Data->CircleSegmentMaxError);
}
// Render-level scissoring. This is passed down to your render function but not used for CPU-side coarse clipping. Prefer using higher-level ImGui::PushClipRect() to affect logic (hit-testing and widget culling)
void ImDrawList::PushClipRect(ImVec2 cr_min, ImVec2 cr_max, bool intersect_with_current_clip_rect)
{
ImVec4 cr(cr_min.x, cr_min.y, cr_max.x, cr_max.y);
if (intersect_with_current_clip_rect)
{
ImVec4 current = _CmdHeader.ClipRect;
if (cr.x < current.x) cr.x = current.x;
if (cr.y < current.y) cr.y = current.y;
if (cr.z > current.z) cr.z = current.z;
if (cr.w > current.w) cr.w = current.w;
}
cr.z = ImMax(cr.x, cr.z);
cr.w = ImMax(cr.y, cr.w);
_ClipRectStack.push_back(cr);
_CmdHeader.ClipRect = cr;
_OnChangedClipRect();
}
void ImDrawList::PushClipRectFullScreen()
{
PushClipRect(ImVec2(_Data->ClipRectFullscreen.x, _Data->ClipRectFullscreen.y), ImVec2(_Data->ClipRectFullscreen.z, _Data->ClipRectFullscreen.w));
}
void ImDrawList::PopClipRect()
{
_ClipRectStack.pop_back();
_CmdHeader.ClipRect = (_ClipRectStack.Size == 0) ? _Data->ClipRectFullscreen : _ClipRectStack.Data[_ClipRectStack.Size - 1];
_OnChangedClipRect();
}
void ImDrawList::PushTextureID(ImTextureID texture_id)
{
_TextureIdStack.push_back(texture_id);
_CmdHeader.TextureId = texture_id;
_OnChangedTextureID();
}
void ImDrawList::PopTextureID()
{
_TextureIdStack.pop_back();
_CmdHeader.TextureId = (_TextureIdStack.Size == 0) ? (ImTextureID)NULL : _TextureIdStack.Data[_TextureIdStack.Size - 1];
_OnChangedTextureID();
}
// Reserve space for a number of vertices and indices.
// You must finish filling your reserved data before calling PrimReserve() again, as it may reallocate or
// submit the intermediate results. PrimUnreserve() can be used to release unused allocations.
void ImDrawList::PrimReserve(int idx_count, int vtx_count)
{
// Large mesh support (when enabled)
IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);
if (sizeof(ImDrawIdx) == 2 && (_VtxCurrentIdx + vtx_count >= (1 << 16)) && (Flags & ImDrawListFlags_AllowVtxOffset))
{
// FIXME: In theory we should be testing that vtx_count <64k here.
// In practice, RenderText() relies on reserving ahead for a worst case scenario so it is currently useful for us
// to not make that check until we rework the text functions to handle clipping and large horizontal lines better.
_CmdHeader.VtxOffset = VtxBuffer.Size;
_OnChangedVtxOffset();
}
ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
draw_cmd->ElemCount += idx_count;
int vtx_buffer_old_size = VtxBuffer.Size;
VtxBuffer.resize(vtx_buffer_old_size + vtx_count);
_VtxWritePtr = VtxBuffer.Data + vtx_buffer_old_size;
int idx_buffer_old_size = IdxBuffer.Size;
IdxBuffer.resize(idx_buffer_old_size + idx_count);
_IdxWritePtr = IdxBuffer.Data + idx_buffer_old_size;
}
// Release the a number of reserved vertices/indices from the end of the last reservation made with PrimReserve().
void ImDrawList::PrimUnreserve(int idx_count, int vtx_count)
{
IM_ASSERT_PARANOID(idx_count >= 0 && vtx_count >= 0);
ImDrawCmd* draw_cmd = &CmdBuffer.Data[CmdBuffer.Size - 1];
draw_cmd->ElemCount -= idx_count;
VtxBuffer.shrink(VtxBuffer.Size - vtx_count);
IdxBuffer.shrink(IdxBuffer.Size - idx_count);
}
// Fully unrolled with inline call to keep our debug builds decently fast.
void ImDrawList::PrimRect(const ImVec2& a, const ImVec2& c, ImU32 col)
{
ImVec2 b(c.x, a.y), d(a.x, c.y), uv(_Data->TexUvWhitePixel);
ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;
_IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);
_IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);
_VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv; _VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv; _VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
void ImDrawList::PrimRectUV(const ImVec2& a, const ImVec2& c, const ImVec2& uv_a, const ImVec2& uv_c, ImU32 col)
{
ImVec2 b(c.x, a.y), d(a.x, c.y), uv_b(uv_c.x, uv_a.y), uv_d(uv_a.x, uv_c.y);
ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;
_IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);
_IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);
_VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
void ImDrawList::PrimQuadUV(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& d, const ImVec2& uv_a, const ImVec2& uv_b, const ImVec2& uv_c, const ImVec2& uv_d, ImU32 col)
{
ImDrawIdx idx = (ImDrawIdx)_VtxCurrentIdx;
_IdxWritePtr[0] = idx; _IdxWritePtr[1] = (ImDrawIdx)(idx+1); _IdxWritePtr[2] = (ImDrawIdx)(idx+2);
_IdxWritePtr[3] = idx; _IdxWritePtr[4] = (ImDrawIdx)(idx+2); _IdxWritePtr[5] = (ImDrawIdx)(idx+3);
_VtxWritePtr[0].pos = a; _VtxWritePtr[0].uv = uv_a; _VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos = b; _VtxWritePtr[1].uv = uv_b; _VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = c; _VtxWritePtr[2].uv = uv_c; _VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = d; _VtxWritePtr[3].uv = uv_d; _VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_VtxCurrentIdx += 4;
_IdxWritePtr += 6;
}
// On AddPolyline() and AddConvexPolyFilled() we intentionally avoid using ImVec2 and superfluous function calls to optimize debug/non-inlined builds.
// - Those macros expects l-values and need to be used as their own statement.
// - Those macros are intentionally not surrounded by the 'do {} while (0)' idiom because even that translates to runtime with debug compilers.
#define IM_NORMALIZE2F_OVER_ZERO(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.0f) { float inv_len = ImRsqrt(d2); VX *= inv_len; VY *= inv_len; } } (void)0
#define IM_FIXNORMAL2F_MAX_INVLEN2 100.0f // 500.0f (see #4053, #3366)
#define IM_FIXNORMAL2F(VX,VY) { float d2 = VX*VX + VY*VY; if (d2 > 0.000001f) { float inv_len2 = 1.0f / d2; if (inv_len2 > IM_FIXNORMAL2F_MAX_INVLEN2) inv_len2 = IM_FIXNORMAL2F_MAX_INVLEN2; VX *= inv_len2; VY *= inv_len2; } } (void)0
// TODO: Thickness anti-aliased lines cap are missing their AA fringe.
// We avoid using the ImVec2 math operators here to reduce cost to a minimum for debug/non-inlined builds.
void ImDrawList::AddPolyline(const ImVec2* points, const int points_count, ImU32 col, ImDrawFlags flags, float thickness)
{
if (points_count < 2)
return;
const bool closed = (flags & ImDrawFlags_Closed) != 0;
const ImVec2 opaque_uv = _Data->TexUvWhitePixel;
const int count = closed ? points_count : points_count - 1; // The number of line segments we need to draw
const bool thick_line = (thickness > _FringeScale);
if (Flags & ImDrawListFlags_AntiAliasedLines)
{
// Anti-aliased stroke
const float AA_SIZE = _FringeScale;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
// Thicknesses <1.0 should behave like thickness 1.0
thickness = ImMax(thickness, 1.0f);
const int integer_thickness = (int)thickness;
const float fractional_thickness = thickness - integer_thickness;
// Do we want to draw this line using a texture?
// - For now, only draw integer-width lines using textures to avoid issues with the way scaling occurs, could be improved.
// - If AA_SIZE is not 1.0f we cannot use the texture path.
const bool use_texture = (Flags & ImDrawListFlags_AntiAliasedLinesUseTex) && (integer_thickness < IM_DRAWLIST_TEX_LINES_WIDTH_MAX) && (fractional_thickness <= 0.00001f) && (AA_SIZE == 1.0f);
// We should never hit this, because NewFrame() doesn't set ImDrawListFlags_AntiAliasedLinesUseTex unless ImFontAtlasFlags_NoBakedLines is off
IM_ASSERT_PARANOID(!use_texture || !(_Data->Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines));
const int idx_count = use_texture ? (count * 6) : (thick_line ? count * 18 : count * 12);
const int vtx_count = use_texture ? (points_count * 2) : (thick_line ? points_count * 4 : points_count * 3);
PrimReserve(idx_count, vtx_count);
// Temporary buffer
// The first <points_count> items are normals at each line point, then after that there are either 2 or 4 temp points for each line point
ImVec2* temp_normals = (ImVec2*)alloca(points_count * ((use_texture || !thick_line) ? 3 : 5) * sizeof(ImVec2)); //-V630
ImVec2* temp_points = temp_normals + points_count;
// Calculate normals (tangents) for each line segment
for (int i1 = 0; i1 < count; i1++)
{
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
float dx = points[i2].x - points[i1].x;
float dy = points[i2].y - points[i1].y;
IM_NORMALIZE2F_OVER_ZERO(dx, dy);
temp_normals[i1].x = dy;
temp_normals[i1].y = -dx;
}
if (!closed)
temp_normals[points_count - 1] = temp_normals[points_count - 2];
// If we are drawing a one-pixel-wide line without a texture, or a textured line of any width, we only need 2 or 3 vertices per point
if (use_texture || !thick_line)
{
// [PATH 1] Texture-based lines (thick or non-thick)
// [PATH 2] Non texture-based lines (non-thick)
// The width of the geometry we need to draw - this is essentially <thickness> pixels for the line itself, plus "one pixel" for AA.
// - In the texture-based path, we don't use AA_SIZE here because the +1 is tied to the generated texture
// (see ImFontAtlasBuildRenderLinesTexData() function), and so alternate values won't work without changes to that code.
// - In the non texture-based paths, we would allow AA_SIZE to potentially be != 1.0f with a patch (e.g. fringe_scale patch to
// allow scaling geometry while preserving one-screen-pixel AA fringe).
const float half_draw_size = use_texture ? ((thickness * 0.5f) + 1) : AA_SIZE;
// If line is not closed, the first and last points need to be generated differently as there are no normals to blend
if (!closed)
{
temp_points[0] = points[0] + temp_normals[0] * half_draw_size;
temp_points[1] = points[0] - temp_normals[0] * half_draw_size;
temp_points[(points_count-1)*2+0] = points[points_count-1] + temp_normals[points_count-1] * half_draw_size;
temp_points[(points_count-1)*2+1] = points[points_count-1] - temp_normals[points_count-1] * half_draw_size;
}
// Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges
// This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment
for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment
{
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1; // i2 is the second point of the line segment
const unsigned int idx2 = ((i1 + 1) == points_count) ? _VtxCurrentIdx : (idx1 + (use_texture ? 2 : 3)); // Vertex index for end of segment
// Average normals
float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;
float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f;
IM_FIXNORMAL2F(dm_x, dm_y);
dm_x *= half_draw_size; // dm_x, dm_y are offset to the outer edge of the AA area
dm_y *= half_draw_size;
// Add temporary vertexes for the outer edges
ImVec2* out_vtx = &temp_points[i2 * 2];
out_vtx[0].x = points[i2].x + dm_x;
out_vtx[0].y = points[i2].y + dm_y;
out_vtx[1].x = points[i2].x - dm_x;
out_vtx[1].y = points[i2].y - dm_y;
if (use_texture)
{
// Add indices for two triangles
_IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 1); // Right tri
_IdxWritePtr[3] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[4] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Left tri
_IdxWritePtr += 6;
}
else
{
// Add indexes for four triangles
_IdxWritePtr[0] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2); // Right tri 1
_IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 0); // Right tri 2
_IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0); // Left tri 1
_IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1); // Left tri 2
_IdxWritePtr += 12;
}
idx1 = idx2;
}
// Add vertexes for each point on the line
if (use_texture)
{
// If we're using textures we only need to emit the left/right edge vertices
ImVec4 tex_uvs = _Data->TexUvLines[integer_thickness];
/*if (fractional_thickness != 0.0f) // Currently always zero when use_texture==false!
{
const ImVec4 tex_uvs_1 = _Data->TexUvLines[integer_thickness + 1];
tex_uvs.x = tex_uvs.x + (tex_uvs_1.x - tex_uvs.x) * fractional_thickness; // inlined ImLerp()
tex_uvs.y = tex_uvs.y + (tex_uvs_1.y - tex_uvs.y) * fractional_thickness;
tex_uvs.z = tex_uvs.z + (tex_uvs_1.z - tex_uvs.z) * fractional_thickness;
tex_uvs.w = tex_uvs.w + (tex_uvs_1.w - tex_uvs.w) * fractional_thickness;
}*/
ImVec2 tex_uv0(tex_uvs.x, tex_uvs.y);
ImVec2 tex_uv1(tex_uvs.z, tex_uvs.w);
for (int i = 0; i < points_count; i++)
{
_VtxWritePtr[0].pos = temp_points[i * 2 + 0]; _VtxWritePtr[0].uv = tex_uv0; _VtxWritePtr[0].col = col; // Left-side outer edge
_VtxWritePtr[1].pos = temp_points[i * 2 + 1]; _VtxWritePtr[1].uv = tex_uv1; _VtxWritePtr[1].col = col; // Right-side outer edge
_VtxWritePtr += 2;
}
}
else
{
// If we're not using a texture, we need the center vertex as well
for (int i = 0; i < points_count; i++)
{
_VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col; // Center of line
_VtxWritePtr[1].pos = temp_points[i * 2 + 0]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col_trans; // Left-side outer edge
_VtxWritePtr[2].pos = temp_points[i * 2 + 1]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col_trans; // Right-side outer edge
_VtxWritePtr += 3;
}
}
}
else
{
// [PATH 2] Non texture-based lines (thick): we need to draw the solid line core and thus require four vertices per point
const float half_inner_thickness = (thickness - AA_SIZE) * 0.5f;
// If line is not closed, the first and last points need to be generated differently as there are no normals to blend
if (!closed)
{
const int points_last = points_count - 1;
temp_points[0] = points[0] + temp_normals[0] * (half_inner_thickness + AA_SIZE);
temp_points[1] = points[0] + temp_normals[0] * (half_inner_thickness);
temp_points[2] = points[0] - temp_normals[0] * (half_inner_thickness);
temp_points[3] = points[0] - temp_normals[0] * (half_inner_thickness + AA_SIZE);
temp_points[points_last * 4 + 0] = points[points_last] + temp_normals[points_last] * (half_inner_thickness + AA_SIZE);
temp_points[points_last * 4 + 1] = points[points_last] + temp_normals[points_last] * (half_inner_thickness);
temp_points[points_last * 4 + 2] = points[points_last] - temp_normals[points_last] * (half_inner_thickness);
temp_points[points_last * 4 + 3] = points[points_last] - temp_normals[points_last] * (half_inner_thickness + AA_SIZE);
}
// Generate the indices to form a number of triangles for each line segment, and the vertices for the line edges
// This takes points n and n+1 and writes into n+1, with the first point in a closed line being generated from the final one (as n+1 wraps)
// FIXME-OPT: Merge the different loops, possibly remove the temporary buffer.
unsigned int idx1 = _VtxCurrentIdx; // Vertex index for start of line segment
for (int i1 = 0; i1 < count; i1++) // i1 is the first point of the line segment
{
const int i2 = (i1 + 1) == points_count ? 0 : (i1 + 1); // i2 is the second point of the line segment
const unsigned int idx2 = (i1 + 1) == points_count ? _VtxCurrentIdx : (idx1 + 4); // Vertex index for end of segment
// Average normals
float dm_x = (temp_normals[i1].x + temp_normals[i2].x) * 0.5f;
float dm_y = (temp_normals[i1].y + temp_normals[i2].y) * 0.5f;
IM_FIXNORMAL2F(dm_x, dm_y);
float dm_out_x = dm_x * (half_inner_thickness + AA_SIZE);
float dm_out_y = dm_y * (half_inner_thickness + AA_SIZE);
float dm_in_x = dm_x * half_inner_thickness;
float dm_in_y = dm_y * half_inner_thickness;
// Add temporary vertices
ImVec2* out_vtx = &temp_points[i2 * 4];
out_vtx[0].x = points[i2].x + dm_out_x;
out_vtx[0].y = points[i2].y + dm_out_y;
out_vtx[1].x = points[i2].x + dm_in_x;
out_vtx[1].y = points[i2].y + dm_in_y;
out_vtx[2].x = points[i2].x - dm_in_x;
out_vtx[2].y = points[i2].y - dm_in_y;
out_vtx[3].x = points[i2].x - dm_out_x;
out_vtx[3].y = points[i2].y - dm_out_y;
// Add indexes
_IdxWritePtr[0] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[1] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[2] = (ImDrawIdx)(idx1 + 2);
_IdxWritePtr[3] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[4] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[5] = (ImDrawIdx)(idx2 + 1);
_IdxWritePtr[6] = (ImDrawIdx)(idx2 + 1); _IdxWritePtr[7] = (ImDrawIdx)(idx1 + 1); _IdxWritePtr[8] = (ImDrawIdx)(idx1 + 0);
_IdxWritePtr[9] = (ImDrawIdx)(idx1 + 0); _IdxWritePtr[10] = (ImDrawIdx)(idx2 + 0); _IdxWritePtr[11] = (ImDrawIdx)(idx2 + 1);
_IdxWritePtr[12] = (ImDrawIdx)(idx2 + 2); _IdxWritePtr[13] = (ImDrawIdx)(idx1 + 2); _IdxWritePtr[14] = (ImDrawIdx)(idx1 + 3);
_IdxWritePtr[15] = (ImDrawIdx)(idx1 + 3); _IdxWritePtr[16] = (ImDrawIdx)(idx2 + 3); _IdxWritePtr[17] = (ImDrawIdx)(idx2 + 2);
_IdxWritePtr += 18;
idx1 = idx2;
}
// Add vertices
for (int i = 0; i < points_count; i++)
{
_VtxWritePtr[0].pos = temp_points[i * 4 + 0]; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col_trans;
_VtxWritePtr[1].pos = temp_points[i * 4 + 1]; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos = temp_points[i * 4 + 2]; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos = temp_points[i * 4 + 3]; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col_trans;
_VtxWritePtr += 4;
}
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
}
else
{
// [PATH 4] Non texture-based, Non anti-aliased lines
const int idx_count = count * 6;
const int vtx_count = count * 4; // FIXME-OPT: Not sharing edges
PrimReserve(idx_count, vtx_count);
for (int i1 = 0; i1 < count; i1++)
{
const int i2 = (i1 + 1) == points_count ? 0 : i1 + 1;
const ImVec2& p1 = points[i1];
const ImVec2& p2 = points[i2];
float dx = p2.x - p1.x;
float dy = p2.y - p1.y;
IM_NORMALIZE2F_OVER_ZERO(dx, dy);
dx *= (thickness * 0.5f);
dy *= (thickness * 0.5f);
_VtxWritePtr[0].pos.x = p1.x + dy; _VtxWritePtr[0].pos.y = p1.y - dx; _VtxWritePtr[0].uv = opaque_uv; _VtxWritePtr[0].col = col;
_VtxWritePtr[1].pos.x = p2.x + dy; _VtxWritePtr[1].pos.y = p2.y - dx; _VtxWritePtr[1].uv = opaque_uv; _VtxWritePtr[1].col = col;
_VtxWritePtr[2].pos.x = p2.x - dy; _VtxWritePtr[2].pos.y = p2.y + dx; _VtxWritePtr[2].uv = opaque_uv; _VtxWritePtr[2].col = col;
_VtxWritePtr[3].pos.x = p1.x - dy; _VtxWritePtr[3].pos.y = p1.y + dx; _VtxWritePtr[3].uv = opaque_uv; _VtxWritePtr[3].col = col;
_VtxWritePtr += 4;
_IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + 2);
_IdxWritePtr[3] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[4] = (ImDrawIdx)(_VtxCurrentIdx + 2); _IdxWritePtr[5] = (ImDrawIdx)(_VtxCurrentIdx + 3);
_IdxWritePtr += 6;
_VtxCurrentIdx += 4;
}
}
}
// We intentionally avoid using ImVec2 and its math operators here to reduce cost to a minimum for debug/non-inlined builds.
void ImDrawList::AddConvexPolyFilled(const ImVec2* points, const int points_count, ImU32 col)
{
if (points_count < 3)
return;
const ImVec2 uv = _Data->TexUvWhitePixel;
if (Flags & ImDrawListFlags_AntiAliasedFill)
{
// Anti-aliased Fill
const float AA_SIZE = _FringeScale;
const ImU32 col_trans = col & ~IM_COL32_A_MASK;
const int idx_count = (points_count - 2)*3 + points_count * 6;
const int vtx_count = (points_count * 2);
PrimReserve(idx_count, vtx_count);
// Add indexes for fill
unsigned int vtx_inner_idx = _VtxCurrentIdx;
unsigned int vtx_outer_idx = _VtxCurrentIdx + 1;
for (int i = 2; i < points_count; i++)
{
_IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + ((i - 1) << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_inner_idx + (i << 1));
_IdxWritePtr += 3;
}
// Compute normals
ImVec2* temp_normals = (ImVec2*)alloca(points_count * sizeof(ImVec2)); //-V630
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
const ImVec2& p0 = points[i0];
const ImVec2& p1 = points[i1];
float dx = p1.x - p0.x;
float dy = p1.y - p0.y;
IM_NORMALIZE2F_OVER_ZERO(dx, dy);
temp_normals[i0].x = dy;
temp_normals[i0].y = -dx;
}
for (int i0 = points_count - 1, i1 = 0; i1 < points_count; i0 = i1++)
{
// Average normals
const ImVec2& n0 = temp_normals[i0];
const ImVec2& n1 = temp_normals[i1];
float dm_x = (n0.x + n1.x) * 0.5f;
float dm_y = (n0.y + n1.y) * 0.5f;
IM_FIXNORMAL2F(dm_x, dm_y);
dm_x *= AA_SIZE * 0.5f;
dm_y *= AA_SIZE * 0.5f;
// Add vertices
_VtxWritePtr[0].pos.x = (points[i1].x - dm_x); _VtxWritePtr[0].pos.y = (points[i1].y - dm_y); _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col; // Inner
_VtxWritePtr[1].pos.x = (points[i1].x + dm_x); _VtxWritePtr[1].pos.y = (points[i1].y + dm_y); _VtxWritePtr[1].uv = uv; _VtxWritePtr[1].col = col_trans; // Outer
_VtxWritePtr += 2;
// Add indexes for fringes
_IdxWritePtr[0] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1)); _IdxWritePtr[1] = (ImDrawIdx)(vtx_inner_idx + (i0 << 1)); _IdxWritePtr[2] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1));
_IdxWritePtr[3] = (ImDrawIdx)(vtx_outer_idx + (i0 << 1)); _IdxWritePtr[4] = (ImDrawIdx)(vtx_outer_idx + (i1 << 1)); _IdxWritePtr[5] = (ImDrawIdx)(vtx_inner_idx + (i1 << 1));
_IdxWritePtr += 6;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
}
else
{
// Non Anti-aliased Fill
const int idx_count = (points_count - 2)*3;
const int vtx_count = points_count;
PrimReserve(idx_count, vtx_count);
for (int i = 0; i < vtx_count; i++)
{
_VtxWritePtr[0].pos = points[i]; _VtxWritePtr[0].uv = uv; _VtxWritePtr[0].col = col;
_VtxWritePtr++;
}
for (int i = 2; i < points_count; i++)
{
_IdxWritePtr[0] = (ImDrawIdx)(_VtxCurrentIdx); _IdxWritePtr[1] = (ImDrawIdx)(_VtxCurrentIdx + i - 1); _IdxWritePtr[2] = (ImDrawIdx)(_VtxCurrentIdx + i);
_IdxWritePtr += 3;
}
_VtxCurrentIdx += (ImDrawIdx)vtx_count;
}
}
void ImDrawList::_PathArcToFastEx(const ImVec2& center, float radius, int a_min_sample, int a_max_sample, int a_step)
{
if (radius <= 0.0f)
{
_Path.push_back(center);
return;
}
// Calculate arc auto segment step size
if (a_step <= 0)
a_step = IM_DRAWLIST_ARCFAST_SAMPLE_MAX / _CalcCircleAutoSegmentCount(radius);
// Make sure we never do steps larger than one quarter of the circle
a_step = ImClamp(a_step, 1, IM_DRAWLIST_ARCFAST_TABLE_SIZE / 4);
const int sample_range = ImAbs(a_max_sample - a_min_sample);
const int a_next_step = a_step;
int samples = sample_range + 1;
bool extra_max_sample = false;
if (a_step > 1)
{
samples = sample_range / a_step + 1;
const int overstep = sample_range % a_step;
if (overstep > 0)
{
extra_max_sample = true;
samples++;
// When we have overstep to avoid awkwardly looking one long line and one tiny one at the end,
// distribute first step range evenly between them by reducing first step size.
if (sample_range > 0)
a_step -= (a_step - overstep) / 2;
}
}
_Path.resize(_Path.Size + samples);
ImVec2* out_ptr = _Path.Data + (_Path.Size - samples);
int sample_index = a_min_sample;
if (sample_index < 0 || sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX)
{
sample_index = sample_index % IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
if (sample_index < 0)
sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
}
if (a_max_sample >= a_min_sample)
{
for (int a = a_min_sample; a <= a_max_sample; a += a_step, sample_index += a_step, a_step = a_next_step)
{
// a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more
if (sample_index >= IM_DRAWLIST_ARCFAST_SAMPLE_MAX)
sample_index -= IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
const ImVec2 s = _Data->ArcFastVtx[sample_index];
out_ptr->x = center.x + s.x * radius;
out_ptr->y = center.y + s.y * radius;
out_ptr++;
}
}
else
{
for (int a = a_min_sample; a >= a_max_sample; a -= a_step, sample_index -= a_step, a_step = a_next_step)
{
// a_step is clamped to IM_DRAWLIST_ARCFAST_SAMPLE_MAX, so we have guaranteed that it will not wrap over range twice or more
if (sample_index < 0)
sample_index += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
const ImVec2 s = _Data->ArcFastVtx[sample_index];
out_ptr->x = center.x + s.x * radius;
out_ptr->y = center.y + s.y * radius;
out_ptr++;
}
}
if (extra_max_sample)
{
int normalized_max_sample = a_max_sample % IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
if (normalized_max_sample < 0)
normalized_max_sample += IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
const ImVec2 s = _Data->ArcFastVtx[normalized_max_sample];
out_ptr->x = center.x + s.x * radius;
out_ptr->y = center.y + s.y * radius;
out_ptr++;
}
IM_ASSERT_PARANOID(_Path.Data + _Path.Size == out_ptr);
}
void ImDrawList::_PathArcToN(const ImVec2& center, float radius, float a_min, float a_max, int num_segments)
{
if (radius <= 0.0f)
{
_Path.push_back(center);
return;
}
// Note that we are adding a point at both a_min and a_max.
// If you are trying to draw a full closed circle you don't want the overlapping points!
_Path.reserve(_Path.Size + (num_segments + 1));
for (int i = 0; i <= num_segments; i++)
{
const float a = a_min + ((float)i / (float)num_segments) * (a_max - a_min);
_Path.push_back(ImVec2(center.x + ImCos(a) * radius, center.y + ImSin(a) * radius));
}
}
// 0: East, 3: South, 6: West, 9: North, 12: East
void ImDrawList::PathArcToFast(const ImVec2& center, float radius, int a_min_of_12, int a_max_of_12)
{
if (radius <= 0.0f)
{
_Path.push_back(center);
return;
}
_PathArcToFastEx(center, radius, a_min_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, a_max_of_12 * IM_DRAWLIST_ARCFAST_SAMPLE_MAX / 12, 0);
}
void ImDrawList::PathArcTo(const ImVec2& center, float radius, float a_min, float a_max, int num_segments)
{
if (radius <= 0.0f)
{
_Path.push_back(center);
return;
}
if (num_segments > 0)
{
_PathArcToN(center, radius, a_min, a_max, num_segments);
return;
}
// Automatic segment count
if (radius <= _Data->ArcFastRadiusCutoff)
{
const bool a_is_reverse = a_max < a_min;
// We are going to use precomputed values for mid samples.
// Determine first and last sample in lookup table that belong to the arc.
const float a_min_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_min / (IM_PI * 2.0f);
const float a_max_sample_f = IM_DRAWLIST_ARCFAST_SAMPLE_MAX * a_max / (IM_PI * 2.0f);
const int a_min_sample = a_is_reverse ? (int)ImFloorSigned(a_min_sample_f) : (int)ImCeil(a_min_sample_f);
const int a_max_sample = a_is_reverse ? (int)ImCeil(a_max_sample_f) : (int)ImFloorSigned(a_max_sample_f);
const int a_mid_samples = a_is_reverse ? ImMax(a_min_sample - a_max_sample, 0) : ImMax(a_max_sample - a_min_sample, 0);
const float a_min_segment_angle = a_min_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
const float a_max_segment_angle = a_max_sample * IM_PI * 2.0f / IM_DRAWLIST_ARCFAST_SAMPLE_MAX;
const bool a_emit_start = (a_min_segment_angle - a_min) != 0.0f;
const bool a_emit_end = (a_max - a_max_segment_angle) != 0.0f;
_Path.reserve(_Path.Size + (a_mid_samples + 1 + (a_emit_start ? 1 : 0) + (a_emit_end ? 1 : 0)));
if (a_emit_start)
_Path.push_back(ImVec2(center.x + ImCos(a_min) * radius, center.y + ImSin(a_min) * radius));
if (a_mid_samples > 0)
_PathArcToFastEx(center, radius, a_min_sample, a_max_sample, 0);
if (a_emit_end)
_Path.push_back(ImVec2(center.x + ImCos(a_max) * radius, center.y + ImSin(a_max) * radius));
}
else
{
const float arc_length = ImAbs(a_max - a_min);
const int circle_segment_count = _CalcCircleAutoSegmentCount(radius);
const int arc_segment_count = ImMax((int)ImCeil(circle_segment_count * arc_length / (IM_PI * 2.0f)), (int)(2.0f * IM_PI / arc_length));
_PathArcToN(center, radius, a_min, a_max, arc_segment_count);
}
}
ImVec2 ImBezierCubicCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, float t)
{
float u = 1.0f - t;
float w1 = u * u * u;
float w2 = 3 * u * u * t;
float w3 = 3 * u * t * t;
float w4 = t * t * t;
return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x + w4 * p4.x, w1 * p1.y + w2 * p2.y + w3 * p3.y + w4 * p4.y);
}
ImVec2 ImBezierQuadraticCalc(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, float t)
{
float u = 1.0f - t;
float w1 = u * u;
float w2 = 2 * u * t;
float w3 = t * t;
return ImVec2(w1 * p1.x + w2 * p2.x + w3 * p3.x, w1 * p1.y + w2 * p2.y + w3 * p3.y);
}
// Closely mimics ImBezierCubicClosestPointCasteljau() in imgui.cpp
static void PathBezierCubicCurveToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
float d2 = (x2 - x4) * dy - (y2 - y4) * dx;
float d3 = (x3 - x4) * dy - (y3 - y4) * dx;
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
{
path->push_back(ImVec2(x4, y4));
}
else if (level < 10)
{
float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;
float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;
float x34 = (x3 + x4) * 0.5f, y34 = (y3 + y4) * 0.5f;
float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;
float x234 = (x23 + x34) * 0.5f, y234 = (y23 + y34) * 0.5f;
float x1234 = (x123 + x234) * 0.5f, y1234 = (y123 + y234) * 0.5f;
PathBezierCubicCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
PathBezierCubicCurveToCasteljau(path, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
static void PathBezierQuadraticCurveToCasteljau(ImVector<ImVec2>* path, float x1, float y1, float x2, float y2, float x3, float y3, float tess_tol, int level)
{
float dx = x3 - x1, dy = y3 - y1;
float det = (x2 - x3) * dy - (y2 - y3) * dx;
if (det * det * 4.0f < tess_tol * (dx * dx + dy * dy))
{
path->push_back(ImVec2(x3, y3));
}
else if (level < 10)
{
float x12 = (x1 + x2) * 0.5f, y12 = (y1 + y2) * 0.5f;
float x23 = (x2 + x3) * 0.5f, y23 = (y2 + y3) * 0.5f;
float x123 = (x12 + x23) * 0.5f, y123 = (y12 + y23) * 0.5f;
PathBezierQuadraticCurveToCasteljau(path, x1, y1, x12, y12, x123, y123, tess_tol, level + 1);
PathBezierQuadraticCurveToCasteljau(path, x123, y123, x23, y23, x3, y3, tess_tol, level + 1);
}
}
void ImDrawList::PathBezierCubicCurveTo(const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, int num_segments)
{
ImVec2 p1 = _Path.back();
if (num_segments == 0)
{
PathBezierCubicCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, _Data->CurveTessellationTol, 0); // Auto-tessellated
}
else
{
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
_Path.push_back(ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step));
}
}
void ImDrawList::PathBezierQuadraticCurveTo(const ImVec2& p2, const ImVec2& p3, int num_segments)
{
ImVec2 p1 = _Path.back();
if (num_segments == 0)
{
PathBezierQuadraticCurveToCasteljau(&_Path, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, _Data->CurveTessellationTol, 0);// Auto-tessellated
}
else
{
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
_Path.push_back(ImBezierQuadraticCalc(p1, p2, p3, t_step * i_step));
}
}
IM_STATIC_ASSERT(ImDrawFlags_RoundCornersTopLeft == (1 << 4));
static inline ImDrawFlags FixRectCornerFlags(ImDrawFlags flags)
{
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
// Legacy Support for hard coded ~0 (used to be a suggested equivalent to ImDrawCornerFlags_All)
// ~0 --> ImDrawFlags_RoundCornersAll or 0
if (flags == ~0)
return ImDrawFlags_RoundCornersAll;
// Legacy Support for hard coded 0x01 to 0x0F (matching 15 out of 16 old flags combinations)
// 0x01 --> ImDrawFlags_RoundCornersTopLeft (VALUE 0x01 OVERLAPS ImDrawFlags_Closed but ImDrawFlags_Closed is never valid in this path!)
// 0x02 --> ImDrawFlags_RoundCornersTopRight
// 0x03 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersTopRight
// 0x04 --> ImDrawFlags_RoundCornersBotLeft
// 0x05 --> ImDrawFlags_RoundCornersTopLeft | ImDrawFlags_RoundCornersBotLeft
// ...
// 0x0F --> ImDrawFlags_RoundCornersAll or 0
// (See all values in ImDrawCornerFlags_)
if (flags >= 0x01 && flags <= 0x0F)
return (flags << 4);
// We cannot support hard coded 0x00 with 'float rounding > 0.0f' --> replace with ImDrawFlags_RoundCornersNone or use 'float rounding = 0.0f'
#endif
// If this triggers, please update your code replacing hardcoded values with new ImDrawFlags_RoundCorners* values.
// Note that ImDrawFlags_Closed (== 0x01) is an invalid flag for AddRect(), AddRectFilled(), PathRect() etc...
IM_ASSERT((flags & 0x0F) == 0 && "Misuse of legacy hardcoded ImDrawCornerFlags values!");
if ((flags & ImDrawFlags_RoundCornersMask_) == 0)
flags |= ImDrawFlags_RoundCornersAll;
return flags;
}
void ImDrawList::PathRect(const ImVec2& a, const ImVec2& b, float rounding, ImDrawFlags flags)
{
flags = FixRectCornerFlags(flags);
rounding = ImMin(rounding, ImFabs(b.x - a.x) * ( ((flags & ImDrawFlags_RoundCornersTop) == ImDrawFlags_RoundCornersTop) || ((flags & ImDrawFlags_RoundCornersBottom) == ImDrawFlags_RoundCornersBottom) ? 0.5f : 1.0f ) - 1.0f);
rounding = ImMin(rounding, ImFabs(b.y - a.y) * ( ((flags & ImDrawFlags_RoundCornersLeft) == ImDrawFlags_RoundCornersLeft) || ((flags & ImDrawFlags_RoundCornersRight) == ImDrawFlags_RoundCornersRight) ? 0.5f : 1.0f ) - 1.0f);
if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)
{
PathLineTo(a);
PathLineTo(ImVec2(b.x, a.y));
PathLineTo(b);
PathLineTo(ImVec2(a.x, b.y));
}
else
{
const float rounding_tl = (flags & ImDrawFlags_RoundCornersTopLeft) ? rounding : 0.0f;
const float rounding_tr = (flags & ImDrawFlags_RoundCornersTopRight) ? rounding : 0.0f;
const float rounding_br = (flags & ImDrawFlags_RoundCornersBottomRight) ? rounding : 0.0f;
const float rounding_bl = (flags & ImDrawFlags_RoundCornersBottomLeft) ? rounding : 0.0f;
PathArcToFast(ImVec2(a.x + rounding_tl, a.y + rounding_tl), rounding_tl, 6, 9);
PathArcToFast(ImVec2(b.x - rounding_tr, a.y + rounding_tr), rounding_tr, 9, 12);
PathArcToFast(ImVec2(b.x - rounding_br, b.y - rounding_br), rounding_br, 0, 3);
PathArcToFast(ImVec2(a.x + rounding_bl, b.y - rounding_bl), rounding_bl, 3, 6);
}
}
void ImDrawList::AddLine(const ImVec2& p1, const ImVec2& p2, ImU32 col, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1 + ImVec2(0.5f, 0.5f));
PathLineTo(p2 + ImVec2(0.5f, 0.5f));
PathStroke(col, 0, thickness);
}
// p_min = upper-left, p_max = lower-right
// Note we don't render 1 pixels sized rectangles properly.
void ImDrawList::AddRect(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
if (Flags & ImDrawListFlags_AntiAliasedLines)
PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.50f, 0.50f), rounding, flags);
else
PathRect(p_min + ImVec2(0.50f, 0.50f), p_max - ImVec2(0.49f, 0.49f), rounding, flags); // Better looking lower-right corner and rounded non-AA shapes.
PathStroke(col, ImDrawFlags_Closed, thickness);
}
void ImDrawList::AddRectFilled(const ImVec2& p_min, const ImVec2& p_max, ImU32 col, float rounding, ImDrawFlags flags)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)
{
PrimReserve(6, 4);
PrimRect(p_min, p_max, col);
}
else
{
PathRect(p_min, p_max, rounding, flags);
PathFillConvex(col);
}
}
// p_min = upper-left, p_max = lower-right
void ImDrawList::AddRectFilledMultiColor(const ImVec2& p_min, const ImVec2& p_max, ImU32 col_upr_left, ImU32 col_upr_right, ImU32 col_bot_right, ImU32 col_bot_left)
{
if (((col_upr_left | col_upr_right | col_bot_right | col_bot_left) & IM_COL32_A_MASK) == 0)
return;
const ImVec2 uv = _Data->TexUvWhitePixel;
PrimReserve(6, 4);
PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 1)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2));
PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 2)); PrimWriteIdx((ImDrawIdx)(_VtxCurrentIdx + 3));
PrimWriteVtx(p_min, uv, col_upr_left);
PrimWriteVtx(ImVec2(p_max.x, p_min.y), uv, col_upr_right);
PrimWriteVtx(p_max, uv, col_bot_right);
PrimWriteVtx(ImVec2(p_min.x, p_max.y), uv, col_bot_left);
}
void ImDrawList::AddQuad(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathLineTo(p2);
PathLineTo(p3);
PathLineTo(p4);
PathStroke(col, ImDrawFlags_Closed, thickness);
}
void ImDrawList::AddQuadFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathLineTo(p2);
PathLineTo(p3);
PathLineTo(p4);
PathFillConvex(col);
}
void ImDrawList::AddTriangle(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathLineTo(p2);
PathLineTo(p3);
PathStroke(col, ImDrawFlags_Closed, thickness);
}
void ImDrawList::AddTriangleFilled(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathLineTo(p2);
PathLineTo(p3);
PathFillConvex(col);
}
void ImDrawList::AddCircle(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)
return;
// Obtain segment count
if (num_segments <= 0)
{
// Automatic segment count
num_segments = _CalcCircleAutoSegmentCount(radius);
}
else
{
// Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);
}
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
if (num_segments == 12)
PathArcToFast(center, radius - 0.5f, 0, 12 - 1);
else
PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1);
PathStroke(col, ImDrawFlags_Closed, thickness);
}
void ImDrawList::AddCircleFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0 || radius <= 0.0f)
return;
// Obtain segment count
if (num_segments <= 0)
{
// Automatic segment count
num_segments = _CalcCircleAutoSegmentCount(radius);
}
else
{
// Explicit segment count (still clamp to avoid drawing insanely tessellated shapes)
num_segments = ImClamp(num_segments, 3, IM_DRAWLIST_CIRCLE_AUTO_SEGMENT_MAX);
}
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
if (num_segments == 12)
PathArcToFast(center, radius, 0, 12 - 1);
else
PathArcTo(center, radius, 0.0f, a_max, num_segments - 1);
PathFillConvex(col);
}
// Guaranteed to honor 'num_segments'
void ImDrawList::AddNgon(const ImVec2& center, float radius, ImU32 col, int num_segments, float thickness)
{
if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)
return;
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
PathArcTo(center, radius - 0.5f, 0.0f, a_max, num_segments - 1);
PathStroke(col, ImDrawFlags_Closed, thickness);
}
// Guaranteed to honor 'num_segments'
void ImDrawList::AddNgonFilled(const ImVec2& center, float radius, ImU32 col, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0 || num_segments <= 2)
return;
// Because we are filling a closed shape we remove 1 from the count of segments/points
const float a_max = (IM_PI * 2.0f) * ((float)num_segments - 1.0f) / (float)num_segments;
PathArcTo(center, radius, 0.0f, a_max, num_segments - 1);
PathFillConvex(col);
}
// Cubic Bezier takes 4 controls points
void ImDrawList::AddBezierCubic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, ImU32 col, float thickness, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathBezierCubicCurveTo(p2, p3, p4, num_segments);
PathStroke(col, 0, thickness);
}
// Quadratic Bezier takes 3 controls points
void ImDrawList::AddBezierQuadratic(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, ImU32 col, float thickness, int num_segments)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
PathLineTo(p1);
PathBezierQuadraticCurveTo(p2, p3, num_segments);
PathStroke(col, 0, thickness);
}
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 ImVec4* cpu_fine_clip_rect)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
if (text_end == NULL)
text_end = text_begin + strlen(text_begin);
if (text_begin == text_end)
return;
// Pull default font/size from the shared ImDrawListSharedData instance
if (font == NULL)
font = _Data->Font;
if (font_size == 0.0f)
font_size = _Data->FontSize;
IM_ASSERT(font->ContainerAtlas->TexID == _CmdHeader.TextureId); // Use high-level ImGui::PushFont() or low-level ImDrawList::PushTextureId() to change font.
ImVec4 clip_rect = _CmdHeader.ClipRect;
if (cpu_fine_clip_rect)
{
clip_rect.x = ImMax(clip_rect.x, cpu_fine_clip_rect->x);
clip_rect.y = ImMax(clip_rect.y, cpu_fine_clip_rect->y);
clip_rect.z = ImMin(clip_rect.z, cpu_fine_clip_rect->z);
clip_rect.w = ImMin(clip_rect.w, cpu_fine_clip_rect->w);
}
font->RenderText(this, font_size, pos, col, clip_rect, text_begin, text_end, wrap_width, cpu_fine_clip_rect != NULL);
}
void ImDrawList::AddText(const ImVec2& pos, ImU32 col, const char* text_begin, const char* text_end)
{
AddText(NULL, 0.0f, pos, col, text_begin, text_end);
}
void ImDrawList::AddImage(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
if (push_texture_id)
PushTextureID(user_texture_id);
PrimReserve(6, 4);
PrimRectUV(p_min, p_max, uv_min, uv_max, col);
if (push_texture_id)
PopTextureID();
}
void ImDrawList::AddImageQuad(ImTextureID user_texture_id, const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& uv1, const ImVec2& uv2, const ImVec2& uv3, const ImVec2& uv4, ImU32 col)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
if (push_texture_id)
PushTextureID(user_texture_id);
PrimReserve(6, 4);
PrimQuadUV(p1, p2, p3, p4, uv1, uv2, uv3, uv4, col);
if (push_texture_id)
PopTextureID();
}
void ImDrawList::AddImageRounded(ImTextureID user_texture_id, const ImVec2& p_min, const ImVec2& p_max, const ImVec2& uv_min, const ImVec2& uv_max, ImU32 col, float rounding, ImDrawFlags flags)
{
if ((col & IM_COL32_A_MASK) == 0)
return;
flags = FixRectCornerFlags(flags);
if (rounding <= 0.0f || (flags & ImDrawFlags_RoundCornersMask_) == ImDrawFlags_RoundCornersNone)
{
AddImage(user_texture_id, p_min, p_max, uv_min, uv_max, col);
return;
}
const bool push_texture_id = user_texture_id != _CmdHeader.TextureId;
if (push_texture_id)
PushTextureID(user_texture_id);
int vert_start_idx = VtxBuffer.Size;
PathRect(p_min, p_max, rounding, flags);
PathFillConvex(col);
int vert_end_idx = VtxBuffer.Size;
ImGui::ShadeVertsLinearUV(this, vert_start_idx, vert_end_idx, p_min, p_max, uv_min, uv_max, true);
if (push_texture_id)
PopTextureID();
}
//-----------------------------------------------------------------------------
// [SECTION] ImDrawListSplitter
//-----------------------------------------------------------------------------
// FIXME: This may be a little confusing, trying to be a little too low-level/optimal instead of just doing vector swap..
//-----------------------------------------------------------------------------
void ImDrawListSplitter::ClearFreeMemory()
{
for (int i = 0; i < _Channels.Size; i++)
{
if (i == _Current)
memset(&_Channels[i], 0, sizeof(_Channels[i])); // Current channel is a copy of CmdBuffer/IdxBuffer, don't destruct again
_Channels[i]._CmdBuffer.clear();
_Channels[i]._IdxBuffer.clear();
}
_Current = 0;
_Count = 1;
_Channels.clear();
}
void ImDrawListSplitter::Split(ImDrawList* draw_list, int channels_count)
{
IM_UNUSED(draw_list);
IM_ASSERT(_Current == 0 && _Count <= 1 && "Nested channel splitting is not supported. Please use separate instances of ImDrawListSplitter.");
int old_channels_count = _Channels.Size;
if (old_channels_count < channels_count)
{
_Channels.reserve(channels_count); // Avoid over reserving since this is likely to stay stable
_Channels.resize(channels_count);
}
_Count = channels_count;
// Channels[] (24/32 bytes each) hold storage that we'll swap with draw_list->_CmdBuffer/_IdxBuffer
// The content of Channels[0] at this point doesn't matter. We clear it to make state tidy in a debugger but we don't strictly need to.
// When we switch to the next channel, we'll copy draw_list->_CmdBuffer/_IdxBuffer into Channels[0] and then Channels[1] into draw_list->CmdBuffer/_IdxBuffer
memset(&_Channels[0], 0, sizeof(ImDrawChannel));
for (int i = 1; i < channels_count; i++)
{
if (i >= old_channels_count)
{
IM_PLACEMENT_NEW(&_Channels[i]) ImDrawChannel();
}
else
{
_Channels[i]._CmdBuffer.resize(0);
_Channels[i]._IdxBuffer.resize(0);
}
}
}
void ImDrawListSplitter::Merge(ImDrawList* draw_list)
{
// Note that we never use or rely on _Channels.Size because it is merely a buffer that we never shrink back to 0 to keep all sub-buffers ready for use.
if (_Count <= 1)
return;
SetCurrentChannel(draw_list, 0);
draw_list->_PopUnusedDrawCmd();
// Calculate our final buffer sizes. Also fix the incorrect IdxOffset values in each command.
int new_cmd_buffer_count = 0;
int new_idx_buffer_count = 0;
ImDrawCmd* last_cmd = (_Count > 0 && draw_list->CmdBuffer.Size > 0) ? &draw_list->CmdBuffer.back() : NULL;
int idx_offset = last_cmd ? last_cmd->IdxOffset + last_cmd->ElemCount : 0;
for (int i = 1; i < _Count; i++)
{
ImDrawChannel& ch = _Channels[i];
// Equivalent of PopUnusedDrawCmd() for this channel's cmdbuffer and except we don't need to test for UserCallback.
if (ch._CmdBuffer.Size > 0 && ch._CmdBuffer.back().ElemCount == 0)
ch._CmdBuffer.pop_back();
if (ch._CmdBuffer.Size > 0 && last_cmd != NULL)
{
ImDrawCmd* next_cmd = &ch._CmdBuffer[0];
if (ImDrawCmd_HeaderCompare(last_cmd, next_cmd) == 0 && last_cmd->UserCallback == NULL && next_cmd->UserCallback == NULL)
{
// Merge previous channel last draw command with current channel first draw command if matching.
last_cmd->ElemCount += next_cmd->ElemCount;
idx_offset += next_cmd->ElemCount;
ch._CmdBuffer.erase(ch._CmdBuffer.Data); // FIXME-OPT: Improve for multiple merges.
}
}
if (ch._CmdBuffer.Size > 0)
last_cmd = &ch._CmdBuffer.back();
new_cmd_buffer_count += ch._CmdBuffer.Size;
new_idx_buffer_count += ch._IdxBuffer.Size;
for (int cmd_n = 0; cmd_n < ch._CmdBuffer.Size; cmd_n++)
{
ch._CmdBuffer.Data[cmd_n].IdxOffset = idx_offset;
idx_offset += ch._CmdBuffer.Data[cmd_n].ElemCount;
}
}
draw_list->CmdBuffer.resize(draw_list->CmdBuffer.Size + new_cmd_buffer_count);
draw_list->IdxBuffer.resize(draw_list->IdxBuffer.Size + new_idx_buffer_count);
// Write commands and indices in order (they are fairly small structures, we don't copy vertices only indices)
ImDrawCmd* cmd_write = draw_list->CmdBuffer.Data + draw_list->CmdBuffer.Size - new_cmd_buffer_count;
ImDrawIdx* idx_write = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size - new_idx_buffer_count;
for (int i = 1; i < _Count; i++)
{
ImDrawChannel& ch = _Channels[i];
if (int sz = ch._CmdBuffer.Size) { memcpy(cmd_write, ch._CmdBuffer.Data, sz * sizeof(ImDrawCmd)); cmd_write += sz; }
if (int sz = ch._IdxBuffer.Size) { memcpy(idx_write, ch._IdxBuffer.Data, sz * sizeof(ImDrawIdx)); idx_write += sz; }
}
draw_list->_IdxWritePtr = idx_write;
// Ensure there's always a non-callback draw command trailing the command-buffer
if (draw_list->CmdBuffer.Size == 0 || draw_list->CmdBuffer.back().UserCallback != NULL)
draw_list->AddDrawCmd();
// If current command is used with different settings we need to add a new command
ImDrawCmd* curr_cmd = &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];
if (curr_cmd->ElemCount == 0)
ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset
else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
draw_list->AddDrawCmd();
_Count = 1;
}
void ImDrawListSplitter::SetCurrentChannel(ImDrawList* draw_list, int idx)
{
IM_ASSERT(idx >= 0 && idx < _Count);
if (_Current == idx)
return;
// Overwrite ImVector (12/16 bytes), four times. This is merely a silly optimization instead of doing .swap()
memcpy(&_Channels.Data[_Current]._CmdBuffer, &draw_list->CmdBuffer, sizeof(draw_list->CmdBuffer));
memcpy(&_Channels.Data[_Current]._IdxBuffer, &draw_list->IdxBuffer, sizeof(draw_list->IdxBuffer));
_Current = idx;
memcpy(&draw_list->CmdBuffer, &_Channels.Data[idx]._CmdBuffer, sizeof(draw_list->CmdBuffer));
memcpy(&draw_list->IdxBuffer, &_Channels.Data[idx]._IdxBuffer, sizeof(draw_list->IdxBuffer));
draw_list->_IdxWritePtr = draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size;
// If current command is used with different settings we need to add a new command
ImDrawCmd* curr_cmd = (draw_list->CmdBuffer.Size == 0) ? NULL : &draw_list->CmdBuffer.Data[draw_list->CmdBuffer.Size - 1];
if (curr_cmd == NULL)
draw_list->AddDrawCmd();
else if (curr_cmd->ElemCount == 0)
ImDrawCmd_HeaderCopy(curr_cmd, &draw_list->_CmdHeader); // Copy ClipRect, TextureId, VtxOffset
else if (ImDrawCmd_HeaderCompare(curr_cmd, &draw_list->_CmdHeader) != 0)
draw_list->AddDrawCmd();
}
//-----------------------------------------------------------------------------
// [SECTION] ImDrawData
//-----------------------------------------------------------------------------
// For backward compatibility: convert all buffers from indexed to de-indexed, in case you cannot render indexed. Note: this is slow and most likely a waste of resources. Always prefer indexed rendering!
void ImDrawData::DeIndexAllBuffers()
{
ImVector<ImDrawVert> new_vtx_buffer;
TotalVtxCount = TotalIdxCount = 0;
for (int i = 0; i < CmdListsCount; i++)
{
ImDrawList* cmd_list = CmdLists[i];
if (cmd_list->IdxBuffer.empty())
continue;
new_vtx_buffer.resize(cmd_list->IdxBuffer.Size);
for (int j = 0; j < cmd_list->IdxBuffer.Size; j++)
new_vtx_buffer[j] = cmd_list->VtxBuffer[cmd_list->IdxBuffer[j]];
cmd_list->VtxBuffer.swap(new_vtx_buffer);
cmd_list->IdxBuffer.resize(0);
TotalVtxCount += cmd_list->VtxBuffer.Size;
}
}
// Helper to scale the ClipRect field of each ImDrawCmd.
// Use if your final output buffer is at a different scale than draw_data->DisplaySize,
// or if there is a difference between your window resolution and framebuffer resolution.
void ImDrawData::ScaleClipRects(const ImVec2& fb_scale)
{
for (int i = 0; i < CmdListsCount; i++)
{
ImDrawList* cmd_list = CmdLists[i];
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
ImDrawCmd* cmd = &cmd_list->CmdBuffer[cmd_i];
cmd->ClipRect = ImVec4(cmd->ClipRect.x * fb_scale.x, cmd->ClipRect.y * fb_scale.y, cmd->ClipRect.z * fb_scale.x, cmd->ClipRect.w * fb_scale.y);
}
}
}
//-----------------------------------------------------------------------------
// [SECTION] Helpers ShadeVertsXXX functions
//-----------------------------------------------------------------------------
// Generic linear color gradient, write to RGB fields, leave A untouched.
void ImGui::ShadeVertsLinearColorGradientKeepAlpha(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, ImVec2 gradient_p0, ImVec2 gradient_p1, ImU32 col0, ImU32 col1)
{
ImVec2 gradient_extent = gradient_p1 - gradient_p0;
float gradient_inv_length2 = 1.0f / ImLengthSqr(gradient_extent);
ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;
ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;
const int col0_r = (int)(col0 >> IM_COL32_R_SHIFT) & 0xFF;
const int col0_g = (int)(col0 >> IM_COL32_G_SHIFT) & 0xFF;
const int col0_b = (int)(col0 >> IM_COL32_B_SHIFT) & 0xFF;
const int col_delta_r = ((int)(col1 >> IM_COL32_R_SHIFT) & 0xFF) - col0_r;
const int col_delta_g = ((int)(col1 >> IM_COL32_G_SHIFT) & 0xFF) - col0_g;
const int col_delta_b = ((int)(col1 >> IM_COL32_B_SHIFT) & 0xFF) - col0_b;
for (ImDrawVert* vert = vert_start; vert < vert_end; vert++)
{
float d = ImDot(vert->pos - gradient_p0, gradient_extent);
float t = ImClamp(d * gradient_inv_length2, 0.0f, 1.0f);
int r = (int)(col0_r + col_delta_r * t);
int g = (int)(col0_g + col_delta_g * t);
int b = (int)(col0_b + col_delta_b * t);
vert->col = (r << IM_COL32_R_SHIFT) | (g << IM_COL32_G_SHIFT) | (b << IM_COL32_B_SHIFT) | (vert->col & IM_COL32_A_MASK);
}
}
// Distribute UV over (a, b) rectangle
void ImGui::ShadeVertsLinearUV(ImDrawList* draw_list, int vert_start_idx, int vert_end_idx, const ImVec2& a, const ImVec2& b, const ImVec2& uv_a, const ImVec2& uv_b, bool clamp)
{
const ImVec2 size = b - a;
const ImVec2 uv_size = uv_b - uv_a;
const ImVec2 scale = ImVec2(
size.x != 0.0f ? (uv_size.x / size.x) : 0.0f,
size.y != 0.0f ? (uv_size.y / size.y) : 0.0f);
ImDrawVert* vert_start = draw_list->VtxBuffer.Data + vert_start_idx;
ImDrawVert* vert_end = draw_list->VtxBuffer.Data + vert_end_idx;
if (clamp)
{
const ImVec2 min = ImMin(uv_a, uv_b);
const ImVec2 max = ImMax(uv_a, uv_b);
for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)
vertex->uv = ImClamp(uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale), min, max);
}
else
{
for (ImDrawVert* vertex = vert_start; vertex < vert_end; ++vertex)
vertex->uv = uv_a + ImMul(ImVec2(vertex->pos.x, vertex->pos.y) - a, scale);
}
}
//-----------------------------------------------------------------------------
// [SECTION] ImFontConfig
//-----------------------------------------------------------------------------
ImFontConfig::ImFontConfig()
{
memset(this, 0, sizeof(*this));
FontDataOwnedByAtlas = true;
OversampleH = 3; // FIXME: 2 may be a better default?
OversampleV = 1;
GlyphMaxAdvanceX = FLT_MAX;
RasterizerMultiply = 1.0f;
EllipsisChar = (ImWchar)-1;
}
//-----------------------------------------------------------------------------
// [SECTION] ImFontAtlas
//-----------------------------------------------------------------------------
// A work of art lies ahead! (. = white layer, X = black layer, others are blank)
// The 2x2 white texels on the top left are the ones we'll use everywhere in Dear ImGui to render filled shapes.
const int FONT_ATLAS_DEFAULT_TEX_DATA_W = 108; // Actual texture will be 2 times that + 1 spacing.
const int FONT_ATLAS_DEFAULT_TEX_DATA_H = 27;
static const char FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS[FONT_ATLAS_DEFAULT_TEX_DATA_W * FONT_ATLAS_DEFAULT_TEX_DATA_H + 1] =
{
"..- -XXXXXXX- X - X -XXXXXXX - XXXXXXX- XX "
"..- -X.....X- 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 - X...X- X..X "
"XX - X.X -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..XXX "
"X..X - X.X - X.X - X.X -XX X.X - X.X XX- X..X..XXX "
"X...X - X.X - X.X - XX X.X XX - X.X - X.X - X..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 -XXX X..X..X..X..X"
"X......X - X.X - X.X - X...XXXXXX.XXXXXX...X - X.X XX-XX X.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...XXXXXX.XXXXXX...X - 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.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 - X.X - XXXXXXX-XXXXXXX - X...........X "
"X..X X..X - -XXXX.XXXX- XXXX.XXXX ------------------------------------- X..........X "
"X.X X..X - -X.......X- X.......X - XX 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 "
" XX - X.X - X.X - X...XXXXXXXXXXXXX...X - - XXXXXXXXXX "
"------------ - X - X -X.....................X- ------------------"
" ----------------------------------- X...XXXXXXXXXXXXX...X - "
" - X..X X..X - "
" - X.X X.X - "
" - XX XX - "
};
static const ImVec2 FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[ImGuiMouseCursor_COUNT][3] =
{
// Pos ........ Size ......... Offset ......
{ ImVec2( 0,3), ImVec2(12,19), ImVec2( 0, 0) }, // ImGuiMouseCursor_Arrow
{ ImVec2(13,0), ImVec2( 7,16), ImVec2( 1, 8) }, // ImGuiMouseCursor_TextInput
{ ImVec2(31,0), ImVec2(23,23), ImVec2(11,11) }, // ImGuiMouseCursor_ResizeAll
{ ImVec2(21,0), ImVec2( 9,23), ImVec2( 4,11) }, // ImGuiMouseCursor_ResizeNS
{ ImVec2(55,18),ImVec2(23, 9), ImVec2(11, 4) }, // ImGuiMouseCursor_ResizeEW
{ ImVec2(73,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNESW
{ ImVec2(55,0), ImVec2(17,17), ImVec2( 8, 8) }, // ImGuiMouseCursor_ResizeNWSE
{ ImVec2(91,0), ImVec2(17,22), ImVec2( 5, 0) }, // ImGuiMouseCursor_Hand
};
ImFontAtlas::ImFontAtlas()
{
memset(this, 0, sizeof(*this));
TexGlyphPadding = 1;
PackIdMouseCursors = PackIdLines = -1;
}
ImFontAtlas::~ImFontAtlas()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
Clear();
}
void ImFontAtlas::ClearInputData()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
for (int i = 0; i < ConfigData.Size; i++)
if (ConfigData[i].FontData && ConfigData[i].FontDataOwnedByAtlas)
{
IM_FREE(ConfigData[i].FontData);
ConfigData[i].FontData = NULL;
}
// When clearing this we lose access to the font name and other information used to build the font.
for (int i = 0; i < Fonts.Size; i++)
if (Fonts[i]->ConfigData >= ConfigData.Data && Fonts[i]->ConfigData < ConfigData.Data + ConfigData.Size)
{
Fonts[i]->ConfigData = NULL;
Fonts[i]->ConfigDataCount = 0;
}
ConfigData.clear();
CustomRects.clear();
PackIdMouseCursors = PackIdLines = -1;
}
void ImFontAtlas::ClearTexData()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
if (TexPixelsAlpha8)
IM_FREE(TexPixelsAlpha8);
if (TexPixelsRGBA32)
IM_FREE(TexPixelsRGBA32);
TexPixelsAlpha8 = NULL;
TexPixelsRGBA32 = NULL;
TexPixelsUseColors = false;
}
void ImFontAtlas::ClearFonts()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
Fonts.clear_delete();
}
void ImFontAtlas::Clear()
{
ClearInputData();
ClearTexData();
ClearFonts();
}
void ImFontAtlas::GetTexDataAsAlpha8(unsigned char** out_pixels, int* out_width, int* out_height, int* out_bytes_per_pixel)
{
// Build atlas on demand
if (TexPixelsAlpha8 == NULL)
{
if (ConfigData.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)
{
// Convert to RGBA32 format on demand
// Although it is likely to be the most commonly used format, our font rendering is 1 channel / 8 bpp
if (!TexPixelsRGBA32)
{
unsigned char* pixels = NULL;
GetTexDataAsAlpha8(&pixels, NULL, NULL);
if (pixels)
{
TexPixelsRGBA32 = (unsigned int*)IM_ALLOC((size_t)TexWidth * (size_t)TexHeight * 4);
const unsigned char* src = pixels;
unsigned int* dst = TexPixelsRGBA32;
for (int n = TexWidth * TexHeight; n > 0; n--)
*dst++ = IM_COL32(255, 255, 255, (unsigned int)(*src++));
}
}
*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;
}
ImFont* ImFontAtlas::AddFont(const ImFontConfig* font_cfg)
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
IM_ASSERT(font_cfg->FontData != NULL && font_cfg->FontDataSize > 0);
IM_ASSERT(font_cfg->SizePixels > 0.0f);
// Create new font
if (!font_cfg->MergeMode)
Fonts.push_back(IM_NEW(ImFont));
else
IM_ASSERT(!Fonts.empty() && "Cannot use MergeMode for the first font"); // When using MergeMode make sure that a font has already been added before. You can use ImGui::GetIO().Fonts->AddFontDefault() to add the default imgui font.
ConfigData.push_back(*font_cfg);
ImFontConfig& new_font_cfg = ConfigData.back();
if (new_font_cfg.DstFont == NULL)
new_font_cfg.DstFont = Fonts.back();
if (!new_font_cfg.FontDataOwnedByAtlas)
{
new_font_cfg.FontData = IM_ALLOC(new_font_cfg.FontDataSize);
new_font_cfg.FontDataOwnedByAtlas = true;
memcpy(new_font_cfg.FontData, font_cfg->FontData, (size_t)new_font_cfg.FontDataSize);
}
if (new_font_cfg.DstFont->EllipsisChar == (ImWchar)-1)
new_font_cfg.DstFont->EllipsisChar = font_cfg->EllipsisChar;
// Invalidate texture
ClearTexData();
return new_font_cfg.DstFont;
}
// Default font TTF is compressed with stb_compress then base85 encoded (see misc/fonts/binary_to_compressed_c.cpp for encoder)
static unsigned int stb_decompress_length(const unsigned char* input);
static unsigned int stb_decompress(unsigned char* output, const unsigned char* input, unsigned int length);
static const char* GetDefaultCompressedFontDataTTFBase85();
static unsigned int Decode85Byte(char c) { return c >= '\\' ? c-36 : c-35; }
static void Decode85(const unsigned char* src, unsigned char* dst)
{
while (*src)
{
unsigned int tmp = Decode85Byte(src[0]) + 85 * (Decode85Byte(src[1]) + 85 * (Decode85Byte(src[2]) + 85 * (Decode85Byte(src[3]) + 85 * Decode85Byte(src[4]))));
dst[0] = ((tmp >> 0) & 0xFF); dst[1] = ((tmp >> 8) & 0xFF); dst[2] = ((tmp >> 16) & 0xFF); dst[3] = ((tmp >> 24) & 0xFF); // We can't assume little-endianness.
src += 5;
dst += 4;
}
}
// Load embedded ProggyClean.ttf at size 13, disable oversampling
ImFont* ImFontAtlas::AddFontDefault(const ImFontConfig* font_cfg_template)
{
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
if (!font_cfg_template)
{
font_cfg.OversampleH = font_cfg.OversampleV = 1;
font_cfg.PixelSnapH = true;
}
if (font_cfg.SizePixels <= 0.0f)
font_cfg.SizePixels = 13.0f * 1.0f;
if (font_cfg.Name[0] == '\0')
ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "ProggyClean.ttf, %dpx", (int)font_cfg.SizePixels);
font_cfg.EllipsisChar = (ImWchar)0x0085;
font_cfg.GlyphOffset.y = 1.0f * IM_FLOOR(font_cfg.SizePixels / 13.0f); // Add +1 offset per 13 units
const char* ttf_compressed_base85 = GetDefaultCompressedFontDataTTFBase85();
const ImWchar* glyph_ranges = font_cfg.GlyphRanges != NULL ? font_cfg.GlyphRanges : GetGlyphRangesDefault();
ImFont* font = AddFontFromMemoryCompressedBase85TTF(ttf_compressed_base85, font_cfg.SizePixels, &font_cfg, glyph_ranges);
return font;
}
ImFont* ImFontAtlas::AddFontFromFileTTF(const char* filename, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
size_t data_size = 0;
void* data = ImFileLoadToMemory(filename, "rb", &data_size, 0);
if (!data)
{
IM_ASSERT_USER_ERROR(0, "Could not load font file!");
return NULL;
}
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
if (font_cfg.Name[0] == '\0')
{
// Store a short copy of filename into into the font name for convenience
const char* p;
for (p = filename + strlen(filename); p > filename && p[-1] != '/' && p[-1] != '\\'; p--) {}
ImFormatString(font_cfg.Name, IM_ARRAYSIZE(font_cfg.Name), "%s, %.0fpx", p, size_pixels);
}
return AddFontFromMemoryTTF(data, (int)data_size, size_pixels, &font_cfg, glyph_ranges);
}
// NB: Transfer ownership of 'ttf_data' to ImFontAtlas, unless font_cfg_template->FontDataOwnedByAtlas == false. Owned TTF buffer will be deleted after Build().
ImFont* ImFontAtlas::AddFontFromMemoryTTF(void* ttf_data, int ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
font_cfg.FontData = ttf_data;
font_cfg.FontDataSize = ttf_size;
font_cfg.SizePixels = size_pixels > 0.0f ? size_pixels : font_cfg.SizePixels;
if (glyph_ranges)
font_cfg.GlyphRanges = glyph_ranges;
return AddFont(&font_cfg);
}
ImFont* ImFontAtlas::AddFontFromMemoryCompressedTTF(const void* compressed_ttf_data, int compressed_ttf_size, float size_pixels, const ImFontConfig* font_cfg_template, const ImWchar* glyph_ranges)
{
const unsigned int buf_decompressed_size = stb_decompress_length((const unsigned char*)compressed_ttf_data);
unsigned char* buf_decompressed_data = (unsigned char*)IM_ALLOC(buf_decompressed_size);
stb_decompress(buf_decompressed_data, (const unsigned char*)compressed_ttf_data, (unsigned int)compressed_ttf_size);
ImFontConfig font_cfg = font_cfg_template ? *font_cfg_template : ImFontConfig();
IM_ASSERT(font_cfg.FontData == NULL);
font_cfg.FontDataOwnedByAtlas = true;
return AddFontFromMemoryTTF(buf_decompressed_data, (int)buf_decompressed_size, size_pixels, &font_cfg, glyph_ranges);
}
ImFont* ImFontAtlas::AddFontFromMemoryCompressedBase85TTF(const char* compressed_ttf_data_base85, float size_pixels, const ImFontConfig* font_cfg, const ImWchar* glyph_ranges)
{
int compressed_ttf_size = (((int)strlen(compressed_ttf_data_base85) + 4) / 5) * 4;
void* compressed_ttf = IM_ALLOC((size_t)compressed_ttf_size);
Decode85((const unsigned char*)compressed_ttf_data_base85, (unsigned char*)compressed_ttf);
ImFont* font = AddFontFromMemoryCompressedTTF(compressed_ttf, compressed_ttf_size, size_pixels, font_cfg, glyph_ranges);
IM_FREE(compressed_ttf);
return font;
}
int ImFontAtlas::AddCustomRectRegular(int width, int height)
{
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
ImFontAtlasCustomRect r;
r.Width = (unsigned short)width;
r.Height = (unsigned short)height;
CustomRects.push_back(r);
return CustomRects.Size - 1; // Return index
}
int ImFontAtlas::AddCustomRectFontGlyph(ImFont* font, ImWchar id, int width, int height, float advance_x, const ImVec2& offset)
{
#ifdef IMGUI_USE_WCHAR32
IM_ASSERT(id <= IM_UNICODE_CODEPOINT_MAX);
#endif
IM_ASSERT(font != NULL);
IM_ASSERT(width > 0 && width <= 0xFFFF);
IM_ASSERT(height > 0 && height <= 0xFFFF);
ImFontAtlasCustomRect r;
r.Width = (unsigned short)width;
r.Height = (unsigned short)height;
r.GlyphID = id;
r.GlyphAdvanceX = advance_x;
r.GlyphOffset = offset;
r.Font = font;
CustomRects.push_back(r);
return CustomRects.Size - 1; // Return index
}
void ImFontAtlas::CalcCustomRectUV(const ImFontAtlasCustomRect* rect, ImVec2* out_uv_min, ImVec2* out_uv_max) const
{
IM_ASSERT(TexWidth > 0 && TexHeight > 0); // Font atlas needs to be built before we can calculate UV coordinates
IM_ASSERT(rect->IsPacked()); // Make sure the rectangle has been packed
*out_uv_min = ImVec2((float)rect->X * TexUvScale.x, (float)rect->Y * TexUvScale.y);
*out_uv_max = ImVec2((float)(rect->X + rect->Width) * TexUvScale.x, (float)(rect->Y + rect->Height) * TexUvScale.y);
}
bool ImFontAtlas::GetMouseCursorTexData(ImGuiMouseCursor cursor_type, ImVec2* out_offset, ImVec2* out_size, ImVec2 out_uv_border[2], ImVec2 out_uv_fill[2])
{
if (cursor_type <= ImGuiMouseCursor_None || cursor_type >= ImGuiMouseCursor_COUNT)
return false;
if (Flags & ImFontAtlasFlags_NoMouseCursors)
return false;
IM_ASSERT(PackIdMouseCursors != -1);
ImFontAtlasCustomRect* r = GetCustomRectByIndex(PackIdMouseCursors);
ImVec2 pos = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][0] + ImVec2((float)r->X, (float)r->Y);
ImVec2 size = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][1];
*out_size = size;
*out_offset = FONT_ATLAS_DEFAULT_TEX_CURSOR_DATA[cursor_type][2];
out_uv_border[0] = (pos) * TexUvScale;
out_uv_border[1] = (pos + size) * TexUvScale;
pos.x += FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
out_uv_fill[0] = (pos) * TexUvScale;
out_uv_fill[1] = (pos + size) * TexUvScale;
return true;
}
bool ImFontAtlas::Build()
{
IM_ASSERT(!Locked && "Cannot modify a locked ImFontAtlas between NewFrame() and EndFrame/Render()!");
// Select builder
// - Note that we do not reassign to atlas->FontBuilderIO, since it is likely to point to static data which
// may mess with some hot-reloading schemes. If you need to assign to this (for dynamic selection) AND are
// using a hot-reloading scheme that messes up static data, store your own instance of ImFontBuilderIO somewhere
// and point to it instead of pointing directly to return value of the GetBuilderXXX functions.
const ImFontBuilderIO* builder_io = FontBuilderIO;
if (builder_io == NULL)
{
#ifdef IMGUI_ENABLE_FREETYPE
builder_io = ImGuiFreeType::GetBuilderForFreeType();
#elif defined(IMGUI_ENABLE_STB_TRUETYPE)
builder_io = ImFontAtlasGetBuilderForStbTruetype();
#else
IM_ASSERT(0); // Invalid Build function
#endif
}
// Build
return builder_io->FontBuilder_Build(this);
}
void ImFontAtlasBuildMultiplyCalcLookupTable(unsigned char out_table[256], float in_brighten_factor)
{
for (unsigned int i = 0; i < 256; i++)
{
unsigned int value = (unsigned int)(i * in_brighten_factor);
out_table[i] = value > 255 ? 255 : (value & 0xFF);
}
}
void ImFontAtlasBuildMultiplyRectAlpha8(const unsigned char table[256], unsigned char* pixels, int x, int y, int w, int h, int stride)
{
unsigned char* data = pixels + x + y * stride;
for (int j = h; j > 0; j--, data += stride)
for (int i = 0; i < w; i++)
data[i] = table[data[i]];
}
#ifdef IMGUI_ENABLE_STB_TRUETYPE
// Temporary data for one source font (multiple source fonts can be merged into one destination ImFont)
// (C++03 doesn't allow instancing ImVector<> with function-local types so we declare the type here.)
struct ImFontBuildSrcData
{
stbtt_fontinfo FontInfo;
stbtt_pack_range PackRange; // Hold the list of codepoints to pack (essentially points to Codepoints.Data)
stbrp_rect* Rects; // Rectangle to pack. We first fill in their size and the packer will give us their position.
stbtt_packedchar* PackedChars; // Output glyphs
const ImWchar* SrcRanges; // Ranges as requested by user (user is allowed to request too much, e.g. 0x0020..0xFFFF)
int DstIndex; // Index into atlas->Fonts[] and dst_tmp_array[]
int GlyphsHighest; // Highest requested codepoint
int GlyphsCount; // Glyph count (excluding missing glyphs and glyphs already set by an earlier source font)
ImBitVector GlyphsSet; // Glyph bit map (random access, 1-bit per codepoint. This will be a maximum of 8KB)
ImVector<int> GlyphsList; // Glyph codepoints list (flattened version of GlyphsMap)
};
// Temporary data for one destination ImFont* (multiple source fonts can be merged into one destination ImFont)
struct ImFontBuildDstData
{
int SrcCount; // Number of source fonts targeting this destination font.
int GlyphsHighest;
int GlyphsCount;
ImBitVector GlyphsSet; // This is used to resolve collision when multiple sources are merged into a same destination font.
};
static void UnpackBitVectorToFlatIndexList(const ImBitVector* in, ImVector<int>* out)
{
IM_ASSERT(sizeof(in->Storage.Data[0]) == sizeof(int));
const ImU32* it_begin = in->Storage.begin();
const ImU32* it_end = in->Storage.end();
for (const ImU32* it = it_begin; it < it_end; it++)
if (ImU32 entries_32 = *it)
for (ImU32 bit_n = 0; bit_n < 32; bit_n++)
if (entries_32 & ((ImU32)1 << bit_n))
out->push_back((int)(((it - it_begin) << 5) + bit_n));
}
static bool ImFontAtlasBuildWithStbTruetype(ImFontAtlas* atlas)
{
IM_ASSERT(atlas->ConfigData.Size > 0);
ImFontAtlasBuildInit(atlas);
// Clear atlas
atlas->TexID = (ImTextureID)NULL;
atlas->TexWidth = atlas->TexHeight = 0;
atlas->TexUvScale = ImVec2(0.0f, 0.0f);
atlas->TexUvWhitePixel = ImVec2(0.0f, 0.0f);
atlas->ClearTexData();
// Temporary storage for building
ImVector<ImFontBuildSrcData> src_tmp_array;
ImVector<ImFontBuildDstData> dst_tmp_array;
src_tmp_array.resize(atlas->ConfigData.Size);
dst_tmp_array.resize(atlas->Fonts.Size);
memset(src_tmp_array.Data, 0, (size_t)src_tmp_array.size_in_bytes());
memset(dst_tmp_array.Data, 0, (size_t)dst_tmp_array.size_in_bytes());
// 1. Initialize font loading structure, check font data validity
for (int src_i = 0; src_i < atlas->ConfigData.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
ImFontConfig& cfg = atlas->ConfigData[src_i];
IM_ASSERT(cfg.DstFont && (!cfg.DstFont->IsLoaded() || cfg.DstFont->ContainerAtlas == atlas));
// Find index from cfg.DstFont (we allow the user to set cfg.DstFont. Also it makes casual debugging nicer than when storing indices)
src_tmp.DstIndex = -1;
for (int output_i = 0; output_i < atlas->Fonts.Size && src_tmp.DstIndex == -1; output_i++)
if (cfg.DstFont == atlas->Fonts[output_i])
src_tmp.DstIndex = output_i;
if (src_tmp.DstIndex == -1)
{
IM_ASSERT(src_tmp.DstIndex != -1); // cfg.DstFont not pointing within atlas->Fonts[] array?
return false;
}
// Initialize helper structure for font loading and verify that the TTF/OTF data is correct
const int font_offset = stbtt_GetFontOffsetForIndex((unsigned char*)cfg.FontData, cfg.FontNo);
IM_ASSERT(font_offset >= 0 && "FontData is incorrect, or FontNo cannot be found.");
if (!stbtt_InitFont(&src_tmp.FontInfo, (unsigned char*)cfg.FontData, font_offset))
return false;
// Measure highest codepoints
ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.SrcRanges = cfg.GlyphRanges ? cfg.GlyphRanges : atlas->GetGlyphRangesDefault();
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
src_tmp.GlyphsHighest = ImMax(src_tmp.GlyphsHighest, (int)src_range[1]);
dst_tmp.SrcCount++;
dst_tmp.GlyphsHighest = ImMax(dst_tmp.GlyphsHighest, src_tmp.GlyphsHighest);
}
// 2. For every requested codepoint, check for their presence in the font data, and handle redundancy or overlaps between source fonts to avoid unused glyphs.
int total_glyphs_count = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
ImFontBuildDstData& dst_tmp = dst_tmp_array[src_tmp.DstIndex];
src_tmp.GlyphsSet.Create(src_tmp.GlyphsHighest + 1);
if (dst_tmp.GlyphsSet.Storage.empty())
dst_tmp.GlyphsSet.Create(dst_tmp.GlyphsHighest + 1);
for (const ImWchar* src_range = src_tmp.SrcRanges; src_range[0] && src_range[1]; src_range += 2)
for (unsigned int codepoint = src_range[0]; codepoint <= src_range[1]; codepoint++)
{
if (dst_tmp.GlyphsSet.TestBit(codepoint)) // Don't overwrite existing glyphs. We could make this an option for MergeMode (e.g. MergeOverwrite==true)
continue;
if (!stbtt_FindGlyphIndex(&src_tmp.FontInfo, codepoint)) // It is actually in the font?
continue;
// Add to avail set/counters
src_tmp.GlyphsCount++;
dst_tmp.GlyphsCount++;
src_tmp.GlyphsSet.SetBit(codepoint);
dst_tmp.GlyphsSet.SetBit(codepoint);
total_glyphs_count++;
}
}
// 3. Unpack our bit map into a flat list (we now have all the Unicode points that we know are requested _and_ available _and_ not overlapping another)
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
src_tmp.GlyphsList.reserve(src_tmp.GlyphsCount);
UnpackBitVectorToFlatIndexList(&src_tmp.GlyphsSet, &src_tmp.GlyphsList);
src_tmp.GlyphsSet.Clear();
IM_ASSERT(src_tmp.GlyphsList.Size == src_tmp.GlyphsCount);
}
for (int dst_i = 0; dst_i < dst_tmp_array.Size; dst_i++)
dst_tmp_array[dst_i].GlyphsSet.Clear();
dst_tmp_array.clear();
// Allocate packing character data and flag packed characters buffer as non-packed (x0=y0=x1=y1=0)
// (We technically don't need to zero-clear buf_rects, but let's do it for the sake of sanity)
ImVector<stbrp_rect> buf_rects;
ImVector<stbtt_packedchar> buf_packedchars;
buf_rects.resize(total_glyphs_count);
buf_packedchars.resize(total_glyphs_count);
memset(buf_rects.Data, 0, (size_t)buf_rects.size_in_bytes());
memset(buf_packedchars.Data, 0, (size_t)buf_packedchars.size_in_bytes());
// 4. Gather glyphs sizes so we can pack them in our virtual canvas.
int total_surface = 0;
int buf_rects_out_n = 0;
int buf_packedchars_out_n = 0;
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
src_tmp.Rects = &buf_rects[buf_rects_out_n];
src_tmp.PackedChars = &buf_packedchars[buf_packedchars_out_n];
buf_rects_out_n += src_tmp.GlyphsCount;
buf_packedchars_out_n += src_tmp.GlyphsCount;
// Convert our ranges in the format stb_truetype wants
ImFontConfig& cfg = atlas->ConfigData[src_i];
src_tmp.PackRange.font_size = cfg.SizePixels;
src_tmp.PackRange.first_unicode_codepoint_in_range = 0;
src_tmp.PackRange.array_of_unicode_codepoints = src_tmp.GlyphsList.Data;
src_tmp.PackRange.num_chars = src_tmp.GlyphsList.Size;
src_tmp.PackRange.chardata_for_range = src_tmp.PackedChars;
src_tmp.PackRange.h_oversample = (unsigned char)cfg.OversampleH;
src_tmp.PackRange.v_oversample = (unsigned char)cfg.OversampleV;
// Gather the sizes of all rectangles we will need to pack (this loop is based on stbtt_PackFontRangesGatherRects)
const float scale = (cfg.SizePixels > 0) ? stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels) : stbtt_ScaleForMappingEmToPixels(&src_tmp.FontInfo, -cfg.SizePixels);
const int padding = atlas->TexGlyphPadding;
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsList.Size; glyph_i++)
{
int x0, y0, x1, y1;
const int glyph_index_in_font = stbtt_FindGlyphIndex(&src_tmp.FontInfo, src_tmp.GlyphsList[glyph_i]);
IM_ASSERT(glyph_index_in_font != 0);
stbtt_GetGlyphBitmapBoxSubpixel(&src_tmp.FontInfo, glyph_index_in_font, scale * cfg.OversampleH, scale * cfg.OversampleV, 0, 0, &x0, &y0, &x1, &y1);
src_tmp.Rects[glyph_i].w = (stbrp_coord)(x1 - x0 + padding + cfg.OversampleH - 1);
src_tmp.Rects[glyph_i].h = (stbrp_coord)(y1 - y0 + padding + cfg.OversampleV - 1);
total_surface += src_tmp.Rects[glyph_i].w * src_tmp.Rects[glyph_i].h;
}
}
// We need a width for the skyline algorithm, any width!
// The exact width doesn't really matter much, but some API/GPU have texture size limitations and increasing width can decrease height.
// User can override TexDesiredWidth and TexGlyphPadding if they wish, otherwise we use a simple heuristic to select the width based on expected surface.
const int surface_sqrt = (int)ImSqrt((float)total_surface) + 1;
atlas->TexHeight = 0;
if (atlas->TexDesiredWidth > 0)
atlas->TexWidth = atlas->TexDesiredWidth;
else
atlas->TexWidth = (surface_sqrt >= 4096 * 0.7f) ? 4096 : (surface_sqrt >= 2048 * 0.7f) ? 2048 : (surface_sqrt >= 1024 * 0.7f) ? 1024 : 512;
// 5. Start packing
// Pack our extra data rectangles first, so it will be on the upper-left corner of our texture (UV will have small values).
const int TEX_HEIGHT_MAX = 1024 * 32;
stbtt_pack_context spc = {};
stbtt_PackBegin(&spc, NULL, atlas->TexWidth, TEX_HEIGHT_MAX, 0, atlas->TexGlyphPadding, NULL);
ImFontAtlasBuildPackCustomRects(atlas, spc.pack_info);
// 6. Pack each source font. No rendering yet, we are working with rectangles in an infinitely tall texture at this point.
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
stbrp_pack_rects((stbrp_context*)spc.pack_info, src_tmp.Rects, src_tmp.GlyphsCount);
// Extend texture height and mark missing glyphs as non-packed so we won't render them.
// FIXME: We are not handling packing failure here (would happen if we got off TEX_HEIGHT_MAX or if a single if larger than TexWidth?)
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
if (src_tmp.Rects[glyph_i].was_packed)
atlas->TexHeight = ImMax(atlas->TexHeight, src_tmp.Rects[glyph_i].y + src_tmp.Rects[glyph_i].h);
}
// 7. Allocate texture
atlas->TexHeight = (atlas->Flags & ImFontAtlasFlags_NoPowerOfTwoHeight) ? (atlas->TexHeight + 1) : ImUpperPowerOfTwo(atlas->TexHeight);
atlas->TexUvScale = ImVec2(1.0f / atlas->TexWidth, 1.0f / atlas->TexHeight);
atlas->TexPixelsAlpha8 = (unsigned char*)IM_ALLOC(atlas->TexWidth * atlas->TexHeight);
memset(atlas->TexPixelsAlpha8, 0, atlas->TexWidth * atlas->TexHeight);
spc.pixels = atlas->TexPixelsAlpha8;
spc.height = atlas->TexHeight;
// 8. Render/rasterize font characters into the texture
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontConfig& cfg = atlas->ConfigData[src_i];
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
stbtt_PackFontRangesRenderIntoRects(&spc, &src_tmp.FontInfo, &src_tmp.PackRange, 1, src_tmp.Rects);
// Apply multiply operator
if (cfg.RasterizerMultiply != 1.0f)
{
unsigned char multiply_table[256];
ImFontAtlasBuildMultiplyCalcLookupTable(multiply_table, cfg.RasterizerMultiply);
stbrp_rect* r = &src_tmp.Rects[0];
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++, r++)
if (r->was_packed)
ImFontAtlasBuildMultiplyRectAlpha8(multiply_table, atlas->TexPixelsAlpha8, r->x, r->y, r->w, r->h, atlas->TexWidth * 1);
}
src_tmp.Rects = NULL;
}
// End packing
stbtt_PackEnd(&spc);
buf_rects.clear();
// 9. Setup ImFont and glyphs for runtime
for (int src_i = 0; src_i < src_tmp_array.Size; src_i++)
{
ImFontBuildSrcData& src_tmp = src_tmp_array[src_i];
if (src_tmp.GlyphsCount == 0)
continue;
// When merging fonts with MergeMode=true:
// - We can have multiple input fonts writing into a same destination font.
// - dst_font->ConfigData is != from cfg which is our source configuration.
ImFontConfig& cfg = atlas->ConfigData[src_i];
ImFont* dst_font = cfg.DstFont;
const float font_scale = stbtt_ScaleForPixelHeight(&src_tmp.FontInfo, cfg.SizePixels);
int unscaled_ascent, unscaled_descent, unscaled_line_gap;
stbtt_GetFontVMetrics(&src_tmp.FontInfo, &unscaled_ascent, &unscaled_descent, &unscaled_line_gap);
const float ascent = ImFloor(unscaled_ascent * font_scale + ((unscaled_ascent > 0.0f) ? +1 : -1));
const float descent = ImFloor(unscaled_descent * font_scale + ((unscaled_descent > 0.0f) ? +1 : -1));
ImFontAtlasBuildSetupFont(atlas, dst_font, &cfg, ascent, descent);
const float font_off_x = cfg.GlyphOffset.x;
const float font_off_y = cfg.GlyphOffset.y + IM_ROUND(dst_font->Ascent);
for (int glyph_i = 0; glyph_i < src_tmp.GlyphsCount; glyph_i++)
{
// Register glyph
const int codepoint = src_tmp.GlyphsList[glyph_i];
const stbtt_packedchar& pc = src_tmp.PackedChars[glyph_i];
stbtt_aligned_quad q;
float unused_x = 0.0f, unused_y = 0.0f;
stbtt_GetPackedQuad(src_tmp.PackedChars, atlas->TexWidth, atlas->TexHeight, glyph_i, &unused_x, &unused_y, &q, 0);
dst_font->AddGlyph(&cfg, (ImWchar)codepoint, q.x0 + font_off_x, q.y0 + font_off_y, q.x1 + font_off_x, q.y1 + font_off_y, q.s0, q.t0, q.s1, q.t1, pc.xadvance);
}
}
// Cleanup
src_tmp_array.clear_destruct();
ImFontAtlasBuildFinish(atlas);
return true;
}
const ImFontBuilderIO* ImFontAtlasGetBuilderForStbTruetype()
{
static ImFontBuilderIO io;
io.FontBuilder_Build = ImFontAtlasBuildWithStbTruetype;
return &io;
}
#endif // IMGUI_ENABLE_STB_TRUETYPE
void ImFontAtlasBuildSetupFont(ImFontAtlas* atlas, ImFont* font, ImFontConfig* font_config, float ascent, float descent)
{
if (!font_config->MergeMode)
{
font->ClearOutputData();
font->FontSize = font_config->SizePixels;
font->ConfigData = font_config;
font->ConfigDataCount = 0;
font->ContainerAtlas = atlas;
font->Ascent = ascent;
font->Descent = descent;
}
font->ConfigDataCount++;
}
void ImFontAtlasBuildPackCustomRects(ImFontAtlas* atlas, void* stbrp_context_opaque)
{
stbrp_context* pack_context = (stbrp_context*)stbrp_context_opaque;
IM_ASSERT(pack_context != NULL);
ImVector<ImFontAtlasCustomRect>& user_rects = atlas->CustomRects;
IM_ASSERT(user_rects.Size >= 1); // We expect at least the default custom rects to be registered, else something went wrong.
ImVector<stbrp_rect> pack_rects;
pack_rects.resize(user_rects.Size);
memset(pack_rects.Data, 0, (size_t)pack_rects.size_in_bytes());
for (int i = 0; i < user_rects.Size; i++)
{
pack_rects[i].w = user_rects[i].Width;
pack_rects[i].h = user_rects[i].Height;
}
stbrp_pack_rects(pack_context, &pack_rects[0], pack_rects.Size);
for (int i = 0; i < pack_rects.Size; i++)
if (pack_rects[i].was_packed)
{
user_rects[i].X = pack_rects[i].x;
user_rects[i].Y = pack_rects[i].y;
IM_ASSERT(pack_rects[i].w == user_rects[i].Width && pack_rects[i].h == user_rects[i].Height);
atlas->TexHeight = ImMax(atlas->TexHeight, pack_rects[i].y + pack_rects[i].h);
}
}
void ImFontAtlasBuildRender8bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned char in_marker_pixel_value)
{
IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);
IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);
unsigned char* out_pixel = atlas->TexPixelsAlpha8 + x + (y * atlas->TexWidth);
for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w)
for (int off_x = 0; off_x < w; off_x++)
out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : 0x00;
}
void ImFontAtlasBuildRender32bppRectFromString(ImFontAtlas* atlas, int x, int y, int w, int h, const char* in_str, char in_marker_char, unsigned int in_marker_pixel_value)
{
IM_ASSERT(x >= 0 && x + w <= atlas->TexWidth);
IM_ASSERT(y >= 0 && y + h <= atlas->TexHeight);
unsigned int* out_pixel = atlas->TexPixelsRGBA32 + x + (y * atlas->TexWidth);
for (int off_y = 0; off_y < h; off_y++, out_pixel += atlas->TexWidth, in_str += w)
for (int off_x = 0; off_x < w; off_x++)
out_pixel[off_x] = (in_str[off_x] == in_marker_char) ? in_marker_pixel_value : IM_COL32_BLACK_TRANS;
}
static void ImFontAtlasBuildRenderDefaultTexData(ImFontAtlas* atlas)
{
ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdMouseCursors);
IM_ASSERT(r->IsPacked());
const int w = atlas->TexWidth;
if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
{
// Render/copy pixels
IM_ASSERT(r->Width == FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1 && r->Height == FONT_ATLAS_DEFAULT_TEX_DATA_H);
const int x_for_white = r->X;
const int x_for_black = r->X + FONT_ATLAS_DEFAULT_TEX_DATA_W + 1;
if (atlas->TexPixelsAlpha8 != NULL)
{
ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', 0xFF);
ImFontAtlasBuildRender8bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', 0xFF);
}
else
{
ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_white, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, '.', IM_COL32_WHITE);
ImFontAtlasBuildRender32bppRectFromString(atlas, x_for_black, r->Y, FONT_ATLAS_DEFAULT_TEX_DATA_W, FONT_ATLAS_DEFAULT_TEX_DATA_H, FONT_ATLAS_DEFAULT_TEX_DATA_PIXELS, 'X', IM_COL32_WHITE);
}
}
else
{
// Render 4 white pixels
IM_ASSERT(r->Width == 2 && r->Height == 2);
const int offset = (int)r->X + (int)r->Y * w;
if (atlas->TexPixelsAlpha8 != NULL)
{
atlas->TexPixelsAlpha8[offset] = atlas->TexPixelsAlpha8[offset + 1] = atlas->TexPixelsAlpha8[offset + w] = atlas->TexPixelsAlpha8[offset + w + 1] = 0xFF;
}
else
{
atlas->TexPixelsRGBA32[offset] = atlas->TexPixelsRGBA32[offset + 1] = atlas->TexPixelsRGBA32[offset + w] = atlas->TexPixelsRGBA32[offset + w + 1] = IM_COL32_WHITE;
}
}
atlas->TexUvWhitePixel = ImVec2((r->X + 0.5f) * atlas->TexUvScale.x, (r->Y + 0.5f) * atlas->TexUvScale.y);
}
static void ImFontAtlasBuildRenderLinesTexData(ImFontAtlas* atlas)
{
if (atlas->Flags & ImFontAtlasFlags_NoBakedLines)
return;
// This generates a triangular shape in the texture, with the various line widths stacked on top of each other to allow interpolation between them
ImFontAtlasCustomRect* r = atlas->GetCustomRectByIndex(atlas->PackIdLines);
IM_ASSERT(r->IsPacked());
for (unsigned int n = 0; n < IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1; n++) // +1 because of the zero-width row
{
// Each line consists of at least two empty pixels at the ends, with a line of solid pixels in the middle
unsigned int y = n;
unsigned int line_width = n;
unsigned int pad_left = (r->Width - line_width) / 2;
unsigned int pad_right = r->Width - (pad_left + line_width);
// Write each slice
IM_ASSERT(pad_left + line_width + pad_right == r->Width && y < r->Height); // Make sure we're inside the texture bounds before we start writing pixels
if (atlas->TexPixelsAlpha8 != NULL)
{
unsigned char* write_ptr = &atlas->TexPixelsAlpha8[r->X + ((r->Y + y) * atlas->TexWidth)];
for (unsigned int i = 0; i < pad_left; i++)
*(write_ptr + i) = 0x00;
for (unsigned int i = 0; i < line_width; i++)
*(write_ptr + pad_left + i) = 0xFF;
for (unsigned int i = 0; i < pad_right; i++)
*(write_ptr + pad_left + line_width + i) = 0x00;
}
else
{
unsigned int* write_ptr = &atlas->TexPixelsRGBA32[r->X + ((r->Y + y) * atlas->TexWidth)];
for (unsigned int i = 0; i < pad_left; i++)
*(write_ptr + i) = IM_COL32_BLACK_TRANS;
for (unsigned int i = 0; i < line_width; i++)
*(write_ptr + pad_left + i) = IM_COL32_WHITE;
for (unsigned int i = 0; i < pad_right; i++)
*(write_ptr + pad_left + line_width + i) = IM_COL32_BLACK_TRANS;
}
// Calculate UVs for this line
ImVec2 uv0 = ImVec2((float)(r->X + pad_left - 1), (float)(r->Y + y)) * atlas->TexUvScale;
ImVec2 uv1 = ImVec2((float)(r->X + pad_left + line_width + 1), (float)(r->Y + y + 1)) * atlas->TexUvScale;
float half_v = (uv0.y + uv1.y) * 0.5f; // Calculate a constant V in the middle of the row to avoid sampling artifacts
atlas->TexUvLines[n] = ImVec4(uv0.x, half_v, uv1.x, half_v);
}
}
// Note: this is called / shared by both the stb_truetype and the FreeType builder
void ImFontAtlasBuildInit(ImFontAtlas* atlas)
{
// Register texture region for mouse cursors or standard white pixels
if (atlas->PackIdMouseCursors < 0)
{
if (!(atlas->Flags & ImFontAtlasFlags_NoMouseCursors))
atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(FONT_ATLAS_DEFAULT_TEX_DATA_W * 2 + 1, FONT_ATLAS_DEFAULT_TEX_DATA_H);
else
atlas->PackIdMouseCursors = atlas->AddCustomRectRegular(2, 2);
}
// Register texture region for thick lines
// The +2 here is to give space for the end caps, whilst height +1 is to accommodate the fact we have a zero-width row
if (atlas->PackIdLines < 0)
{
if (!(atlas->Flags & ImFontAtlasFlags_NoBakedLines))
atlas->PackIdLines = atlas->AddCustomRectRegular(IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 2, IM_DRAWLIST_TEX_LINES_WIDTH_MAX + 1);
}
}
// This is called/shared by both the stb_truetype and the FreeType builder.
void ImFontAtlasBuildFinish(ImFontAtlas* atlas)
{
// Render into our custom data blocks
IM_ASSERT(atlas->TexPixelsAlpha8 != NULL || atlas->TexPixelsRGBA32 != NULL);
ImFontAtlasBuildRenderDefaultTexData(atlas);
ImFontAtlasBuildRenderLinesTexData(atlas);
// Register custom rectangle glyphs
for (int i = 0; i < atlas->CustomRects.Size; i++)
{
const ImFontAtlasCustomRect* r = &atlas->CustomRects[i];
if (r->Font == NULL || r->GlyphID == 0)
continue;
// Will ignore ImFontConfig settings: GlyphMinAdvanceX, GlyphMinAdvanceY, GlyphExtraSpacing, PixelSnapH
IM_ASSERT(r->Font->ContainerAtlas == atlas);
ImVec2 uv0, uv1;
atlas->CalcCustomRectUV(r, &uv0, &uv1);
r->Font->AddGlyph(NULL, (ImWchar)r->GlyphID, r->GlyphOffset.x, r->GlyphOffset.y, r->GlyphOffset.x + r->Width, r->GlyphOffset.y + r->Height, uv0.x, uv0.y, uv1.x, uv1.y, r->GlyphAdvanceX);
}
// Build all fonts lookup tables
for (int i = 0; i < atlas->Fonts.Size; i++)
if (atlas->Fonts[i]->DirtyLookupTables)
atlas->Fonts[i]->BuildLookupTable();
// Ellipsis character is required for rendering elided text. We prefer using U+2026 (horizontal ellipsis).
// However some old fonts may contain ellipsis at U+0085. Here we auto-detect most suitable ellipsis character.
// FIXME: Also note that 0x2026 is currently seldom included in our font ranges. Because of this we are more likely to use three individual dots.
for (int i = 0; i < atlas->Fonts.size(); i++)
{
ImFont* font = atlas->Fonts[i];
if (font->EllipsisChar != (ImWchar)-1)
continue;
const ImWchar ellipsis_variants[] = { (ImWchar)0x2026, (ImWchar)0x0085 };
for (int j = 0; j < IM_ARRAYSIZE(ellipsis_variants); j++)
if (font->FindGlyphNoFallback(ellipsis_variants[j]) != NULL) // Verify glyph exists
{
font->EllipsisChar = ellipsis_variants[j];
break;
}
}
}
// 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::GetGlyphRangesKorean()
{
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3131, 0x3163, // Korean alphabets
0xAC00, 0xD7A3, // Korean characters
0,
};
return &ranges[0];
}
const ImWchar* ImFontAtlas::GetGlyphRangesChineseFull()
{
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF, // Half-width characters
0x4e00, 0x9FAF, // CJK Ideograms
0,
};
return &ranges[0];
}
static void UnpackAccumulativeOffsetsIntoRanges(int base_codepoint, const short* accumulative_offsets, int accumulative_offsets_count, ImWchar* out_ranges)
{
for (int n = 0; n < accumulative_offsets_count; n++, out_ranges += 2)
{
out_ranges[0] = out_ranges[1] = (ImWchar)(base_codepoint + accumulative_offsets[n]);
base_codepoint += accumulative_offsets[n];
}
out_ranges[0] = 0;
}
//-------------------------------------------------------------------------
// [SECTION] ImFontAtlas glyph ranges helpers
//-------------------------------------------------------------------------
const ImWchar* ImFontAtlas::GetGlyphRangesChineseSimplifiedCommon()
{
// Store 2500 regularly used characters for Simplified Chinese.
// Sourced from https://zh.wiktionary.org/wiki/%E9%99%84%E5%BD%95:%E7%8E%B0%E4%BB%A3%E6%B1%89%E8%AF%AD%E5%B8%B8%E7%94%A8%E5%AD%97%E8%A1%A8
// This table covers 97.97% of all characters used during the month in July, 1987.
// You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.
// (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)
static const short accumulative_offsets_from_0x4E00[] =
{
0,1,2,4,1,1,1,1,2,1,3,2,1,2,2,1,1,1,1,1,5,2,1,2,3,3,3,2,2,4,1,1,1,2,1,5,2,3,1,2,1,2,1,1,2,1,1,2,2,1,4,1,1,1,1,5,10,1,2,19,2,1,2,1,2,1,2,1,2,
1,5,1,6,3,2,1,2,2,1,1,1,4,8,5,1,1,4,1,1,3,1,2,1,5,1,2,1,1,1,10,1,1,5,2,4,6,1,4,2,2,2,12,2,1,1,6,1,1,1,4,1,1,4,6,5,1,4,2,2,4,10,7,1,1,4,2,4,
2,1,4,3,6,10,12,5,7,2,14,2,9,1,1,6,7,10,4,7,13,1,5,4,8,4,1,1,2,28,5,6,1,1,5,2,5,20,2,2,9,8,11,2,9,17,1,8,6,8,27,4,6,9,20,11,27,6,68,2,2,1,1,
1,2,1,2,2,7,6,11,3,3,1,1,3,1,2,1,1,1,1,1,3,1,1,8,3,4,1,5,7,2,1,4,4,8,4,2,1,2,1,1,4,5,6,3,6,2,12,3,1,3,9,2,4,3,4,1,5,3,3,1,3,7,1,5,1,1,1,1,2,
3,4,5,2,3,2,6,1,1,2,1,7,1,7,3,4,5,15,2,2,1,5,3,22,19,2,1,1,1,1,2,5,1,1,1,6,1,1,12,8,2,9,18,22,4,1,1,5,1,16,1,2,7,10,15,1,1,6,2,4,1,2,4,1,6,
1,1,3,2,4,1,6,4,5,1,2,1,1,2,1,10,3,1,3,2,1,9,3,2,5,7,2,19,4,3,6,1,1,1,1,1,4,3,2,1,1,1,2,5,3,1,1,1,2,2,1,1,2,1,1,2,1,3,1,1,1,3,7,1,4,1,1,2,1,
1,2,1,2,4,4,3,8,1,1,1,2,1,3,5,1,3,1,3,4,6,2,2,14,4,6,6,11,9,1,15,3,1,28,5,2,5,5,3,1,3,4,5,4,6,14,3,2,3,5,21,2,7,20,10,1,2,19,2,4,28,28,2,3,
2,1,14,4,1,26,28,42,12,40,3,52,79,5,14,17,3,2,2,11,3,4,6,3,1,8,2,23,4,5,8,10,4,2,7,3,5,1,1,6,3,1,2,2,2,5,28,1,1,7,7,20,5,3,29,3,17,26,1,8,4,
27,3,6,11,23,5,3,4,6,13,24,16,6,5,10,25,35,7,3,2,3,3,14,3,6,2,6,1,4,2,3,8,2,1,1,3,3,3,4,1,1,13,2,2,4,5,2,1,14,14,1,2,2,1,4,5,2,3,1,14,3,12,
3,17,2,16,5,1,2,1,8,9,3,19,4,2,2,4,17,25,21,20,28,75,1,10,29,103,4,1,2,1,1,4,2,4,1,2,3,24,2,2,2,1,1,2,1,3,8,1,1,1,2,1,1,3,1,1,1,6,1,5,3,1,1,
1,3,4,1,1,5,2,1,5,6,13,9,16,1,1,1,1,3,2,3,2,4,5,2,5,2,2,3,7,13,7,2,2,1,1,1,1,2,3,3,2,1,6,4,9,2,1,14,2,14,2,1,18,3,4,14,4,11,41,15,23,15,23,
176,1,3,4,1,1,1,1,5,3,1,2,3,7,3,1,1,2,1,2,4,4,6,2,4,1,9,7,1,10,5,8,16,29,1,1,2,2,3,1,3,5,2,4,5,4,1,1,2,2,3,3,7,1,6,10,1,17,1,44,4,6,2,1,1,6,
5,4,2,10,1,6,9,2,8,1,24,1,2,13,7,8,8,2,1,4,1,3,1,3,3,5,2,5,10,9,4,9,12,2,1,6,1,10,1,1,7,7,4,10,8,3,1,13,4,3,1,6,1,3,5,2,1,2,17,16,5,2,16,6,
1,4,2,1,3,3,6,8,5,11,11,1,3,3,2,4,6,10,9,5,7,4,7,4,7,1,1,4,2,1,3,6,8,7,1,6,11,5,5,3,24,9,4,2,7,13,5,1,8,82,16,61,1,1,1,4,2,2,16,10,3,8,1,1,
6,4,2,1,3,1,1,1,4,3,8,4,2,2,1,1,1,1,1,6,3,5,1,1,4,6,9,2,1,1,1,2,1,7,2,1,6,1,5,4,4,3,1,8,1,3,3,1,3,2,2,2,2,3,1,6,1,2,1,2,1,3,7,1,8,2,1,2,1,5,
2,5,3,5,10,1,2,1,1,3,2,5,11,3,9,3,5,1,1,5,9,1,2,1,5,7,9,9,8,1,3,3,3,6,8,2,3,2,1,1,32,6,1,2,15,9,3,7,13,1,3,10,13,2,14,1,13,10,2,1,3,10,4,15,
2,15,15,10,1,3,9,6,9,32,25,26,47,7,3,2,3,1,6,3,4,3,2,8,5,4,1,9,4,2,2,19,10,6,2,3,8,1,2,2,4,2,1,9,4,4,4,6,4,8,9,2,3,1,1,1,1,3,5,5,1,3,8,4,6,
2,1,4,12,1,5,3,7,13,2,5,8,1,6,1,2,5,14,6,1,5,2,4,8,15,5,1,23,6,62,2,10,1,1,8,1,2,2,10,4,2,2,9,2,1,1,3,2,3,1,5,3,3,2,1,3,8,1,1,1,11,3,1,1,4,
3,7,1,14,1,2,3,12,5,2,5,1,6,7,5,7,14,11,1,3,1,8,9,12,2,1,11,8,4,4,2,6,10,9,13,1,1,3,1,5,1,3,2,4,4,1,18,2,3,14,11,4,29,4,2,7,1,3,13,9,2,2,5,
3,5,20,7,16,8,5,72,34,6,4,22,12,12,28,45,36,9,7,39,9,191,1,1,1,4,11,8,4,9,2,3,22,1,1,1,1,4,17,1,7,7,1,11,31,10,2,4,8,2,3,2,1,4,2,16,4,32,2,
3,19,13,4,9,1,5,2,14,8,1,1,3,6,19,6,5,1,16,6,2,10,8,5,1,2,3,1,5,5,1,11,6,6,1,3,3,2,6,3,8,1,1,4,10,7,5,7,7,5,8,9,2,1,3,4,1,1,3,1,3,3,2,6,16,
1,4,6,3,1,10,6,1,3,15,2,9,2,10,25,13,9,16,6,2,2,10,11,4,3,9,1,2,6,6,5,4,30,40,1,10,7,12,14,33,6,3,6,7,3,1,3,1,11,14,4,9,5,12,11,49,18,51,31,
140,31,2,2,1,5,1,8,1,10,1,4,4,3,24,1,10,1,3,6,6,16,3,4,5,2,1,4,2,57,10,6,22,2,22,3,7,22,6,10,11,36,18,16,33,36,2,5,5,1,1,1,4,10,1,4,13,2,7,
5,2,9,3,4,1,7,43,3,7,3,9,14,7,9,1,11,1,1,3,7,4,18,13,1,14,1,3,6,10,73,2,2,30,6,1,11,18,19,13,22,3,46,42,37,89,7,3,16,34,2,2,3,9,1,7,1,1,1,2,
2,4,10,7,3,10,3,9,5,28,9,2,6,13,7,3,1,3,10,2,7,2,11,3,6,21,54,85,2,1,4,2,2,1,39,3,21,2,2,5,1,1,1,4,1,1,3,4,15,1,3,2,4,4,2,3,8,2,20,1,8,7,13,
4,1,26,6,2,9,34,4,21,52,10,4,4,1,5,12,2,11,1,7,2,30,12,44,2,30,1,1,3,6,16,9,17,39,82,2,2,24,7,1,7,3,16,9,14,44,2,1,2,1,2,3,5,2,4,1,6,7,5,3,
2,6,1,11,5,11,2,1,18,19,8,1,3,24,29,2,1,3,5,2,2,1,13,6,5,1,46,11,3,5,1,1,5,8,2,10,6,12,6,3,7,11,2,4,16,13,2,5,1,1,2,2,5,2,28,5,2,23,10,8,4,
4,22,39,95,38,8,14,9,5,1,13,5,4,3,13,12,11,1,9,1,27,37,2,5,4,4,63,211,95,2,2,2,1,3,5,2,1,1,2,2,1,1,1,3,2,4,1,2,1,1,5,2,2,1,1,2,3,1,3,1,1,1,
3,1,4,2,1,3,6,1,1,3,7,15,5,3,2,5,3,9,11,4,2,22,1,6,3,8,7,1,4,28,4,16,3,3,25,4,4,27,27,1,4,1,2,2,7,1,3,5,2,28,8,2,14,1,8,6,16,25,3,3,3,14,3,
3,1,1,2,1,4,6,3,8,4,1,1,1,2,3,6,10,6,2,3,18,3,2,5,5,4,3,1,5,2,5,4,23,7,6,12,6,4,17,11,9,5,1,1,10,5,12,1,1,11,26,33,7,3,6,1,17,7,1,5,12,1,11,
2,4,1,8,14,17,23,1,2,1,7,8,16,11,9,6,5,2,6,4,16,2,8,14,1,11,8,9,1,1,1,9,25,4,11,19,7,2,15,2,12,8,52,7,5,19,2,16,4,36,8,1,16,8,24,26,4,6,2,9,
5,4,36,3,28,12,25,15,37,27,17,12,59,38,5,32,127,1,2,9,17,14,4,1,2,1,1,8,11,50,4,14,2,19,16,4,17,5,4,5,26,12,45,2,23,45,104,30,12,8,3,10,2,2,
3,3,1,4,20,7,2,9,6,15,2,20,1,3,16,4,11,15,6,134,2,5,59,1,2,2,2,1,9,17,3,26,137,10,211,59,1,2,4,1,4,1,1,1,2,6,2,3,1,1,2,3,2,3,1,3,4,4,2,3,3,
1,4,3,1,7,2,2,3,1,2,1,3,3,3,2,2,3,2,1,3,14,6,1,3,2,9,6,15,27,9,34,145,1,1,2,1,1,1,1,2,1,1,1,1,2,2,2,3,1,2,1,1,1,2,3,5,8,3,5,2,4,1,3,2,2,2,12,
4,1,1,1,10,4,5,1,20,4,16,1,15,9,5,12,2,9,2,5,4,2,26,19,7,1,26,4,30,12,15,42,1,6,8,172,1,1,4,2,1,1,11,2,2,4,2,1,2,1,10,8,1,2,1,4,5,1,2,5,1,8,
4,1,3,4,2,1,6,2,1,3,4,1,2,1,1,1,1,12,5,7,2,4,3,1,1,1,3,3,6,1,2,2,3,3,3,2,1,2,12,14,11,6,6,4,12,2,8,1,7,10,1,35,7,4,13,15,4,3,23,21,28,52,5,
26,5,6,1,7,10,2,7,53,3,2,1,1,1,2,163,532,1,10,11,1,3,3,4,8,2,8,6,2,2,23,22,4,2,2,4,2,1,3,1,3,3,5,9,8,2,1,2,8,1,10,2,12,21,20,15,105,2,3,1,1,
3,2,3,1,1,2,5,1,4,15,11,19,1,1,1,1,5,4,5,1,1,2,5,3,5,12,1,2,5,1,11,1,1,15,9,1,4,5,3,26,8,2,1,3,1,1,15,19,2,12,1,2,5,2,7,2,19,2,20,6,26,7,5,
2,2,7,34,21,13,70,2,128,1,1,2,1,1,2,1,1,3,2,2,2,15,1,4,1,3,4,42,10,6,1,49,85,8,1,2,1,1,4,4,2,3,6,1,5,7,4,3,211,4,1,2,1,2,5,1,2,4,2,2,6,5,6,
10,3,4,48,100,6,2,16,296,5,27,387,2,2,3,7,16,8,5,38,15,39,21,9,10,3,7,59,13,27,21,47,5,21,6
};
static ImWchar base_ranges[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x2000, 0x206F, // General Punctuation
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF // Half-width characters
};
static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00) * 2 + 1] = { 0 };
if (!full_ranges[0])
{
memcpy(full_ranges, base_ranges, sizeof(base_ranges));
UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges));
}
return &full_ranges[0];
}
const ImWchar* ImFontAtlas::GetGlyphRangesJapanese()
{
// 2999 ideograms code points for Japanese
// - 2136 Joyo (meaning "for regular use" or "for common use") Kanji code points
// - 863 Jinmeiyo (meaning "for personal name") Kanji code points
// - Sourced from the character information database of the Information-technology Promotion Agency, Japan
// - https://mojikiban.ipa.go.jp/mji/
// - Available under the terms of the Creative Commons Attribution-ShareAlike 2.1 Japan (CC BY-SA 2.1 JP).
// - https://creativecommons.org/licenses/by-sa/2.1/jp/deed.en
// - https://creativecommons.org/licenses/by-sa/2.1/jp/legalcode
// - You can generate this code by the script at:
// - https://github.com/vaiorabbit/everyday_use_kanji
// - References:
// - List of Joyo Kanji
// - (Official list by the Agency for Cultural Affairs) https://www.bunka.go.jp/kokugo_nihongo/sisaku/joho/joho/kakuki/14/tosin02/index.html
// - (Wikipedia) https://en.wikipedia.org/wiki/List_of_j%C5%8Dy%C5%8D_kanji
// - List of Jinmeiyo Kanji
// - (Official list by the Ministry of Justice) http://www.moj.go.jp/MINJI/minji86.html
// - (Wikipedia) https://en.wikipedia.org/wiki/Jinmeiy%C5%8D_kanji
// - Missing 1 Joyo Kanji: U+20B9F (Kun'yomi: Shikaru, On'yomi: Shitsu,shichi), see https://github.com/ocornut/imgui/pull/3627 for details.
// You can use ImFontGlyphRangesBuilder to create your own ranges derived from this, by merging existing ranges or adding new characters.
// (Stored as accumulative offsets from the initial unicode codepoint 0x4E00. This encoding is designed to helps us compact the source code size.)
static const short accumulative_offsets_from_0x4E00[] =
{
0,1,2,4,1,1,1,1,2,1,3,3,2,2,1,5,3,5,7,5,6,1,2,1,7,2,6,3,1,8,1,1,4,1,1,18,2,11,2,6,2,1,2,1,5,1,2,1,3,1,2,1,2,3,3,1,1,2,3,1,1,1,12,7,9,1,4,5,1,
1,2,1,10,1,1,9,2,2,4,5,6,9,3,1,1,1,1,9,3,18,5,2,2,2,2,1,6,3,7,1,1,1,1,2,2,4,2,1,23,2,10,4,3,5,2,4,10,2,4,13,1,6,1,9,3,1,1,6,6,7,6,3,1,2,11,3,
2,2,3,2,15,2,2,5,4,3,6,4,1,2,5,2,12,16,6,13,9,13,2,1,1,7,16,4,7,1,19,1,5,1,2,2,7,7,8,2,6,5,4,9,18,7,4,5,9,13,11,8,15,2,1,1,1,2,1,2,2,1,2,2,8,
2,9,3,3,1,1,4,4,1,1,1,4,9,1,4,3,5,5,2,7,5,3,4,8,2,1,13,2,3,3,1,14,1,1,4,5,1,3,6,1,5,2,1,1,3,3,3,3,1,1,2,7,6,6,7,1,4,7,6,1,1,1,1,1,12,3,3,9,5,
2,6,1,5,6,1,2,3,18,2,4,14,4,1,3,6,1,1,6,3,5,5,3,2,2,2,2,12,3,1,4,2,3,2,3,11,1,7,4,1,2,1,3,17,1,9,1,24,1,1,4,2,2,4,1,2,7,1,1,1,3,1,2,2,4,15,1,
1,2,1,1,2,1,5,2,5,20,2,5,9,1,10,8,7,6,1,1,1,1,1,1,6,2,1,2,8,1,1,1,1,5,1,1,3,1,1,1,1,3,1,1,12,4,1,3,1,1,1,1,1,10,3,1,7,5,13,1,2,3,4,6,1,1,30,
2,9,9,1,15,38,11,3,1,8,24,7,1,9,8,10,2,1,9,31,2,13,6,2,9,4,49,5,2,15,2,1,10,2,1,1,1,2,2,6,15,30,35,3,14,18,8,1,16,10,28,12,19,45,38,1,3,2,3,
13,2,1,7,3,6,5,3,4,3,1,5,7,8,1,5,3,18,5,3,6,1,21,4,24,9,24,40,3,14,3,21,3,2,1,2,4,2,3,1,15,15,6,5,1,1,3,1,5,6,1,9,7,3,3,2,1,4,3,8,21,5,16,4,
5,2,10,11,11,3,6,3,2,9,3,6,13,1,2,1,1,1,1,11,12,6,6,1,4,2,6,5,2,1,1,3,3,6,13,3,1,1,5,1,2,3,3,14,2,1,2,2,2,5,1,9,5,1,1,6,12,3,12,3,4,13,2,14,
2,8,1,17,5,1,16,4,2,2,21,8,9,6,23,20,12,25,19,9,38,8,3,21,40,25,33,13,4,3,1,4,1,2,4,1,2,5,26,2,1,1,2,1,3,6,2,1,1,1,1,1,1,2,3,1,1,1,9,2,3,1,1,
1,3,6,3,2,1,1,6,6,1,8,2,2,2,1,4,1,2,3,2,7,3,2,4,1,2,1,2,2,1,1,1,1,1,3,1,2,5,4,10,9,4,9,1,1,1,1,1,1,5,3,2,1,6,4,9,6,1,10,2,31,17,8,3,7,5,40,1,
7,7,1,6,5,2,10,7,8,4,15,39,25,6,28,47,18,10,7,1,3,1,1,2,1,1,1,3,3,3,1,1,1,3,4,2,1,4,1,3,6,10,7,8,6,2,2,1,3,3,2,5,8,7,9,12,2,15,1,1,4,1,2,1,1,
1,3,2,1,3,3,5,6,2,3,2,10,1,4,2,8,1,1,1,11,6,1,21,4,16,3,1,3,1,4,2,3,6,5,1,3,1,1,3,3,4,6,1,1,10,4,2,7,10,4,7,4,2,9,4,3,1,1,1,4,1,8,3,4,1,3,1,
6,1,4,2,1,4,7,2,1,8,1,4,5,1,1,2,2,4,6,2,7,1,10,1,1,3,4,11,10,8,21,4,6,1,3,5,2,1,2,28,5,5,2,3,13,1,2,3,1,4,2,1,5,20,3,8,11,1,3,3,3,1,8,10,9,2,
10,9,2,3,1,1,2,4,1,8,3,6,1,7,8,6,11,1,4,29,8,4,3,1,2,7,13,1,4,1,6,2,6,12,12,2,20,3,2,3,6,4,8,9,2,7,34,5,1,18,6,1,1,4,4,5,7,9,1,2,2,4,3,4,1,7,
2,2,2,6,2,3,25,5,3,6,1,4,6,7,4,2,1,4,2,13,6,4,4,3,1,5,3,4,4,3,2,1,1,4,1,2,1,1,3,1,11,1,6,3,1,7,3,6,2,8,8,6,9,3,4,11,3,2,10,12,2,5,11,1,6,4,5,
3,1,8,5,4,6,6,3,5,1,1,3,2,1,2,2,6,17,12,1,10,1,6,12,1,6,6,19,9,6,16,1,13,4,4,15,7,17,6,11,9,15,12,6,7,2,1,2,2,15,9,3,21,4,6,49,18,7,3,2,3,1,
6,8,2,2,6,2,9,1,3,6,4,4,1,2,16,2,5,2,1,6,2,3,5,3,1,2,5,1,2,1,9,3,1,8,6,4,8,11,3,1,1,1,1,3,1,13,8,4,1,3,2,2,1,4,1,11,1,5,2,1,5,2,5,8,6,1,1,7,
4,3,8,3,2,7,2,1,5,1,5,2,4,7,6,2,8,5,1,11,4,5,3,6,18,1,2,13,3,3,1,21,1,1,4,1,4,1,1,1,8,1,2,2,7,1,2,4,2,2,9,2,1,1,1,4,3,6,3,12,5,1,1,1,5,6,3,2,
4,8,2,2,4,2,7,1,8,9,5,2,3,2,1,3,2,13,7,14,6,5,1,1,2,1,4,2,23,2,1,1,6,3,1,4,1,15,3,1,7,3,9,14,1,3,1,4,1,1,5,8,1,3,8,3,8,15,11,4,14,4,4,2,5,5,
1,7,1,6,14,7,7,8,5,15,4,8,6,5,6,2,1,13,1,20,15,11,9,2,5,6,2,11,2,6,2,5,1,5,8,4,13,19,25,4,1,1,11,1,34,2,5,9,14,6,2,2,6,1,1,14,1,3,14,13,1,6,
12,21,14,14,6,32,17,8,32,9,28,1,2,4,11,8,3,1,14,2,5,15,1,1,1,1,3,6,4,1,3,4,11,3,1,1,11,30,1,5,1,4,1,5,8,1,1,3,2,4,3,17,35,2,6,12,17,3,1,6,2,
1,1,12,2,7,3,3,2,1,16,2,8,3,6,5,4,7,3,3,8,1,9,8,5,1,2,1,3,2,8,1,2,9,12,1,1,2,3,8,3,24,12,4,3,7,5,8,3,3,3,3,3,3,1,23,10,3,1,2,2,6,3,1,16,1,16,
22,3,10,4,11,6,9,7,7,3,6,2,2,2,4,10,2,1,1,2,8,7,1,6,4,1,3,3,3,5,10,12,12,2,3,12,8,15,1,1,16,6,6,1,5,9,11,4,11,4,2,6,12,1,17,5,13,1,4,9,5,1,11,
2,1,8,1,5,7,28,8,3,5,10,2,17,3,38,22,1,2,18,12,10,4,38,18,1,4,44,19,4,1,8,4,1,12,1,4,31,12,1,14,7,75,7,5,10,6,6,13,3,2,11,11,3,2,5,28,15,6,18,
18,5,6,4,3,16,1,7,18,7,36,3,5,3,1,7,1,9,1,10,7,2,4,2,6,2,9,7,4,3,32,12,3,7,10,2,23,16,3,1,12,3,31,4,11,1,3,8,9,5,1,30,15,6,12,3,2,2,11,19,9,
14,2,6,2,3,19,13,17,5,3,3,25,3,14,1,1,1,36,1,3,2,19,3,13,36,9,13,31,6,4,16,34,2,5,4,2,3,3,5,1,1,1,4,3,1,17,3,2,3,5,3,1,3,2,3,5,6,3,12,11,1,3,
1,2,26,7,12,7,2,14,3,3,7,7,11,25,25,28,16,4,36,1,2,1,6,2,1,9,3,27,17,4,3,4,13,4,1,3,2,2,1,10,4,2,4,6,3,8,2,1,18,1,1,24,2,2,4,33,2,3,63,7,1,6,
40,7,3,4,4,2,4,15,18,1,16,1,1,11,2,41,14,1,3,18,13,3,2,4,16,2,17,7,15,24,7,18,13,44,2,2,3,6,1,1,7,5,1,7,1,4,3,3,5,10,8,2,3,1,8,1,1,27,4,2,1,
12,1,2,1,10,6,1,6,7,5,2,3,7,11,5,11,3,6,6,2,3,15,4,9,1,1,2,1,2,11,2,8,12,8,5,4,2,3,1,5,2,2,1,14,1,12,11,4,1,11,17,17,4,3,2,5,5,7,3,1,5,9,9,8,
2,5,6,6,13,13,2,1,2,6,1,2,2,49,4,9,1,2,10,16,7,8,4,3,2,23,4,58,3,29,1,14,19,19,11,11,2,7,5,1,3,4,6,2,18,5,12,12,17,17,3,3,2,4,1,6,2,3,4,3,1,
1,1,1,5,1,1,9,1,3,1,3,6,1,8,1,1,2,6,4,14,3,1,4,11,4,1,3,32,1,2,4,13,4,1,2,4,2,1,3,1,11,1,4,2,1,4,4,6,3,5,1,6,5,7,6,3,23,3,5,3,5,3,3,13,3,9,10,
1,12,10,2,3,18,13,7,160,52,4,2,2,3,2,14,5,4,12,4,6,4,1,20,4,11,6,2,12,27,1,4,1,2,2,7,4,5,2,28,3,7,25,8,3,19,3,6,10,2,2,1,10,2,5,4,1,3,4,1,5,
3,2,6,9,3,6,2,16,3,3,16,4,5,5,3,2,1,2,16,15,8,2,6,21,2,4,1,22,5,8,1,1,21,11,2,1,11,11,19,13,12,4,2,3,2,3,6,1,8,11,1,4,2,9,5,2,1,11,2,9,1,1,2,
14,31,9,3,4,21,14,4,8,1,7,2,2,2,5,1,4,20,3,3,4,10,1,11,9,8,2,1,4,5,14,12,14,2,17,9,6,31,4,14,1,20,13,26,5,2,7,3,6,13,2,4,2,19,6,2,2,18,9,3,5,
12,12,14,4,6,2,3,6,9,5,22,4,5,25,6,4,8,5,2,6,27,2,35,2,16,3,7,8,8,6,6,5,9,17,2,20,6,19,2,13,3,1,1,1,4,17,12,2,14,7,1,4,18,12,38,33,2,10,1,1,
2,13,14,17,11,50,6,33,20,26,74,16,23,45,50,13,38,33,6,6,7,4,4,2,1,3,2,5,8,7,8,9,3,11,21,9,13,1,3,10,6,7,1,2,2,18,5,5,1,9,9,2,68,9,19,13,2,5,
1,4,4,7,4,13,3,9,10,21,17,3,26,2,1,5,2,4,5,4,1,7,4,7,3,4,2,1,6,1,1,20,4,1,9,2,2,1,3,3,2,3,2,1,1,1,20,2,3,1,6,2,3,6,2,4,8,1,3,2,10,3,5,3,4,4,
3,4,16,1,6,1,10,2,4,2,1,1,2,10,11,2,2,3,1,24,31,4,10,10,2,5,12,16,164,15,4,16,7,9,15,19,17,1,2,1,1,5,1,1,1,1,1,3,1,4,3,1,3,1,3,1,2,1,1,3,3,7,
2,8,1,2,2,2,1,3,4,3,7,8,12,92,2,10,3,1,3,14,5,25,16,42,4,7,7,4,2,21,5,27,26,27,21,25,30,31,2,1,5,13,3,22,5,6,6,11,9,12,1,5,9,7,5,5,22,60,3,5,
13,1,1,8,1,1,3,3,2,1,9,3,3,18,4,1,2,3,7,6,3,1,2,3,9,1,3,1,3,2,1,3,1,1,1,2,1,11,3,1,6,9,1,3,2,3,1,2,1,5,1,1,4,3,4,1,2,2,4,4,1,7,2,1,2,2,3,5,13,
18,3,4,14,9,9,4,16,3,7,5,8,2,6,48,28,3,1,1,4,2,14,8,2,9,2,1,15,2,4,3,2,10,16,12,8,7,1,1,3,1,1,1,2,7,4,1,6,4,38,39,16,23,7,15,15,3,2,12,7,21,
37,27,6,5,4,8,2,10,8,8,6,5,1,2,1,3,24,1,16,17,9,23,10,17,6,1,51,55,44,13,294,9,3,6,2,4,2,2,15,1,1,1,13,21,17,68,14,8,9,4,1,4,9,3,11,7,1,1,1,
5,6,3,2,1,1,1,2,3,8,1,2,2,4,1,5,5,2,1,4,3,7,13,4,1,4,1,3,1,1,1,5,5,10,1,6,1,5,2,1,5,2,4,1,4,5,7,3,18,2,9,11,32,4,3,3,2,4,7,11,16,9,11,8,13,38,
32,8,4,2,1,1,2,1,2,4,4,1,1,1,4,1,21,3,11,1,16,1,1,6,1,3,2,4,9,8,57,7,44,1,3,3,13,3,10,1,1,7,5,2,7,21,47,63,3,15,4,7,1,16,1,1,2,8,2,3,42,15,4,
1,29,7,22,10,3,78,16,12,20,18,4,67,11,5,1,3,15,6,21,31,32,27,18,13,71,35,5,142,4,10,1,2,50,19,33,16,35,37,16,19,27,7,1,133,19,1,4,8,7,20,1,4,
4,1,10,3,1,6,1,2,51,5,40,15,24,43,22928,11,1,13,154,70,3,1,1,7,4,10,1,2,1,1,2,1,2,1,2,2,1,1,2,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,
3,2,1,1,1,1,2,1,1,
};
static ImWchar base_ranges[] = // not zero-terminated
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x3000, 0x30FF, // CJK Symbols and Punctuations, Hiragana, Katakana
0x31F0, 0x31FF, // Katakana Phonetic Extensions
0xFF00, 0xFFEF // Half-width characters
};
static ImWchar full_ranges[IM_ARRAYSIZE(base_ranges) + IM_ARRAYSIZE(accumulative_offsets_from_0x4E00)*2 + 1] = { 0 };
if (!full_ranges[0])
{
memcpy(full_ranges, base_ranges, sizeof(base_ranges));
UnpackAccumulativeOffsetsIntoRanges(0x4E00, accumulative_offsets_from_0x4E00, IM_ARRAYSIZE(accumulative_offsets_from_0x4E00), full_ranges + IM_ARRAYSIZE(base_ranges));
}
return &full_ranges[0];
}
const ImWchar* ImFontAtlas::GetGlyphRangesCyrillic()
{
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin + Latin Supplement
0x0400, 0x052F, // Cyrillic + Cyrillic Supplement
0x2DE0, 0x2DFF, // Cyrillic Extended-A
0xA640, 0xA69F, // Cyrillic Extended-B
0,
};
return &ranges[0];
}
const ImWchar* ImFontAtlas::GetGlyphRangesThai()
{
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin
0x2010, 0x205E, // Punctuations
0x0E00, 0x0E7F, // Thai
0,
};
return &ranges[0];
}
const ImWchar* ImFontAtlas::GetGlyphRangesVietnamese()
{
static const ImWchar ranges[] =
{
0x0020, 0x00FF, // Basic Latin
0x0102, 0x0103,
0x0110, 0x0111,
0x0128, 0x0129,
0x0168, 0x0169,
0x01A0, 0x01A1,
0x01AF, 0x01B0,
0x1EA0, 0x1EF9,
0,
};
return &ranges[0];
}
//-----------------------------------------------------------------------------
// [SECTION] ImFontGlyphRangesBuilder
//-----------------------------------------------------------------------------
void ImFontGlyphRangesBuilder::AddText(const char* text, const char* text_end)
{
while (text_end ? (text < text_end) : *text)
{
unsigned int c = 0;
int c_len = ImTextCharFromUtf8(&c, text, text_end);
text += c_len;
if (c_len == 0)
break;
AddChar((ImWchar)c);
}
}
void ImFontGlyphRangesBuilder::AddRanges(const ImWchar* ranges)
{
for (; ranges[0]; ranges += 2)
for (ImWchar c = ranges[0]; c <= ranges[1]; c++)
AddChar(c);
}
void ImFontGlyphRangesBuilder::BuildRanges(ImVector<ImWchar>* out_ranges)
{
const int max_codepoint = IM_UNICODE_CODEPOINT_MAX;
for (int n = 0; n <= max_codepoint; n++)
if (GetBit(n))
{
out_ranges->push_back((ImWchar)n);
while (n < max_codepoint && GetBit(n + 1))
n++;
out_ranges->push_back((ImWchar)n);
}
out_ranges->push_back(0);
}
//-----------------------------------------------------------------------------
// [SECTION] ImFont
//-----------------------------------------------------------------------------
ImFont::ImFont()
{
FontSize = 0.0f;
FallbackAdvanceX = 0.0f;
FallbackChar = (ImWchar)'?';
EllipsisChar = (ImWchar)-1;
FallbackGlyph = NULL;
ContainerAtlas = NULL;
ConfigData = NULL;
ConfigDataCount = 0;
DirtyLookupTables = false;
Scale = 1.0f;
Ascent = Descent = 0.0f;
MetricsTotalSurface = 0;
memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
}
ImFont::~ImFont()
{
ClearOutputData();
}
void ImFont::ClearOutputData()
{
FontSize = 0.0f;
FallbackAdvanceX = 0.0f;
Glyphs.clear();
IndexAdvanceX.clear();
IndexLookup.clear();
FallbackGlyph = NULL;
ContainerAtlas = NULL;
DirtyLookupTables = true;
Ascent = Descent = 0.0f;
MetricsTotalSurface = 0;
}
void ImFont::BuildLookupTable()
{
int max_codepoint = 0;
for (int i = 0; i != Glyphs.Size; i++)
max_codepoint = ImMax(max_codepoint, (int)Glyphs[i].Codepoint);
// Build lookup table
IM_ASSERT(Glyphs.Size < 0xFFFF); // -1 is reserved
IndexAdvanceX.clear();
IndexLookup.clear();
DirtyLookupTables = false;
memset(Used4kPagesMap, 0, sizeof(Used4kPagesMap));
GrowIndex(max_codepoint + 1);
for (int i = 0; i < Glyphs.Size; i++)
{
int codepoint = (int)Glyphs[i].Codepoint;
IndexAdvanceX[codepoint] = Glyphs[i].AdvanceX;
IndexLookup[codepoint] = (ImWchar)i;
// Mark 4K page as used
const int page_n = codepoint / 4096;
Used4kPagesMap[page_n >> 3] |= 1 << (page_n & 7);
}
// Create a glyph to handle TAB
// FIXME: Needs proper TAB handling but it needs to be contextualized (or we could arbitrary say that each string starts at "column 0" ?)
if (FindGlyph((ImWchar)' '))
{
if (Glyphs.back().Codepoint != '\t') // So we can call this function multiple times (FIXME: Flaky)
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph& tab_glyph = Glyphs.back();
tab_glyph = *FindGlyph((ImWchar)' ');
tab_glyph.Codepoint = '\t';
tab_glyph.AdvanceX *= IM_TABSIZE;
IndexAdvanceX[(int)tab_glyph.Codepoint] = (float)tab_glyph.AdvanceX;
IndexLookup[(int)tab_glyph.Codepoint] = (ImWchar)(Glyphs.Size - 1);
}
// Mark special glyphs as not visible (note that AddGlyph already mark as non-visible glyphs with zero-size polygons)
SetGlyphVisible((ImWchar)' ', false);
SetGlyphVisible((ImWchar)'\t', false);
// Setup fall-backs
FallbackGlyph = FindGlyphNoFallback(FallbackChar);
FallbackAdvanceX = FallbackGlyph ? FallbackGlyph->AdvanceX : 0.0f;
for (int i = 0; i < max_codepoint + 1; i++)
if (IndexAdvanceX[i] < 0.0f)
IndexAdvanceX[i] = FallbackAdvanceX;
}
// API is designed this way to avoid exposing the 4K page size
// e.g. use with IsGlyphRangeUnused(0, 255)
bool ImFont::IsGlyphRangeUnused(unsigned int c_begin, unsigned int c_last)
{
unsigned int page_begin = (c_begin / 4096);
unsigned int page_last = (c_last / 4096);
for (unsigned int page_n = page_begin; page_n <= page_last; page_n++)
if ((page_n >> 3) < sizeof(Used4kPagesMap))
if (Used4kPagesMap[page_n >> 3] & (1 << (page_n & 7)))
return false;
return true;
}
void ImFont::SetGlyphVisible(ImWchar c, bool visible)
{
if (ImFontGlyph* glyph = (ImFontGlyph*)(void*)FindGlyph((ImWchar)c))
glyph->Visible = visible ? 1 : 0;
}
void ImFont::SetFallbackChar(ImWchar c)
{
FallbackChar = c;
BuildLookupTable();
}
void ImFont::GrowIndex(int new_size)
{
IM_ASSERT(IndexAdvanceX.Size == IndexLookup.Size);
if (new_size <= IndexLookup.Size)
return;
IndexAdvanceX.resize(new_size, -1.0f);
IndexLookup.resize(new_size, (ImWchar)-1);
}
// x0/y0/x1/y1 are offset from the character upper-left layout position, in pixels. Therefore x0/y0 are often fairly close to zero.
// Not to be mistaken with texture coordinates, which are held by u0/v0/u1/v1 in normalized format (0.0..1.0 on each texture axis).
// 'cfg' is not necessarily == 'this->ConfigData' because multiple source fonts+configs can be used to build one target font.
void ImFont::AddGlyph(const ImFontConfig* cfg, ImWchar codepoint, float x0, float y0, float x1, float y1, float u0, float v0, float u1, float v1, float advance_x)
{
if (cfg != NULL)
{
// Clamp & recenter if needed
const float advance_x_original = advance_x;
advance_x = ImClamp(advance_x, cfg->GlyphMinAdvanceX, cfg->GlyphMaxAdvanceX);
if (advance_x != advance_x_original)
{
float char_off_x = cfg->PixelSnapH ? ImFloor((advance_x - advance_x_original) * 0.5f) : (advance_x - advance_x_original) * 0.5f;
x0 += char_off_x;
x1 += char_off_x;
}
// Snap to pixel
if (cfg->PixelSnapH)
advance_x = IM_ROUND(advance_x);
// Bake spacing
advance_x += cfg->GlyphExtraSpacing.x;
}
Glyphs.resize(Glyphs.Size + 1);
ImFontGlyph& glyph = Glyphs.back();
glyph.Codepoint = (unsigned int)codepoint;
glyph.Visible = (x0 != x1) && (y0 != y1);
glyph.Colored = false;
glyph.X0 = x0;
glyph.Y0 = y0;
glyph.X1 = x1;
glyph.Y1 = y1;
glyph.U0 = u0;
glyph.V0 = v0;
glyph.U1 = u1;
glyph.V1 = v1;
glyph.AdvanceX = advance_x;
// Compute rough surface usage metrics (+1 to account for average padding, +0.99 to round)
// We use (U1-U0)*TexWidth instead of X1-X0 to account for oversampling.
float pad = ContainerAtlas->TexGlyphPadding + 0.99f;
DirtyLookupTables = true;
MetricsTotalSurface += (int)((glyph.U1 - glyph.U0) * ContainerAtlas->TexWidth + pad) * (int)((glyph.V1 - glyph.V0) * ContainerAtlas->TexHeight + pad);
}
void ImFont::AddRemapChar(ImWchar dst, ImWchar src, bool overwrite_dst)
{
IM_ASSERT(IndexLookup.Size > 0); // Currently this can only be called AFTER the font has been built, aka after calling ImFontAtlas::GetTexDataAs*() function.
unsigned int index_size = (unsigned int)IndexLookup.Size;
if (dst < index_size && IndexLookup.Data[dst] == (ImWchar)-1 && !overwrite_dst) // 'dst' already exists
return;
if (src >= index_size && dst >= index_size) // both 'dst' and 'src' don't exist -> no-op
return;
GrowIndex(dst + 1);
IndexLookup[dst] = (src < index_size) ? IndexLookup.Data[src] : (ImWchar)-1;
IndexAdvanceX[dst] = (src < index_size) ? IndexAdvanceX.Data[src] : 1.0f;
}
const ImFontGlyph* ImFont::FindGlyph(ImWchar c) const
{
if (c >= (size_t)IndexLookup.Size)
return FallbackGlyph;
const ImWchar i = IndexLookup.Data[c];
if (i == (ImWchar)-1)
return FallbackGlyph;
return &Glyphs.Data[i];
}
const ImFontGlyph* ImFont::FindGlyphNoFallback(ImWchar c) const
{
if (c >= (size_t)IndexLookup.Size)
return NULL;
const ImWchar i = IndexLookup.Data[c];
if (i == (ImWchar)-1)
return NULL;
return &Glyphs.Data[i];
}
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;
wrap_width /= scale; // We work with unscaled widths to avoid scaling every characters
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 < 32)
{
if (c == '\n')
{
line_width = word_width = blank_width = 0.0f;
inside_word = true;
s = next_s;
continue;
}
if (c == '\r')
{
s = next_s;
continue;
}
}
const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX);
if (ImCharIsBlankW(c))
{
if (inside_word)
{
line_width += blank_width;
blank_width = 0.0f;
word_end = s;
}
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 line_height = size;
const float scale = size / FontSize;
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 (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
}
continue;
}
}
// Decode and advance source
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) // Malformed UTF-8?
break;
}
if (c < 32)
{
if (c == '\n')
{
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
continue;
}
if (c == '\r')
continue;
}
const float char_width = ((int)c < IndexAdvanceX.Size ? IndexAdvanceX.Data[c] : FallbackAdvanceX) * scale;
if (line_width + char_width >= max_width)
{
s = prev_s;
break;
}
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (line_width > 0 || text_size.y == 0.0f)
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
void ImFont::RenderChar(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, ImWchar c) const
{
const ImFontGlyph* glyph = FindGlyph(c);
if (!glyph || !glyph->Visible)
return;
if (glyph->Colored)
col |= ~IM_COL32_A_MASK;
float scale = (size >= 0.0f) ? (size / FontSize) : 1.0f;
pos.x = IM_FLOOR(pos.x);
pos.y = IM_FLOOR(pos.y);
draw_list->PrimReserve(6, 4);
draw_list->PrimRectUV(ImVec2(pos.x + glyph->X0 * scale, pos.y + glyph->Y0 * scale), ImVec2(pos.x + glyph->X1 * scale, pos.y + glyph->Y1 * scale), ImVec2(glyph->U0, glyph->V0), ImVec2(glyph->U1, glyph->V1), col);
}
// Note: as with every ImDrawList drawing function, this expects that the font atlas texture is bound.
void ImFont::RenderText(ImDrawList* draw_list, float size, ImVec2 pos, ImU32 col, const ImVec4& clip_rect, const char* text_begin, const char* text_end, float wrap_width, bool cpu_fine_clip) const
{
if (!text_end)
text_end = text_begin + strlen(text_begin); // ImGui:: functions generally already provides a valid text_end, so this is merely to handle direct calls.
// Align to be pixel perfect
pos.x = IM_FLOOR(pos.x);
pos.y = IM_FLOOR(pos.y);
float x = pos.x;
float y = pos.y;
if (y > clip_rect.w)
return;
const float scale = size / FontSize;
const float line_height = FontSize * scale;
const bool word_wrap_enabled = (wrap_width > 0.0f);
const char* word_wrap_eol = NULL;
// Fast-forward to first visible line
const char* s = text_begin;
if (y + line_height < clip_rect.y && !word_wrap_enabled)
while (y + line_height < clip_rect.y && s < text_end)
{
s = (const char*)memchr(s, '\n', text_end - s);
s = s ? s + 1 : text_end;
y += line_height;
}
// For large text, scan for the last visible line in order to avoid over-reserving in the call to PrimReserve()
// Note that very large horizontal line will still be affected by the issue (e.g. a one megabyte string buffer without a newline will likely crash atm)
if (text_end - s > 10000 && !word_wrap_enabled)
{
const char* s_end = s;
float y_end = y;
while (y_end < clip_rect.w && s_end < text_end)
{
s_end = (const char*)memchr(s_end, '\n', text_end - s_end);
s_end = s_end ? s_end + 1 : text_end;
y_end += line_height;
}
text_end = s_end;
}
if (s == text_end)
return;
// Reserve vertices for remaining worse case (over-reserving is useful and easily amortized)
const int vtx_count_max = (int)(text_end - s) * 4;
const int idx_count_max = (int)(text_end - s) * 6;
const int idx_expected_size = draw_list->IdxBuffer.Size + idx_count_max;
draw_list->PrimReserve(idx_count_max, vtx_count_max);
ImDrawVert* vtx_write = draw_list->_VtxWritePtr;
ImDrawIdx* idx_write = draw_list->_IdxWritePtr;
unsigned int vtx_current_idx = draw_list->_VtxCurrentIdx;
const ImU32 col_untinted = col | ~IM_COL32_A_MASK;
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 (ImCharIsBlankA(c)) { s++; } else if (c == '\n') { s++; break; } else { break; }
}
continue;
}
}
// Decode and advance source
unsigned int c = (unsigned int)*s;
if (c < 0x80)
{
s += 1;
}
else
{
s += ImTextCharFromUtf8(&c, s, text_end);
if (c == 0) // Malformed UTF-8?
break;
}
if (c < 32)
{
if (c == '\n')
{
x = pos.x;
y += line_height;
if (y > clip_rect.w)
break; // break out of main loop
continue;
}
if (c == '\r')
continue;
}
const ImFontGlyph* glyph = FindGlyph((ImWchar)c);
if (glyph == NULL)
continue;
float char_width = glyph->AdvanceX * scale;
if (glyph->Visible)
{
// We don't do a second finer clipping test on the Y axis as we've already skipped anything before clip_rect.y and exit once we pass clip_rect.w
float x1 = x + glyph->X0 * scale;
float x2 = x + glyph->X1 * scale;
float y1 = y + glyph->Y0 * scale;
float y2 = y + glyph->Y1 * 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 quads.
if (cpu_fine_clip)
{
if (x1 < clip_rect.x)
{
u1 = u1 + (1.0f - (x2 - clip_rect.x) / (x2 - x1)) * (u2 - u1);
x1 = clip_rect.x;
}
if (y1 < clip_rect.y)
{
v1 = v1 + (1.0f - (y2 - clip_rect.y) / (y2 - y1)) * (v2 - v1);
y1 = clip_rect.y;
}
if (x2 > clip_rect.z)
{
u2 = u1 + ((clip_rect.z - x1) / (x2 - x1)) * (u2 - u1);
x2 = clip_rect.z;
}
if (y2 > clip_rect.w)
{
v2 = v1 + ((clip_rect.w - y1) / (y2 - y1)) * (v2 - v1);
y2 = clip_rect.w;
}
if (y1 >= y2)
{
x += char_width;
continue;
}
}
// Support for untinted glyphs
ImU32 glyph_col = glyph->Colored ? col_untinted : col;
// We are NOT calling PrimRectUV() here because non-inlined causes too much overhead in a debug builds. Inlined here:
{
idx_write[0] = (ImDrawIdx)(vtx_current_idx); idx_write[1] = (ImDrawIdx)(vtx_current_idx+1); idx_write[2] = (ImDrawIdx)(vtx_current_idx+2);
idx_write[3] = (ImDrawIdx)(vtx_current_idx); idx_write[4] = (ImDrawIdx)(vtx_current_idx+2); idx_write[5] = (ImDrawIdx)(vtx_current_idx+3);
vtx_write[0].pos.x = x1; vtx_write[0].pos.y = y1; vtx_write[0].col = glyph_col; vtx_write[0].uv.x = u1; vtx_write[0].uv.y = v1;
vtx_write[1].pos.x = x2; vtx_write[1].pos.y = y1; vtx_write[1].col = glyph_col; vtx_write[1].uv.x = u2; vtx_write[1].uv.y = v1;
vtx_write[2].pos.x = x2; vtx_write[2].pos.y = y2; vtx_write[2].col = glyph_col; vtx_write[2].uv.x = u2; vtx_write[2].uv.y = v2;
vtx_write[3].pos.x = x1; vtx_write[3].pos.y = y2; vtx_write[3].col = glyph_col; vtx_write[3].uv.x = u1; vtx_write[3].uv.y = v2;
vtx_write += 4;
vtx_current_idx += 4;
idx_write += 6;
}
}
}
x += char_width;
}
// Give back unused vertices (clipped ones, blanks) ~ this is essentially a PrimUnreserve() action.
draw_list->VtxBuffer.Size = (int)(vtx_write - draw_list->VtxBuffer.Data); // Same as calling shrink()
draw_list->IdxBuffer.Size = (int)(idx_write - draw_list->IdxBuffer.Data);
draw_list->CmdBuffer[draw_list->CmdBuffer.Size - 1].ElemCount -= (idx_expected_size - draw_list->IdxBuffer.Size);
draw_list->_VtxWritePtr = vtx_write;
draw_list->_IdxWritePtr = idx_write;
draw_list->_VtxCurrentIdx = vtx_current_idx;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGui Internal Render Helpers
//-----------------------------------------------------------------------------
// Vaguely redesigned to stop accessing ImGui global state:
// - RenderArrow()
// - RenderBullet()
// - RenderCheckMark()
// - RenderMouseCursor()
// - RenderArrowPointingAt()
// - RenderRectFilledRangeH()
//-----------------------------------------------------------------------------
// Function in need of a redesign (legacy mess)
// - RenderColorRectWithAlphaCheckerboard()
//-----------------------------------------------------------------------------
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
void ImGui::RenderArrow(ImDrawList* draw_list, ImVec2 pos, ImU32 col, ImGuiDir dir, float scale)
{
const float h = draw_list->_Data->FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = pos + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
{
case ImGuiDir_Up:
case ImGuiDir_Down:
if (dir == ImGuiDir_Up) r = -r;
a = ImVec2(+0.000f, +0.750f) * r;
b = ImVec2(-0.866f, -0.750f) * r;
c = ImVec2(+0.866f, -0.750f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
a = ImVec2(+0.750f, +0.000f) * r;
b = ImVec2(-0.750f, +0.866f) * r;
c = ImVec2(-0.750f, -0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
draw_list->AddTriangleFilled(center + a, center + b, center + c, col);
}
void ImGui::RenderBullet(ImDrawList* draw_list, ImVec2 pos, ImU32 col)
{
draw_list->AddCircleFilled(pos, draw_list->_Data->FontSize * 0.20f, col, 8);
}
void ImGui::RenderCheckMark(ImDrawList* draw_list, ImVec2 pos, ImU32 col, float sz)
{
float thickness = ImMax(sz / 5.0f, 1.0f);
sz -= thickness * 0.5f;
pos += ImVec2(thickness * 0.25f, thickness * 0.25f);
float third = sz / 3.0f;
float bx = pos.x + third;
float by = pos.y + sz - third * 0.5f;
draw_list->PathLineTo(ImVec2(bx - third, by - third));
draw_list->PathLineTo(ImVec2(bx, by));
draw_list->PathLineTo(ImVec2(bx + third * 2.0f, by - third * 2.0f));
draw_list->PathStroke(col, 0, thickness);
}
void ImGui::RenderMouseCursor(ImDrawList* draw_list, ImVec2 pos, float scale, ImGuiMouseCursor mouse_cursor, ImU32 col_fill, ImU32 col_border, ImU32 col_shadow)
{
if (mouse_cursor == ImGuiMouseCursor_None)
return;
IM_ASSERT(mouse_cursor > ImGuiMouseCursor_None && mouse_cursor < ImGuiMouseCursor_COUNT);
ImFontAtlas* font_atlas = draw_list->_Data->Font->ContainerAtlas;
ImVec2 offset, size, uv[4];
if (font_atlas->GetMouseCursorTexData(mouse_cursor, &offset, &size, &uv[0], &uv[2]))
{
pos -= offset;
ImTextureID tex_id = font_atlas->TexID;
draw_list->PushTextureID(tex_id);
draw_list->AddImage(tex_id, pos + ImVec2(1, 0) * scale, pos + (ImVec2(1, 0) + size) * scale, uv[2], uv[3], col_shadow);
draw_list->AddImage(tex_id, pos + ImVec2(2, 0) * scale, pos + (ImVec2(2, 0) + size) * scale, uv[2], uv[3], col_shadow);
draw_list->AddImage(tex_id, pos, pos + size * scale, uv[2], uv[3], col_border);
draw_list->AddImage(tex_id, pos, pos + size * scale, uv[0], uv[1], col_fill);
draw_list->PopTextureID();
}
}
// Render an arrow. 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
void ImGui::RenderArrowPointingAt(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, ImGuiDir direction, ImU32 col)
{
switch (direction)
{
case ImGuiDir_Left: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), pos, col); return;
case ImGuiDir_Right: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), pos, col); return;
case ImGuiDir_Up: draw_list->AddTriangleFilled(ImVec2(pos.x + half_sz.x, pos.y + half_sz.y), ImVec2(pos.x - half_sz.x, pos.y + half_sz.y), pos, col); return;
case ImGuiDir_Down: draw_list->AddTriangleFilled(ImVec2(pos.x - half_sz.x, pos.y - half_sz.y), ImVec2(pos.x + half_sz.x, pos.y - half_sz.y), pos, col); return;
case ImGuiDir_None: case ImGuiDir_COUNT: break; // Fix warnings
}
}
static inline float ImAcos01(float x)
{
if (x <= 0.0f) return IM_PI * 0.5f;
if (x >= 1.0f) return 0.0f;
return ImAcos(x);
//return (-0.69813170079773212f * x * x - 0.87266462599716477f) * x + 1.5707963267948966f; // Cheap approximation, may be enough for what we do.
}
// FIXME: Cleanup and move code to ImDrawList.
void ImGui::RenderRectFilledRangeH(ImDrawList* draw_list, const ImRect& rect, ImU32 col, float x_start_norm, float x_end_norm, float rounding)
{
if (x_end_norm == x_start_norm)
return;
if (x_start_norm > x_end_norm)
ImSwap(x_start_norm, x_end_norm);
ImVec2 p0 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_start_norm), rect.Min.y);
ImVec2 p1 = ImVec2(ImLerp(rect.Min.x, rect.Max.x, x_end_norm), rect.Max.y);
if (rounding == 0.0f)
{
draw_list->AddRectFilled(p0, p1, col, 0.0f);
return;
}
rounding = ImClamp(ImMin((rect.Max.x - rect.Min.x) * 0.5f, (rect.Max.y - rect.Min.y) * 0.5f) - 1.0f, 0.0f, rounding);
const float inv_rounding = 1.0f / rounding;
const float arc0_b = ImAcos01(1.0f - (p0.x - rect.Min.x) * inv_rounding);
const float arc0_e = ImAcos01(1.0f - (p1.x - rect.Min.x) * inv_rounding);
const float half_pi = IM_PI * 0.5f; // We will == compare to this because we know this is the exact value ImAcos01 can return.
const float x0 = ImMax(p0.x, rect.Min.x + rounding);
if (arc0_b == arc0_e)
{
draw_list->PathLineTo(ImVec2(x0, p1.y));
draw_list->PathLineTo(ImVec2(x0, p0.y));
}
else if (arc0_b == 0.0f && arc0_e == half_pi)
{
draw_list->PathArcToFast(ImVec2(x0, p1.y - rounding), rounding, 3, 6); // BL
draw_list->PathArcToFast(ImVec2(x0, p0.y + rounding), rounding, 6, 9); // TR
}
else
{
draw_list->PathArcTo(ImVec2(x0, p1.y - rounding), rounding, IM_PI - arc0_e, IM_PI - arc0_b, 3); // BL
draw_list->PathArcTo(ImVec2(x0, p0.y + rounding), rounding, IM_PI + arc0_b, IM_PI + arc0_e, 3); // TR
}
if (p1.x > rect.Min.x + rounding)
{
const float arc1_b = ImAcos01(1.0f - (rect.Max.x - p1.x) * inv_rounding);
const float arc1_e = ImAcos01(1.0f - (rect.Max.x - p0.x) * inv_rounding);
const float x1 = ImMin(p1.x, rect.Max.x - rounding);
if (arc1_b == arc1_e)
{
draw_list->PathLineTo(ImVec2(x1, p0.y));
draw_list->PathLineTo(ImVec2(x1, p1.y));
}
else if (arc1_b == 0.0f && arc1_e == half_pi)
{
draw_list->PathArcToFast(ImVec2(x1, p0.y + rounding), rounding, 9, 12); // TR
draw_list->PathArcToFast(ImVec2(x1, p1.y - rounding), rounding, 0, 3); // BR
}
else
{
draw_list->PathArcTo(ImVec2(x1, p0.y + rounding), rounding, -arc1_e, -arc1_b, 3); // TR
draw_list->PathArcTo(ImVec2(x1, p1.y - rounding), rounding, +arc1_b, +arc1_e, 3); // BR
}
}
draw_list->PathFillConvex(col);
}
void ImGui::RenderRectFilledWithHole(ImDrawList* draw_list, ImRect outer, ImRect inner, ImU32 col, float rounding)
{
const bool fill_L = (inner.Min.x > outer.Min.x);
const bool fill_R = (inner.Max.x < outer.Max.x);
const bool fill_U = (inner.Min.y > outer.Min.y);
const bool fill_D = (inner.Max.y < outer.Max.y);
if (fill_L) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Min.y), ImVec2(inner.Min.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomLeft));
if (fill_R) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Min.y), ImVec2(outer.Max.x, inner.Max.y), col, rounding, (fill_U ? 0 : ImDrawFlags_RoundCornersTopRight) | (fill_D ? 0 : ImDrawFlags_RoundCornersBottomRight));
if (fill_U) draw_list->AddRectFilled(ImVec2(inner.Min.x, outer.Min.y), ImVec2(inner.Max.x, inner.Min.y), col, rounding, (fill_L ? 0 : ImDrawFlags_RoundCornersTopLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersTopRight));
if (fill_D) draw_list->AddRectFilled(ImVec2(inner.Min.x, inner.Max.y), ImVec2(inner.Max.x, outer.Max.y), col, rounding, (fill_L ? 0 : ImDrawFlags_RoundCornersBottomLeft) | (fill_R ? 0 : ImDrawFlags_RoundCornersBottomRight));
if (fill_L && fill_U) draw_list->AddRectFilled(ImVec2(outer.Min.x, outer.Min.y), ImVec2(inner.Min.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopLeft);
if (fill_R && fill_U) draw_list->AddRectFilled(ImVec2(inner.Max.x, outer.Min.y), ImVec2(outer.Max.x, inner.Min.y), col, rounding, ImDrawFlags_RoundCornersTopRight);
if (fill_L && fill_D) draw_list->AddRectFilled(ImVec2(outer.Min.x, inner.Max.y), ImVec2(inner.Min.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomLeft);
if (fill_R && fill_D) draw_list->AddRectFilled(ImVec2(inner.Max.x, inner.Max.y), ImVec2(outer.Max.x, outer.Max.y), col, rounding, ImDrawFlags_RoundCornersBottomRight);
}
// Helper for ColorPicker4()
// NB: This is rather brittle and will show artifact when rounding this enabled if rounded corners overlap multiple cells. Caller currently responsible for avoiding that.
// Spent a non reasonable amount of time trying to getting this right for ColorButton with rounding+anti-aliasing+ImGuiColorEditFlags_HalfAlphaPreview flag + various grid sizes and offsets, and eventually gave up... probably more reasonable to disable rounding altogether.
// FIXME: uses ImGui::GetColorU32
void ImGui::RenderColorRectWithAlphaCheckerboard(ImDrawList* draw_list, ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, ImDrawFlags flags)
{
if ((flags & ImDrawFlags_RoundCornersMask_) == 0)
flags = ImDrawFlags_RoundCornersDefault_;
if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
{
ImU32 col_bg1 = GetColorU32(ImAlphaBlendColors(IM_COL32(204, 204, 204, 255), col));
ImU32 col_bg2 = GetColorU32(ImAlphaBlendColors(IM_COL32(128, 128, 128, 255), col));
draw_list->AddRectFilled(p_min, p_max, col_bg1, rounding, flags);
int yi = 0;
for (float y = p_min.y + grid_off.y; y < p_max.y; y += grid_step, yi++)
{
float y1 = ImClamp(y, p_min.y, p_max.y), y2 = ImMin(y + grid_step, p_max.y);
if (y2 <= y1)
continue;
for (float x = p_min.x + grid_off.x + (yi & 1) * grid_step; x < p_max.x; x += grid_step * 2.0f)
{
float x1 = ImClamp(x, p_min.x, p_max.x), x2 = ImMin(x + grid_step, p_max.x);
if (x2 <= x1)
continue;
ImDrawFlags cell_flags = ImDrawFlags_RoundCornersNone;
if (y1 <= p_min.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersTopLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersTopRight; }
if (y2 >= p_max.y) { if (x1 <= p_min.x) cell_flags |= ImDrawFlags_RoundCornersBottomLeft; if (x2 >= p_max.x) cell_flags |= ImDrawFlags_RoundCornersBottomRight; }
// Combine flags
cell_flags = (flags == ImDrawFlags_RoundCornersNone || cell_flags == ImDrawFlags_RoundCornersNone) ? ImDrawFlags_RoundCornersNone : (cell_flags & flags);
draw_list->AddRectFilled(ImVec2(x1, y1), ImVec2(x2, y2), col_bg2, rounding, cell_flags);
}
}
}
else
{
draw_list->AddRectFilled(p_min, p_max, col, rounding, flags);
}
}
//-----------------------------------------------------------------------------
// [SECTION] Decompression code
//-----------------------------------------------------------------------------
// Compressed with stb_compress() then converted to a C array and encoded as base85.
// Use the program in misc/fonts/binary_to_compressed_c.cpp to create the array from a TTF file.
// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size.
// Decompression from stb.h (public domain) by Sean Barrett https://github.com/nothings/stb/blob/master/stb.h
//-----------------------------------------------------------------------------
static unsigned int stb_decompress_length(const unsigned char *input)
{
return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11];
}
static unsigned char *stb__barrier_out_e, *stb__barrier_out_b;
static const unsigned char *stb__barrier_in_b;
static unsigned char *stb__dout;
static void stb__match(const unsigned char *data, unsigned int length)
{
// INVERSE of memmove... write each byte before copying the next...
IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }
if (data < stb__barrier_out_b) { stb__dout = stb__barrier_out_e+1; return; }
while (length--) *stb__dout++ = *data++;
}
static void stb__lit(const unsigned char *data, unsigned int length)
{
IM_ASSERT(stb__dout + length <= stb__barrier_out_e);
if (stb__dout + length > stb__barrier_out_e) { stb__dout += length; return; }
if (data < stb__barrier_in_b) { stb__dout = stb__barrier_out_e+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 const unsigned char *stb_decompress_token(const 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 = buflen % 5552;
unsigned long i;
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, const unsigned char *i, unsigned int /*length*/)
{
if (stb__in4(0) != 0x57bC0000) return 0;
if (stb__in4(4) != 0) return 0; // error! stream is > 4GB
const unsigned int olen = stb_decompress_length(i);
stb__barrier_in_b = i;
stb__barrier_out_e = output + olen;
stb__barrier_out_b = output;
i += 16;
stb__dout = output;
for (;;) {
const 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;
}
}
//-----------------------------------------------------------------------------
// [SECTION] Default font data (ProggyClean.ttf)
//-----------------------------------------------------------------------------
// 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
//-----------------------------------------------------------------------------
// File: 'ProggyClean.ttf' (41208 bytes)
// Exported using misc/fonts/binary_to_compressed_c.cpp (with compression + base85 string encoding).
// The purpose of encoding as base85 instead of "0x00,0x01,..." style is only save on _source code_ size.
//-----------------------------------------------------------------------------
static const char proggy_clean_ttf_compressed_data_base85[11980 + 1] =
"7])#######hV0qs'/###[),##/l:$#Q6>##5[n42>c-TH`->>#/e>11NNV=Bv(*:.F?uu#(gRU.o0XGH`$vhLG1hxt9?W`#,5LsCp#-i>.r$<$6pD>Lb';9Crc6tgXmKVeU2cD4Eo3R/"
"2*>]b(MC;$jPfY.;h^`IWM9<Lh2TlS+f-s$o6Q<BWH`YiU.xfLq$N;$0iR/GX:U(jcW2p/W*q?-qmnUCI;jHSAiFWM.R*kU@C=GH?a9wp8f$e.-4^Qg1)Q-GL(lf(r/7GrRgwV%MS=C#"
"`8ND>Qo#t'X#(v#Y9w0#1D$CIf;W'#pWUPXOuxXuU(H9M(1<q-UE31#^-V'8IRUo7Qf./L>=Ke$$'5F%)]0^#0X@U.a<r:QLtFsLcL6##lOj)#.Y5<-R&KgLwqJfLgN&;Q?gI^#DY2uL"
"i@^rMl9t=cWq6##weg>$FBjVQTSDgEKnIS7EM9>ZY9w0#L;>>#Mx&4Mvt//L[MkA#W@lK.N'[0#7RL_&#w+F%HtG9M#XL`N&.,GM4Pg;-<nLENhvx>-VsM.M0rJfLH2eTM`*oJMHRC`N"
"kfimM2J,W-jXS:)r0wK#@Fge$U>`w'N7G#$#fB#$E^$#:9:hk+eOe--6x)F7*E%?76%^GMHePW-Z5l'&GiF#$956:rS?dA#fiK:)Yr+`�j@'DbG&#^$PG.Ll+DNa<XCMKEV*N)LN/N"
"*b=%Q6pia-Xg8I$<MR&,VdJe$<(7G;Ckl'&hF;;$<_=X(b.RS%%)###MPBuuE1V:v&cXm#(&cV]`k9OhLMbn%s$G2,B$BfD3X*sp5#l,$R#]x_X1xKX%b5U*[r5iMfUo9U`N99hG)"
"tm+/Us9pG)XPu`<0s-)WTt(gCRxIg(%6sfh=ktMKn3j)<6<b5Sk_/0(^]AaN#(p/L>&VZ>1i%h1S9u5o@YaaW$e+b<TWFn/Z:Oh(Cx2$lNEoN^e)#CFY@@I;BOQ*sRwZtZxRcU7uW6CX"
"ow0i(?$Q[cjOd[P4d)]>ROPOpxTO7Stwi1::iB1q)C_=dV26J;2,]7op$]uQr@_V7$q^%lQwtuHY]=DX,n3L#0PHDO4f9>dC@O>HBuKPpP*E,N+b3L#lpR/MrTEH.IAQk.a>D[.e;mc."
"x]Ip.PH^'/aqUO/$1WxLoW0[iLA<QT;5HKD+@qQ'NQ(3_PLhE48R.qAPSwQ0/WK?Z,[x?-J;jQTWA0X@KJ(_Y8N-:/M74:/-ZpKrUss?d#dZq]DAbkU*JqkL+nwX@@47`5>w=4h(9.`G"
"CRUxHPeR`5Mjol(dUWxZa(>STrPkrJiWx`5U7F#.g*jrohGg`cg:lSTvEY/EV_7H4Q9[Z%cnv;JQYZ5q.l7Zeas:HOIZOB?G<Nald$qs]@]L<J7bR*>gv:[7MI2k).'2($5FNP&EQ(,)"
"U]W]+fh18.vsai00);D3@4ku5P?DP8aJt+;qUM]=+b'8@;mViBKx0DE[-auGl8:PJ&Dj+M6OC]O^((##]`0i)drT;-7X`=-H3[igUnPG-NZlo.#k@h#=Ork$m>a>$-?Tm$UV(?#P6YY#"
"'/###xe7q.73rI3*pP/$1>s9)W,JrM7SN]'/4C#v$U`0#V.[0>xQsH$fEmPMgY2u7Kh(G%siIfLSoS+MK2eTM$=5,M8p`A.;_R%#u[K#$x4AG8.kK/HSB==-'Ie/QTtG?-.*^N-4B/ZM"
"_3YlQC7(p7q)&](`6_c)$/*JL(L-^(]$wIM`dPtOdGA,U3:w2M-0<q-]L_?^)1vw'.,MRsqVr.L;aN&#/EgJ)PBc[-f>+WomX2u7lqM2iEumMTcsF?-aT=Z-97UEnXglEn1K-bnEO`gu"
"Ft(c%=;Am_Qs@jLooI&NX;]0#j4#F14;gl8-GQpgwhrq8'=l_f-b49'UOqkLu7-##oDY2L(te+Mch&gLYtJ,MEtJfLh'x'M=$CS-ZZ%P]8bZ>#S?YY#%Q&q'3^Fw&?D)UDNrocM3A76/"
"/oL?#h7gl85[qW/NDOk%16ij;+:1a'iNIdb-ou8.P*w,v5#EI$TWS>Pot-R*H'-SEpA:g)f+O$%%`kA#G=8RMmG1&O`>to8bC]T&$,n.LoO>29sp3dt-52U%VM#q7'DHpg+#Z9%H[K<L"
"%a2E-grWVM3@2=-k22tL]4$##6We'8UJCKE[d_=%wI;'6X-GsLX4j^SgJ$##R*w,vP3wK#iiW&#*h^D&R?jp7+/u&#(AP##XU8c$fSYW-J95_-Dp[g9wcO&#M-h1OcJlc-*vpw0xUX&#"
"OQFKNX@QI'IoPp7nb,QU//MQ&ZDkKP)X<WSVL(68uVl&#c'[0#(s1X&xm$Y%B7*K:eDA323j998GXbA#pwMs-jgD$9QISB-A_(aN4xoFM^@C58D0+Q+q3n0#3U1InDjF682-SjMXJK)("
"h$hxua_K]ul92%'BOU&#BRRh-slg8KDlr:%L71Ka:.A;%YULjDPmL<LYs8i#XwJOYaKPKc1h:'9Ke,g)b),78=I39B;xiY$bgGw-&.Zi9InXDuYa%G*f2Bq7mn9^#p1vv%#(Wi-;/Z5h"
"o;#2:;%d	v68C5g?ntX0X)pT`;%pB3q7mgGN)3%(P8nTd5L7GeA-GL@+%J3u2:(Yf>et`e;)f#Km8&+DC$I46>#Kr]]u-[=99tts1.qb#q72g1WJO81q+eN'03'eM>&1XxY-caEnO"
"j%2n8)),?ILR5^.Ibn<-X-Mq7[a82Lq:F&#ce+S9wsCK*x`569E8ew'He]h:sI[2LM$[guka3ZRd6:t%IG:;$%YiJ:Nq=?eAw;/:nnDq0(CYcMpG)qLN4$##&J<j$UpK<Q4a1]MupW^-"
"sj_$%[HK%'F####QRZJ::Y3EGl4'@%FkiAOg#p[##O`gukTfBHagL<LHw%q&OV0##F=6/:chIm0@eCP8X]:kFI%hl8hgO@RcBhS-@Qb$%+m=hPDLg*%K8ln(wcf3/'DW-$.lR?n[nCH-"
"eXOONTJlh:.RYF%3'p6sq:UIMA945&^HFS87@$EP2iG<-lCO$%c`uKGD3rC$x0BL8aFn--`ke%#HMP'vh1/R&O_J9'um,.<tx[@%wsJk&bUT2`0uMv7gg#qp/ij.L56'hl;.s5CUrxjO"
"M7-##.l+Au'A&O:-T72L]P`&=;ctp'XScX*rU.>-XTt,%OVU4)S1+R-#dg0/Nn?Ku1^0f$B*P:Rowwm-`0PKjYDDM'3]d39VZHEl4,.j']Pk-M.h^&:0FACm$maq-&sgw0t7/6(^xtk%"
"LuH88Fj-ekm>GA#_>568x6(OFRl-IZp`&b,_P'$M<Jnq79VsJW/mWS*PUiq76;]/NM_>hLbxfc$mj`,O;&%W2m`Zh:/)Uetw:aJ%]K9h:TcF]u_-Sj9,VK3M.*'&0D[Ca]J9gp8,kAW]"
"%(?A%R$f<->Zts'^kn=-^@c4%-pY6qI%J%1IGxfLU9CP8cbPlXv);C=b),<2mOvP8up,UVf3839acAWAW-W?#ao/^#%KYo8fRULNd2.>%m]UK:n%r$'sw]J;5pAoO_#2mO3n,'=H5(et"
"Hg*`+RLgv>=4U8guD$I%D:W>-r5V*%j*W:Kvej.Lp$<M-SGZ':+Q_k+uvOSLiEo(<aD/K<CCc`'Lx>'?;++O'>()jLR-^u68PHm8ZFWe+ej8h:9r6L*0//c&iH&R8pRbA#Kjm%upV1g:"
"a_#Ur7FuA#(tRh#.Y5K+@?3<-8m0$PEn;J:rh6?I6uG<-`wMU'ircp0LaE_OtlMb&1#6T.#FDKu#1Lw%u%+GM+X'e?YLfjM[VO0MbuFp7;>Q&#WIo)0@F%q7c#4XAXN-U&VB<HFF*qL("
"$/V,;(kXZejWO`<[5?\?ewY(*9=%wDc;,u<'9t3W-(H1th3+G]ucQ]kLs7df($/*JL]@*t7Bu_G3_7mp7<iaQjO@.kLg;x3B0lqp7Hf,^Ze7-##@/c58Mo(3;knp0%)A7?-W+eI'o8)b<"
"nKnw'Ho8C=Y>pqB>0ie&jhZ[?iLR@@_AvA-iQC(=ksRZRVp7`.=+NpBC%rh&3]R:8XDmE5^V8O(x<<aG/1N$#FX$0V5Y6x'aErI3I$7x%E`v<-BY,)%-?Psf*l?%C3.mM(=/M0:JxG'?"
"7WhH%o'a<-80g0NBxoO(GH<dM]n.+%q@jH?f.UsJ2Ggs&4<-e47&Kl+f//9@`b+?.TeN_&B8Ss?v;^Trk;f#YvJkl&w$]>-+k?'(<S:68tq*WoDfZu';mM?8X[ma8W%*`-=;D.(nc7/;"
")g:T1=^J$&BRV(-lTmNB6xqB[@0*o.erM*<SWF]u2=st-*(6v>^](H.aREZSi,#1:[IXaZFOm<-ui#qUq2$##Ri;u75OK#(RtaW-K-F`S+cF]uN`-KMQ%rP/Xri.LRcB##=YL3BgM/3M"
"D?@f&1'BW-)Ju<L25gl8uhVm1hL$##*8###'A3/LkKW+(^rWX?5W_8g)a(m&K8P>#bmmWCMkk&#TR`C,5d>g)F;t,4:@_l8G/5h4vUd%&%950:VXD'QdWoY-F$BtUwmfe$YqL'8(PWX("
"P?^@Po3$##`MSs?DWBZ/S>+4%>fX,VWv/w'KD`LP5IbH;rTV>n3cEK8U#bX]l-/V+^lj3;vlMb&[5YQ8#pekX9JP3XUC72L,,?+Ni&co7ApnO*5NK,((W-i:$,kp'UDAO(G0Sq7MVjJs"
"bIu)'Z,*[>br5fX^:FPAWr-m2KgL<LUN098kTF&#lvo58=/vjDo;.;)Ka*hLR#/k=rKbxuV`>Q_nN6'8uTGT5g)uLv:873UpTLgH+#FgpH'_o1780Ph8KmxQJ8#H72L4@768@Tm&Q"
"h4CB/5OvmA&,Q&QbUoi$a_%3M01H)4x7I^&KQVgtFnV+;[Pc>[m4k//,]1?#`VY[Jr*3&&slRfLiVZJ:]?=K3Sw=[$=uRB?3xk48@aeg<Z'<$#4H)6,>e0jT6'N#(q%.O=?2S]u*(m<-"
"V8J'(1)G][68hW$5'q[GC&5j`TE?m'esFGNRM)j,ffZ?-qx8;->g4t*:CIP/[Qap7/9'#(1sao7w-.qNUdkJ)tCF&#B^;xGvn2r9FEPFFFcL@.iFNkTve$m%#QvQS8U@)2Z+3K:AKM5i"
"sZ88+dKQ)W6>J%CL<KE>`.d*(B`-n8D9oK<Up]c$X$(,)M8Zt7/[rdkqTgl-0cuGMv'?>-XV1q['-5k'cAZ69e;D_?$ZPP&s^+7])$*$#@QYi9,5P	r+$%CE=68>K8r0=dSC%%(@p7"
".m7jilQ02'0-VWAg<a/''3u.=4L$Y)6k/K:_[3=&jvL<L0C/2'v:^;-DIBW,B4E68:kZ;%?8(Q8BH=kO65BW?xSG&#@uU,DS*,?.+(o(#1vCS8#CHF>TlGW'b)Tq7VT9q^*^$$.:&N@@"
"$&)WHtPm*5_rO0&e%K&#-30j(E4#'Zb.o/(Tpm$>K'f@[PvFl,hfINTNU6u'0pao7%XUp9]5.>%h`8_=VYbxuel.NTSsJfLacFu3B'lQSu/m6-Oqem8T+oE--$0a/k]uj9EwsG>%veR*"
"hv^BFpQj:K'#SJ,sB-'#](j.Lg92rTw-*n%@/;39rrJF,l#qV%OrtBeC6/,;qB3ebNW[?,Hqj2L.1NP&GjUR=1D8QaS3Up&@*9wP?+lo7b?@%'k4`p0Z$22%K3+iCZj?XJN4Nm&+YF]u"
"@-W$U%VEQ/,,>>#)D<h#`)h0:<Q6909ua+&VU%n2:cG3FJ-%@Bj-DgLr`Hw&HAKjKjseK</xKT*)B,N9X3]krc12t'pgTV(Lv-tL[xg_%=M_q7a^x?7Ubd>#%8cY#YZ?=,`Wdxu/ae&#"
"w6)R89tI#6@s'(6Bf7a&?S=^ZI_kS&ai`&=tE72L_D,;^R)7[$s<Eh#c&)q.MXI%#v9ROa5FZO%sF7q7Nwb&#ptUJ:aqJe$Sl68%.D###EC><?-aF&#RNQv>o8lKN%5/$(vdfq7+ebA#"
"u1p]ovUKW&Y%q]'>$1@-[xfn$7ZTp7mM,G,Ko7a&Gu%G[RMxJs[0MM%wci.LFDK)(<c`Q8N)jEIF*+?P2a8g%)$q]o2aH8C&<SibC/q,(e:v;-b#6[$NtDZ84Je2KNvB#$P5?tQ3nt(0"
"d=j.LQf./Ll33+(;q3L-w=8dX$#WF&uIJ@-bfI>%:_i2B5CsR8&9Z&#=mPEnm0f`<&c)QL5uJ#%u%lJj+D-r;BoFDoS97h5g)E#o:&S4weDF,9^Hoe`h*L+_a*NrLW-1pG_&2UdB8"
"6e%B/:=>)N4xeW.*wft-;$'58-ESqr<b?UI(_%@[P46>#U`'6AQ]m&6/`Z>#S?YY#Vc;r7U2&326d=w&H####?TZ`*4?&.MK?LP8Vxg>$[QXc%QJv92.(Db*B)gb*BM9dM*hJMAo*c&#"
"b0v=Pjer]$gG&JXDf->'StvU7505l9$AFvgYRI^&<^b68?j#q9QX4SM'RO#&sL1IM.rJfLUAj221]d##DW=m83u5;'bYx,*Sl0hL(W;;$doB&O/TQ:(Z^xBdLjL<Lni;''X.`$#8+1GD"
":k$YUWsbn8ogh6rxZ2Z9]%nd+>V#*8U_72Lh+2Q8Cj0i:6hp&$C/:p(HK>T8Y[gHQ4`4)'$Ab(Nof%V'8hL&#<NEdtg(n'=S1A(Q1/I&4([%dM`,Iu'1:_hL>SfD07&6D<fp8dHM7/g+"
"tlPN9J*rKaPct&?'uBCem^jn%9_K)<,C5K3s=5g&GmJb*[SYq7K;TRLGCsM-$$;S%:Y@r7AK0pprpL<Lrh,q7e/%KWK:50I^+m'vi`3?%Zp+<-d+$L-Sv:@.o19n$s0&39;kn;S%BSq*"
"$3WoJSCLweV[aZ'MQIjO<7;X-X;&+dMLvu#^UsGEC9WEc[X(wI7#2.(F0jV*eZf<-Qv3J-c+J5AlrB#$p(H68LvEA'q3n0#m,[`*8Ft)FcYgEud]CWfm68,(aLA$@EFTgLXoBq/UPlp7"
":d[/;r_ix=:TF`S5H-b<LI&HY(K=h#)]Lk$K14lVfm:x$H<3^Ql<M`$OhapBnkup'D#L$Pb_`N*g]2e;X/Dtg,bsj&K#2[-:iYr'_wgH)NUIR8a1n#S?Yej'h8^58UbZd+^FKD*T@;6A"
"7aQC[K8d-(v6GI$x:T<&'Gp5Uf>@M.*J:;$-rv29'M]8qMv-tLp,'886iaC=Hb*YJoKJ,(j%K=H`K.v9HggqBIiZu'QvBT.#=)0ukruV&.)3=(^1`o*Pj4<-<aN((^7('#Z0wK#5GX@7"
"u][`*S^43933A4rl][`*O4CgLEl]v$1Q3AeF37dbXk,.)vj#x'd`;qgbQR%FW,2(?LO=s%Sc68%NP'##Aotl8x=BE#j1UD([3$M(]UI2LX3RpKN@;/#f'f/&_mt&F)XdF<9t4)Qa.*kT"
"LwQ'(TTB9.xH'>#MJ+gLq9-##@HuZPN0]u:h7.T..G:;$/Usj(T7`Q8tT72LnYl<-qx8;-HV7Q-&Xdx%1a,hC=0u+HlsV>nuIQL-5<N?)NBS)QN*_I,?&)2'IM%L3I)X((e/dl2&8'<M"
":^#M*Q+[T.Xri.LYS3v%fF`68h;b-X[/En'CR.q7E)p'/kle2HM,u;^%OKC-N+Ll%F9CF<Nf'^#t2L,;27W:0O@6##U6W7:$rJfLWHj$#)woqBefIZ.PK<b*t7ed;p*_m;4ExK#h@&]>"
"_>@kXQtMacfD.m-VAb8;IReM3$wf0''hra*so568'Ip&vRs849'MRYSp%:t:h5qSgwpEr$B>Q,;s(C#$)`svQuF$##-D,##,g68@2[T;.XSdN9Qe)rpt._K-#5wF)sP'##p#C0c%-Gb%"
"hd+<-j'Ai*x&&HMkT]C'OSl##5RG[JXaHN;d'uA#x._U;.`PU@(Z3dt4r152@:v,'R.Sj'w#0<-;kPI)FfJ&#AYJ&#//)>-k=m=*XnK$>=)72L]0I%>.G690a:$##<,);?;72#?x9+d;"
"^V'9;jY@;)br#q^YQpx:X#Te$Z^'=-=bGhLf:D6&bNwZ9-ZD#n^9HhLMr5G;']d&6'wYmTFmL<LD)F^%[tC'8;+9E#C$g%#5Y>q9wI>P(9mI[>kC-ekLC/R&CH+s'B;K-M6$EB%is00:"
"+A4[7xks.LrNk0&E)wILYF@2L'0Nb$+pv<(2.768/FrY&h$^3i&@+G%JT'<-,v`3;_)I9M^AE]CN?Cl2AZg+%4iTpT3<n-&%H%b<FDj2M<hH=&Eh<2Len$b*aTX=-8QxN)k11IM1c^j%"
"9s<L<NFSo)B?+<-(GxsF,^-Eh@$4dXhN$+#rxK8'je'D7k`e;)2pYwPA'_p9&@^18ml1^[@g4t*[JOa*[=Qp7(qJ_oOL^('7fB&Hq-:sf,sNj8xq^>$U4O]GKx'm9)b@p7YsvK3w^YR-"
"CdQ*:Ir<($u&)#(&?L9Rg3H)4fiEp^iI9O8KnTj,]H?D*r7'M;PwZ9K0E^k&-cpI;.p/6_vwoFMV<->#%Xi.LxVnrU(4&8/P+:hLSKj$#U%]49t'I:rgMi'FL@a:0Y-uA[39',(vbma*"
"hU%<-SRF`Tt:542R_VV$p@[p8DV[A,?1839FWdF<TddF<9Ah-6&9tWoDlh]&1SpGMq>Ti1O*H&#(AL8[_P%.M>v^-))qOT*F5Cq0`Ye%+$B6i:7@0IX<N+T+0MlMBPQ*Vj>SsD<U4JHY"
"8kD2)2fU/M#$e.)T4,_=8hLim[&);?UkK'-x?'(:siIfL<$pFM`i<?%W(mGDHM%>iWP,##P`%/L<eXi:@Z9C.7o=@(pXdAO/NLQ8lPl+HPOQa8wD8=^GlPa8TKI1CjhsCTSLJM'/Wl>-"
"S(qw%sf/@%#B6;/U7K]uZbi^Oc^2n<bhPmUkMw>%t<)'mEVE''n`WnJra$^TKvX5B>;_aSEK',(hwa0:i4G?.Bci.(X[?b*($,=-n<.Q%`(X=?+@Am*Js0&=3bh8K]mL<LoNs'6,'85`"
"0?t/'_U59@]ddF<#LdF<eWdF<OuN/45rY<-L@&#+fm>69=Lb,OcZV/);TTm8VI;?%OtJ<(b4mq7M6:u?KRdF<gR@2L=FNU-<b[(9c/ML3m;Z[$oF3g)GAWqpARc=<ROu7cL5l;-[A]%/"
"+fsd;l#SafT/f*W]0=O'$(Tb<[)*@e775R-:Yob%g*>l*:xP?Yb.5)%w_I?7uk5JC+FS(m#i'k.'a0i)9<7b'fs'59hq$*5Uhv##pi^8+hIEBF`nvo`;'l0.^S1<-wUK2/Coh58KKhLj"
"M=SO*rfO`+qC`W-On.=AJ56>>i2@2LH6A:&5q`?9I3@@'04&p2/LVa*T-4<-i3;M9UvZd+N7>b*eIwg:CC)c<>nO&#<IGe;__.thjZl<%w(Wk2xmp4Q@I#I9,DF]u7-P=.-_:YJ]aS@V"
"?6*C()dOp7:WL,b&3Rg/.cmM9&r^>$(>.Z-I&J(Q0Hd5Q%7Co-b`-c<N(6r@ip+AurK<m86QIth*#v;-OBqi+L7wDE-Ir8K['m+DDSLwK&/.?-V%U_%3:qKNu$_b*B-kp7NaD'QdWQPK"
"Yq[@>P)hI;*_F]u`Rb[.j8_Q/<&>uu+VsH$sM9TA%?)(vmJ80),P7E>)tjD%2L=-t#fK[%`v=Q8<FfNkgg^oIbah*#8/Qt$F&:K*-(N/'+1vMB,u()-a.VUU*#[e%gAAO(S>WlA2);Sa"
">gXm8YB`1d@K#n]76-a$U,mF<fX]idqd)<3,]J7JmW4`6]uks=4-72L(jEk+:bJ0M^q-8Dm_Z?0olP1C9Sa&H[d&c$ooQUj]Exd*3ZM@-WGW2%s',B-_M%>%Ul:#/'xoFM9QX-$.QN'>"
"[%$Z$uF6pA6Ki2O5:8w*vP1<-1`[G,)-m#>0`P&#eb#.3i)rtB61(o'$?X3B</R90;eZ]%Ncq;-Tl]#F>2Qft^ae_5tKL9MUe9b*sLEQ95C&`=G?@Mj=wh*'3E>=-<)Gt*Iw)'QG:`@I"
"wOf7&]1i'S01B+Ev/Nac#9S;=;YQpg_6U`*kVY39xK,[/6Aj7:'1Bm-_1EYfa1+o&o4hp7KN_Q(OlIo@S%;jVdn0'1<Vc52=u`3^o-n1'g4v58Hj&6_t7$##?M)c<$bgQ_'SY((-xkA#"
"Y(,p'H9rIVY-b,'%bCPF7.J<Up^,(dU1VY*5#WkTU>h19w,WQhLI)3S#f$2(eb,jr*b;3Vw]*7NH%$c4Vs,eD9>XW8?N]o+(*pgC%/72LV-u<Hp,3@e^9UB1J+ak9-TN/mhKPg+AJYd$"
"MlvAF_jCK*.O-^(63adMT->W%iewS8W6m2rtCpo'RS1R84=@paTKt)>=%&1[)*vp'u+x,VrwN;&]kuO9JDbg=pO$J*.jVe;u'm0dr9l,<*wMK*Oe=g8lV_KEBFkO'oU]^=[-792#ok,)"
"i]lR8qQ2oA8wcRCZ^7w/Njh;?.stX?Q1>S1q4Bn$)K1<-rGdO'$Wr.Lc.CG)$/*JL4tNR/,SVO3,aUw'DJN:)Ss;wGn9A32ijw%FL+Z0Fn.U9;reSq)bmI32U==5ALuG&#Vf1398/pVo"
"1*c-(aY168o<`JsSbk-,1N;$>0:OUas(3:8Z972LSfF8eb=c-;>SPw7.6hn3m`9^Xkn(r.qS[0;T%&Qc=+STRxX'q1BNk3&*eu2;&8q$&x>Q#Q7^Tf+6<(d%ZVmj2bDi%.3L2n+4W'$P"
"iDDG)g,r%+?,$@?uou5tSe2aN_AQU*<h`e-GI7)?OK2A.d7_c)?wQ5AS@DL3r#7fSkgl6-++D:'A,uq7SvlB$pcpH'q3n0#_%dY#xCpr-l<F0NR@-##FEV6NTF6##$l84N1w?AO>'IAO"
"URQ##V^Fv-XFbGM7Fl(N<3DhLGF%q.1rC$#:T__&Pi68%0xi_&[qFJ(77j_&JWoF.V735&T,[R*:xFR*K5>>#`bW-?4Ne_&6Ne_&6Ne_&n`kr-#GJcM6X;uM6X;uM(.a..^2TkL%oR(#"
";u.T%fAr%4tJ8&><1=GHZ_+m9/#H1F^R#SC#*N=BA9(D?v[UiFY>>^8p,KKF.W]L29uLkLlu/+4T<XoIB&hx=T1PcDaB&;HH+-AFr?(m9HZV)FKS8JCw;SD=6[^/DZUL`EUDf]GGlG&>"
"w$)F./^n3+rlo+DB;5sIYGNk+i1t-69Jg--0pao7Sm#K)pdHW&;LuDNH@H>#/X-TI(;P>#,Gc>#0Su>#4`1?#8lC?#<xU?#@.i?#D:%@#HF7@#LRI@#P_[@#Tkn@#Xw*A#]-=A#a9OA#"
"d<F&#*;G##.GY##2Sl##6`($#:l:$#>xL$#B.`$#F:r$#JF.%#NR@%#R_R%#Vke%#Zww%#_-4^Rh%Sflr-k'MS.o?.5/sWel/wpEM0%3'/1)K^f1-d>G21&v(35>V`39V7A4=onx4"
"A1OY5EI0;6Ibgr6M$HS7Q<)58C5w,;WoA*#[%T*#`1g*#d=#+#hI5+#lUG+#pbY+#tnl+#x$),#&1;,#*=M,#.I`,#2Ur,#6b.-#;w[H#iQtA#m^0B#qjBB#uvTB##-hB#'9$C#+E6C#"
"/QHC#3^ZC#7jmC#;v)D#?,<D#C8ND#GDaD#KPsD#O]/E#g1A5#KA*1#gC17#MGd;#8(02#L-d3#rWM4#Hga1#,<w0#T.j<#O#'2#CYN1#qa^:#_4m3#o@/=#eG8=#t8J5#`+78#4uI-#"
"m3B2#SB[8#Q0@8#i[*9#iOn8#1Nm;#^sN9#qh<9#:=x-#P;K2#$%X9#bC+.#Rg;<#mN=.#MTF.#RZO.#2?)4#Y#(/#[)1/#b;L/#dAU/#0Sv;#lY$0#n`-0#sf60#(F24#wrH0#%/e0#"
"TmD<#%JSMFove:CTBEXI:<eh2g)B,3h2^G3i;#d3jD>)4kMYD4lVu`4m`:&5niUA5@(A5BA1]PBB:xlBCC=2CDLXMCEUtiCf&0g2'tN?PGT4CPGT4CPGT4CPGT4CPGT4CPGT4CPGT4CP"
"GT4CPGT4CPGT4CPGT4CPGT4CPGT4CP-qekC`.9kEg^+F$kwViFJTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5KTB&5o,^<-28ZI'O?;xp"
"O?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xpO?;xp;7q-#lLYI:xvD=#";
static const char* GetDefaultCompressedFontDataTTFBase85()
{
return proggy_clean_ttf_compressed_data_base85;
}
#endif // #ifndef IMGUI_DISABLE
| [
"johnw@LAPTOP-BBT0HUPT"
] | johnw@LAPTOP-BBT0HUPT |
cd2807f7e4d6ea1c835bd9586ef1171023e65890 | c6b2e01fabbc0d78e5a8db9865eaf2fb947d3628 | /Software-Rendering/src/Window.h | 3bfd74a94c31b3d25f250a5a447f77d9576b9480 | [] | no_license | toshko3331/TPEngine | cb57b0214753957323ba157f96088429f9f5a87b | 8af567a1ee7de6bd19e577582ad28140dc4f0d29 | refs/heads/master | 2021-01-17T11:58:17.018995 | 2015-06-09T17:46:27 | 2015-06-09T17:46:27 | 28,250,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | h | #pragma once
#include "HeadersInclude.h"
#include <string>
class Window
{
public:
Window(const char* title,int x,int y,int width, int height,Uint32 flags);
void destroy();
//Getters
SDL_Window* GetWindow() {return m_window; }
SDL_Renderer* GetRenderer() {return m_renderer;}
SDL_Texture* GetTexture() {return m_texture;}
int GetWindowWidth() { return m_windowWidth; }
int GetWindowHeight() { return m_windowHeight; }
/////
private:
SDL_Window* m_window;
SDL_Renderer* m_renderer;
SDL_Texture* m_texture;
int m_windowWidth;
int m_windowHeight;
};
| [
"toshko9999@gmail.com"
] | toshko9999@gmail.com |
5b7a2abfce65f5c4b99cbd6015bf7fc7c0c092c8 | 0a4101915d11da91739a14fa9613a5acb9fcd7f4 | /src/Blazar/Blazar/Renderer/RenderCommand.cpp | f411cd97b0a9e412010727328ee9fa8ac0027d07 | [] | no_license | Ryanel/Blazar | 43111c0887c106673c344b36f5691c90a8a8be17 | ccc203efcf1ff4dc182fb3cb099c3ecf36e8b4a6 | refs/heads/main | 2023-07-02T06:34:19.230176 | 2021-08-09T00:15:16 | 2021-08-09T00:15:16 | 365,810,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,466 | cpp | #include "bzpch.h"
#include "RenderCommand.h"
namespace Blazar {
const char* RenderCommand_GetString(RenderCommandID v) {
switch (v) {
case Blazar::RenderCommandID::FRAME_SYNC:
return "Frame Sync";
case Blazar::RenderCommandID::SET_SHADER:
return "Set Shader";
case Blazar::RenderCommandID::BIND_VERTEX_ARRAY:
return "Bind VAO";
case Blazar::RenderCommandID::DRAW_VERTEX_ARRAY:
return "Render VAO";
case Blazar::RenderCommandID::BIND_TEXTURE2D:
return "Shader <- Texture2D";
case Blazar::RenderCommandID::BIND_TEXTURE2D_RAW:
return "Shader <- Texture2D*";
case Blazar::RenderCommandID::CLEAR_COLOR:
return "Render Clear";
case Blazar::RenderCommandID::PASS_START:
return "Start Pass";
case Blazar::RenderCommandID::PASS_END:
return "End Pass";
case Blazar::RenderCommandID::PASS_SET_CAMERA:
return "Pass Camera";
case Blazar::RenderCommandID::SET_VIEWPORT:
return "Viewport";
case Blazar::RenderCommandID::SET_RENDERTEXTURE:
return "Render Texture";
case Blazar::RenderCommandID::SET_MAT4:
return "Shader <- Mat4";
case Blazar::RenderCommandID::CAMERA_SETSHADERPROPS:
return "Shader <- CameraProps";
default:
return "Unknown";
}
}
} // namespace Blazar
| [
"corwin.mcknight@gmail.com"
] | corwin.mcknight@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.