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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9376cb8fcbfc15eb70e9092008afff3a2e921e97 | aecef693df48abb893627f4762f8f46a83040787 | /2015/CS1410/assignment 2 - connect-n-game/CS1410Assignment2/ConnectNGame.hpp | 8341614f3cfe78db77171cbd0b1a950825c63c65 | [] | no_license | adamtew/USU | 6f269ec6d28b81eb1f64370dc57e57a8da6e7f19 | b4cc88c996f2841ee3776405f1d606b2bd1a1b4e | refs/heads/master | 2021-01-21T05:59:07.492786 | 2017-09-24T06:40:55 | 2017-09-24T06:40:55 | 28,891,531 | 2 | 0 | null | 2016-01-25T04:59:30 | 2015-01-07T01:06:26 | C++ | UTF-8 | C++ | false | false | 770 | hpp | #ifndef CONNECTNGAME_HPP
#define CONNECTNGAME_HPP
#include <iostream>
using namespace std;
class ConnectNGame
{
public:
ConnectNGame(int);
~ConnectNGame();
void play();
private:
struct Position{
int row;
int col;
char team;
};
void displayGameBoard();
Position playerMove();
Position computerMove();
bool checkRowWin(Position);
bool checkColumnWin(Position);
void makeBoard();
bool checkRightDiagonalWin(Position);
bool checkLeftDiagonalWin(Position);
bool checkTie(Position);
bool checkWin(Position);
void winner();
void tie();
int checkNext(int, int, int, int, char);
bool playing();
int m_rows;
int m_cols;
int m_spacesToWin;
char **m_pBoard;
Position m_playerPos;
Position m_computerPos;
bool m_playing;
bool m_winner;
};
#endif | [
"adamjtew@gmail.com"
] | adamjtew@gmail.com |
7b20725da3829672e655c5b817d2e2e673a42c7f | f4d4623da782672a0fc506a64a9e4848af58cd3a | /util.h | c69e2dabba408213b7b341ad15f84c79558b1749 | [] | no_license | goldstar111/jemalloc-experiments | b1d84871f0190dd660ef771619afb09c85618075 | 23f253a750464782b1a7935b4f569093b2bc2d13 | refs/heads/master | 2021-08-15T18:22:47.150139 | 2017-11-17T21:31:13 | 2017-11-18T00:10:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | h | #include <cstdint>
namespace util {
inline void compilerBarrier() {
asm volatile("" : : : "memory");
}
inline std::uint64_t rdtsc() noexcept {
std::uint32_t lo, hi;
asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
return ((uint64_t)lo) | ((uint64_t)hi << 32);
}
// begin and end must be a multiple of 64.
inline void flushCache(void* beginv, void* endv) {
char* begin = static_cast<char*>(beginv);
char* end = static_cast<char*>(endv);
for (char* ptr = begin; ptr != end; ptr += 64) {
__builtin_ia32_clflush(static_cast<void*>(ptr));
}
}
// Returns time to execute func, in cycles.
template <typename Func>
std::uint64_t runTimed(Func func) {
std::uint64_t begin = rdtsc();
compilerBarrier();
func();
compilerBarrier();
std::uint64_t end = rdtsc();
return end - begin;
}
}
| [
"davidgoldblatt@fb.com"
] | davidgoldblatt@fb.com |
23c833e7885b3a3692223bc0e6db471ade897a13 | 2dc20374263c6ef7848125ad7c03a6eb19be4e43 | /Debug/CEllipse.h | aa339499a504bbaeabab2663b5ac7341489815a8 | [] | no_license | parkjunsoo13/painbrush-c- | 44b9afdca5312c717dac4882e8b739a410d2d0f5 | 4a42f578aa298a53ad7064497f324ff72f13b72e | refs/heads/master | 2022-04-19T19:11:52.570354 | 2020-04-18T09:18:04 | 2020-04-18T09:18:04 | 256,712,714 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 189 | h | #pragma once
class View;
class CEllipse : public Figure { // 원의 정보를 담고있는 클래스
public:
CEllipse(int S_x, int S_y, int E_x, int E_y, View *v);
virtual void Draw();
}; | [
"qkrwnstn13@naver.com"
] | qkrwnstn13@naver.com |
39ed0d8b23586eed138f8c53c4b2de24eb360ac8 | e7aae9ba75b7ec635343119db681d1b634032315 | /external/boost/include/boost/regex/v4/regex_replace.hpp | 513810bd0e197c0baaf846ffece17a4e0f0babe4 | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | fortressforever/fortressforever | 2a4a808e83a7a8ce3fc1d0b3de9a6bb5cbbf5a30 | ede19aa5edef95ffecf8c7964861137fde00e6b8 | refs/heads/beta | 2023-05-25T00:56:19.285863 | 2023-05-22T08:35:09 | 2023-05-22T08:44:23 | 25,147,931 | 102 | 30 | NOASSERTION | 2023-05-22T08:44:25 | 2014-10-13T07:21:19 | C++ | UTF-8 | C++ | false | false | 3,677 | hpp | /*
*
* Copyright (c) 1998-2002
* John Maddock
*
* Use, modification and distribution are subject to the
* Boost Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE regex_format.hpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Provides formatting output routines for search and replace
* operations. Note this is an internal header file included
* by regex.hpp, do not include on its own.
*/
#ifndef BOOST_REGEX_V4_REGEX_REPLACE_HPP
#define BOOST_REGEX_V4_REGEX_REPLACE_HPP
namespace boost{
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
template <class OutputIterator, class BidirectionalIterator, class traits, class charT>
OutputIterator regex_replace(OutputIterator out,
BidirectionalIterator first,
BidirectionalIterator last,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
regex_iterator<BidirectionalIterator, charT, traits> i(first, last, e, flags);
regex_iterator<BidirectionalIterator, charT, traits> j;
if(i == j)
{
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(first, last, out);
}
else
{
BidirectionalIterator last_m = first;
while(i != j)
{
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(i->prefix().first, i->prefix().second, out);
out = i->format(out, fmt, flags, e);
last_m = (*i)[0].second;
if(flags & regex_constants::format_first_only)
break;
++i;
}
if(!(flags & regex_constants::format_no_copy))
out = re_detail::copy(last_m, last, out);
}
return out;
}
template <class OutputIterator, class Iterator, class traits, class charT>
inline OutputIterator regex_replace(OutputIterator out,
Iterator first,
Iterator last,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
return regex_replace(out, first, last, e, fmt.c_str(), flags);
}
template <class traits, class charT>
std::basic_string<charT> regex_replace(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const charT* fmt,
match_flag_type flags = match_default)
{
std::basic_string<charT> result;
re_detail::string_out_iterator<std::basic_string<charT> > i(result);
regex_replace(i, s.begin(), s.end(), e, fmt, flags);
return result;
}
template <class traits, class charT>
std::basic_string<charT> regex_replace(const std::basic_string<charT>& s,
const basic_regex<charT, traits>& e,
const std::basic_string<charT>& fmt,
match_flag_type flags = match_default)
{
std::basic_string<charT> result;
re_detail::string_out_iterator<std::basic_string<charT> > i(result);
regex_replace(i, s.begin(), s.end(), e, fmt.c_str(), flags);
return result;
}
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
} // namespace boost
#endif // BOOST_REGEX_V4_REGEX_REPLACE_HPP
| [
"olah@d5e3c355-140c-0410-b1fe-a40c9a77c12c"
] | olah@d5e3c355-140c-0410-b1fe-a40c9a77c12c |
a82e015b7be1e334c21abaf40728860ae492fd7e | c81a8ae5a92af08f5869d486e134d0e6e346ad3c | /examples/timer/TimerTest.h | 7ffcd361f0b14be17a119c09652f3ea9daabf4f6 | [] | no_license | ZhouDaxia929/My_TCP_Server | 413b7765e3517b0c521843fdeb4ccd5e48816d29 | d1879ff65ed3b87fbec24c1e9bb5330807f3c56a | refs/heads/master | 2020-09-19T16:37:49.833494 | 2019-11-30T14:59:31 | 2019-11-30T14:59:31 | 224,245,957 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | #ifndef MTS_DEMO_TIMERTEST
#define MTS_DEMO_TIMERTEST
#include <iostream>
using namespace std;
class TimerTest{
public:
static void callback1(){
cout << "callback 1 test" << endl;
}
static void callback2(){
cout << "callback 2 test" << endl;
}
static void callback3(){
cout << "callback 3 test" << endl;
}
static void callback4(){
cout << "callback 4 test" << endl;
}
};
#endif | [
"zhoudongxu929@outlook.com"
] | zhoudongxu929@outlook.com |
84fe7a62a0aab2ca22615df6f4feb2270cfc7aa1 | b4408b0f5a77250dbda7db6958ae05cc84e4c293 | /CRT code/C_4-15_matolia/12-3.cpp | 5a6537b5a2816d718eb1196f9709b2ca8470f88b | [] | no_license | sakshamtaneja21/JU-notes | 3b61a222c5264cbfe470d06d3158188438c7c2ff | 74eb5f12979b5ffde8b7e85f661217a641acda98 | refs/heads/master | 2022-12-21T16:03:18.780927 | 2020-09-24T06:24:56 | 2020-09-24T06:24:56 | 287,213,254 | 1 | 1 | null | 2020-08-13T08:01:25 | 2020-08-13T07:38:25 | HTML | UTF-8 | C++ | false | false | 522 | cpp | #include<iostream>
using namespace std;
class A
{
protected:
int x;
public:
void getx()
{
cout<<"Enter value for x"<<endl;
cin>>x;
}
void showx()
{
cout<<"Value of x ="<<x<<endl;
}
};
Class B : A
{
private:
int y;
public:
void getxy()
{
cout<<"eter value of x and y"<<endl;
cin >> x >> y;
}
void showxy()
{
cout<<"Value of x ="<<x<<endl;
cout<<"Value of y ="<<y<<endl;
}
};
int main()
{
A ob;
B obj;
ob.getx();
ob.showx();
obj.showxy();
}
| [
"sakshamtaneja7861@gmail.com"
] | sakshamtaneja7861@gmail.com |
19806023d42ccdeb710fa0f6ada58882bfc86bc2 | 9077c0534879dafc006381abe982913bb53e7477 | /src/drivers/Watchdog.h | 4b308052c04c969fc1aa68ed715052ced125308f | [] | no_license | tonytonyfly/Watch_nRF52840 | 062f248571d5e268c81f1dcd4491112fe855b964 | cd108a64bb277161544cb21bb411652df539378e | refs/heads/master | 2023-07-28T15:13:14.518461 | 2021-09-13T04:27:08 | 2021-09-13T04:27:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 822 | h | #pragma once
#include <cstdint>
namespace Watch {
namespace Drivers {
class Watchdog {
public:
enum class ResetReasons { ResetPin, Watchdog, SoftReset, CpuLockup, SystemOff, LpComp, DebugInterface, NFC, HardReset };
void Setup(uint8_t timeoutSeconds);
void Start();
void Kick();
ResetReasons ResetReason() const { return resetReason; }
static const char* ResetReasonToString(ResetReasons reason);
private:
ResetReasons resetReason;
ResetReasons ActualResetReason() const;
};
class WatchdogView {
public:
WatchdogView(const Watchdog& watchdog) : watchdog{watchdog} { }
Watchdog::ResetReasons ResetReason() const { return watchdog.ResetReason();}
private:
const Watchdog& watchdog;
};
}
}
| [
"tucuongbrt@gmail.com"
] | tucuongbrt@gmail.com |
619c21f02a5973e7ae04cf4d6bff77a41fac1535 | 7edd43f18ee450a9b6eb1d38a4aa39aa53b3e1c1 | /2017CVPR-Generative Face Completion/Generative Face Completion-Caffe/src/caffe/layers/st_layer.cpp | a3d0b858165fba16c089aff89d77947381ad0239 | [] | no_license | Oliiveralien/Inpainting-review | 556a363416a65ca252909930c1a69eb3a2bf921c | 727b51fd283a02de6800f33a4326e3e0997c0318 | refs/heads/master | 2022-12-04T16:46:30.968533 | 2021-05-15T02:39:49 | 2021-05-15T02:39:49 | 239,233,146 | 60 | 9 | null | 2022-11-22T07:11:57 | 2020-02-09T02:08:17 | Python | UTF-8 | C++ | false | false | 16,495 | cpp | #include <vector>
#include <boost/shared_ptr.hpp>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <cmath>
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void SpatialTransformerLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
string prefix = "\t\tSpatial Transformer Layer:: LayerSetUp: \t";
if(this->layer_param_.st_param().transform_type() == "affine") {
transform_type_ = "affine";
} else {
CHECK(false) << prefix << "Transformation type only supports affine now!" << std::endl;
}
if(this->layer_param_.st_param().sampler_type() == "bilinear") {
sampler_type_ = "bilinear";
} else {
CHECK(false) << prefix << "Sampler type only supports bilinear now!" << std::endl;
}
if(this->layer_param_.st_param().to_compute_du()) {
to_compute_dU_ = true;
}
std::cout<<prefix<<"Getting output_H_ and output_W_"<<std::endl;
output_H_ = bottom[0]->shape(2);
if(this->layer_param_.st_param().has_output_h()) {
output_H_ = this->layer_param_.st_param().output_h();
}
output_W_ = bottom[0]->shape(3);
if(this->layer_param_.st_param().has_output_w()) {
output_W_ = this->layer_param_.st_param().output_w();
}
std::cout<<prefix<<"output_H_ = "<<output_H_<<", output_W_ = "<<output_W_<<std::endl;
std::cout<<prefix<<"Getting pre-defined parameters"<<std::endl;
is_pre_defined_theta[0] = false;
if(this->layer_param_.st_param().has_theta_1_1()) {
is_pre_defined_theta[0] = true;
++ pre_defined_count;
pre_defined_theta[0] = this->layer_param_.st_param().theta_1_1();
std::cout<<prefix<<"Getting pre-defined theta[1][1] = "<<pre_defined_theta[0]<<std::endl;
}
is_pre_defined_theta[1] = false;
if(this->layer_param_.st_param().has_theta_1_2()) {
is_pre_defined_theta[1] = true;
++ pre_defined_count;
pre_defined_theta[1] = this->layer_param_.st_param().theta_1_2();
std::cout<<prefix<<"Getting pre-defined theta[1][2] = "<<pre_defined_theta[1]<<std::endl;
}
is_pre_defined_theta[2] = false;
if(this->layer_param_.st_param().has_theta_1_3()) {
is_pre_defined_theta[2] = true;
++ pre_defined_count;
pre_defined_theta[2] = this->layer_param_.st_param().theta_1_3();
std::cout<<prefix<<"Getting pre-defined theta[1][3] = "<<pre_defined_theta[2]<<std::endl;
}
is_pre_defined_theta[3] = false;
if(this->layer_param_.st_param().has_theta_2_1()) {
is_pre_defined_theta[3] = true;
++ pre_defined_count;
pre_defined_theta[3] = this->layer_param_.st_param().theta_2_1();
std::cout<<prefix<<"Getting pre-defined theta[2][1] = "<<pre_defined_theta[3]<<std::endl;
}
is_pre_defined_theta[4] = false;
if(this->layer_param_.st_param().has_theta_2_2()) {
is_pre_defined_theta[4] = true;
++ pre_defined_count;
pre_defined_theta[4] = this->layer_param_.st_param().theta_2_2();
std::cout<<prefix<<"Getting pre-defined theta[2][2] = "<<pre_defined_theta[4]<<std::endl;
}
is_pre_defined_theta[5] = false;
if(this->layer_param_.st_param().has_theta_2_3()) {
is_pre_defined_theta[5] = true;
++ pre_defined_count;
pre_defined_theta[5] = this->layer_param_.st_param().theta_2_3();
std::cout<<prefix<<"Getting pre-defined theta[2][3] = "<<pre_defined_theta[5]<<std::endl;
}
// check the validation for the parameter theta
CHECK(bottom[1]->count(1) + pre_defined_count == 6) << "The dimension of theta is not six!"
<< " Only " << bottom[1]->count(1) << " + " << pre_defined_count << std::endl;
CHECK(bottom[1]->shape(0) == bottom[0]->shape(0)) << "The first dimension of theta and " <<
"U should be the same" << std::endl;
// initialize the matrix for output grid
std::cout<<prefix<<"Initializing the matrix for output grid"<<std::endl;
vector<int> shape_output(2);
shape_output[0] = output_H_ * output_W_; shape_output[1] = 3;
output_grid.Reshape(shape_output);
Dtype* data = output_grid.mutable_cpu_data();
for(int i=0; i<output_H_ * output_W_; ++i) {
data[3 * i] = (i / output_W_) * 1.0 / output_H_ * 2 - 1;
data[3 * i + 1] = (i % output_W_) * 1.0 / output_W_ * 2 - 1;
data[3 * i + 2] = 1;
}
// initialize the matrix for input grid
std::cout<<prefix<<"Initializing the matrix for input grid"<<std::endl;
vector<int> shape_input(3);
shape_input[0] = bottom[1]->shape(0); shape_input[1] = output_H_ * output_W_; shape_input[2] = 2;
input_grid.Reshape(shape_input);
std::cout<<prefix<<"Initialization finished."<<std::endl;
}
template <typename Dtype>
void SpatialTransformerLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
string prefix = "\t\tSpatial Transformer Layer:: Reshape: \t";
if(global_debug) std::cout<<prefix<<"Starting!"<<std::endl;
N = bottom[0]->shape(0);
C = bottom[0]->shape(1);
H = bottom[0]->shape(2);
W = bottom[0]->shape(3);
// reshape V
vector<int> shape(4);
shape[0] = N;
shape[1] = C;
shape[2] = output_H_;
shape[3] = output_W_;
top[0]->Reshape(shape);
// reshape dTheta_tmp
vector<int> dTheta_tmp_shape(4);
dTheta_tmp_shape[0] = N;
dTheta_tmp_shape[1] = 2;
dTheta_tmp_shape[2] = 3;
dTheta_tmp_shape[3] = output_H_ * output_W_ * C;
dTheta_tmp.Reshape(dTheta_tmp_shape);
// init all_ones_2
vector<int> all_ones_2_shape(1);
all_ones_2_shape[0] = output_H_ * output_W_ * C;
all_ones_2.Reshape(all_ones_2_shape);
// reshape full_theta
vector<int> full_theta_shape(2);
full_theta_shape[0] = N;
full_theta_shape[1] = 6;
full_theta.Reshape(full_theta_shape);
if(global_debug) std::cout<<prefix<<"Finished."<<std::endl;
}
template <typename Dtype>
Dtype SpatialTransformerLayer<Dtype>::transform_forward_cpu(const Dtype* pic, Dtype px, Dtype py) {
bool debug = false;
string prefix = "\t\tSpatial Transformer Layer:: transform_forward_cpu: \t";
if(debug) std::cout<<prefix<<"Starting!\t"<<std::endl;
if(debug) std::cout<<prefix<<"(px, py) = ("<<px<<", "<<py<<")"<<std::endl;
Dtype res = (Dtype)0.;
Dtype x = (px + 1) / 2 * H; Dtype y = (py + 1) / 2 * W;
if(debug) std::cout<<prefix<<"(x, y) = ("<<x<<", "<<y<<")"<<std::endl;
int m, n; Dtype w;
m = floor(x); n = floor(y); w = 0;
if(debug) std::cout<<prefix<<"1: (m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
res += w * pic[m * W + n];
if(debug) std::cout<<prefix<<"w = "<<w<<", pic[m, n] = "<<pic[m * W + n]<<std::endl;
}
m = floor(x) + 1; n = floor(y); w = 0;
if(debug) std::cout<<prefix<<"2: (m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
res += w * pic[m * W + n];
if(debug) std::cout<<prefix<<"w = "<<w<<", pic[m, n] = "<<pic[m * W + n]<<std::endl;
}
m = floor(x); n = floor(y) + 1; w = 0;
if(debug) std::cout<<prefix<<"3: (m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
res += w * pic[m * W + n];
if(debug) std::cout<<prefix<<"w = "<<w<<", pic[m, n] = "<<pic[m * W + n]<<std::endl;
}
m = floor(x) + 1; n = floor(y) + 1; w = 0;
if(debug) std::cout<<prefix<<"4: (m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
res += w * pic[m * W + n];
if(debug) std::cout<<prefix<<"w = "<<w<<", pic[m, n] = "<<pic[m * W + n]<<std::endl;
}
if(debug) std::cout<<prefix<<"Finished. \tres = "<<res<<std::endl;
return res;
}
template <typename Dtype>
void SpatialTransformerLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
string prefix = "\t\tSpatial Transformer Layer:: Forward_cpu: \t";
CHECK(false) << "Don't use the CPU implementation! If you really want to, delete the" <<
" CHECK in st_layer.cpp file. Line number: 240-241." << std::endl;
if(global_debug) std::cout<<prefix<<"Starting!"<<std::endl;
const Dtype* U = bottom[0]->cpu_data();
const Dtype* theta = bottom[1]->cpu_data();
const Dtype* output_grid_data = output_grid.cpu_data();
Dtype* input_grid_data = input_grid.mutable_cpu_data();
Dtype* V = top[0]->mutable_cpu_data();
caffe_set(input_grid.count(), (Dtype)0, input_grid_data);
caffe_set(top[0]->count(), (Dtype)0, V);
// for each input
for(int i = 0; i < N; ++i) {
Dtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasTrans, output_H_ * output_W_, 2, 3, (Dtype)1.,
output_grid_data, theta + 6 * i, (Dtype)0., coordinates);
int row_idx; Dtype px, py;
for(int j = 0; j < C; ++j)
for(int s = 0; s < output_H_; ++s)
for(int t = 0; t < output_W_; ++t) {
row_idx = output_W_ * s + t;
px = coordinates[row_idx * 2];
py = coordinates[row_idx * 2 + 1];
V[top[0]->offset(i, j, s, t)] = transform_forward_cpu(
U + bottom[0]->offset(i, j, 0, 0), px, py);
}
}
if(global_debug) std::cout<<prefix<<"Finished."<<std::endl;
}
template <typename Dtype>
void SpatialTransformerLayer<Dtype>::transform_backward_cpu(Dtype dV, const Dtype* U, const Dtype px,
const Dtype py, Dtype* dU, Dtype& dpx, Dtype& dpy) {
bool debug = false;
string prefix = "\t\tSpatial Transformer Layer:: transform_backward_cpu: \t";
if(debug) std::cout<<prefix<<"Starting!"<<std::endl;
Dtype x = (px + 1) / 2 * H; Dtype y = (py + 1) / 2 * W;
if(debug) std::cout<<prefix<<"(x, y) = ("<<x<<", "<<y<<")"<<std::endl;
int m, n; Dtype w;
m = floor(x); n = floor(y); w = 0;
if(debug) std::cout<<prefix<<"(m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
dU[m * W + n] += w * dV;
if(abs(x - m) < 1) {
if(m >= x) {
dpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx += "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
} else {
dpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx -= "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
}
}
if(abs(y - n) < 1) {
if(n >= y) {
dpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy += "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
} else {
dpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy -= "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
}
}
}
m = floor(x) + 1; n = floor(y); w = 0;
if(debug) std::cout<<prefix<<"(m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
dU[m * W + n] += w * dV;
if(abs(x - m) < 1) {
if(m >= x) {
dpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx += "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
} else {
dpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx -= "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
}
}
if(abs(y - n) < 1) {
if(n >= y) {
dpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy += "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
} else {
dpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy -= "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
}
}
}
m = floor(x); n = floor(y) + 1; w = 0;
if(debug) std::cout<<prefix<<"(m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
dU[m * W + n] += w * dV;
if(abs(x - m) < 1) {
if(m >= x) {
dpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx += "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
} else {
dpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx -= "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
}
}
if(abs(y - n) < 1) {
if(n >= y) {
dpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy += "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
} else {
dpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy -= "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
}
}
}
m = floor(x) + 1; n = floor(y) + 1; w = 0;
if(debug) std::cout<<prefix<<"(m, n) = ("<<m<<", "<<n<<")"<<std::endl;
if(m >= 0 && m < H && n >= 0 && n < W) {
w = max(0, 1 - abs(x - m)) * max(0, 1 - abs(y - n));
dU[m * W + n] += w * dV;
if(abs(x - m) < 1) {
if(m >= x) {
dpx += max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx += "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
} else {
dpx -= max(0, 1 - abs(y - n)) * U[m * W + n] * dV * H / 2;
if(debug) std::cout<<prefix<<"dpx -= "<<max(0, 1 - abs(y - n))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<H / 2<<std::endl;
}
}
if(abs(y - n) < 1) {
if(n >= y) {
dpy += max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy += "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
} else {
dpy -= max(0, 1 - abs(x - m)) * U[m * W + n] * dV * W / 2;
if(debug) std::cout<<prefix<<"dpy -= "<<max(0, 1 - abs(x - m))<<" * "<<U[m * W + n]<<" * "<<dV<<" * "<<W / 2<<std::endl;
}
}
}
if(debug) std::cout<<prefix<<"Finished."<<std::endl;
}
template <typename Dtype>
void SpatialTransformerLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
string prefix = "\t\tSpatial Transformer Layer:: Backward_cpu: \t";
CHECK(false) << "Don't use the CPU implementation! If you really want to, delete the" <<
" CHECK in st_layer.cpp file. Line number: 420-421." << std::endl;
if(global_debug) std::cout<<prefix<<"Starting!"<<std::endl;
const Dtype* dV = top[0]->cpu_diff();
const Dtype* input_grid_data = input_grid.cpu_data();
const Dtype* U = bottom[0]->cpu_data();
Dtype* dU = bottom[0]->mutable_cpu_diff();
Dtype* dTheta = bottom[1]->mutable_cpu_diff();
Dtype* input_grid_diff = input_grid.mutable_cpu_diff();
caffe_set(bottom[0]->count(), (Dtype)0, dU);
caffe_set(bottom[1]->count(), (Dtype)0, dTheta);
caffe_set(input_grid.count(), (Dtype)0, input_grid_diff);
for(int i = 0; i < N; ++i) {
const Dtype* coordinates = input_grid_data + (output_H_ * output_W_ * 2) * i;
Dtype* coordinates_diff = input_grid_diff + (output_H_ * output_W_ * 2) * i;
int row_idx; Dtype px, py, dpx, dpy, delta_dpx, delta_dpy;
for(int s = 0; s < output_H_; ++s)
for(int t = 0; t < output_W_; ++t) {
row_idx = output_W_ * s + t;
px = coordinates[row_idx * 2];
py = coordinates[row_idx * 2 + 1];
for(int j = 0; j < C; ++j) {
delta_dpx = delta_dpy = (Dtype)0.;
transform_backward_cpu(dV[top[0]->offset(i, j, s, t)], U + bottom[0]->offset(i, j, 0, 0),
px, py, dU + bottom[0]->offset(i, j, 0, 0), delta_dpx, delta_dpy);
coordinates_diff[row_idx * 2] += delta_dpx;
coordinates_diff[row_idx * 2 + 1] += delta_dpy;
}
dpx = coordinates_diff[row_idx * 2];
dpy = coordinates_diff[row_idx * 2 + 1];
dTheta[6 * i] += dpx * (s * 1.0 / output_H_ * 2 - 1);
dTheta[6 * i + 1] += dpx * (t * 1.0 / output_W_ * 2 - 1);
dTheta[6 * i + 2] += dpx;
dTheta[6 * i + 3] += dpy * (s * 1.0 / output_H_ * 2 - 1);
dTheta[6 * i + 4] += dpy * (t * 1.0 / output_W_ * 2 - 1);
dTheta[6 * i + 5] += dpy;
}
}
if(global_debug) std::cout<<prefix<<"Finished."<<std::endl;
}
#ifdef CPU_ONLY
STUB_GPU(SpatialTransformerLayer);
#endif
INSTANTIATE_CLASS(SpatialTransformerLayer);
REGISTER_LAYER_CLASS(SpatialTransformer);
} // namespace caffe
| [
"oliversavealien@gmail.com"
] | oliversavealien@gmail.com |
f850e0fac84621bc1ada05f7611336595c466ffa | 5b06fe91345029324c9e9316c4d8bbda66f803fc | /my_first_project/src/actions/fibonacci_server.cpp | 22000ffbdfae2641b09786d269f2f69583d95d2b | [
"Apache-2.0"
] | permissive | solid-sinusoid/ros_comm_lessons | e0cb48116094ba5126b7bdea770f01672daecb49 | 4d270dd8b8382581480c9a79fb751cf1bd6a446a | refs/heads/main | 2023-08-22T17:35:07.200125 | 2021-09-23T07:15:13 | 2021-09-23T07:15:13 | 409,407,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,274 | cpp | #include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <my_first_project/fibonacciAction.h>
class FibonacciAction
{
protected:
ros::NodeHandle nh_;
actionlib::SimpleActionServer<my_first_project::fibonacciAction> as_; // NodeHandle instance must be created before this line. Otherwise strange error occurs.
std::string action_name_;
// create messages that are used to published feedback/result
my_first_project::fibonacciFeedback feedback_;
my_first_project::fibonacciResult result_;
public:
FibonacciAction(std::string name):
as_(nh_, name, boost::bind(&FibonacciAction::executeCB, this, _1), false),
action_name_(name)
{
as_.start();
}
~FibonacciAction(void)
{
}
void executeCB(const my_first_project::fibonacciGoalConstPtr &goal)
{
// helper variables
ros::Rate r(1);
bool success = true;
// push_back the seeds for the fibonacci sequence
feedback_.sequence.clear();
feedback_.sequence.push_back(0);
feedback_.sequence.push_back(1);
// publish info to the console for the user
ROS_INFO("%s: Executing, creating fibonacci sequence of order %i with seeds %i, %i", action_name_.c_str(), goal->order, feedback_.sequence[0], feedback_.sequence[1]);
// start executing the action
for(int i=1; i<=goal->order; i++)
{
// check that preempt has not been requested by the client
if (as_.isPreemptRequested() || !ros::ok())
{
ROS_INFO("%s: Preempted", action_name_.c_str());
// set the action state to preempted
as_.setPreempted();
success = false;
break;
}
feedback_.sequence.push_back(feedback_.sequence[i] + feedback_.sequence[i-1]);
// publish the feedback
as_.publishFeedback(feedback_);
// this sleep is not necessary, the sequence is computed at 1 Hz for demonstration purposes
r.sleep();
}
if(success)
{
result_.sequence = feedback_.sequence;
ROS_INFO("%s: Succeeded", action_name_.c_str());
// set the action state to succeeded
as_.setSucceeded(result_);
}
}
};
int main(int argc, char** argv)
{
ros::init(argc, argv, "fibonacci");
FibonacciAction fibonacci("fibonacci");
ros::spin();
return 0;
}
| [
"ur.narmak@gmail.com"
] | ur.narmak@gmail.com |
16ba2fe874a3fb8538f8f12e38ba914c4767d9e8 | 33fd5786ddde55a705d74ce2ce909017e2535065 | /build/iOS/Release/include/Uno.IO.BundleFile.h | 8cbb61ae2070e6c3c3cbc458aed5ed225036fbbc | [] | no_license | frpaulas/iphodfuse | 04cee30add8b50ea134eb5a83e355dce886a5d5a | e8886638c4466b3b0c6299da24156d4ee81c9112 | refs/heads/master | 2021-01-23T00:48:31.195577 | 2017-06-01T12:33:13 | 2017-06-01T12:33:13 | 92,842,106 | 3 | 3 | null | 2017-05-30T17:43:28 | 2017-05-30T14:33:26 | C++ | UTF-8 | C++ | false | false | 2,811 | h | // This file was generated based on '../../../../Library/Application Support/Fusetools/Packages/UnoCore/0.47.13/source/uno/io/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Uno{namespace IO{struct Bundle;}}}
namespace g{namespace Uno{namespace IO{struct BundleFile;}}}
namespace g{namespace Uno{namespace IO{struct Stream;}}}
namespace uBase { class Stream; }
namespace g{
namespace Uno{
namespace IO{
// public sealed class BundleFile :632
// {
uType* BundleFile_typeof();
void BundleFile__ctor__fn(BundleFile* __this, ::g::Uno::IO::Bundle* bundle, uString* sourcePath, uString* bundlePath);
void BundleFile__get_Bundle_fn(BundleFile* __this, ::g::Uno::IO::Bundle** __retval);
void BundleFile__set_Bundle_fn(BundleFile* __this, ::g::Uno::IO::Bundle* value);
void BundleFile__get_BundlePath_fn(BundleFile* __this, uString** __retval);
void BundleFile__set_BundlePath_fn(BundleFile* __this, uString* value);
void BundleFile__add_Changed_fn(BundleFile* __this, uDelegate* value);
void BundleFile__remove_Changed_fn(BundleFile* __this, uDelegate* value);
void BundleFile__CppXliOpenRead_fn(BundleFile* __this, uBase::Stream** __retval);
void BundleFile__get_IsFile_fn(BundleFile* __this, bool* __retval);
void BundleFile__set_IsFile_fn(BundleFile* __this, bool* value);
void BundleFile__New1_fn(::g::Uno::IO::Bundle* bundle, uString* sourcePath, uString* bundlePath, BundleFile** __retval);
void BundleFile__OpenRead_fn(BundleFile* __this, ::g::Uno::IO::Stream** __retval);
void BundleFile__ReadAllBytes_fn(BundleFile* __this, uArray** __retval);
void BundleFile__ReadAllText_fn(BundleFile* __this, uString** __retval);
void BundleFile__get_SourcePath_fn(BundleFile* __this, uString** __retval);
void BundleFile__set_SourcePath_fn(BundleFile* __this, uString* value);
void BundleFile__ToString_fn(BundleFile* __this, uString** __retval);
struct BundleFile : uObject
{
uWeak< ::g::Uno::IO::Bundle*> _Bundle;
uStrong<uString*> _BundlePath;
bool _IsFile;
uStrong<uString*> _SourcePath;
uStrong<uDelegate*> Changed1;
void ctor_(::g::Uno::IO::Bundle* bundle, uString* sourcePath, uString* bundlePath);
::g::Uno::IO::Bundle* Bundle();
void Bundle(::g::Uno::IO::Bundle* value);
uString* BundlePath();
void BundlePath(uString* value);
void add_Changed(uDelegate* value);
void remove_Changed(uDelegate* value);
uBase::Stream* CppXliOpenRead();
bool IsFile();
void IsFile(bool value);
::g::Uno::IO::Stream* OpenRead();
uArray* ReadAllBytes();
uString* ReadAllText();
uString* SourcePath();
void SourcePath(uString* value);
static BundleFile* New1(::g::Uno::IO::Bundle* bundle, uString* sourcePath, uString* bundlePath);
};
// }
}}} // ::g::Uno::IO
| [
"frpaulas@gmail.com"
] | frpaulas@gmail.com |
44c7caa7399dbf3f09f3423a1a796cc5268ba0ef | 1aa263e78bc4271d1c261ec6e710eb68d175dfd9 | /fsiv/fsiv_tutorial_opencv/p1/pract1.cc | 0a2370bc9515ad830067d858aa750e53172f7c47 | [] | no_license | Anhesr/algo | b4c48464fcdd8414b37572b036d0a7a0746b7d49 | 2ea27075c3e528794332482153b61294efc466ec | refs/heads/master | 2020-08-22T11:53:35.795527 | 2020-02-13T19:16:11 | 2020-02-13T19:16:11 | 216,388,513 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,924 | cc | #include <iostream>
#include <exception>
//Includes para OpenCV, Descomentar según los módulo utilizados.
#include <opencv2/core/core.hpp>
#include <opencv2/core/utility.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/opencv.hpp>
#include <opencv2/calib3d/calib3d.hpp>
using namespace cv;
cv::Mat img;
cv::Mat imgaux;
bool dibujar=false;
const cv::String keys =
"{help h usage ? | | print this message }"
"{@image1 | | image1 for compare }"
"{@image2 |<none>| image2 for compare }"
;
void mouseEvents(int event,int x ,int y, int flags,void *userdata){
Point punto(x,y);
if(event == EVENT_LBUTTONDOWN){
dibujar=true;
static_cast<Point*>(userdata)[0]=punto;
static_cast<Point*>(userdata)[1]=punto;
}
if((event == EVENT_MOUSEMOVE) and (dibujar==true)){
static_cast<Point*>(userdata)[1]=punto;
imgaux=img.clone();
rectangle(imgaux,static_cast<Point*>(userdata)[0],static_cast<Point*>(userdata)[1],Scalar(255,0,0),2);
imshow("IMG",imgaux);
}
if(event == EVENT_LBUTTONUP){
dibujar=false;
static_cast<Point*>(userdata)[1]=punto;
}
}
int
main (int argc, char* const* argv)
{
int retCode=EXIT_SUCCESS;
try {
cv::CommandLineParser parser(argc, argv, keys);
parser.about("Application name v1.0.0");
if (parser.has("help"))
{
parser.printMessage();
return 0;
}
cv::String img1 = parser.get<cv::String>(0);
cv::String img2 = parser.get<cv::String>(1);
if (!parser.check())
{
parser.printErrors();
return 0;
}
//Carga de la imagen
img = cv::imread(img1, cv::IMREAD_COLOR);
if (img.empty())
{
std::cerr << "Error: no he podido abrir el fichero '" << img1 << "'." << std::endl;
return EXIT_FAILURE;
}
Point punto[2];
cv::namedWindow("IMG");
setMouseCallback("IMG",mouseEvents,punto);
imshow("IMG",img);
waitKey(0);
for (int i = 0; i < img.rows; ++i)
{
for (int j = 0; j < img.cols; ++j)
{
Vec3b pixel=img.at<Vec3b>(i,j);
uchar B = pixel[0];
uchar G = pixel[1];
uchar R = pixel[2];
if( (i < min(punto[0].y,punto[1].y) or (i > max(punto[0].y,punto[1].y))) or
((j < min(punto[0].x,punto[1].x)) or (j > max(punto[0].x,punto[1].x)))) {
uchar avg= (B+G+R)/3;
pixel[0]=avg;
pixel[1]=avg;
pixel[2]=avg;
}
imgaux.at<Vec3b>(i,j)=pixel;
}
}
cv::imshow("IMG", imgaux);
int wait = cv::waitKey(0);
if (wait != 27){
cv::imwrite(img2,img);
}
}
catch (std::exception& e)
{
std::cerr << "Capturada excepcion: " << e.what() << std::endl;
retCode = EXIT_FAILURE;
}
return retCode;
} | [
"i72saraf@uco.es"
] | i72saraf@uco.es |
e9406275d3d0429a73d77245e27ad089613bf366 | cbb4d75e9718a1d4b5215b31d33ec89d18ec9b5b | /Lab4/Lab4.4/Source.cpp | 65d8e4f325b452dea20c4e2d264fc3299c6ab54c | [] | no_license | WarerBit/OOP | d861343def75e9b1a06d6f1dbc5d7012a8dd1af3 | d77a8fda90bc66b465c6503322e4483ba938970a | refs/heads/master | 2020-04-24T20:03:12.788230 | 2019-06-04T09:28:51 | 2019-06-04T09:28:51 | 172,232,093 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | #include"Child.h"
#include<iostream>
using namespace std;
int main()
{
Child son, daughter;
son.setVal(AGE_CH, 12);
son.setVal(NAME_CH, "Tolik");
son.setVal(SURNAME_CH, "Ivanov");
cout << "Son:\n";
son.getVal(AGE_CH);
son.getVal(NAME_CH);
son.getVal(SURNAME_CH);
daughter.setVal(AGE_CH, 8);
daughter.setVal(NAME_CH, "Masha");
daughter.setVal(SURNAME_CH, "Ivanova");
cout << "\nDaughter:\n";
daughter.getVal(AGE_CH);
daughter.getVal(NAME_CH);
daughter.getVal(SURNAME_CH);
system("pause");
} | [
"47922230+WarerBit@users.noreply.github.com"
] | 47922230+WarerBit@users.noreply.github.com |
f20dd481598c41caa1beaced1e3dde486ad18084 | 9f0d42c412db503f0759980a35136618ac6fda79 | /MyProjects/C++/2020/12.26/P3803(FFT).cpp | 2bb69f1f26337acba0957d74dca320a54d0b1fba | [] | no_license | lieppham/MyCode | 38a8c1353a2627d68b47b5f959bb827819058357 | 469d87f9d859123dec754b2e4ae0dced53f68660 | refs/heads/main | 2023-08-25T04:00:00.495534 | 2021-10-21T12:15:44 | 2021-10-21T12:15:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,894 | cpp | //File: P3803.cpp
//Author: yanyanlongxia
//Date: 2020/12/31
//
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=5e6+5;
const double PI=acos(-1.0);
int n,m,len,cnt,rev[N << 1];
struct Complex{
double x,y;
Complex() {}
Complex(double _x,double _y): x(_x),y(_y) {}
Complex operator + (Complex val)const {
return Complex(x+val.x,y+val.y);
}
Complex operator - (Complex val)const{
return Complex(x-val.x,y-val.y);
}
Complex operator * (Complex val)const {
return Complex(x*val.x-y*val.y,x*val.y+y*val.x);
}
}a[N<<1],b[N<<1],c[N<<1];
void FFT(Complex *a,int len,int flag){
for(int i=0;i<len;i++){
if(i > rev[i])
swap(a[i],a[rev[i]]);
}
for(int i=2;i<=len;i<<=1){
Complex wn(double(cos(flag*2*PI/i)),double(sin(flag*2*PI/i)));
for(int j=0;j<len;j+=i){
Complex w(1,0);
for(int k=j;k<j+(i>>1);k++){
Complex u=a[k];
Complex t=a[k+(i>>1)]*w;
a[k]=u+t;
a[k+(i>>1)]=u-t;
w=w*wn;
}
}
}
if(flag==-1){
for(int i=0;i<len;i++)
a[i].x/=len;
}
}
int main() {
freopen("data.in","rev",stdin);
//freopen("P3803.out","w",stdout);
scanf("%d", &n);
scanf("%d", &m);
for(int i=0;i<=n;i++)
scanf("%lf", &a[i].x);
for(int i=0;i<=m;i++)
scanf("%lf", &b[i].x);
len=1,cnt=0;
while(len<=n+m){
len<<=1;
cnt++;
}
for(int i=0;i<len;i++)
rev[i]= (rev[i >> 1] >> 1) | ((i & 1) << (cnt - 1));
FFT(a,len,1);
FFT(b,len,1);
for(int i=0;i<len;i++)
c[i]=a[i]*b[i];
FFT(c,len,-1);
for(int i=0;i<=n+m;i++)
printf("%d ",int(c[i].x+0.5));
return 0;
}
| [
"yanyanlongxia@outlook.com"
] | yanyanlongxia@outlook.com |
47f5e1dc17a05765ab9697f8861fe939280bd53b | 1e381f2b974bc82cd2f0bd0cc5029cbda1baedb2 | /SPOJ-SOLUTION/PUCMM025.cpp | 0c9d3e7c667690a68f0e2df605fbf66bd66091ac | [] | no_license | rajat189/Competetive_programming | 7655678935d40cada5a3d39ed400ee430f0311db | 709065b3527eceb3923c13091608c174ae3a5d64 | refs/heads/master | 2021-01-19T05:53:35.790236 | 2016-04-12T19:12:34 | 2016-04-12T19:12:34 | 38,609,439 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,206 | cpp | #include <iostream>
#include <cstdio>
#include <string>
using namespace std;
int main()
{
string s,s1,s2,s3;
int a[10000];
int b[10]={0, 1, 3, 2, 6, 4 , 5};
int ans=0;
int sum=0,n,m,i,c,d,e;
while(cin>>s)
{
ans=0;
sum=0;
for(i=0;i<s.size();i++)
{
a[i+2]=s[i]-'0';
sum=sum+a[i+2];
}
m=s.size()+1;
for(i=1;i<=m;i++)
{
if(a[i]==1)
ans++;
if(a[i]==2 && a[m]%2==0)
ans++;
if(a[i]==3 && sum%3==0)
ans++;
if(a[i]==4 && (a[m]+a[m-1]*10)%4==0)
ans++;
if(a[i]==5 && a[m]%5==0)
ans++;
if(a[i]==6 && sum%3==0 && a[m]%2==0)
ans++;
if(a[i]==8 && (a[m]+10*a[m-1]+100*a[m-2])%8==0)
ans++;
if(a[i]==9 && sum%9==0)
ans++;
if(a[i]==7)
{
c=1;
d=m;
e=0;
while(d>1)
{
e=e+a[d]*b[c];
c++;
d--;
if(c>6)
c=1;
}
if(e%7==0)
ans++;
}
}
cout<<ans<<endl;
}
return 0;
}
| [
"coolrajatsharma18@gmail.com"
] | coolrajatsharma18@gmail.com |
e7890556d20d7d69d81c9388d2f15006d92ff268 | 1ac559396fce8a55aaeafa15e9782443d507d8f4 | /pj5_beta/isim/work/ea2nor/behavioral.h | 6a4a5e17ba240eabd1e0454a12f3b3b3d10506f2 | [] | no_license | erik1o6/VHDL | 2466a113a24ea5ffbcdfc575c22f27d9eebe6936 | 9de67a0625dce5ad4dc2991ee789453c9dd25aad | refs/heads/master | 2020-12-24T17:45:10.106680 | 2013-01-25T20:09:39 | 2013-01-25T20:09:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 941 | h | ////////////////////////////////////////////////////////////////////////////////
// ____ ____
// / /\/ /
// /___/ \ /
// \ \ \/
// \ \ Copyright (c) 2003-2004 Xilinx, Inc.
// / / All Right Reserved.
// /---/ /\
// \ \ / \
// \___\/\___\
////////////////////////////////////////////////////////////////////////////////
#ifndef H_Work_ea2nor_behavioral_H
#define H_Work_ea2nor_behavioral_H
#ifdef __MINGW32__
#include "xsimMinGW.h"
#else
#include "xsim.h"
#endif
class Work_ea2nor_behavioral: public HSim__s6 {
public:
HSim__s1 SE[3];
char t88;
char t89;
Work_ea2nor_behavioral(const char * name);
~Work_ea2nor_behavioral();
void constructObject();
void constructPorts();
void reset();
void architectureInstantiate(HSimConfigDecl* cfg);
virtual void vhdlArchImplement();
};
HSim__s6 *createWork_ea2nor_behavioral(const char *name);
#endif
| [
"erik.arfvidson@gmail.com"
] | erik.arfvidson@gmail.com |
f4f6da379ce3178d28493af6dd7d76324e2e8f23 | 7d8b6427b5c0fc80777fb340688d496905b0363b | /win32OOP/PalmAOOP/eventcontrol.cpp | 2c1e34d67d1db345cd779669f8bbedf765f181f0 | [] | no_license | peitaosu/LeapSHOU | a5e5f43a2a47b1f119cc1d3f3c54383fe993f0e1 | a225f55e7df77655246ef439e6e986a25dd79094 | refs/heads/master | 2021-01-22T19:36:06.075769 | 2015-07-26T07:19:30 | 2015-07-26T07:19:30 | 33,783,742 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,347 | cpp | #include "eventcontrol.h"
#include <QTimer>
#include <QApplication>
#include <QDesktopWidget>
#include "roadmapgesture.h"
#define GRABSTART_SHOW 111
#define GRABKEEP_SHOW 112
#define GRABSTOP_SHOW 110
#define PINCHSTART_SHOW 121
#define PINCHKEEP_SHOW 122
#define PINCHSTOP_SHOW 120
#define HOLDSTART_SHOW 131
#define HOLDKEEP_SHOW 132
#define HOLDDONE_SHOW 133
#define HOLDSTOP_SHOW 130
#define CIRCLESTART_SHOW 141
#define CIRCLEKEEP_SHOW 142
#define CIRCLESTOP_SHOW 140
#define CIRCLEANTISTART_SHOW 151
#define CIRCLEANTIKEEP_SHOW 152
#define CIRCLEANTISTOP_SHOW 150
#define ON 0
#define START 1
#define KEEP 2
#define STOP 3
#define ANTI 4
#define GESMAX 4
int GestureStatus[GESMAX] = {0};
bool GestureStatusPrev[GESMAX] = {0};
bool GestureStatusCrt[GESMAX] ={0};
int FGWPrev = -1;
int delay = 0;
int Turntable[2] = {0};
EventControl::EventControl(QObject *parent) :
QObject(parent)
{
controller.addListener(listenner);
controller.setPolicyFlags(Leap::Controller::PolicyFlag::POLICY_BACKGROUND_FRAMES);
VM.show();
// DP = new Display();
DP.show();
//DS.show();
DML.show();
OP = new Operate(this);
SP = new SettingPanel();
//DG.show();
QTimer *EventTimer = new QTimer(this);
connect(EventTimer,SIGNAL(timeout()),this,SLOT(EventListenner()));
EventTimer->start(20);
connect(this,SIGNAL(showGesture(int)),&DP,SLOT(showGesture(int)));
connect(this,SIGNAL(desktopS()),this,SLOT(desktop()));
connect(this,SIGNAL(browserS()),this,SLOT(browser()));
connect(this,SIGNAL(pcS()),this,SLOT(pc()));
connect(this,SIGNAL(otherS()),this,SLOT(other()));
connect(this,SIGNAL(disconnectAllS()),this,SLOT(disconnectAll()));
//connect(this,SIGNAL(handUp()),OP,SLOT(moveWindowtoUp()));
//connect(this,SIGNAL(handDown()),OP,SLOT(moveWindowtoDown()));
//connect(this,SIGNAL(handLeft()),OP,SLOT(moveWindowtoLeft()));
//connect(this,SIGNAL(handRight()),OP,SLOT(moveWindowtoRight()));
connect(this,SIGNAL(showRoadMapS()),this,SLOT(showRoadMap()));
//connect(this,SIGNAL(releaseRoadMapS()),this,SLOT(releaseRoadMap()));
}
EventControl::~EventControl(){
controller.removeListener(listenner);
}
void EventControl::EventListenner(){
if(Turntable[0] != 0){
DML.setLine(Turntable[0],Turntable[1],GR.getX(),GR.getY());
}else{
DML.setLine(0,0,0,0);
}
//std::cout<<FGW.getFGWinName()<<std::endl;
if(FGW.getFGWinName() != FGWPrev){
switch(FGW.getFGWinName()){
case 1:
emit desktopS();
break;
case 2:
emit browserS();
break;
case 3:
emit pcS();
//emit releaseRoadMapS();
break;
case 0:
emit otherS();
break;
default:
break;
}
FGWPrev = FGW.getFGWinName();
}
for(int i = 0;i<GESMAX;i++){
GestureStatusPrev[i] = GestureStatusCrt[i];
}
GestureStatusCrt[0] = GR.gesGrabRight();
GestureStatusCrt[1] = GR.gesPinchRight();
GestureStatusCrt[2] = GR.gesCircle();
GestureStatusCrt[3] = GR.gesCircleAnti();
for(int i = 0;i<GESMAX;i++){
if(!GestureStatusPrev[i] && !GestureStatusCrt[i]){
//00
GestureStatus[i] = ON;
}else if(!GestureStatusPrev[i] && GestureStatusCrt[i]){
//01
GestureStatus[i] = START;
}else if(GestureStatusPrev[i] && GestureStatusCrt[i]){
//11
GestureStatus[i] = KEEP;
}else if(GestureStatusPrev[i] && !GestureStatusCrt[i]){
//10
GestureStatus[i] = STOP;
}
}
//
switch(GestureStatus[0]){
case ON:
break;
case START:
emit grabStart();
emit showGesture(GRABSTART_SHOW);
break;
case KEEP:
emit showGesture(GRABKEEP_SHOW);
break;
case STOP:
emit showGesture(GRABSTOP_SHOW);
emit grabStop();
break;
default:
break;
}
switch(GestureStatus[1]){
case ON:
break;
case START:
emit pinchStart();
emit showGesture(PINCHSTART_SHOW);
break;
case KEEP:
emit showGesture(PINCHKEEP_SHOW);
break;
case STOP:
emit pinchStop();
emit showGesture(PINCHSTOP_SHOW);
break;
default:
break;
}
switch(GestureStatus[2]){
case ON:
break;
case START:
emit circleStart();
emit showGesture(CIRCLESTART_SHOW);
break;
case KEEP:
emit circleKeep();
emit showGesture(CIRCLEKEEP_SHOW);
break;
case STOP:
emit circleStop();
emit showGesture(CIRCLESTOP_SHOW);
break;
default:
break;
}
switch(GestureStatus[3]){
case ON:
break;
case START:
emit circleAntiStart();
emit showGesture(CIRCLEANTISTART_SHOW);
break;
case KEEP:
emit circleAntiKeep();
emit showGesture(CIRCLEANTIKEEP_SHOW);
break;
case STOP:
emit circleAntiStop();
emit showGesture(CIRCLEANTISTOP_SHOW);
break;
default:
break;
}
switch(GR.gesHoldRight()){
case 1:
emit holdStart();
emit showGesture(HOLDSTART_SHOW);
break;
case 2:
emit holdKeep();
emit showGesture(HOLDKEEP_SHOW);
break;
case 3:
emit holdDone();
emit showGesture(HOLDDONE_SHOW);
break;
case 4:
emit holdStop();
emit showGesture(HOLDSTOP_SHOW);
break;
case 0:
break;
default:
break;
}
if(delay%10 == 0){
//std::cout<<GR.gesHandDirection()<<std::endl;
switch(GR.gesHandDirection()){
case 1:
emit handLeft();
std::cout<<"LEFT"<<std::endl;
break;
case 2:
emit handRight();
std::cout<<"RIGHT"<<std::endl;
break;
case 3:
emit handUp();
std::cout<<"UP"<<std::endl;
break;
case 4:
emit handDown();
std::cout<<"DOWN"<<std::endl;
break;
case 5:
emit handForward();
std::cout<<"FWARD"<<std::endl;
break;
case 6:
emit handBackward();
std::cout<<"BWARD"<<std::endl;
break;
default:
break;
}
}
delay++;
}
void EventControl::desktop(){
emit disconnectAllS();
connect(this,SIGNAL(grabStart()),OP,SLOT(swipeWindow()));
connect(this,SIGNAL(pinchStart()),this,SLOT(showDT()));
connect(this,SIGNAL(pinchStart()),this,SLOT(MouseLeftClick()));
connect(this,SIGNAL(pinchStop()),this,SLOT(hideDT()));
connect(this,SIGNAL(turntableUp()),this,SIGNAL(showRoadMapS()));
connect(this,SIGNAL(turntableDown()),SP,SLOT(show()));
connect(this,SIGNAL(turntableLeft()),OP,SLOT(openBrowser()));
connect(this,SIGNAL(turntableRight()),OP,SLOT(openFileManager()));
connect(this,SIGNAL(RoadMapS(int,int,int,int)),this,SLOT(RoadMap(int,int,int,int)));
}
void EventControl::browser(){
emit disconnectAllS();
connect(this,SIGNAL(circleStart()),OP,SLOT(MouseWheel()));
connect(this,SIGNAL(circleKeep()),OP,SLOT(MouseWheel()));
connect(this,SIGNAL(circleStop()),OP,SLOT(MouseWheelStop()));
connect(this,SIGNAL(circleAntiStart()),OP,SLOT(MouseWheelN()));
connect(this,SIGNAL(circleAntiKeep()),OP,SLOT(MouseWheelN()));
connect(this,SIGNAL(circleAntiStop()),OP,SLOT(MouseWheelStop()));
connect(this,SIGNAL(pinchStart()),OP,SLOT(swipeBrowserTab()));
connect(this,SIGNAL(holdDone()),this,SLOT(MouseLeftClick()));
connect(this,SIGNAL(grabStart()),OP,SLOT(goBack()));
}
void EventControl::pc(){
emit disconnectAllS();
connect(this,SIGNAL(circleStart()),OP,SLOT(MouseWheel()));
connect(this,SIGNAL(circleKeep()),OP,SLOT(MouseWheel()));
connect(this,SIGNAL(circleStop()),OP,SLOT(MouseWheelStop()));
connect(this,SIGNAL(circleAntiStart()),OP,SLOT(MouseWheelN()));
connect(this,SIGNAL(circleAntiKeep()),OP,SLOT(MouseWheelN()));
connect(this,SIGNAL(circleAntiStop()),OP,SLOT(MouseWheelStop()));
connect(this,SIGNAL(pinchStart()),this,SLOT(showDT()));
connect(this,SIGNAL(pinchStart()),this,SLOT(MouseLeftClick()));
connect(this,SIGNAL(pinchStop()),this,SLOT(hideDT()));
connect(this,SIGNAL(turntableUp()),OP,SLOT(goEnter()));
connect(this,SIGNAL(turntableDown()),OP,SLOT(goBack()));
connect(this,SIGNAL(turntableLeft()),OP,SLOT(goRefresh()));
connect(this,SIGNAL(turntableRight()),OP,SLOT(showDesktop()));
}
void EventControl::other(){
emit disconnectAllS();
}
void EventControl::disconnectAll(){
disconnect(this,SIGNAL(circleStart()),0,0);
disconnect(this,SIGNAL(circleKeep()),0,0);
disconnect(this,SIGNAL(circleStop()),0,0);
disconnect(this,SIGNAL(circleAntiStart()),0,0);
disconnect(this,SIGNAL(circleAntiKeep()),0,0);
disconnect(this,SIGNAL(circleAntiStop()),0,0);
disconnect(this,SIGNAL(pinchStart()),0,0);
disconnect(this,SIGNAL(pinchStop()),0,0);
disconnect(this,SIGNAL(grabStart()),0,0);
disconnect(this,SIGNAL(grabStop()),0,0);
disconnect(this,SIGNAL(holdDone()),0,0);
disconnect(this,SIGNAL(turntableUp()),0,0);
disconnect(this,SIGNAL(turntableDown()),0,0);
disconnect(this,SIGNAL(turntableLeft()),0,0);
disconnect(this,SIGNAL(turntableRight()),0,0);
disconnect(this,SIGNAL(RoadMapS(int,int,int,int)),0,0);
}
void EventControl::MouseLeftClick(){
Leap::InteractionBox iBox = controller.frame().interactionBox();
int mouse_x = iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).x * 65535;
int mouse_y = (1-iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).y) * 65535;
OP->MouseLeftClick(mouse_x,mouse_y);
}
void EventControl::MouseLeftDClick(){
Leap::InteractionBox iBox = controller.frame().interactionBox();
int mouse_x = iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).x * 65535;
int mouse_y = (1-iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).y) * 65535;
OP->MouseLeftDClick(mouse_x,mouse_y);
}
void EventControl::showDT(){
Leap::InteractionBox iBox = controller.frame().interactionBox();
int DT_x = iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).x * QApplication::desktop()->width() -160;
int DT_y = (1-iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).y) * QApplication::desktop()->height() -160;
Turntable[0] = DT_x;
Turntable[1] = DT_y;
switch (FGW.getFGWinName()) {
case 1:
DT.setFGWin(1);
DT.showDisplayTurntable(DT_x,DT_y);
break;
case 2:
//DT.showDisplayTurntable(DT_x,DT_y,2);
break;
case 3:
DT.setFGWin(3);
DT.showDisplayTurntable(DT_x,DT_y);
break;
default:
break;
}
}
void EventControl::hideDT(){
Leap::InteractionBox iBox = controller.frame().interactionBox();
int DT_x = iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).x * QApplication::desktop()->width() -160;
int DT_y = (1-iBox.normalizePoint(controller.frame().hands()[0].stabilizedPalmPosition()).y) * QApplication::desktop()->height() -160;
if(Turntable[0] != 0 && DT_x != Turntable[0]){
float slope = (DT_y - Turntable[1])/(DT_x - Turntable[0]);
int Horizontal,Vertical=0;
if(DT_x - Turntable[0] >= 0){
Horizontal = 1;
}else{
Horizontal = -1;
}
if(DT_y - Turntable[1] >= 0){
Vertical = -1;
}else{
Vertical = 1;
}
Turntable[0] = 0;
Turntable[1] = 0;
if(slope >= 1 || slope <= -1){
if(Vertical == 1){
emit turntableUp();
}else if(Vertical == -1){
emit turntableDown();
}
}else{
if(Horizontal == 1){
emit turntableRight();
}else if(Horizontal == -1){
emit turntableLeft();
}
}
}
DT.hide();
}
void EventControl::showRoadMap(){
RMG = new RoadMapGesture();
RMG->show();
connect(RMG,SIGNAL(Done(int*)),this,SLOT(outRoadMap(int*)));
}
void EventControl::outRoadMap(int *RoadMap)
{
// std::cout<<"~~~~~~~~~"<<std::endl;
// for(int i=0;i<17;i++){
// std::cout<<RoadMap[i];
// }
// std::cout<<std::endl;
int RoadMap1 = RoadMap[1]*1000 + RoadMap[2]*100 + RoadMap[3]*10 + RoadMap[4];
int RoadMap2 = RoadMap[5]*1000 + RoadMap[6]*100 + RoadMap[7]*10 + RoadMap[8];
int RoadMap3 = RoadMap[9]*1000 + RoadMap[10]*100 + RoadMap[11]*10 + RoadMap[12];
int RoadMap4 = RoadMap[13]*1000 + RoadMap[14]*100 + RoadMap[15]*10 + RoadMap[16];
emit RoadMapS(RoadMap1,RoadMap2,RoadMap3,RoadMap4);
}
void EventControl::RoadMap(int RoadMap1, int RoadMap2, int RoadMap3, int RoadMap4)
{
if(RoadMap1 == 0 && RoadMap2 == 1111 && RoadMap3 == 0 && RoadMap4 == 0){
OP->lockscreen();
}else if(RoadMap1 == 0 && RoadMap2 == 0 && RoadMap3 == 1111 && RoadMap4 == 0){
OP->logout();
}
}
| [
"peitaosu@163.com"
] | peitaosu@163.com |
78e09ea65b03d46af26f949ff14adc58bb54d743 | 055948e30ca33e4eacbd345e20cb885f6c9779d5 | /Challenges/Challenges/BasicChallenges.cpp | 2f4bf6e4bc3cbd3821ad40f87b7f4e95016af839 | [] | no_license | mshigezumi/The-Tech-Academy-C-Plus-Plus-and-Unreal-Engine-Projects | 6d976730f309f3767b300f7d8b0c6c3fd3cb4927 | 53366f8c45231e81b1ce42c40c3a30350e9e2638 | refs/heads/main | 2023-04-30T12:38:00.359071 | 2021-05-24T19:05:08 | 2021-05-24T19:05:08 | 363,712,878 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,328 | cpp | // Challenge1.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
int main()
{
cout << "Hello World!\n";
const char c = 'a';
int i = 1;
float f = 1.1;
double d = 1.2;
bool b = false;
string s = "test";
cout << c;
cout << "\n";
cout << i;
cout << "\n";
cout << f;
cout << "\n";
cout << d;
cout << "\n";
cout << b;
cout << "\n";
cout << s;
cout << "\n";
cout << s.length();
cout << "\n";
s[0] = 'b';
cout << s[0];
cout << "\n";
string text = "";
cin >> text;
cout << text + "\n";
return 0;
}
// Run program: Ctrl + F5 or Debug > Start Without Debugging menu
// Debug program: F5 or Debug > Start Debugging menu
// Tips for Getting Started:
// 1. Use the Solution Explorer window to add/manage files
// 2. Use the Team Explorer window to connect to source control
// 3. Use the Output window to see build output and other messages
// 4. Use the Error List window to view errors
// 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project
// 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
| [
"71560004+mshigezumi@users.noreply.github.com"
] | 71560004+mshigezumi@users.noreply.github.com |
33881e64f2d61d357f2077332416b51c13a16393 | 86787b68ba8039ecaad17d61a11c8d39b2ddb968 | /2009-11675/lab4/build/bdir/mkCop.h | e4032f4a3d0136bc3aa652438299056ba87abf1b | [] | no_license | yujunkim/early2015_computer_architecture_class | 61f456f8f35008e2c7ea0547ca204101aa1d9181 | 25d4bdd019592aacda61321ae848bd70ce46e626 | refs/heads/master | 2021-01-19T05:05:54.302842 | 2016-06-09T08:17:27 | 2016-06-09T08:17:27 | 60,759,499 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,037 | h | /*
* Generated by Bluespec Compiler, version 2012.01.A (build 26572, 2012-01-17)
*
* On Thu Apr 23 21:38:41 KST 2015
*
*/
/* Generation options: */
#ifndef __mkCop_h__
#define __mkCop_h__
#include "bluesim_types.h"
#include "bs_module.h"
#include "bluesim_primitives.h"
#include "bs_vcd.h"
namespace bluesim
{
/* Class declaration for the mkCop module */
class MOD_mkCop : public Module {
/* Clock handles */
private:
tClock __clk_handle_0;
/* Clock gate handles */
public:
tUInt8 *clk_gate[0];
/* Instantiation parameters */
public:
/* Module state */
public:
MOD_Reg<tUWide> INST_copFifo_data;
MOD_Reg<tUWide> INST_copFifo_data_1;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy;
MOD_Reg<tUInt8> INST_copFifo_deqEn_dummy2;
MOD_Reg<tUInt8> INST_copFifo_deqEn_dummy2_1;
MOD_Reg<tUInt8> INST_copFifo_deqEn_dummy2_2;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_1;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_2;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_3;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_4;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_5;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_6;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_7;
MOD_Wire<tUInt8> INST_copFifo_deqEn_dummy_8;
MOD_Wire<tUInt8> INST_copFifo_deqEn_lat;
MOD_Wire<tUInt8> INST_copFifo_deqEn_lat_1;
MOD_Wire<tUInt8> INST_copFifo_deqEn_lat_2;
MOD_Reg<tUInt8> INST_copFifo_deqEn_rl;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy;
MOD_Reg<tUInt8> INST_copFifo_deqP_dummy2;
MOD_Reg<tUInt8> INST_copFifo_deqP_dummy2_1;
MOD_Reg<tUInt8> INST_copFifo_deqP_dummy2_2;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_1;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_2;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_3;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_4;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_5;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_6;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_7;
MOD_Wire<tUInt8> INST_copFifo_deqP_dummy_8;
MOD_Wire<tUInt8> INST_copFifo_deqP_lat;
MOD_Wire<tUInt8> INST_copFifo_deqP_lat_1;
MOD_Wire<tUInt8> INST_copFifo_deqP_lat_2;
MOD_Reg<tUInt8> INST_copFifo_deqP_rl;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy;
MOD_Reg<tUInt8> INST_copFifo_enqEn_dummy2;
MOD_Reg<tUInt8> INST_copFifo_enqEn_dummy2_1;
MOD_Reg<tUInt8> INST_copFifo_enqEn_dummy2_2;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_1;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_2;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_3;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_4;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_5;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_6;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_7;
MOD_Wire<tUInt8> INST_copFifo_enqEn_dummy_8;
MOD_Wire<tUInt8> INST_copFifo_enqEn_lat;
MOD_Wire<tUInt8> INST_copFifo_enqEn_lat_1;
MOD_Wire<tUInt8> INST_copFifo_enqEn_lat_2;
MOD_Reg<tUInt8> INST_copFifo_enqEn_rl;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy;
MOD_Reg<tUInt8> INST_copFifo_enqP_dummy2;
MOD_Reg<tUInt8> INST_copFifo_enqP_dummy2_1;
MOD_Reg<tUInt8> INST_copFifo_enqP_dummy2_2;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_1;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_2;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_3;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_4;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_5;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_6;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_7;
MOD_Wire<tUInt8> INST_copFifo_enqP_dummy_8;
MOD_Wire<tUInt8> INST_copFifo_enqP_lat;
MOD_Wire<tUInt8> INST_copFifo_enqP_lat_1;
MOD_Wire<tUInt8> INST_copFifo_enqP_lat_2;
MOD_Reg<tUInt8> INST_copFifo_enqP_rl;
MOD_Wire<tUWide> INST_copFifo_tempData_dummy;
MOD_Reg<tUInt8> INST_copFifo_tempData_dummy2;
MOD_Reg<tUInt8> INST_copFifo_tempData_dummy2_1;
MOD_Wire<tUWide> INST_copFifo_tempData_dummy_1;
MOD_Wire<tUWide> INST_copFifo_tempData_dummy_2;
MOD_Wire<tUWide> INST_copFifo_tempData_dummy_3;
MOD_Wire<tUWide> INST_copFifo_tempData_lat;
MOD_Wire<tUWide> INST_copFifo_tempData_lat_1;
MOD_Reg<tUWide> INST_copFifo_tempData_rl;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_dummy;
MOD_Reg<tUInt8> INST_copFifo_tempEnqP_dummy2;
MOD_Reg<tUInt8> INST_copFifo_tempEnqP_dummy2_1;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_dummy_1;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_dummy_2;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_dummy_3;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_lat;
MOD_Wire<tUInt8> INST_copFifo_tempEnqP_lat_1;
MOD_Reg<tUInt8> INST_copFifo_tempEnqP_rl;
MOD_Reg<tUInt32> INST_cycles;
MOD_ConfigReg<tUInt32> INST_finishCode;
MOD_ConfigReg<tUInt8> INST_finishReg;
MOD_ConfigReg<tUInt32> INST_numBPMiss;
MOD_ConfigReg<tUInt32> INST_numCtr;
MOD_ConfigReg<tUInt32> INST_numInsts;
MOD_ConfigReg<tUInt32> INST_numMem;
MOD_ConfigReg<tUInt8> INST_startReg;
MOD_ConfigReg<tUInt32> INST_timeReg;
/* Constructor */
public:
MOD_mkCop(char const *name, Module *parent);
/* Symbol init methods */
private:
void init_symbols_0();
/* Reset signal definitions */
private:
tUInt8 PORT_RST_N;
/* Port definitions */
public:
tUWide PORT_cpuToHost;
/* Publicly accessible definitions */
public:
tUInt8 DEF_copFifo_deqEn_rl__h6934;
tUInt8 DEF_copFifo_enqEn_rl__h5333;
tUInt8 DEF_copFifo_deqEn_dummy2_2__h11048;
tUInt8 DEF_copFifo_enqEn_dummy2_2__h9545;
/* Local definitions */
private:
tUInt8 DEF_IF_copFifo_tempEnqP_lat_whas__1_THEN_copFifo_t_ETC___d190;
tUInt8 DEF_IF_copFifo_tempEnqP_lat_whas__1_THEN_NOT_copFi_ETC___d192;
tUInt8 DEF_copFifo_deqEn_lat_1_whas____d213;
tUInt8 DEF_copFifo_enqEn_lat_1_whas____d211;
tUWide DEF_ab__h8052;
tUWide DEF_ab__h8006;
tUWide DEF_ab__h8048;
tUWide DEF_ab__h15888;
tUWide DEF_ab__h15884;
tUInt32 DEF__read__h12828;
tUInt32 DEF_x__h15230;
tUInt8 DEF_copFifo_tempEnqP_rl___d208;
tUInt8 DEF_copFifo_tempEnqP_lat_wget____d209;
tUInt8 DEF_upd__h15542;
tUInt8 DEF_upd__h10168;
tUInt8 DEF_upd__h10201;
tUInt8 DEF_upd__h13602;
tUInt8 DEF_upd__h9888;
tUInt8 DEF_upd__h9921;
tUInt8 DEF_copFifo_tempEnqP_lat_whas____d216;
tUInt8 DEF_copFifo_deqEn_lat_1_wget____d206;
tUInt8 DEF_copFifo_deqEn_lat_whas____d214;
tUInt8 DEF_copFifo_deqEn_lat_wget____d205;
tUInt8 DEF_copFifo_enqEn_lat_1_wget____d204;
tUInt8 DEF_copFifo_enqEn_lat_whas____d212;
tUInt8 DEF_copFifo_enqEn_lat_wget____d203;
tUInt8 DEF_copFifo_deqP_dummy2_2__h10129;
tUInt8 DEF_copFifo_enqP_dummy2_2__h9849;
tUInt8 DEF_copFifo_tempEnqP_lat_wget__2_BITS_2_TO_0___d202;
tUInt8 DEF_copFifo_tempEnqP_rl_4_BIT_3___d218;
tUInt8 DEF_copFifo_tempEnqP_lat_wget__2_BIT_3___d217;
tUWide DEF_IF_copFifo_tempData_dummy2_1_19_THEN_IF_copFif_ETC___d223;
tUWide DEF_IF_copFifo_tempData_lat_whas__3_THEN_copFifo_t_ETC___d189;
tUWide DEF_IF_copFifo_tempData_lat_1_whas__1_THEN_copFifo_ETC___d47;
tUInt8 DEF_IF_copFifo_tempEnqP_lat_whas__1_THEN_copFifo_t_ETC___d201;
tUInt8 DEF_IF_copFifo_deqP_lat_1_whas__3_THEN_copFifo_deq_ETC___d199;
tUInt8 DEF_IF_copFifo_enqP_lat_1_whas_THEN_copFifo_enqP_l_ETC___d197;
tUWide DEF_IF_IF_wr_idx_BIT_5_36_THEN_wr_idx_BITS_3_TO_0__ETC___d150;
/* Rules */
public:
void RL_copFifo_enqP_canon();
void RL_copFifo_deqP_canon();
void RL_copFifo_enqEn_canon();
void RL_copFifo_deqEn_canon();
void RL_copFifo_tempData_canon();
void RL_copFifo_tempEnqP_canon();
void RL_copFifo_canonicalize();
void RL_count();
/* Methods */
public:
void METH_start();
tUInt8 METH_RDY_start();
tUInt8 METH_started();
tUInt8 METH_RDY_started();
tUInt32 METH_rd(tUInt8 ARG_rd_idx);
tUInt8 METH_RDY_rd();
void METH_wr(tUInt8 ARG_wr_idx, tUInt32 ARG_wr_val);
tUInt8 METH_RDY_wr();
void METH_incInstTypeCnt(tUInt8 ARG_incInstTypeCnt_idx);
tUInt8 METH_RDY_incInstTypeCnt();
void METH_incBPMissCnt();
tUInt8 METH_RDY_incBPMissCnt();
tUWide METH_cpuToHost();
tUInt8 METH_RDY_cpuToHost();
/* Reset routines */
public:
void reset_RST_N(tUInt8 ARG_rst_in);
/* Static handles to reset routines */
public:
/* Pointers to reset fns in parent module for asserting output resets */
private:
/* Functions for the parent module to register its reset fns */
public:
/* Functions to set the elaborated clock id */
public:
void set_clk_0(char const *s);
/* State dumping routine */
public:
void dump_state(unsigned int indent);
/* VCD dumping routines */
public:
unsigned int dump_VCD_defs(unsigned int levels);
void dump_VCD(tVCDDumpType dt, unsigned int levels, MOD_mkCop &backing);
void vcd_defs(tVCDDumpType dt, MOD_mkCop &backing);
void vcd_prims(tVCDDumpType dt, MOD_mkCop &backing);
};
}
#endif /* ifndef __mkCop_h__ */
| [
"plmmoknn@newmartini"
] | plmmoknn@newmartini |
ddd707a4f5c75b5c45e71a002511d0c15c9713c1 | cefd6c17774b5c94240d57adccef57d9bba4a2e9 | /WebKit/Source/ThirdParty/ANGLE/src/libGLESv2/renderer/d3d11/Renderer11.cpp | 722f0c5a4553d80530ad7ed9b8b5745855e5e200 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSL-1.0"
] | permissive | adzhou/oragle | 9c054c25b24ff0a65cb9639bafd02aac2bcdce8b | 5442d418b87d0da161429ffa5cb83777e9b38e4d | refs/heads/master | 2022-11-01T05:04:59.368831 | 2014-03-12T15:50:08 | 2014-03-12T15:50:08 | 17,238,063 | 0 | 1 | BSL-1.0 | 2022-10-18T04:23:53 | 2014-02-27T05:39:44 | C++ | UTF-8 | C++ | false | false | 128,017 | cpp | #include "precompiled.h"
//
// Copyright (c) 2012-2013 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// Renderer11.cpp: Implements a back-end specific class for the D3D11 renderer.
#include "libGLESv2/main.h"
#include "libGLESv2/utilities.h"
#include "libGLESv2/Buffer.h"
#include "libGLESv2/ProgramBinary.h"
#include "libGLESv2/Framebuffer.h"
#include "libGLESv2/Renderbuffer.h"
#include "libGLESv2/renderer/d3d11/Renderer11.h"
#include "libGLESv2/renderer/d3d11/RenderTarget11.h"
#include "libGLESv2/renderer/d3d11/renderer11_utils.h"
#include "libGLESv2/renderer/d3d11/ShaderExecutable11.h"
#include "libGLESv2/renderer/d3d11/SwapChain11.h"
#include "libGLESv2/renderer/d3d11/Image11.h"
#include "libGLESv2/renderer/d3d11/VertexBuffer11.h"
#include "libGLESv2/renderer/d3d11/IndexBuffer11.h"
#include "libGLESv2/renderer/d3d11/BufferStorage11.h"
#include "libGLESv2/renderer/VertexDataManager.h"
#include "libGLESv2/renderer/IndexDataManager.h"
#include "libGLESv2/renderer/d3d11/TextureStorage11.h"
#include "libGLESv2/renderer/d3d11/Query11.h"
#include "libGLESv2/renderer/d3d11/Fence11.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/passthrough11vs.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/passthroughrgba11ps.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/passthroughrgb11ps.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/passthroughlum11ps.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/passthroughlumalpha11ps.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/clear11vs.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/clearsingle11ps.h"
#include "libGLESv2/renderer/d3d11/shaders/compiled/clearmultiple11ps.h"
#include "libEGL/Display.h"
// Enable ANGLE_SKIP_DXGI_1_2_CHECK if there is not a possibility of using cross-process
// HWNDs or the Windows 7 Platform Update (KB2670838) is expected to be installed.
#ifndef ANGLE_SKIP_DXGI_1_2_CHECK
#define ANGLE_SKIP_DXGI_1_2_CHECK 0
#endif
#ifdef _DEBUG
// this flag enables suppressing some spurious warnings that pop up in certain WebGL samples
// and conformance tests. to enable all warnings, remove this define.
#define ANGLE_SUPPRESS_D3D11_HAZARD_WARNINGS 1
#endif
namespace rx
{
static const DXGI_FORMAT RenderTargetFormats[] =
{
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM
};
static const DXGI_FORMAT DepthStencilFormats[] =
{
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_D24_UNORM_S8_UINT,
DXGI_FORMAT_D16_UNORM
};
enum
{
MAX_TEXTURE_IMAGE_UNITS_VTF_SM4 = 16
};
Renderer11::Renderer11(egl::Display *display, HDC hDc) : Renderer(display), mDc(hDc)
{
mVertexDataManager = NULL;
mIndexDataManager = NULL;
mLineLoopIB = NULL;
mTriangleFanIB = NULL;
mCopyResourcesInitialized = false;
mCopyVB = NULL;
mCopySampler = NULL;
mCopyIL = NULL;
mCopyVS = NULL;
mCopyRGBAPS = NULL;
mCopyRGBPS = NULL;
mCopyLumPS = NULL;
mCopyLumAlphaPS = NULL;
mClearResourcesInitialized = false;
mClearVB = NULL;
mClearIL = NULL;
mClearVS = NULL;
mClearSinglePS = NULL;
mClearMultiplePS = NULL;
mClearScissorRS = NULL;
mClearNoScissorRS = NULL;
mSyncQuery = NULL;
mD3d11Module = NULL;
mDxgiModule = NULL;
mDeviceLost = false;
mMaxSupportedSamples = 0;
mDevice = NULL;
mDeviceContext = NULL;
mDxgiAdapter = NULL;
mDxgiFactory = NULL;
mDriverConstantBufferVS = NULL;
mDriverConstantBufferPS = NULL;
mBGRATextureSupport = false;
mIsGeometryShaderActive = false;
}
Renderer11::~Renderer11()
{
release();
}
Renderer11 *Renderer11::makeRenderer11(Renderer *renderer)
{
ASSERT(HAS_DYNAMIC_TYPE(rx::Renderer11*, renderer));
return static_cast<rx::Renderer11*>(renderer);
}
#ifndef __d3d11_1_h__
#define D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET ((D3D11_MESSAGE_ID)3146081)
#endif
EGLint Renderer11::initialize()
{
if (!initializeCompiler())
{
return EGL_NOT_INITIALIZED;
}
mDxgiModule = LoadLibrary(TEXT("dxgi.dll"));
mD3d11Module = LoadLibrary(TEXT("d3d11.dll"));
if (mD3d11Module == NULL || mDxgiModule == NULL)
{
ERR("Could not load D3D11 or DXGI library - aborting!\n");
return EGL_NOT_INITIALIZED;
}
// create the D3D11 device
ASSERT(mDevice == NULL);
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
if (D3D11CreateDevice == NULL)
{
ERR("Could not retrieve D3D11CreateDevice address - aborting!\n");
return EGL_NOT_INITIALIZED;
}
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
HRESULT result = S_OK;
#ifdef _DEBUG
result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
D3D11_CREATE_DEVICE_DEBUG,
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&mDevice,
&mFeatureLevel,
&mDeviceContext);
if (!mDevice || FAILED(result))
{
ERR("Failed creating Debug D3D11 device - falling back to release runtime.\n");
}
if (!mDevice || FAILED(result))
#endif
{
result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
0,
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&mDevice,
&mFeatureLevel,
&mDeviceContext);
if (!mDevice || FAILED(result))
{
ERR("Could not create D3D11 device - aborting!\n");
return EGL_NOT_INITIALIZED; // Cleanup done by destructor through glDestroyRenderer
}
}
#if !ANGLE_SKIP_DXGI_1_2_CHECK
// In order to create a swap chain for an HWND owned by another process, DXGI 1.2 is required.
// The easiest way to check is to query for a IDXGIDevice2.
bool requireDXGI1_2 = false;
HWND hwnd = WindowFromDC(mDc);
if (hwnd)
{
DWORD currentProcessId = GetCurrentProcessId();
DWORD wndProcessId;
GetWindowThreadProcessId(hwnd, &wndProcessId);
requireDXGI1_2 = (currentProcessId != wndProcessId);
}
else
{
requireDXGI1_2 = true;
}
if (requireDXGI1_2)
{
IDXGIDevice2 *dxgiDevice2 = NULL;
result = mDevice->QueryInterface(__uuidof(IDXGIDevice2), (void**)&dxgiDevice2);
if (FAILED(result))
{
ERR("DXGI 1.2 required to present to HWNDs owned by another process.\n");
return EGL_NOT_INITIALIZED;
}
SafeRelease(dxgiDevice2);
}
#endif
IDXGIDevice *dxgiDevice = NULL;
result = mDevice->QueryInterface(__uuidof(IDXGIDevice), (void**)&dxgiDevice);
if (FAILED(result))
{
ERR("Could not query DXGI device - aborting!\n");
return EGL_NOT_INITIALIZED;
}
result = dxgiDevice->GetParent(__uuidof(IDXGIAdapter), (void**)&mDxgiAdapter);
if (FAILED(result))
{
ERR("Could not retrieve DXGI adapter - aborting!\n");
return EGL_NOT_INITIALIZED;
}
dxgiDevice->Release();
mDxgiAdapter->GetDesc(&mAdapterDescription);
memset(mDescription, 0, sizeof(mDescription));
wcstombs(mDescription, mAdapterDescription.Description, sizeof(mDescription) - 1);
result = mDxgiAdapter->GetParent(__uuidof(IDXGIFactory), (void**)&mDxgiFactory);
if (!mDxgiFactory || FAILED(result))
{
ERR("Could not create DXGI factory - aborting!\n");
return EGL_NOT_INITIALIZED;
}
// Disable some spurious D3D11 debug warnings to prevent them from flooding the output log
#if defined(ANGLE_SUPPRESS_D3D11_HAZARD_WARNINGS) && defined(_DEBUG)
ID3D11InfoQueue *infoQueue;
result = mDevice->QueryInterface(__uuidof(ID3D11InfoQueue), (void **)&infoQueue);
if (SUCCEEDED(result))
{
D3D11_MESSAGE_ID hideMessages[] =
{
D3D11_MESSAGE_ID_DEVICE_DRAW_RENDERTARGETVIEW_NOT_SET
};
D3D11_INFO_QUEUE_FILTER filter = {0};
filter.DenyList.NumIDs = ArraySize(hideMessages);
filter.DenyList.pIDList = hideMessages;
infoQueue->AddStorageFilterEntries(&filter);
infoQueue->Release();
}
#endif
unsigned int maxSupportedSamples = 0;
unsigned int rtFormatCount = ArraySize(RenderTargetFormats);
unsigned int dsFormatCount = ArraySize(DepthStencilFormats);
for (unsigned int i = 0; i < rtFormatCount + dsFormatCount; ++i)
{
DXGI_FORMAT format = (i < rtFormatCount) ? RenderTargetFormats[i] : DepthStencilFormats[i - rtFormatCount];
if (format != DXGI_FORMAT_UNKNOWN)
{
UINT formatSupport;
result = mDevice->CheckFormatSupport(format, &formatSupport);
if (SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_MULTISAMPLE_RENDERTARGET))
{
MultisampleSupportInfo supportInfo;
for (unsigned int j = 1; j <= D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; j++)
{
result = mDevice->CheckMultisampleQualityLevels(format, j, &supportInfo.qualityLevels[j - 1]);
if (SUCCEEDED(result) && supportInfo.qualityLevels[j - 1] > 0)
{
maxSupportedSamples = std::max(j, maxSupportedSamples);
}
else
{
supportInfo.qualityLevels[j - 1] = 0;
}
}
mMultisampleSupportMap.insert(std::make_pair(format, supportInfo));
}
}
}
mMaxSupportedSamples = maxSupportedSamples;
initializeDevice();
// BGRA texture support is optional in feature levels 10 and 10_1
UINT formatSupport;
result = mDevice->CheckFormatSupport(DXGI_FORMAT_B8G8R8A8_UNORM, &formatSupport);
if (FAILED(result))
{
ERR("Error checking BGRA format support: 0x%08X", result);
}
else
{
const int flags = (D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET);
mBGRATextureSupport = (formatSupport & flags) == flags;
}
// Check floating point texture support
static const unsigned int requiredTextureFlags = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_TEXTURECUBE;
static const unsigned int requiredRenderableFlags = D3D11_FORMAT_SUPPORT_RENDER_TARGET;
static const unsigned int requiredFilterFlags = D3D11_FORMAT_SUPPORT_SHADER_SAMPLE;
DXGI_FORMAT float16Formats[] =
{
DXGI_FORMAT_R16_FLOAT,
DXGI_FORMAT_R16G16_FLOAT,
DXGI_FORMAT_R16G16B16A16_FLOAT,
};
DXGI_FORMAT float32Formats[] =
{
DXGI_FORMAT_R32_FLOAT,
DXGI_FORMAT_R32G32_FLOAT,
DXGI_FORMAT_R32G32B32A32_FLOAT,
};
mFloat16TextureSupport = true;
mFloat16FilterSupport = true;
mFloat16RenderSupport = true;
for (unsigned int i = 0; i < ArraySize(float16Formats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(float16Formats[i], &formatSupport)))
{
mFloat16TextureSupport = mFloat16TextureSupport && (formatSupport & requiredTextureFlags) == requiredTextureFlags;
mFloat16FilterSupport = mFloat16FilterSupport && (formatSupport & requiredFilterFlags) == requiredFilterFlags;
mFloat16RenderSupport = mFloat16RenderSupport && (formatSupport & requiredRenderableFlags) == requiredRenderableFlags;
}
else
{
mFloat16TextureSupport = false;
mFloat16RenderSupport = false;
mFloat16FilterSupport = false;
}
}
mFloat32TextureSupport = true;
mFloat32FilterSupport = true;
mFloat32RenderSupport = true;
for (unsigned int i = 0; i < ArraySize(float32Formats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(float32Formats[i], &formatSupport)))
{
mFloat32TextureSupport = mFloat32TextureSupport && (formatSupport & requiredTextureFlags) == requiredTextureFlags;
mFloat32FilterSupport = mFloat32FilterSupport && (formatSupport & requiredFilterFlags) == requiredFilterFlags;
mFloat32RenderSupport = mFloat32RenderSupport && (formatSupport & requiredRenderableFlags) == requiredRenderableFlags;
}
else
{
mFloat32TextureSupport = false;
mFloat32FilterSupport = false;
mFloat32RenderSupport = false;
}
}
// Check compressed texture support
const unsigned int requiredCompressedTextureFlags = D3D11_FORMAT_SUPPORT_TEXTURE2D;
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC1_UNORM, &formatSupport)))
{
mDXT1TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT1TextureSupport = false;
}
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC3_UNORM, &formatSupport)))
{
mDXT3TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT3TextureSupport = false;
}
if (SUCCEEDED(mDevice->CheckFormatSupport(DXGI_FORMAT_BC5_UNORM, &formatSupport)))
{
mDXT5TextureSupport = (formatSupport & requiredCompressedTextureFlags) == requiredCompressedTextureFlags;
}
else
{
mDXT5TextureSupport = false;
}
// Check depth texture support
DXGI_FORMAT depthTextureFormats[] =
{
DXGI_FORMAT_D16_UNORM,
DXGI_FORMAT_D24_UNORM_S8_UINT,
};
static const unsigned int requiredDepthTextureFlags = D3D11_FORMAT_SUPPORT_DEPTH_STENCIL |
D3D11_FORMAT_SUPPORT_TEXTURE2D;
mDepthTextureSupport = true;
for (unsigned int i = 0; i < ArraySize(depthTextureFormats); i++)
{
if (SUCCEEDED(mDevice->CheckFormatSupport(depthTextureFormats[i], &formatSupport)))
{
mDepthTextureSupport = mDepthTextureSupport && ((formatSupport & requiredDepthTextureFlags) == requiredDepthTextureFlags);
}
else
{
mDepthTextureSupport = false;
}
}
return EGL_SUCCESS;
}
// do any one-time device initialization
// NOTE: this is also needed after a device lost/reset
// to reset the scene status and ensure the default states are reset.
void Renderer11::initializeDevice()
{
mStateCache.initialize(mDevice);
mInputLayoutCache.initialize(mDevice, mDeviceContext);
ASSERT(!mVertexDataManager && !mIndexDataManager);
mVertexDataManager = new VertexDataManager(this);
mIndexDataManager = new IndexDataManager(this);
markAllStateDirty();
}
int Renderer11::generateConfigs(ConfigDesc **configDescList)
{
unsigned int numRenderFormats = ArraySize(RenderTargetFormats);
unsigned int numDepthFormats = ArraySize(DepthStencilFormats);
(*configDescList) = new ConfigDesc[numRenderFormats * numDepthFormats];
int numConfigs = 0;
for (unsigned int formatIndex = 0; formatIndex < numRenderFormats; formatIndex++)
{
for (unsigned int depthStencilIndex = 0; depthStencilIndex < numDepthFormats; depthStencilIndex++)
{
DXGI_FORMAT renderTargetFormat = RenderTargetFormats[formatIndex];
UINT formatSupport = 0;
HRESULT result = mDevice->CheckFormatSupport(renderTargetFormat, &formatSupport);
if (SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_RENDER_TARGET))
{
DXGI_FORMAT depthStencilFormat = DepthStencilFormats[depthStencilIndex];
bool depthStencilFormatOK = true;
if (depthStencilFormat != DXGI_FORMAT_UNKNOWN)
{
UINT formatSupport = 0;
result = mDevice->CheckFormatSupport(depthStencilFormat, &formatSupport);
depthStencilFormatOK = SUCCEEDED(result) && (formatSupport & D3D11_FORMAT_SUPPORT_DEPTH_STENCIL);
}
if (depthStencilFormatOK)
{
ConfigDesc newConfig;
newConfig.renderTargetFormat = d3d11_gl::ConvertBackBufferFormat(renderTargetFormat);
newConfig.depthStencilFormat = d3d11_gl::ConvertDepthStencilFormat(depthStencilFormat);
newConfig.multiSample = 0; // FIXME: enumerate multi-sampling
newConfig.fastConfig = true; // Assume all DX11 format conversions to be fast
(*configDescList)[numConfigs++] = newConfig;
}
}
}
}
return numConfigs;
}
void Renderer11::deleteConfigs(ConfigDesc *configDescList)
{
delete [] (configDescList);
}
void Renderer11::sync(bool block)
{
if (block)
{
HRESULT result;
if (!mSyncQuery)
{
D3D11_QUERY_DESC queryDesc;
queryDesc.Query = D3D11_QUERY_EVENT;
queryDesc.MiscFlags = 0;
result = mDevice->CreateQuery(&queryDesc, &mSyncQuery);
ASSERT(SUCCEEDED(result));
}
mDeviceContext->End(mSyncQuery);
mDeviceContext->Flush();
do
{
result = mDeviceContext->GetData(mSyncQuery, NULL, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH);
// Keep polling, but allow other threads to do something useful first
Sleep(0);
if (testDeviceLost(true))
{
return;
}
}
while (result == S_FALSE);
}
else
{
mDeviceContext->Flush();
}
}
SwapChain *Renderer11::createSwapChain(HWND window, HANDLE shareHandle, GLenum backBufferFormat, GLenum depthBufferFormat)
{
return new rx::SwapChain11(this, window, shareHandle, backBufferFormat, depthBufferFormat);
}
void Renderer11::setSamplerState(gl::SamplerType type, int index, const gl::SamplerState &samplerState)
{
if (type == gl::SAMPLER_PIXEL)
{
if (index < 0 || index >= gl::MAX_TEXTURE_IMAGE_UNITS)
{
ERR("Pixel shader sampler index %i is not valid.", index);
return;
}
if (mForceSetPixelSamplerStates[index] || memcmp(&samplerState, &mCurPixelSamplerStates[index], sizeof(gl::SamplerState)) != 0)
{
ID3D11SamplerState *dxSamplerState = mStateCache.getSamplerState(samplerState);
if (!dxSamplerState)
{
ERR("NULL sampler state returned by RenderStateCache::getSamplerState, setting the default"
"sampler state for pixel shaders at slot %i.", index);
}
mDeviceContext->PSSetSamplers(index, 1, &dxSamplerState);
mCurPixelSamplerStates[index] = samplerState;
}
mForceSetPixelSamplerStates[index] = false;
}
else if (type == gl::SAMPLER_VERTEX)
{
if (index < 0 || index >= (int)getMaxVertexTextureImageUnits())
{
ERR("Vertex shader sampler index %i is not valid.", index);
return;
}
if (mForceSetVertexSamplerStates[index] || memcmp(&samplerState, &mCurVertexSamplerStates[index], sizeof(gl::SamplerState)) != 0)
{
ID3D11SamplerState *dxSamplerState = mStateCache.getSamplerState(samplerState);
if (!dxSamplerState)
{
ERR("NULL sampler state returned by RenderStateCache::getSamplerState, setting the default"
"sampler state for vertex shaders at slot %i.", index);
}
mDeviceContext->VSSetSamplers(index, 1, &dxSamplerState);
mCurVertexSamplerStates[index] = samplerState;
}
mForceSetVertexSamplerStates[index] = false;
}
else UNREACHABLE();
}
void Renderer11::setTexture(gl::SamplerType type, int index, gl::Texture *texture)
{
ID3D11ShaderResourceView *textureSRV = NULL;
unsigned int serial = 0;
bool forceSetTexture = false;
if (texture)
{
TextureStorageInterface *texStorage = texture->getNativeTexture();
if (texStorage)
{
TextureStorage11 *storage11 = TextureStorage11::makeTextureStorage11(texStorage->getStorageInstance());
textureSRV = storage11->getSRV();
}
// If we get NULL back from getSRV here, something went wrong in the texture class and we're unexpectedly
// missing the shader resource view
ASSERT(textureSRV != NULL);
serial = texture->getTextureSerial();
forceSetTexture = texture->hasDirtyImages();
}
if (type == gl::SAMPLER_PIXEL)
{
if (index < 0 || index >= gl::MAX_TEXTURE_IMAGE_UNITS)
{
ERR("Pixel shader sampler index %i is not valid.", index);
return;
}
if (forceSetTexture || mCurPixelTextureSerials[index] != serial)
{
mDeviceContext->PSSetShaderResources(index, 1, &textureSRV);
}
mCurPixelTextureSerials[index] = serial;
}
else if (type == gl::SAMPLER_VERTEX)
{
if (index < 0 || index >= (int)getMaxVertexTextureImageUnits())
{
ERR("Vertex shader sampler index %i is not valid.", index);
return;
}
if (forceSetTexture || mCurVertexTextureSerials[index] != serial)
{
mDeviceContext->VSSetShaderResources(index, 1, &textureSRV);
}
mCurVertexTextureSerials[index] = serial;
}
else UNREACHABLE();
}
void Renderer11::setRasterizerState(const gl::RasterizerState &rasterState)
{
if (mForceSetRasterState || memcmp(&rasterState, &mCurRasterState, sizeof(gl::RasterizerState)) != 0)
{
ID3D11RasterizerState *dxRasterState = mStateCache.getRasterizerState(rasterState, mScissorEnabled,
mCurDepthSize);
if (!dxRasterState)
{
ERR("NULL rasterizer state returned by RenderStateCache::getRasterizerState, setting the default"
"rasterizer state.");
}
mDeviceContext->RSSetState(dxRasterState);
mCurRasterState = rasterState;
}
mForceSetRasterState = false;
}
void Renderer11::setBlendState(gl::Framebuffer *framebuffer, const gl::BlendState &blendState, const gl::Color &blendColor,
unsigned int sampleMask)
{
if (mForceSetBlendState ||
memcmp(&blendState, &mCurBlendState, sizeof(gl::BlendState)) != 0 ||
memcmp(&blendColor, &mCurBlendColor, sizeof(gl::Color)) != 0 ||
sampleMask != mCurSampleMask)
{
ID3D11BlendState *dxBlendState = mStateCache.getBlendState(framebuffer, blendState);
if (!dxBlendState)
{
ERR("NULL blend state returned by RenderStateCache::getBlendState, setting the default "
"blend state.");
}
float blendColors[4] = {0.0f};
if (blendState.sourceBlendRGB != GL_CONSTANT_ALPHA && blendState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
blendState.destBlendRGB != GL_CONSTANT_ALPHA && blendState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
{
blendColors[0] = blendColor.red;
blendColors[1] = blendColor.green;
blendColors[2] = blendColor.blue;
blendColors[3] = blendColor.alpha;
}
else
{
blendColors[0] = blendColor.alpha;
blendColors[1] = blendColor.alpha;
blendColors[2] = blendColor.alpha;
blendColors[3] = blendColor.alpha;
}
mDeviceContext->OMSetBlendState(dxBlendState, blendColors, sampleMask);
mCurBlendState = blendState;
mCurBlendColor = blendColor;
mCurSampleMask = sampleMask;
}
mForceSetBlendState = false;
}
void Renderer11::setDepthStencilState(const gl::DepthStencilState &depthStencilState, int stencilRef,
int stencilBackRef, bool frontFaceCCW)
{
if (mForceSetDepthStencilState ||
memcmp(&depthStencilState, &mCurDepthStencilState, sizeof(gl::DepthStencilState)) != 0 ||
stencilRef != mCurStencilRef || stencilBackRef != mCurStencilBackRef)
{
if (depthStencilState.stencilWritemask != depthStencilState.stencilBackWritemask ||
stencilRef != stencilBackRef ||
depthStencilState.stencilMask != depthStencilState.stencilBackMask)
{
ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are "
"invalid under WebGL.");
return gl::error(GL_INVALID_OPERATION);
}
ID3D11DepthStencilState *dxDepthStencilState = mStateCache.getDepthStencilState(depthStencilState);
if (!dxDepthStencilState)
{
ERR("NULL depth stencil state returned by RenderStateCache::getDepthStencilState, "
"setting the default depth stencil state.");
}
mDeviceContext->OMSetDepthStencilState(dxDepthStencilState, static_cast<UINT>(stencilRef));
mCurDepthStencilState = depthStencilState;
mCurStencilRef = stencilRef;
mCurStencilBackRef = stencilBackRef;
}
mForceSetDepthStencilState = false;
}
void Renderer11::setScissorRectangle(const gl::Rectangle &scissor, bool enabled)
{
if (mForceSetScissor || memcmp(&scissor, &mCurScissor, sizeof(gl::Rectangle)) != 0 ||
enabled != mScissorEnabled)
{
if (enabled)
{
D3D11_RECT rect;
rect.left = std::max(0, scissor.x);
rect.top = std::max(0, scissor.y);
rect.right = scissor.x + std::max(0, scissor.width);
rect.bottom = scissor.y + std::max(0, scissor.height);
mDeviceContext->RSSetScissorRects(1, &rect);
}
if (enabled != mScissorEnabled)
{
mForceSetRasterState = true;
}
mCurScissor = scissor;
mScissorEnabled = enabled;
}
mForceSetScissor = false;
}
bool Renderer11::setViewport(const gl::Rectangle &viewport, float zNear, float zFar, GLenum drawMode, GLenum frontFace,
bool ignoreViewport)
{
gl::Rectangle actualViewport = viewport;
float actualZNear = gl::clamp01(zNear);
float actualZFar = gl::clamp01(zFar);
if (ignoreViewport)
{
actualViewport.x = 0;
actualViewport.y = 0;
actualViewport.width = mRenderTargetDesc.width;
actualViewport.height = mRenderTargetDesc.height;
actualZNear = 0.0f;
actualZFar = 1.0f;
}
// Get D3D viewport bounds, which depends on the feature level
const Range& viewportBounds = getViewportBounds();
// Clamp width and height first to the gl maximum, then clamp further if we extend past the D3D maximum bounds
D3D11_VIEWPORT dxViewport;
dxViewport.TopLeftX = gl::clamp(actualViewport.x, viewportBounds.start, viewportBounds.end);
dxViewport.TopLeftY = gl::clamp(actualViewport.y, viewportBounds.start, viewportBounds.end);
dxViewport.Width = gl::clamp(actualViewport.width, 0, getMaxViewportDimension());
dxViewport.Height = gl::clamp(actualViewport.height, 0, getMaxViewportDimension());
dxViewport.Width = std::min((int)dxViewport.Width, viewportBounds.end - static_cast<int>(dxViewport.TopLeftX));
dxViewport.Height = std::min((int)dxViewport.Height, viewportBounds.end - static_cast<int>(dxViewport.TopLeftY));
dxViewport.MinDepth = actualZNear;
dxViewport.MaxDepth = actualZFar;
if (dxViewport.Width <= 0 || dxViewport.Height <= 0)
{
return false; // Nothing to render
}
bool viewportChanged = mForceSetViewport || memcmp(&actualViewport, &mCurViewport, sizeof(gl::Rectangle)) != 0 ||
actualZNear != mCurNear || actualZFar != mCurFar;
if (viewportChanged)
{
mDeviceContext->RSSetViewports(1, &dxViewport);
mCurViewport = actualViewport;
mCurNear = actualZNear;
mCurFar = actualZFar;
mPixelConstants.viewCoords[0] = actualViewport.width * 0.5f;
mPixelConstants.viewCoords[1] = actualViewport.height * 0.5f;
mPixelConstants.viewCoords[2] = actualViewport.x + (actualViewport.width * 0.5f);
mPixelConstants.viewCoords[3] = actualViewport.y + (actualViewport.height * 0.5f);
mPixelConstants.depthFront[0] = (actualZFar - actualZNear) * 0.5f;
mPixelConstants.depthFront[1] = (actualZNear + actualZFar) * 0.5f;
mVertexConstants.depthRange[0] = actualZNear;
mVertexConstants.depthRange[1] = actualZFar;
mVertexConstants.depthRange[2] = actualZFar - actualZNear;
mPixelConstants.depthRange[0] = actualZNear;
mPixelConstants.depthRange[1] = actualZFar;
mPixelConstants.depthRange[2] = actualZFar - actualZNear;
}
mForceSetViewport = false;
return true;
}
bool Renderer11::applyPrimitiveType(GLenum mode, GLsizei count)
{
D3D11_PRIMITIVE_TOPOLOGY primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
GLsizei minCount = 0;
switch (mode)
{
case GL_POINTS: primitiveTopology = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST; minCount = 1; break;
case GL_LINES: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINELIST; minCount = 2; break;
case GL_LINE_LOOP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; minCount = 2; break;
case GL_LINE_STRIP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_LINESTRIP; minCount = 2; break;
case GL_TRIANGLES: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; minCount = 3; break;
case GL_TRIANGLE_STRIP: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP; minCount = 3; break;
// emulate fans via rewriting index buffer
case GL_TRIANGLE_FAN: primitiveTopology = D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST; minCount = 3; break;
default:
return gl::error(GL_INVALID_ENUM, false);
}
if (primitiveTopology != mCurrentPrimitiveTopology)
{
mDeviceContext->IASetPrimitiveTopology(primitiveTopology);
mCurrentPrimitiveTopology = primitiveTopology;
}
return count >= minCount;
}
bool Renderer11::applyRenderTarget(gl::Framebuffer *framebuffer)
{
// Get the color render buffer and serial
// Also extract the render target dimensions and view
unsigned int renderTargetWidth = 0;
unsigned int renderTargetHeight = 0;
GLenum renderTargetFormat = 0;
unsigned int renderTargetSerials[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {0};
ID3D11RenderTargetView* framebufferRTVs[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {NULL};
bool missingColorRenderTarget = true;
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
const GLenum drawBufferState = framebuffer->getDrawBufferState(colorAttachment);
if (framebuffer->getColorbufferType(colorAttachment) != GL_NONE && drawBufferState != GL_NONE)
{
// the draw buffer must be either "none", "back" for the default buffer or the same index as this color (in order)
ASSERT(drawBufferState == GL_BACK || drawBufferState == (GL_COLOR_ATTACHMENT0_EXT + colorAttachment));
gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer(colorAttachment);
if (!colorbuffer)
{
ERR("render target pointer unexpectedly null.");
return false;
}
// check for zero-sized default framebuffer, which is a special case.
// in this case we do not wish to modify any state and just silently return false.
// this will not report any gl error but will cause the calling method to return.
if (colorbuffer->getWidth() == 0 || colorbuffer->getHeight() == 0)
{
return false;
}
renderTargetSerials[colorAttachment] = colorbuffer->getSerial();
// Extract the render target dimensions and view
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return false;
}
framebufferRTVs[colorAttachment] = renderTarget->getRenderTargetView();
if (!framebufferRTVs[colorAttachment])
{
ERR("render target view pointer unexpectedly null.");
return false;
}
if (missingColorRenderTarget)
{
renderTargetWidth = colorbuffer->getWidth();
renderTargetHeight = colorbuffer->getHeight();
renderTargetFormat = colorbuffer->getActualFormat();
missingColorRenderTarget = false;
}
#ifdef _DEBUG
// Workaround for Debug SETSHADERRESOURCES_HAZARD D3D11 warnings
for (unsigned int vertexSerialIndex = 0; vertexSerialIndex < gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; vertexSerialIndex++)
{
if (colorbuffer->getTextureSerial() != 0 && mCurVertexTextureSerials[vertexSerialIndex] == colorbuffer->getTextureSerial())
{
setTexture(gl::SAMPLER_VERTEX, vertexSerialIndex, NULL);
}
}
for (unsigned int pixelSerialIndex = 0; pixelSerialIndex < gl::MAX_TEXTURE_IMAGE_UNITS; pixelSerialIndex++)
{
if (colorbuffer->getTextureSerial() != 0 && mCurPixelTextureSerials[pixelSerialIndex] == colorbuffer->getTextureSerial())
{
setTexture(gl::SAMPLER_PIXEL, pixelSerialIndex, NULL);
}
}
#endif
}
}
// Get the depth stencil render buffer and serials
gl::Renderbuffer *depthStencil = NULL;
unsigned int depthbufferSerial = 0;
unsigned int stencilbufferSerial = 0;
if (framebuffer->getDepthbufferType() != GL_NONE)
{
depthStencil = framebuffer->getDepthbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
depthbufferSerial = depthStencil->getSerial();
}
else if (framebuffer->getStencilbufferType() != GL_NONE)
{
depthStencil = framebuffer->getStencilbuffer();
if (!depthStencil)
{
ERR("Depth stencil pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
stencilbufferSerial = depthStencil->getSerial();
}
// Extract the depth stencil sizes and view
unsigned int depthSize = 0;
unsigned int stencilSize = 0;
ID3D11DepthStencilView* framebufferDSV = NULL;
if (depthStencil)
{
RenderTarget11 *depthStencilRenderTarget = RenderTarget11::makeRenderTarget11(depthStencil->getDepthStencil());
if (!depthStencilRenderTarget)
{
ERR("render target pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
framebufferDSV = depthStencilRenderTarget->getDepthStencilView();
if (!framebufferDSV)
{
ERR("depth stencil view pointer unexpectedly null.");
SafeRelease(framebufferRTVs);
return false;
}
// If there is no render buffer, the width, height and format values come from
// the depth stencil
if (missingColorRenderTarget)
{
renderTargetWidth = depthStencil->getWidth();
renderTargetHeight = depthStencil->getHeight();
renderTargetFormat = depthStencil->getActualFormat();
}
depthSize = depthStencil->getDepthSize();
stencilSize = depthStencil->getStencilSize();
}
// Apply the render target and depth stencil
if (!mRenderTargetDescInitialized || !mDepthStencilInitialized ||
memcmp(renderTargetSerials, mAppliedRenderTargetSerials, sizeof(renderTargetSerials)) != 0 ||
depthbufferSerial != mAppliedDepthbufferSerial ||
stencilbufferSerial != mAppliedStencilbufferSerial)
{
mDeviceContext->OMSetRenderTargets(getMaxRenderTargets(), framebufferRTVs, framebufferDSV);
mRenderTargetDesc.width = renderTargetWidth;
mRenderTargetDesc.height = renderTargetHeight;
mRenderTargetDesc.format = renderTargetFormat;
mForceSetViewport = true;
mForceSetScissor = true;
if (!mDepthStencilInitialized || depthSize != mCurDepthSize)
{
mCurDepthSize = depthSize;
mForceSetRasterState = true;
}
mCurStencilSize = stencilSize;
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = renderTargetSerials[rtIndex];
}
mAppliedDepthbufferSerial = depthbufferSerial;
mAppliedStencilbufferSerial = stencilbufferSerial;
mRenderTargetDescInitialized = true;
mDepthStencilInitialized = true;
}
return true;
}
GLenum Renderer11::applyVertexBuffer(gl::ProgramBinary *programBinary, gl::VertexAttribute vertexAttributes[], GLint first, GLsizei count, GLsizei instances)
{
TranslatedAttribute attributes[gl::MAX_VERTEX_ATTRIBS];
GLenum err = mVertexDataManager->prepareVertexData(vertexAttributes, programBinary, first, count, attributes, instances);
if (err != GL_NO_ERROR)
{
return err;
}
return mInputLayoutCache.applyVertexBuffers(attributes, programBinary);
}
GLenum Renderer11::applyIndexBuffer(const GLvoid *indices, gl::Buffer *elementArrayBuffer, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
{
GLenum err = mIndexDataManager->prepareIndexData(type, count, elementArrayBuffer, indices, indexInfo);
if (err == GL_NO_ERROR)
{
if (indexInfo->storage)
{
if (indexInfo->serial != mAppliedStorageIBSerial || indexInfo->startOffset != mAppliedIBOffset)
{
BufferStorage11 *storage = BufferStorage11::makeBufferStorage11(indexInfo->storage);
IndexBuffer11* indexBuffer = IndexBuffer11::makeIndexBuffer11(indexInfo->indexBuffer);
mDeviceContext->IASetIndexBuffer(storage->getBuffer(BUFFER_USAGE_INDEX), indexBuffer->getIndexFormat(), indexInfo->startOffset);
mAppliedIBSerial = 0;
mAppliedStorageIBSerial = storage->getSerial();
mAppliedIBOffset = indexInfo->startOffset;
}
}
else if (indexInfo->serial != mAppliedIBSerial || indexInfo->startOffset != mAppliedIBOffset)
{
IndexBuffer11* indexBuffer = IndexBuffer11::makeIndexBuffer11(indexInfo->indexBuffer);
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexInfo->startOffset);
mAppliedIBSerial = indexInfo->serial;
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexInfo->startOffset;
}
}
return err;
}
void Renderer11::drawArrays(GLenum mode, GLsizei count, GLsizei instances)
{
if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, GL_NONE, NULL, 0, NULL);
}
else if (mode == GL_TRIANGLE_FAN)
{
drawTriangleFan(count, GL_NONE, NULL, 0, NULL, instances);
}
else if (instances > 0)
{
mDeviceContext->DrawInstanced(count, instances, 0, 0);
}
else
{
mDeviceContext->Draw(count, 0);
}
}
void Renderer11::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, gl::Buffer *elementArrayBuffer, const TranslatedIndexData &indexInfo, GLsizei instances)
{
if (mode == GL_LINE_LOOP)
{
drawLineLoop(count, type, indices, indexInfo.minIndex, elementArrayBuffer);
}
else if (mode == GL_TRIANGLE_FAN)
{
drawTriangleFan(count, type, indices, indexInfo.minIndex, elementArrayBuffer, instances);
}
else if (instances > 0)
{
mDeviceContext->DrawIndexedInstanced(count, instances, 0, -static_cast<int>(indexInfo.minIndex), 0);
}
else
{
mDeviceContext->DrawIndexed(count, 0, -static_cast<int>(indexInfo.minIndex));
}
}
void Renderer11::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer)
{
// Get the raw indices for an indexed draw
if (type != GL_NONE && elementArrayBuffer)
{
gl::Buffer *indexBuffer = elementArrayBuffer;
BufferStorage *storage = indexBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
if (!mLineLoopIB)
{
mLineLoopIB = new StreamingIndexBufferInterface(this);
if (!mLineLoopIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mLineLoopIB;
mLineLoopIB = NULL;
ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
// Checked by Renderer11::applyPrimitiveType
ASSERT(count >= 0);
if (static_cast<unsigned int>(count) + 1 > (std::numeric_limits<unsigned int>::max() / sizeof(unsigned int)))
{
ERR("Could not create a 32-bit looping index buffer for GL_LINE_LOOP, too many indices required.");
return gl::error(GL_OUT_OF_MEMORY);
}
const unsigned int spaceNeeded = (static_cast<unsigned int>(count) + 1) * sizeof(unsigned int);
if (!mLineLoopIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
{
ERR("Could not reserve enough space in looping index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
unsigned int offset;
if (!mLineLoopIB->mapBuffer(spaceNeeded, &mappedMemory, &offset))
{
ERR("Could not map index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
unsigned int indexBufferOffset = offset;
switch (type)
{
case GL_NONE: // Non-indexed draw
for (int i = 0; i < count; i++)
{
data[i] = i;
}
data[count] = 0;
break;
case GL_UNSIGNED_BYTE:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLubyte*>(indices)[i];
}
data[count] = static_cast<const GLubyte*>(indices)[0];
break;
case GL_UNSIGNED_SHORT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLushort*>(indices)[i];
}
data[count] = static_cast<const GLushort*>(indices)[0];
break;
case GL_UNSIGNED_INT:
for (int i = 0; i < count; i++)
{
data[i] = static_cast<const GLuint*>(indices)[i];
}
data[count] = static_cast<const GLuint*>(indices)[0];
break;
default: UNREACHABLE();
}
if (!mLineLoopIB->unmapBuffer())
{
ERR("Could not unmap index buffer for GL_LINE_LOOP.");
return gl::error(GL_OUT_OF_MEMORY);
}
if (mAppliedIBSerial != mLineLoopIB->getSerial() || mAppliedIBOffset != indexBufferOffset)
{
IndexBuffer11 *indexBuffer = IndexBuffer11::makeIndexBuffer11(mLineLoopIB->getIndexBuffer());
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexBufferOffset);
mAppliedIBSerial = mLineLoopIB->getSerial();
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexBufferOffset;
}
mDeviceContext->DrawIndexed(count + 1, 0, -minIndex);
}
void Renderer11::drawTriangleFan(GLsizei count, GLenum type, const GLvoid *indices, int minIndex, gl::Buffer *elementArrayBuffer, int instances)
{
// Get the raw indices for an indexed draw
if (type != GL_NONE && elementArrayBuffer)
{
gl::Buffer *indexBuffer = elementArrayBuffer;
BufferStorage *storage = indexBuffer->getStorage();
intptr_t offset = reinterpret_cast<intptr_t>(indices);
indices = static_cast<const GLubyte*>(storage->getData()) + offset;
}
if (!mTriangleFanIB)
{
mTriangleFanIB = new StreamingIndexBufferInterface(this);
if (!mTriangleFanIB->reserveBufferSpace(INITIAL_INDEX_BUFFER_SIZE, GL_UNSIGNED_INT))
{
delete mTriangleFanIB;
mTriangleFanIB = NULL;
ERR("Could not create a scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
}
// Checked by Renderer11::applyPrimitiveType
ASSERT(count >= 3);
const unsigned int numTris = count - 2;
if (numTris > (std::numeric_limits<unsigned int>::max() / (sizeof(unsigned int) * 3)))
{
ERR("Could not create a scratch index buffer for GL_TRIANGLE_FAN, too many indices required.");
return gl::error(GL_OUT_OF_MEMORY);
}
const unsigned int spaceNeeded = (numTris * 3) * sizeof(unsigned int);
if (!mTriangleFanIB->reserveBufferSpace(spaceNeeded, GL_UNSIGNED_INT))
{
ERR("Could not reserve enough space in scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
void* mappedMemory = NULL;
unsigned int offset;
if (!mTriangleFanIB->mapBuffer(spaceNeeded, &mappedMemory, &offset))
{
ERR("Could not map scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
unsigned int *data = reinterpret_cast<unsigned int*>(mappedMemory);
unsigned int indexBufferOffset = offset;
switch (type)
{
case GL_NONE: // Non-indexed draw
for (unsigned int i = 0; i < numTris; i++)
{
data[i*3 + 0] = 0;
data[i*3 + 1] = i + 1;
data[i*3 + 2] = i + 2;
}
break;
case GL_UNSIGNED_BYTE:
for (unsigned int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLubyte*>(indices)[0];
data[i*3 + 1] = static_cast<const GLubyte*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLubyte*>(indices)[i + 2];
}
break;
case GL_UNSIGNED_SHORT:
for (unsigned int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLushort*>(indices)[0];
data[i*3 + 1] = static_cast<const GLushort*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLushort*>(indices)[i + 2];
}
break;
case GL_UNSIGNED_INT:
for (unsigned int i = 0; i < numTris; i++)
{
data[i*3 + 0] = static_cast<const GLuint*>(indices)[0];
data[i*3 + 1] = static_cast<const GLuint*>(indices)[i + 1];
data[i*3 + 2] = static_cast<const GLuint*>(indices)[i + 2];
}
break;
default: UNREACHABLE();
}
if (!mTriangleFanIB->unmapBuffer())
{
ERR("Could not unmap scratch index buffer for GL_TRIANGLE_FAN.");
return gl::error(GL_OUT_OF_MEMORY);
}
if (mAppliedIBSerial != mTriangleFanIB->getSerial() || mAppliedIBOffset != indexBufferOffset)
{
IndexBuffer11 *indexBuffer = IndexBuffer11::makeIndexBuffer11(mTriangleFanIB->getIndexBuffer());
mDeviceContext->IASetIndexBuffer(indexBuffer->getBuffer(), indexBuffer->getIndexFormat(), indexBufferOffset);
mAppliedIBSerial = mTriangleFanIB->getSerial();
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = indexBufferOffset;
}
if (instances > 0)
{
mDeviceContext->DrawIndexedInstanced(numTris * 3, instances, 0, -minIndex, 0);
}
else
{
mDeviceContext->DrawIndexed(numTris * 3, 0, -minIndex);
}
}
void Renderer11::applyShaders(gl::ProgramBinary *programBinary)
{
unsigned int programBinarySerial = programBinary->getSerial();
const bool updateProgramState = (programBinarySerial != mAppliedProgramBinarySerial);
if (updateProgramState)
{
ShaderExecutable *vertexExe = programBinary->getVertexExecutable();
ShaderExecutable *pixelExe = programBinary->getPixelExecutable();
ID3D11VertexShader *vertexShader = NULL;
if (vertexExe) vertexShader = ShaderExecutable11::makeShaderExecutable11(vertexExe)->getVertexShader();
ID3D11PixelShader *pixelShader = NULL;
if (pixelExe) pixelShader = ShaderExecutable11::makeShaderExecutable11(pixelExe)->getPixelShader();
mDeviceContext->PSSetShader(pixelShader, NULL, 0);
mDeviceContext->VSSetShader(vertexShader, NULL, 0);
programBinary->dirtyAllUniforms();
mAppliedProgramBinarySerial = programBinarySerial;
}
// Only use the geometry shader currently for point sprite drawing
const bool usesGeometryShader = (programBinary->usesGeometryShader() && mCurRasterState.pointDrawMode);
if (updateProgramState || usesGeometryShader != mIsGeometryShaderActive)
{
if (usesGeometryShader)
{
ShaderExecutable *geometryExe = programBinary->getGeometryExecutable();
ID3D11GeometryShader *geometryShader = ShaderExecutable11::makeShaderExecutable11(geometryExe)->getGeometryShader();
mDeviceContext->GSSetShader(geometryShader, NULL, 0);
}
else
{
mDeviceContext->GSSetShader(NULL, NULL, 0);
}
mIsGeometryShaderActive = usesGeometryShader;
}
}
void Renderer11::applyUniforms(gl::ProgramBinary *programBinary, gl::UniformArray *uniformArray)
{
ShaderExecutable11 *vertexExecutable = ShaderExecutable11::makeShaderExecutable11(programBinary->getVertexExecutable());
ShaderExecutable11 *pixelExecutable = ShaderExecutable11::makeShaderExecutable11(programBinary->getPixelExecutable());
unsigned int totalRegisterCountVS = 0;
unsigned int totalRegisterCountPS = 0;
bool vertexUniformsDirty = false;
bool pixelUniformsDirty = false;
for (gl::UniformArray::const_iterator uniform_iterator = uniformArray->begin(); uniform_iterator != uniformArray->end(); uniform_iterator++)
{
const gl::Uniform *uniform = *uniform_iterator;
if (uniform->vsRegisterIndex >= 0)
{
totalRegisterCountVS += uniform->registerCount;
vertexUniformsDirty = vertexUniformsDirty || uniform->dirty;
}
if (uniform->psRegisterIndex >= 0)
{
totalRegisterCountPS += uniform->registerCount;
pixelUniformsDirty = pixelUniformsDirty || uniform->dirty;
}
}
ID3D11Buffer *vertexConstantBuffer = vertexExecutable->getConstantBuffer(mDevice, totalRegisterCountVS);
ID3D11Buffer *pixelConstantBuffer = pixelExecutable->getConstantBuffer(mDevice, totalRegisterCountPS);
float (*mapVS)[4] = NULL;
float (*mapPS)[4] = NULL;
if (totalRegisterCountVS > 0 && vertexUniformsDirty)
{
D3D11_MAPPED_SUBRESOURCE map = {0};
HRESULT result = mDeviceContext->Map(vertexConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
ASSERT(SUCCEEDED(result));
mapVS = (float(*)[4])map.pData;
}
if (totalRegisterCountPS > 0 && pixelUniformsDirty)
{
D3D11_MAPPED_SUBRESOURCE map = {0};
HRESULT result = mDeviceContext->Map(pixelConstantBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map);
ASSERT(SUCCEEDED(result));
mapPS = (float(*)[4])map.pData;
}
for (gl::UniformArray::iterator uniform_iterator = uniformArray->begin(); uniform_iterator != uniformArray->end(); uniform_iterator++)
{
gl::Uniform *uniform = *uniform_iterator;
if (uniform->type != GL_SAMPLER_2D && uniform->type != GL_SAMPLER_CUBE)
{
if (uniform->vsRegisterIndex >= 0 && mapVS)
{
memcpy(mapVS + uniform->vsRegisterIndex, uniform->data, uniform->registerCount * sizeof(float[4]));
}
if (uniform->psRegisterIndex >= 0 && mapPS)
{
memcpy(mapPS + uniform->psRegisterIndex, uniform->data, uniform->registerCount * sizeof(float[4]));
}
}
uniform->dirty = false;
}
if (mapVS)
{
mDeviceContext->Unmap(vertexConstantBuffer, 0);
}
if (mapPS)
{
mDeviceContext->Unmap(pixelConstantBuffer, 0);
}
if (mCurrentVertexConstantBuffer != vertexConstantBuffer)
{
mDeviceContext->VSSetConstantBuffers(0, 1, &vertexConstantBuffer);
mCurrentVertexConstantBuffer = vertexConstantBuffer;
}
if (mCurrentPixelConstantBuffer != pixelConstantBuffer)
{
mDeviceContext->PSSetConstantBuffers(0, 1, &pixelConstantBuffer);
mCurrentPixelConstantBuffer = pixelConstantBuffer;
}
// Driver uniforms
if (!mDriverConstantBufferVS)
{
D3D11_BUFFER_DESC constantBufferDescription = {0};
constantBufferDescription.ByteWidth = sizeof(dx_VertexConstants);
constantBufferDescription.Usage = D3D11_USAGE_DEFAULT;
constantBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDescription.CPUAccessFlags = 0;
constantBufferDescription.MiscFlags = 0;
constantBufferDescription.StructureByteStride = 0;
HRESULT result = mDevice->CreateBuffer(&constantBufferDescription, NULL, &mDriverConstantBufferVS);
ASSERT(SUCCEEDED(result));
mDeviceContext->VSSetConstantBuffers(1, 1, &mDriverConstantBufferVS);
}
if (!mDriverConstantBufferPS)
{
D3D11_BUFFER_DESC constantBufferDescription = {0};
constantBufferDescription.ByteWidth = sizeof(dx_PixelConstants);
constantBufferDescription.Usage = D3D11_USAGE_DEFAULT;
constantBufferDescription.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
constantBufferDescription.CPUAccessFlags = 0;
constantBufferDescription.MiscFlags = 0;
constantBufferDescription.StructureByteStride = 0;
HRESULT result = mDevice->CreateBuffer(&constantBufferDescription, NULL, &mDriverConstantBufferPS);
ASSERT(SUCCEEDED(result));
mDeviceContext->PSSetConstantBuffers(1, 1, &mDriverConstantBufferPS);
}
if (memcmp(&mVertexConstants, &mAppliedVertexConstants, sizeof(dx_VertexConstants)) != 0)
{
mDeviceContext->UpdateSubresource(mDriverConstantBufferVS, 0, NULL, &mVertexConstants, 16, 0);
memcpy(&mAppliedVertexConstants, &mVertexConstants, sizeof(dx_VertexConstants));
}
if (memcmp(&mPixelConstants, &mAppliedPixelConstants, sizeof(dx_PixelConstants)) != 0)
{
mDeviceContext->UpdateSubresource(mDriverConstantBufferPS, 0, NULL, &mPixelConstants, 16, 0);
memcpy(&mAppliedPixelConstants, &mPixelConstants, sizeof(dx_PixelConstants));
}
// needed for the point sprite geometry shader
if (mCurrentGeometryConstantBuffer != mDriverConstantBufferPS)
{
mDeviceContext->GSSetConstantBuffers(0, 1, &mDriverConstantBufferPS);
mCurrentGeometryConstantBuffer = mDriverConstantBufferPS;
}
}
void Renderer11::clear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
{
gl::Renderbuffer *firstRenderbuffer = frameBuffer->getFirstColorbuffer();
GLenum internalFormat = firstRenderbuffer ? firstRenderbuffer->getInternalFormat() : GL_NONE;
bool needMaskedColorClear = (clearParams.mask & GL_COLOR_BUFFER_BIT) &&
((!clearParams.colorMaskRed && gl::GetRedSize(internalFormat) > 0) ||
(!clearParams.colorMaskGreen && gl::GetGreenSize(internalFormat) > 0) ||
(!clearParams.colorMaskBlue && gl::GetBlueSize(internalFormat) > 0) ||
(!clearParams.colorMaskAlpha && gl::GetAlphaSize(internalFormat) > 0));
unsigned int stencilUnmasked = 0x0;
if (frameBuffer->hasStencil())
{
unsigned int stencilSize = gl::GetStencilSize(frameBuffer->getStencilbuffer()->getActualFormat());
stencilUnmasked = (0x1 << stencilSize) - 1;
}
bool needMaskedStencilClear = (clearParams.mask & GL_STENCIL_BUFFER_BIT) &&
(clearParams.stencilWriteMask & stencilUnmasked) != stencilUnmasked;
bool needScissoredClear = mScissorEnabled && (mCurScissor.x > 0 || mCurScissor.y > 0 ||
mCurScissor.x + mCurScissor.width < mRenderTargetDesc.width ||
mCurScissor.y + mCurScissor.height < mRenderTargetDesc.height);
if (needMaskedColorClear || needMaskedStencilClear || needScissoredClear)
{
maskedClear(clearParams, frameBuffer);
}
else
{
if (clearParams.mask & GL_COLOR_BUFFER_BIT)
{
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (frameBuffer->isEnabledColorAttachment(colorAttachment))
{
gl::Renderbuffer *renderbufferObject = frameBuffer->getColorbuffer(colorAttachment);
if (renderbufferObject)
{
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(renderbufferObject->getRenderTarget());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return;
}
ID3D11RenderTargetView *framebufferRTV = renderTarget->getRenderTargetView();
if (!framebufferRTV)
{
ERR("render target view pointer unexpectedly null.");
return;
}
GLenum format = renderbufferObject->getInternalFormat();
const float clearValues[4] = { (gl::GetRedSize(format) > 0) ? clearParams.colorClearValue.red : 0.0f,
(gl::GetGreenSize(format) > 0) ? clearParams.colorClearValue.green : 0.0f,
(gl::GetBlueSize(format) > 0) ? clearParams.colorClearValue.blue : 0.0f,
(gl::GetAlphaSize(format) > 0) ? clearParams.colorClearValue.alpha : 1.0f };
mDeviceContext->ClearRenderTargetView(framebufferRTV, clearValues);
}
}
}
}
if (clearParams.mask & GL_DEPTH_BUFFER_BIT || clearParams.mask & GL_STENCIL_BUFFER_BIT)
{
gl::Renderbuffer *renderbufferObject = frameBuffer->getDepthOrStencilbuffer();
if (renderbufferObject)
{
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(renderbufferObject->getDepthStencil());
if (!renderTarget)
{
ERR("render target pointer unexpectedly null.");
return;
}
ID3D11DepthStencilView *framebufferDSV = renderTarget->getDepthStencilView();
if (!framebufferDSV)
{
ERR("depth stencil view pointer unexpectedly null.");
return;
}
UINT clearFlags = 0;
if (clearParams.mask & GL_DEPTH_BUFFER_BIT)
{
clearFlags |= D3D11_CLEAR_DEPTH;
}
if (clearParams.mask & GL_STENCIL_BUFFER_BIT)
{
clearFlags |= D3D11_CLEAR_STENCIL;
}
float depthClear = gl::clamp01(clearParams.depthClearValue);
UINT8 stencilClear = clearParams.stencilClearValue & 0x000000FF;
mDeviceContext->ClearDepthStencilView(framebufferDSV, clearFlags, depthClear, stencilClear);
}
}
}
}
void Renderer11::maskedClear(const gl::ClearParameters &clearParams, gl::Framebuffer *frameBuffer)
{
HRESULT result;
if (!mClearResourcesInitialized)
{
ASSERT(!mClearVB && !mClearVS && !mClearSinglePS && !mClearMultiplePS && !mClearScissorRS && !mClearNoScissorRS);
D3D11_BUFFER_DESC vbDesc;
vbDesc.ByteWidth = sizeof(d3d11::PositionDepthColorVertex) * 4;
vbDesc.Usage = D3D11_USAGE_DYNAMIC;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
result = mDevice->CreateBuffer(&vbDesc, NULL, &mClearVB);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearVB, "Renderer11 masked clear vertex buffer");
D3D11_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
result = mDevice->CreateInputLayout(quadLayout, 2, g_VS_Clear, sizeof(g_VS_Clear), &mClearIL);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearIL, "Renderer11 masked clear input layout");
result = mDevice->CreateVertexShader(g_VS_Clear, sizeof(g_VS_Clear), NULL, &mClearVS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearVS, "Renderer11 masked clear vertex shader");
result = mDevice->CreatePixelShader(g_PS_ClearSingle, sizeof(g_PS_ClearSingle), NULL, &mClearSinglePS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearSinglePS, "Renderer11 masked clear pixel shader (1 RT)");
result = mDevice->CreatePixelShader(g_PS_ClearMultiple, sizeof(g_PS_ClearMultiple), NULL, &mClearMultiplePS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearMultiplePS, "Renderer11 masked clear pixel shader (MRT)");
D3D11_RASTERIZER_DESC rsScissorDesc;
rsScissorDesc.FillMode = D3D11_FILL_SOLID;
rsScissorDesc.CullMode = D3D11_CULL_NONE;
rsScissorDesc.FrontCounterClockwise = FALSE;
rsScissorDesc.DepthBias = 0;
rsScissorDesc.DepthBiasClamp = 0.0f;
rsScissorDesc.SlopeScaledDepthBias = 0.0f;
rsScissorDesc.DepthClipEnable = FALSE;
rsScissorDesc.ScissorEnable = TRUE;
rsScissorDesc.MultisampleEnable = FALSE;
rsScissorDesc.AntialiasedLineEnable = FALSE;
result = mDevice->CreateRasterizerState(&rsScissorDesc, &mClearScissorRS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearScissorRS, "Renderer11 masked clear scissor rasterizer state");
D3D11_RASTERIZER_DESC rsNoScissorDesc;
rsNoScissorDesc.FillMode = D3D11_FILL_SOLID;
rsNoScissorDesc.CullMode = D3D11_CULL_NONE;
rsNoScissorDesc.FrontCounterClockwise = FALSE;
rsNoScissorDesc.DepthBias = 0;
rsNoScissorDesc.DepthBiasClamp = 0.0f;
rsNoScissorDesc.SlopeScaledDepthBias = 0.0f;
rsNoScissorDesc.DepthClipEnable = FALSE;
rsNoScissorDesc.ScissorEnable = FALSE;
rsNoScissorDesc.MultisampleEnable = FALSE;
rsNoScissorDesc.AntialiasedLineEnable = FALSE;
result = mDevice->CreateRasterizerState(&rsNoScissorDesc, &mClearNoScissorRS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mClearNoScissorRS, "Renderer11 masked clear no scissor rasterizer state");
mClearResourcesInitialized = true;
}
// Prepare the depth stencil state to write depth values if the depth should be cleared
// and stencil values if the stencil should be cleared
gl::DepthStencilState glDSState;
glDSState.depthTest = (clearParams.mask & GL_DEPTH_BUFFER_BIT) != 0;
glDSState.depthFunc = GL_ALWAYS;
glDSState.depthMask = (clearParams.mask & GL_DEPTH_BUFFER_BIT) != 0;
glDSState.stencilTest = (clearParams.mask & GL_STENCIL_BUFFER_BIT) != 0;
glDSState.stencilFunc = GL_ALWAYS;
glDSState.stencilMask = 0;
glDSState.stencilFail = GL_REPLACE;
glDSState.stencilPassDepthFail = GL_REPLACE;
glDSState.stencilPassDepthPass = GL_REPLACE;
glDSState.stencilWritemask = clearParams.stencilWriteMask;
glDSState.stencilBackFunc = GL_ALWAYS;
glDSState.stencilBackMask = 0;
glDSState.stencilBackFail = GL_REPLACE;
glDSState.stencilBackPassDepthFail = GL_REPLACE;
glDSState.stencilBackPassDepthPass = GL_REPLACE;
glDSState.stencilBackWritemask = clearParams.stencilWriteMask;
int stencilClear = clearParams.stencilClearValue & 0x000000FF;
ID3D11DepthStencilState *dsState = mStateCache.getDepthStencilState(glDSState);
// Prepare the blend state to use a write mask if the color buffer should be cleared
gl::BlendState glBlendState;
glBlendState.blend = false;
glBlendState.sourceBlendRGB = GL_ONE;
glBlendState.destBlendRGB = GL_ZERO;
glBlendState.sourceBlendAlpha = GL_ONE;
glBlendState.destBlendAlpha = GL_ZERO;
glBlendState.blendEquationRGB = GL_FUNC_ADD;
glBlendState.blendEquationAlpha = GL_FUNC_ADD;
glBlendState.colorMaskRed = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskRed : false;
glBlendState.colorMaskGreen = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskGreen : false;
glBlendState.colorMaskBlue = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskBlue : false;
glBlendState.colorMaskAlpha = (clearParams.mask & GL_COLOR_BUFFER_BIT) ? clearParams.colorMaskAlpha : false;
glBlendState.sampleAlphaToCoverage = false;
glBlendState.dither = false;
static const float blendFactors[4] = { 1.0f, 1.0f, 1.0f, 1.0f };
static const UINT sampleMask = 0xFFFFFFFF;
ID3D11BlendState *blendState = mStateCache.getBlendState(frameBuffer, glBlendState);
// Set the vertices
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = mDeviceContext->Map(mClearVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Failed to map masked clear vertex buffer, HRESULT: 0x%X.", result);
return;
}
d3d11::PositionDepthColorVertex *vertices = reinterpret_cast<d3d11::PositionDepthColorVertex*>(mappedResource.pData);
float depthClear = gl::clamp01(clearParams.depthClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[0], -1.0f, 1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[1], -1.0f, -1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[2], 1.0f, 1.0f, depthClear, clearParams.colorClearValue);
d3d11::SetPositionDepthColorVertex(&vertices[3], 1.0f, -1.0f, depthClear, clearParams.colorClearValue);
mDeviceContext->Unmap(mClearVB, 0);
// Apply state
mDeviceContext->OMSetBlendState(blendState, blendFactors, sampleMask);
mDeviceContext->OMSetDepthStencilState(dsState, stencilClear);
mDeviceContext->RSSetState(mScissorEnabled ? mClearScissorRS : mClearNoScissorRS);
// Apply shaders
ID3D11PixelShader *pixelShader = frameBuffer->usingExtendedDrawBuffers() ? mClearMultiplePS : mClearSinglePS;
mDeviceContext->IASetInputLayout(mClearIL);
mDeviceContext->VSSetShader(mClearVS, NULL, 0);
mDeviceContext->PSSetShader(pixelShader, NULL, 0);
mDeviceContext->GSSetShader(NULL, NULL, 0);
// Apply vertex buffer
static UINT stride = sizeof(d3d11::PositionDepthColorVertex);
static UINT startIdx = 0;
mDeviceContext->IASetVertexBuffers(0, 1, &mClearVB, &stride, &startIdx);
mDeviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
// Draw the clear quad
mDeviceContext->Draw(4, 0);
// Clean up
markAllStateDirty();
}
void Renderer11::markAllStateDirty()
{
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = 0;
}
mAppliedDepthbufferSerial = 0;
mAppliedStencilbufferSerial = 0;
mDepthStencilInitialized = false;
mRenderTargetDescInitialized = false;
for (int i = 0; i < gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetVertexSamplerStates[i] = true;
mCurVertexTextureSerials[i] = 0;
}
for (int i = 0; i < gl::MAX_TEXTURE_IMAGE_UNITS; i++)
{
mForceSetPixelSamplerStates[i] = true;
mCurPixelTextureSerials[i] = 0;
}
mForceSetBlendState = true;
mForceSetRasterState = true;
mForceSetDepthStencilState = true;
mForceSetScissor = true;
mForceSetViewport = true;
mAppliedIBSerial = 0;
mAppliedStorageIBSerial = 0;
mAppliedIBOffset = 0;
mAppliedProgramBinarySerial = 0;
memset(&mAppliedVertexConstants, 0, sizeof(dx_VertexConstants));
memset(&mAppliedPixelConstants, 0, sizeof(dx_PixelConstants));
mInputLayoutCache.markDirty();
mCurrentVertexConstantBuffer = NULL;
mCurrentPixelConstantBuffer = NULL;
mCurrentGeometryConstantBuffer = NULL;
mCurrentPrimitiveTopology = D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
}
void Renderer11::releaseDeviceResources()
{
mStateCache.clear();
mInputLayoutCache.clear();
delete mVertexDataManager;
mVertexDataManager = NULL;
delete mIndexDataManager;
mIndexDataManager = NULL;
delete mLineLoopIB;
mLineLoopIB = NULL;
delete mTriangleFanIB;
mTriangleFanIB = NULL;
SafeRelease(mCopyVB);
SafeRelease(mCopySampler);
SafeRelease(mCopyIL);
SafeRelease(mCopyIL);
SafeRelease(mCopyVS);
SafeRelease(mCopyRGBAPS);
SafeRelease(mCopyRGBPS);
SafeRelease(mCopyLumPS);
SafeRelease(mCopyLumAlphaPS);
mCopyResourcesInitialized = false;
SafeRelease(mClearVB);
SafeRelease(mClearIL);
SafeRelease(mClearVS);
SafeRelease(mClearSinglePS);
SafeRelease(mClearMultiplePS);
SafeRelease(mClearScissorRS);
SafeRelease(mClearNoScissorRS);
mClearResourcesInitialized = false;
SafeRelease(mDriverConstantBufferVS);
SafeRelease(mDriverConstantBufferPS);
SafeRelease(mSyncQuery);
}
void Renderer11::notifyDeviceLost()
{
mDeviceLost = true;
mDisplay->notifyDeviceLost();
}
bool Renderer11::isDeviceLost()
{
return mDeviceLost;
}
// set notify to true to broadcast a message to all contexts of the device loss
bool Renderer11::testDeviceLost(bool notify)
{
bool isLost = false;
// GetRemovedReason is used to test if the device is removed
HRESULT result = mDevice->GetDeviceRemovedReason();
isLost = d3d11::isDeviceLostError(result);
if (isLost)
{
// Log error if this is a new device lost event
if (mDeviceLost == false)
{
ERR("The D3D11 device was removed: 0x%08X", result);
}
// ensure we note the device loss --
// we'll probably get this done again by notifyDeviceLost
// but best to remember it!
// Note that we don't want to clear the device loss status here
// -- this needs to be done by resetDevice
mDeviceLost = true;
if (notify)
{
notifyDeviceLost();
}
}
return isLost;
}
bool Renderer11::testDeviceResettable()
{
// determine if the device is resettable by creating a dummy device
PFN_D3D11_CREATE_DEVICE D3D11CreateDevice = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(mD3d11Module, "D3D11CreateDevice");
if (D3D11CreateDevice == NULL)
{
return false;
}
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
ID3D11Device* dummyDevice;
D3D_FEATURE_LEVEL dummyFeatureLevel;
ID3D11DeviceContext* dummyContext;
HRESULT result = D3D11CreateDevice(NULL,
D3D_DRIVER_TYPE_HARDWARE,
NULL,
#if defined(_DEBUG)
D3D11_CREATE_DEVICE_DEBUG,
#else
0,
#endif
featureLevels,
ArraySize(featureLevels),
D3D11_SDK_VERSION,
&dummyDevice,
&dummyFeatureLevel,
&dummyContext);
if (!mDevice || FAILED(result))
{
return false;
}
dummyContext->Release();
dummyDevice->Release();
return true;
}
void Renderer11::release()
{
releaseDeviceResources();
if (mDxgiFactory)
{
mDxgiFactory->Release();
mDxgiFactory = NULL;
}
if (mDxgiAdapter)
{
mDxgiAdapter->Release();
mDxgiAdapter = NULL;
}
if (mDeviceContext)
{
mDeviceContext->ClearState();
mDeviceContext->Flush();
mDeviceContext->Release();
mDeviceContext = NULL;
}
if (mDevice)
{
mDevice->Release();
mDevice = NULL;
}
if (mD3d11Module)
{
FreeLibrary(mD3d11Module);
mD3d11Module = NULL;
}
if (mDxgiModule)
{
FreeLibrary(mDxgiModule);
mDxgiModule = NULL;
}
}
bool Renderer11::resetDevice()
{
// recreate everything
release();
EGLint result = initialize();
if (result != EGL_SUCCESS)
{
ERR("Could not reinitialize D3D11 device: %08X", result);
return false;
}
mDeviceLost = false;
return true;
}
DWORD Renderer11::getAdapterVendor() const
{
return mAdapterDescription.VendorId;
}
std::string Renderer11::getRendererDescription() const
{
std::ostringstream rendererString;
rendererString << mDescription;
rendererString << " Direct3D11";
rendererString << " vs_" << getMajorShaderModel() << "_" << getMinorShaderModel();
rendererString << " ps_" << getMajorShaderModel() << "_" << getMinorShaderModel();
return rendererString.str();
}
GUID Renderer11::getAdapterIdentifier() const
{
// Use the adapter LUID as our adapter ID
// This number is local to a machine is only guaranteed to be unique between restarts
META_ASSERT(sizeof(LUID) <= sizeof(GUID));
GUID adapterId = {0};
memcpy(&adapterId, &mAdapterDescription.AdapterLuid, sizeof(LUID));
return adapterId;
}
bool Renderer11::getBGRATextureSupport() const
{
return mBGRATextureSupport;
}
bool Renderer11::getDXT1TextureSupport()
{
return mDXT1TextureSupport;
}
bool Renderer11::getDXT3TextureSupport()
{
return mDXT3TextureSupport;
}
bool Renderer11::getDXT5TextureSupport()
{
return mDXT5TextureSupport;
}
bool Renderer11::getDepthTextureSupport() const
{
return mDepthTextureSupport;
}
bool Renderer11::getFloat32TextureSupport(bool *filtering, bool *renderable)
{
*renderable = mFloat32RenderSupport;
*filtering = mFloat32FilterSupport;
return mFloat32TextureSupport;
}
bool Renderer11::getFloat16TextureSupport(bool *filtering, bool *renderable)
{
*renderable = mFloat16RenderSupport;
*filtering = mFloat16FilterSupport;
return mFloat16TextureSupport;
}
bool Renderer11::getLuminanceTextureSupport()
{
return false;
}
bool Renderer11::getLuminanceAlphaTextureSupport()
{
return false;
}
bool Renderer11::getTextureFilterAnisotropySupport() const
{
return true;
}
float Renderer11::getTextureMaxAnisotropy() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_MAX_MAXANISOTROPY;
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_MAX_MAXANISOTROPY;
default: UNREACHABLE();
return 0;
}
}
bool Renderer11::getEventQuerySupport()
{
return true;
}
Range Renderer11::getViewportBounds() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return Range(D3D11_VIEWPORT_BOUNDS_MIN, D3D11_VIEWPORT_BOUNDS_MAX);
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return Range(D3D10_VIEWPORT_BOUNDS_MIN, D3D10_VIEWPORT_BOUNDS_MAX);
default: UNREACHABLE();
return Range(0, 0);
}
}
unsigned int Renderer11::getMaxVertexTextureImageUnits() const
{
META_ASSERT(MAX_TEXTURE_IMAGE_UNITS_VTF_SM4 <= gl::IMPLEMENTATION_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return MAX_TEXTURE_IMAGE_UNITS_VTF_SM4;
default: UNREACHABLE();
return 0;
}
}
unsigned int Renderer11::getMaxCombinedTextureImageUnits() const
{
return gl::MAX_TEXTURE_IMAGE_UNITS + getMaxVertexTextureImageUnits();
}
unsigned int Renderer11::getReservedVertexUniformVectors() const
{
return 0; // Driver uniforms are stored in a separate constant buffer
}
unsigned int Renderer11::getReservedFragmentUniformVectors() const
{
return 0; // Driver uniforms are stored in a separate constant buffer
}
unsigned int Renderer11::getMaxVertexUniformVectors() const
{
META_ASSERT(MAX_VERTEX_UNIFORM_VECTORS_D3D11 <= D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT);
ASSERT(mFeatureLevel >= D3D_FEATURE_LEVEL_10_0);
return MAX_VERTEX_UNIFORM_VECTORS_D3D11;
}
unsigned int Renderer11::getMaxFragmentUniformVectors() const
{
META_ASSERT(MAX_FRAGMENT_UNIFORM_VECTORS_D3D11 <= D3D10_REQ_CONSTANT_BUFFER_ELEMENT_COUNT);
ASSERT(mFeatureLevel >= D3D_FEATURE_LEVEL_10_0);
return MAX_FRAGMENT_UNIFORM_VECTORS_D3D11;
}
unsigned int Renderer11::getMaxVaryingVectors() const
{
META_ASSERT(gl::IMPLEMENTATION_MAX_VARYING_VECTORS == D3D11_VS_OUTPUT_REGISTER_COUNT);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_VS_OUTPUT_REGISTER_COUNT;
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_VS_OUTPUT_REGISTER_COUNT;
default: UNREACHABLE();
return 0;
}
}
bool Renderer11::getNonPower2TextureSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getOcclusionQuerySupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getInstancingSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getShareHandleSupport() const
{
// We only currently support share handles with BGRA surfaces, because
// chrome needs BGRA. Once chrome fixes this, we should always support them.
// PIX doesn't seem to support using share handles, so disable them.
return getBGRATextureSupport() && !gl::perfActive();
}
bool Renderer11::getDerivativeInstructionSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return true;
default: UNREACHABLE();
return false;
}
}
bool Renderer11::getPostSubBufferSupport() const
{
// D3D11 does not support present with dirty rectangles until D3D11.1 and DXGI 1.2.
return false;
}
int Renderer11::getMajorShaderModel() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_SHADER_MAJOR_VERSION; // 5
case D3D_FEATURE_LEVEL_10_1: return D3D10_1_SHADER_MAJOR_VERSION; // 4
case D3D_FEATURE_LEVEL_10_0: return D3D10_SHADER_MAJOR_VERSION; // 4
default: UNREACHABLE(); return 0;
}
}
int Renderer11::getMinorShaderModel() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_SHADER_MINOR_VERSION; // 0
case D3D_FEATURE_LEVEL_10_1: return D3D10_1_SHADER_MINOR_VERSION; // 1
case D3D_FEATURE_LEVEL_10_0: return D3D10_SHADER_MINOR_VERSION; // 0
default: UNREACHABLE(); return 0;
}
}
float Renderer11::getMaxPointSize() const
{
// choose a reasonable maximum. we enforce this in the shader.
// (nb: on a Radeon 2600xt, DX9 reports a 256 max point size)
return 1024.0f;
}
int Renderer11::getMaxViewportDimension() const
{
// Maximum viewport size must be at least as large as the largest render buffer (or larger).
// In our case return the maximum texture size, which is the maximum render buffer size.
META_ASSERT(D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION * 2 - 1 <= D3D11_VIEWPORT_BOUNDS_MAX);
META_ASSERT(D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION * 2 - 1 <= D3D10_VIEWPORT_BOUNDS_MAX);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE();
return 0;
}
}
int Renderer11::getMaxTextureWidth() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE(); return 0;
}
}
int Renderer11::getMaxTextureHeight() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0: return D3D11_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 16384
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_TEXTURE2D_U_OR_V_DIMENSION; // 8192
default: UNREACHABLE(); return 0;
}
}
bool Renderer11::get32BitIndexSupport() const
{
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0: return D3D10_REQ_DRAWINDEXED_INDEX_COUNT_2_TO_EXP >= 32; // true
default: UNREACHABLE(); return false;
}
}
int Renderer11::getMinSwapInterval() const
{
return 0;
}
int Renderer11::getMaxSwapInterval() const
{
return 4;
}
int Renderer11::getMaxSupportedSamples() const
{
return mMaxSupportedSamples;
}
int Renderer11::getNearestSupportedSamples(DXGI_FORMAT format, unsigned int requested) const
{
if (requested == 0)
{
return 0;
}
MultisampleSupportMap::const_iterator iter = mMultisampleSupportMap.find(format);
if (iter != mMultisampleSupportMap.end())
{
const MultisampleSupportInfo& info = iter->second;
for (unsigned int i = requested - 1; i < D3D11_MAX_MULTISAMPLE_SAMPLE_COUNT; i++)
{
if (info.qualityLevels[i] > 0)
{
return i + 1;
}
}
}
return -1;
}
unsigned int Renderer11::getMaxRenderTargets() const
{
META_ASSERT(D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT <= gl::IMPLEMENTATION_MAX_DRAW_BUFFERS);
META_ASSERT(D3D10_SIMULTANEOUS_RENDER_TARGET_COUNT <= gl::IMPLEMENTATION_MAX_DRAW_BUFFERS);
switch (mFeatureLevel)
{
case D3D_FEATURE_LEVEL_11_0:
return D3D11_SIMULTANEOUS_RENDER_TARGET_COUNT; // 8
case D3D_FEATURE_LEVEL_10_1:
case D3D_FEATURE_LEVEL_10_0:
// Feature level 10.0 and 10.1 cards perform very poorly when the pixel shader
// outputs to multiple RTs that are not bound.
// TODO: Remove pixel shader outputs for render targets that are not bound.
return 1;
default:
UNREACHABLE();
return 1;
}
}
bool Renderer11::copyToRenderTarget(TextureStorageInterface2D *dest, TextureStorageInterface2D *source)
{
if (source && dest)
{
TextureStorage11_2D *source11 = TextureStorage11_2D::makeTextureStorage11_2D(source->getStorageInstance());
TextureStorage11_2D *dest11 = TextureStorage11_2D::makeTextureStorage11_2D(dest->getStorageInstance());
mDeviceContext->CopyResource(dest11->getBaseTexture(), source11->getBaseTexture());
return true;
}
return false;
}
bool Renderer11::copyToRenderTarget(TextureStorageInterfaceCube *dest, TextureStorageInterfaceCube *source)
{
if (source && dest)
{
TextureStorage11_Cube *source11 = TextureStorage11_Cube::makeTextureStorage11_Cube(source->getStorageInstance());
TextureStorage11_Cube *dest11 = TextureStorage11_Cube::makeTextureStorage11_Cube(dest->getStorageInstance());
mDeviceContext->CopyResource(dest11->getBaseTexture(), source11->getBaseTexture());
return true;
}
return false;
}
bool Renderer11::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterface2D *storage, GLint level)
{
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (!colorbuffer)
{
ERR("Failed to retrieve the color buffer from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *sourceRenderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!sourceRenderTarget)
{
ERR("Failed to retrieve the render target from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11ShaderResourceView *source = sourceRenderTarget->getShaderResourceView();
if (!source)
{
ERR("Failed to retrieve the render target view from the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage11_2D *storage11 = TextureStorage11_2D::makeTextureStorage11_2D(storage->getStorageInstance());
if (!storage11)
{
ERR("Failed to retrieve the texture storage from the destination.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *destRenderTarget = RenderTarget11::makeRenderTarget11(storage11->getRenderTarget(level));
if (!destRenderTarget)
{
ERR("Failed to retrieve the render target from the destination storage.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11RenderTargetView *dest = destRenderTarget->getRenderTargetView();
if (!dest)
{
ERR("Failed to retrieve the render target view from the destination render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
gl::Rectangle destRect;
destRect.x = xoffset;
destRect.y = yoffset;
destRect.width = sourceRect.width;
destRect.height = sourceRect.height;
bool ret = copyTexture(source, sourceRect, sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(),
dest, destRect, destRenderTarget->getWidth(), destRenderTarget->getHeight(), destFormat);
return ret;
}
bool Renderer11::copyImage(gl::Framebuffer *framebuffer, const gl::Rectangle &sourceRect, GLenum destFormat,
GLint xoffset, GLint yoffset, TextureStorageInterfaceCube *storage, GLenum target, GLint level)
{
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (!colorbuffer)
{
ERR("Failed to retrieve the color buffer from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *sourceRenderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (!sourceRenderTarget)
{
ERR("Failed to retrieve the render target from the frame buffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11ShaderResourceView *source = sourceRenderTarget->getShaderResourceView();
if (!source)
{
ERR("Failed to retrieve the render target view from the render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
TextureStorage11_Cube *storage11 = TextureStorage11_Cube::makeTextureStorage11_Cube(storage->getStorageInstance());
if (!storage11)
{
ERR("Failed to retrieve the texture storage from the destination.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget11 *destRenderTarget = RenderTarget11::makeRenderTarget11(storage11->getRenderTarget(target, level));
if (!destRenderTarget)
{
ERR("Failed to retrieve the render target from the destination storage.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11RenderTargetView *dest = destRenderTarget->getRenderTargetView();
if (!dest)
{
ERR("Failed to retrieve the render target view from the destination render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
gl::Rectangle destRect;
destRect.x = xoffset;
destRect.y = yoffset;
destRect.width = sourceRect.width;
destRect.height = sourceRect.height;
bool ret = copyTexture(source, sourceRect, sourceRenderTarget->getWidth(), sourceRenderTarget->getHeight(),
dest, destRect, destRenderTarget->getWidth(), destRenderTarget->getHeight(), destFormat);
return ret;
}
bool Renderer11::copyTexture(ID3D11ShaderResourceView *source, const gl::Rectangle &sourceArea, unsigned int sourceWidth, unsigned int sourceHeight,
ID3D11RenderTargetView *dest, const gl::Rectangle &destArea, unsigned int destWidth, unsigned int destHeight, GLenum destFormat)
{
HRESULT result;
if (!mCopyResourcesInitialized)
{
ASSERT(!mCopyVB && !mCopySampler && !mCopyIL && !mCopyVS && !mCopyRGBAPS && !mCopyRGBPS && !mCopyLumPS && !mCopyLumAlphaPS);
D3D11_BUFFER_DESC vbDesc;
vbDesc.ByteWidth = sizeof(d3d11::PositionTexCoordVertex) * 4;
vbDesc.Usage = D3D11_USAGE_DYNAMIC;
vbDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
vbDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
vbDesc.MiscFlags = 0;
vbDesc.StructureByteStride = 0;
result = mDevice->CreateBuffer(&vbDesc, NULL, &mCopyVB);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyVB, "Renderer11 copy texture vertex buffer");
D3D11_SAMPLER_DESC samplerDesc;
samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
samplerDesc.MipLODBias = 0.0f;
samplerDesc.MaxAnisotropy = 0;
samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER;
samplerDesc.BorderColor[0] = 0.0f;
samplerDesc.BorderColor[1] = 0.0f;
samplerDesc.BorderColor[2] = 0.0f;
samplerDesc.BorderColor[3] = 0.0f;
samplerDesc.MinLOD = 0.0f;
samplerDesc.MaxLOD = 0.0f;
result = mDevice->CreateSamplerState(&samplerDesc, &mCopySampler);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopySampler, "Renderer11 copy sampler");
D3D11_INPUT_ELEMENT_DESC quadLayout[] =
{
{ "POSITION", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 8, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
result = mDevice->CreateInputLayout(quadLayout, 2, g_VS_Passthrough, sizeof(g_VS_Passthrough), &mCopyIL);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyIL, "Renderer11 copy texture input layout");
result = mDevice->CreateVertexShader(g_VS_Passthrough, sizeof(g_VS_Passthrough), NULL, &mCopyVS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyVS, "Renderer11 copy texture vertex shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughRGBA, sizeof(g_PS_PassthroughRGBA), NULL, &mCopyRGBAPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyRGBAPS, "Renderer11 copy texture RGBA pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughRGB, sizeof(g_PS_PassthroughRGB), NULL, &mCopyRGBPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyRGBPS, "Renderer11 copy texture RGB pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughLum, sizeof(g_PS_PassthroughLum), NULL, &mCopyLumPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyLumPS, "Renderer11 copy texture luminance pixel shader");
result = mDevice->CreatePixelShader(g_PS_PassthroughLumAlpha, sizeof(g_PS_PassthroughLumAlpha), NULL, &mCopyLumAlphaPS);
ASSERT(SUCCEEDED(result));
d3d11::SetDebugName(mCopyLumAlphaPS, "Renderer11 copy texture luminance alpha pixel shader");
mCopyResourcesInitialized = true;
}
// Verify the source and destination area sizes
if (sourceArea.x < 0 || sourceArea.x + sourceArea.width > static_cast<int>(sourceWidth) ||
sourceArea.y < 0 || sourceArea.y + sourceArea.height > static_cast<int>(sourceHeight) ||
destArea.x < 0 || destArea.x + destArea.width > static_cast<int>(destWidth) ||
destArea.y < 0 || destArea.y + destArea.height > static_cast<int>(destHeight))
{
return gl::error(GL_INVALID_VALUE, false);
}
// Set vertices
D3D11_MAPPED_SUBRESOURCE mappedResource;
result = mDeviceContext->Map(mCopyVB, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource);
if (FAILED(result))
{
ERR("Failed to map vertex buffer for texture copy, HRESULT: 0x%X.", result);
return gl::error(GL_OUT_OF_MEMORY, false);
}
d3d11::PositionTexCoordVertex *vertices = static_cast<d3d11::PositionTexCoordVertex*>(mappedResource.pData);
// Create a quad in homogeneous coordinates
float x1 = (destArea.x / float(destWidth)) * 2.0f - 1.0f;
float y1 = ((destHeight - destArea.y - destArea.height) / float(destHeight)) * 2.0f - 1.0f;
float x2 = ((destArea.x + destArea.width) / float(destWidth)) * 2.0f - 1.0f;
float y2 = ((destHeight - destArea.y) / float(destHeight)) * 2.0f - 1.0f;
float u1 = sourceArea.x / float(sourceWidth);
float v1 = sourceArea.y / float(sourceHeight);
float u2 = (sourceArea.x + sourceArea.width) / float(sourceWidth);
float v2 = (sourceArea.y + sourceArea.height) / float(sourceHeight);
d3d11::SetPositionTexCoordVertex(&vertices[0], x1, y1, u1, v2);
d3d11::SetPositionTexCoordVertex(&vertices[1], x1, y2, u1, v1);
d3d11::SetPositionTexCoordVertex(&vertices[2], x2, y1, u2, v2);
d3d11::SetPositionTexCoordVertex(&vertices[3], x2, y2, u2, v1);
mDeviceContext->Unmap(mCopyVB, 0);
static UINT stride = sizeof(d3d11::PositionTexCoordVertex);
static UINT startIdx = 0;
mDeviceContext->IASetVertexBuffers(0, 1, &mCopyVB, &stride, &startIdx);
// Apply state
mDeviceContext->OMSetBlendState(NULL, NULL, 0xFFFFFFF);
mDeviceContext->OMSetDepthStencilState(NULL, 0xFFFFFFFF);
mDeviceContext->RSSetState(NULL);
// Apply shaders
mDeviceContext->IASetInputLayout(mCopyIL);
mDeviceContext->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);
mDeviceContext->VSSetShader(mCopyVS, NULL, 0);
ID3D11PixelShader *ps = NULL;
switch(destFormat)
{
case GL_RGBA: ps = mCopyRGBAPS; break;
case GL_RGB: ps = mCopyRGBPS; break;
case GL_ALPHA: ps = mCopyRGBAPS; break;
case GL_BGRA_EXT: ps = mCopyRGBAPS; break;
case GL_LUMINANCE: ps = mCopyLumPS; break;
case GL_LUMINANCE_ALPHA: ps = mCopyLumAlphaPS; break;
default: UNREACHABLE(); ps = NULL; break;
}
mDeviceContext->PSSetShader(ps, NULL, 0);
mDeviceContext->GSSetShader(NULL, NULL, 0);
// Unset the currently bound shader resource to avoid conflicts
static ID3D11ShaderResourceView *const nullSRV = NULL;
mDeviceContext->PSSetShaderResources(0, 1, &nullSRV);
// Apply render target
setOneTimeRenderTarget(dest);
// Set the viewport
D3D11_VIEWPORT viewport;
viewport.TopLeftX = 0;
viewport.TopLeftY = 0;
viewport.Width = destWidth;
viewport.Height = destHeight;
viewport.MinDepth = 0.0f;
viewport.MaxDepth = 1.0f;
mDeviceContext->RSSetViewports(1, &viewport);
// Apply textures
mDeviceContext->PSSetShaderResources(0, 1, &source);
mDeviceContext->PSSetSamplers(0, 1, &mCopySampler);
// Draw the quad
mDeviceContext->Draw(4, 0);
// Unbind textures and render targets and vertex buffer
mDeviceContext->PSSetShaderResources(0, 1, &nullSRV);
unapplyRenderTargets();
UINT zero = 0;
ID3D11Buffer *const nullBuffer = NULL;
mDeviceContext->IASetVertexBuffers(0, 1, &nullBuffer, &zero, &zero);
markAllStateDirty();
return true;
}
void Renderer11::unapplyRenderTargets()
{
setOneTimeRenderTarget(NULL);
}
void Renderer11::setOneTimeRenderTarget(ID3D11RenderTargetView *renderTargetView)
{
ID3D11RenderTargetView *rtvArray[gl::IMPLEMENTATION_MAX_DRAW_BUFFERS] = {NULL};
rtvArray[0] = renderTargetView;
mDeviceContext->OMSetRenderTargets(getMaxRenderTargets(), rtvArray, NULL);
// Do not preserve the serial for this one-time-use render target
for (unsigned int rtIndex = 0; rtIndex < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; rtIndex++)
{
mAppliedRenderTargetSerials[rtIndex] = 0;
}
}
RenderTarget *Renderer11::createRenderTarget(SwapChain *swapChain, bool depth)
{
SwapChain11 *swapChain11 = SwapChain11::makeSwapChain11(swapChain);
RenderTarget11 *renderTarget = NULL;
if (depth)
{
// Note: depth stencil may be NULL for 0 sized surfaces
renderTarget = new RenderTarget11(this, swapChain11->getDepthStencil(),
swapChain11->getDepthStencilTexture(), NULL,
swapChain11->getWidth(), swapChain11->getHeight());
}
else
{
// Note: render target may be NULL for 0 sized surfaces
renderTarget = new RenderTarget11(this, swapChain11->getRenderTarget(),
swapChain11->getOffscreenTexture(),
swapChain11->getRenderTargetShaderResource(),
swapChain11->getWidth(), swapChain11->getHeight());
}
return renderTarget;
}
RenderTarget *Renderer11::createRenderTarget(int width, int height, GLenum format, GLsizei samples, bool depth)
{
RenderTarget11 *renderTarget = new RenderTarget11(this, width, height, format, samples, depth);
return renderTarget;
}
ShaderExecutable *Renderer11::loadExecutable(const void *function, size_t length, rx::ShaderType type)
{
ShaderExecutable11 *executable = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
{
ID3D11VertexShader *vshader = NULL;
HRESULT result = mDevice->CreateVertexShader(function, length, NULL, &vshader);
ASSERT(SUCCEEDED(result));
if (vshader)
{
executable = new ShaderExecutable11(function, length, vshader);
}
}
break;
case rx::SHADER_PIXEL:
{
ID3D11PixelShader *pshader = NULL;
HRESULT result = mDevice->CreatePixelShader(function, length, NULL, &pshader);
ASSERT(SUCCEEDED(result));
if (pshader)
{
executable = new ShaderExecutable11(function, length, pshader);
}
}
break;
case rx::SHADER_GEOMETRY:
{
ID3D11GeometryShader *gshader = NULL;
HRESULT result = mDevice->CreateGeometryShader(function, length, NULL, &gshader);
ASSERT(SUCCEEDED(result));
if (gshader)
{
executable = new ShaderExecutable11(function, length, gshader);
}
}
break;
default:
UNREACHABLE();
break;
}
return executable;
}
ShaderExecutable *Renderer11::compileToExecutable(gl::InfoLog &infoLog, const char *shaderHLSL, rx::ShaderType type, D3DWorkaroundType workaround)
{
const char *profile = NULL;
switch (type)
{
case rx::SHADER_VERTEX:
profile = "vs_4_0";
break;
case rx::SHADER_PIXEL:
profile = "ps_4_0";
break;
case rx::SHADER_GEOMETRY:
profile = "gs_4_0";
break;
default:
UNREACHABLE();
return NULL;
}
ID3DBlob *binary = (ID3DBlob*)compileToBinary(infoLog, shaderHLSL, profile, D3DCOMPILE_OPTIMIZATION_LEVEL0, false);
if (!binary)
return NULL;
ShaderExecutable *executable = loadExecutable((DWORD *)binary->GetBufferPointer(), binary->GetBufferSize(), type);
binary->Release();
return executable;
}
VertexBuffer *Renderer11::createVertexBuffer()
{
return new VertexBuffer11(this);
}
IndexBuffer *Renderer11::createIndexBuffer()
{
return new IndexBuffer11(this);
}
BufferStorage *Renderer11::createBufferStorage()
{
return new BufferStorage11(this);
}
QueryImpl *Renderer11::createQuery(GLenum type)
{
return new Query11(this, type);
}
FenceImpl *Renderer11::createFence()
{
return new Fence11(this);
}
bool Renderer11::getRenderTargetResource(gl::Renderbuffer *colorbuffer, unsigned int *subresourceIndex, ID3D11Texture2D **resource)
{
ASSERT(colorbuffer != NULL);
RenderTarget11 *renderTarget = RenderTarget11::makeRenderTarget11(colorbuffer->getRenderTarget());
if (renderTarget)
{
*subresourceIndex = renderTarget->getSubresourceIndex();
ID3D11RenderTargetView *colorBufferRTV = renderTarget->getRenderTargetView();
if (colorBufferRTV)
{
ID3D11Resource *textureResource = NULL;
colorBufferRTV->GetResource(&textureResource);
if (textureResource)
{
HRESULT result = textureResource->QueryInterface(IID_ID3D11Texture2D, (void**)resource);
textureResource->Release();
if (SUCCEEDED(result))
{
return true;
}
else
{
ERR("Failed to extract the ID3D11Texture2D from the render target resource, "
"HRESULT: 0x%X.", result);
}
}
}
}
return false;
}
bool Renderer11::blitRect(gl::Framebuffer *readTarget, const gl::Rectangle &readRect, gl::Framebuffer *drawTarget, const gl::Rectangle &drawRect,
bool blitRenderTarget, bool blitDepthStencil)
{
if (blitRenderTarget)
{
gl::Renderbuffer *readBuffer = readTarget->getReadColorbuffer();
if (!readBuffer)
{
ERR("Failed to retrieve the read buffer from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *readRenderTarget = readBuffer->getRenderTarget();
for (unsigned int colorAttachment = 0; colorAttachment < gl::IMPLEMENTATION_MAX_DRAW_BUFFERS; colorAttachment++)
{
if (drawTarget->isEnabledColorAttachment(colorAttachment))
{
gl::Renderbuffer *drawBuffer = drawTarget->getColorbuffer(colorAttachment);
if (!drawBuffer)
{
ERR("Failed to retrieve the draw buffer from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *drawRenderTarget = drawBuffer->getRenderTarget();
if (!blitRenderbufferRect(readRect, drawRect, readRenderTarget, drawRenderTarget, false))
{
return false;
}
}
}
}
if (blitDepthStencil)
{
gl::Renderbuffer *readBuffer = readTarget->getDepthOrStencilbuffer();
gl::Renderbuffer *drawBuffer = drawTarget->getDepthOrStencilbuffer();
if (!readBuffer)
{
ERR("Failed to retrieve the read depth-stencil buffer from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
if (!drawBuffer)
{
ERR("Failed to retrieve the draw depth-stencil buffer from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
RenderTarget *readRenderTarget = readBuffer->getDepthStencil();
RenderTarget *drawRenderTarget = drawBuffer->getDepthStencil();
if (!blitRenderbufferRect(readRect, drawRect, readRenderTarget, drawRenderTarget, true))
{
return false;
}
}
return true;
}
void Renderer11::readPixels(gl::Framebuffer *framebuffer, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type,
GLsizei outputPitch, bool packReverseRowOrder, GLint packAlignment, void* pixels)
{
ID3D11Texture2D *colorBufferTexture = NULL;
unsigned int subresourceIndex = 0;
gl::Renderbuffer *colorbuffer = framebuffer->getReadColorbuffer();
if (colorbuffer && getRenderTargetResource(colorbuffer, &subresourceIndex, &colorBufferTexture))
{
gl::Rectangle area;
area.x = x;
area.y = y;
area.width = width;
area.height = height;
readTextureData(colorBufferTexture, subresourceIndex, area, colorbuffer->getActualFormat(), format, type, outputPitch,
packReverseRowOrder, packAlignment, pixels);
colorBufferTexture->Release();
colorBufferTexture = NULL;
}
}
Image *Renderer11::createImage()
{
return new Image11();
}
void Renderer11::generateMipmap(Image *dest, Image *src)
{
Image11 *dest11 = Image11::makeImage11(dest);
Image11 *src11 = Image11::makeImage11(src);
Image11::generateMipmap(dest11, src11);
}
TextureStorage *Renderer11::createTextureStorage2D(SwapChain *swapChain)
{
SwapChain11 *swapChain11 = SwapChain11::makeSwapChain11(swapChain);
return new TextureStorage11_2D(this, swapChain11);
}
TextureStorage *Renderer11::createTextureStorage2D(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, GLsizei width, GLsizei height)
{
return new TextureStorage11_2D(this, levels, internalformat, usage, forceRenderable, width, height);
}
TextureStorage *Renderer11::createTextureStorageCube(int levels, GLenum internalformat, GLenum usage, bool forceRenderable, int size)
{
return new TextureStorage11_Cube(this, levels, internalformat, usage, forceRenderable, size);
}
static inline unsigned int getFastPixelCopySize(DXGI_FORMAT sourceFormat, GLenum sourceGLFormat, GLenum destFormat, GLenum destType)
{
if (sourceFormat == DXGI_FORMAT_A8_UNORM &&
destFormat == GL_ALPHA &&
destType == GL_UNSIGNED_BYTE)
{
return 1;
}
else if (sourceFormat == DXGI_FORMAT_R8G8B8A8_UNORM &&
sourceGLFormat == GL_RGBA8_OES &&
destFormat == GL_RGBA &&
destType == GL_UNSIGNED_BYTE)
{
return 4;
}
else if (sourceFormat == DXGI_FORMAT_B8G8R8A8_UNORM &&
destFormat == GL_BGRA_EXT &&
destType == GL_UNSIGNED_BYTE)
{
return 4;
}
else if (sourceFormat == DXGI_FORMAT_R16G16B16A16_FLOAT &&
sourceGLFormat == GL_RGBA16F_EXT &&
destFormat == GL_RGBA &&
destType == GL_HALF_FLOAT_OES)
{
return 8;
}
else if (sourceFormat == DXGI_FORMAT_R32G32B32_FLOAT &&
destFormat == GL_RGB &&
destType == GL_FLOAT)
{
return 12;
}
else if (sourceFormat == DXGI_FORMAT_R32G32B32A32_FLOAT &&
sourceGLFormat == GL_RGBA32F_EXT &&
destFormat == GL_RGBA &&
destType == GL_FLOAT)
{
return 16;
}
else
{
return 0;
}
}
static inline void readPixelColor(const unsigned char *data, DXGI_FORMAT format, GLenum glFormat, unsigned int x,
unsigned int y, int inputPitch, gl::Color *outColor)
{
switch (format)
{
case DXGI_FORMAT_R8G8B8A8_UNORM:
{
unsigned int rgba = *reinterpret_cast<const unsigned int*>(data + 4 * x + y * inputPitch);
outColor->red = (rgba & 0x000000FF) * (1.0f / 0x000000FF);
outColor->green = (rgba & 0x0000FF00) * (1.0f / 0x0000FF00);
outColor->blue = (rgba & 0x00FF0000) * (1.0f / 0x00FF0000);
if (gl::GetAlphaSize(glFormat) > 0)
{
outColor->alpha = (rgba & 0xFF000000) * (1.0f / 0xFF000000);
}
else
{
outColor->alpha = 1.0f;
}
}
break;
case DXGI_FORMAT_A8_UNORM:
{
outColor->red = 0.0f;
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = *(data + x + y * inputPitch) / 255.0f;
}
break;
case DXGI_FORMAT_R32G32B32A32_FLOAT:
{
outColor->red = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 0);
outColor->green = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 1);
outColor->blue = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 2);
if (gl::GetAlphaSize(glFormat) > 0)
{
outColor->alpha = *(reinterpret_cast<const float*>(data + 16 * x + y * inputPitch) + 3);
}
else
{
outColor->alpha = 1.0f;
}
}
break;
case DXGI_FORMAT_R32G32B32_FLOAT:
{
outColor->red = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 0);
outColor->green = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 1);
outColor->blue = *(reinterpret_cast<const float*>(data + 12 * x + y * inputPitch) + 2);
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16G16B16A16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 0));
outColor->green = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 1));
outColor->blue = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 2));
if (gl::GetAlphaSize(glFormat) > 0)
{
outColor->alpha = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 8 * x + y * inputPitch) + 3));
}
else
{
outColor->alpha = 1.0f;
}
}
break;
case DXGI_FORMAT_B8G8R8A8_UNORM:
{
unsigned int bgra = *reinterpret_cast<const unsigned int*>(data + 4 * x + y * inputPitch);
outColor->red = (bgra & 0x00FF0000) * (1.0f / 0x00FF0000);
outColor->blue = (bgra & 0x000000FF) * (1.0f / 0x000000FF);
outColor->green = (bgra & 0x0000FF00) * (1.0f / 0x0000FF00);
outColor->alpha = (bgra & 0xFF000000) * (1.0f / 0xFF000000);
}
break;
case DXGI_FORMAT_R8_UNORM:
{
outColor->red = *(data + x + y * inputPitch) / 255.0f;
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R8G8_UNORM:
{
unsigned short rg = *reinterpret_cast<const unsigned short*>(data + 2 * x + y * inputPitch);
outColor->red = (rg & 0xFF00) * (1.0f / 0xFF00);
outColor->green = (rg & 0x00FF) * (1.0f / 0x00FF);
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*reinterpret_cast<const unsigned short*>(data + 2 * x + y * inputPitch));
outColor->green = 0.0f;
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
case DXGI_FORMAT_R16G16_FLOAT:
{
outColor->red = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 4 * x + y * inputPitch) + 0));
outColor->green = gl::float16ToFloat32(*(reinterpret_cast<const unsigned short*>(data + 4 * x + y * inputPitch) + 1));
outColor->blue = 0.0f;
outColor->alpha = 1.0f;
}
break;
default:
ERR("ReadPixelColor not implemented for DXGI format %u.", format);
UNIMPLEMENTED();
break;
}
}
static inline void writePixelColor(const gl::Color &color, GLenum format, GLenum type, unsigned int x,
unsigned int y, int outputPitch, void *outData)
{
unsigned char* byteData = reinterpret_cast<unsigned char*>(outData);
unsigned short* shortData = reinterpret_cast<unsigned short*>(outData);
switch (format)
{
case GL_RGBA:
switch (type)
{
case GL_UNSIGNED_BYTE:
byteData[4 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[4 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[4 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.blue + 0.5f);
byteData[4 * x + y * outputPitch + 3] = static_cast<unsigned char>(255 * color.alpha + 0.5f);
break;
default:
ERR("WritePixelColor not implemented for format GL_RGBA and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
case GL_BGRA_EXT:
switch (type)
{
case GL_UNSIGNED_BYTE:
byteData[4 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.blue + 0.5f);
byteData[4 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[4 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[4 * x + y * outputPitch + 3] = static_cast<unsigned char>(255 * color.alpha + 0.5f);
break;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>(15 * color.alpha + 0.5f) << 12) |
(static_cast<unsigned short>(15 * color.red + 0.5f) << 8) |
(static_cast<unsigned short>(15 * color.green + 0.5f) << 4) |
(static_cast<unsigned short>(15 * color.blue + 0.5f) << 0);
break;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
// According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
// this type is packed as follows:
// 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
// --------------------------------------------------------------------------------
// | 4th | 3rd | 2nd | 1st component |
// --------------------------------------------------------------------------------
// in the case of BGRA_EXT, B is the first component, G the second, and so forth.
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>( color.alpha + 0.5f) << 15) |
(static_cast<unsigned short>(31 * color.red + 0.5f) << 10) |
(static_cast<unsigned short>(31 * color.green + 0.5f) << 5) |
(static_cast<unsigned short>(31 * color.blue + 0.5f) << 0);
break;
default:
ERR("WritePixelColor not implemented for format GL_BGRA_EXT and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
case GL_RGB:
switch (type)
{
case GL_UNSIGNED_SHORT_5_6_5:
shortData[x + y * outputPitch / sizeof(unsigned short)] =
(static_cast<unsigned short>(31 * color.blue + 0.5f) << 0) |
(static_cast<unsigned short>(63 * color.green + 0.5f) << 5) |
(static_cast<unsigned short>(31 * color.red + 0.5f) << 11);
break;
case GL_UNSIGNED_BYTE:
byteData[3 * x + y * outputPitch + 0] = static_cast<unsigned char>(255 * color.red + 0.5f);
byteData[3 * x + y * outputPitch + 1] = static_cast<unsigned char>(255 * color.green + 0.5f);
byteData[3 * x + y * outputPitch + 2] = static_cast<unsigned char>(255 * color.blue + 0.5f);
break;
default:
ERR("WritePixelColor not implemented for format GL_RGB and type 0x%X.", type);
UNIMPLEMENTED();
break;
}
break;
default:
ERR("WritePixelColor not implemented for format 0x%X.", format);
UNIMPLEMENTED();
break;
}
}
void Renderer11::readTextureData(ID3D11Texture2D *texture, unsigned int subResource, const gl::Rectangle &area,
GLenum sourceFormat, GLenum format, GLenum type, GLsizei outputPitch, bool packReverseRowOrder,
GLint packAlignment, void *pixels)
{
D3D11_TEXTURE2D_DESC textureDesc;
texture->GetDesc(&textureDesc);
D3D11_TEXTURE2D_DESC stagingDesc;
stagingDesc.Width = area.width;
stagingDesc.Height = area.height;
stagingDesc.MipLevels = 1;
stagingDesc.ArraySize = 1;
stagingDesc.Format = textureDesc.Format;
stagingDesc.SampleDesc.Count = 1;
stagingDesc.SampleDesc.Quality = 0;
stagingDesc.Usage = D3D11_USAGE_STAGING;
stagingDesc.BindFlags = 0;
stagingDesc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
stagingDesc.MiscFlags = 0;
ID3D11Texture2D* stagingTex = NULL;
HRESULT result = mDevice->CreateTexture2D(&stagingDesc, NULL, &stagingTex);
if (FAILED(result))
{
ERR("Failed to create staging texture for readPixels, HRESULT: 0x%X.", result);
return;
}
ID3D11Texture2D* srcTex = NULL;
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = D3D11_USAGE_DEFAULT;
resolveDesc.BindFlags = 0;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
result = mDevice->CreateTexture2D(&resolveDesc, NULL, &srcTex);
if (FAILED(result))
{
ERR("Failed to create resolve texture for readPixels, HRESULT: 0x%X.", result);
stagingTex->Release();
return;
}
mDeviceContext->ResolveSubresource(srcTex, 0, texture, subResource, textureDesc.Format);
subResource = 0;
}
else
{
srcTex = texture;
srcTex->AddRef();
}
D3D11_BOX srcBox;
srcBox.left = area.x;
srcBox.right = area.x + area.width;
srcBox.top = area.y;
srcBox.bottom = area.y + area.height;
srcBox.front = 0;
srcBox.back = 1;
mDeviceContext->CopySubresourceRegion(stagingTex, 0, 0, 0, 0, srcTex, subResource, &srcBox);
srcTex->Release();
srcTex = NULL;
D3D11_MAPPED_SUBRESOURCE mapping;
mDeviceContext->Map(stagingTex, 0, D3D11_MAP_READ, 0, &mapping);
unsigned char *source;
int inputPitch;
if (packReverseRowOrder)
{
source = static_cast<unsigned char*>(mapping.pData) + mapping.RowPitch * (area.height - 1);
inputPitch = -static_cast<int>(mapping.RowPitch);
}
else
{
source = static_cast<unsigned char*>(mapping.pData);
inputPitch = static_cast<int>(mapping.RowPitch);
}
unsigned int fastPixelSize = getFastPixelCopySize(textureDesc.Format, sourceFormat, format, type);
if (fastPixelSize != 0)
{
unsigned char *dest = static_cast<unsigned char*>(pixels);
for (int j = 0; j < area.height; j++)
{
memcpy(dest + j * outputPitch, source + j * inputPitch, area.width * fastPixelSize);
}
}
else if (textureDesc.Format == DXGI_FORMAT_B8G8R8A8_UNORM &&
format == GL_RGBA &&
type == GL_UNSIGNED_BYTE)
{
// Fast path for swapping red with blue
unsigned char *dest = static_cast<unsigned char*>(pixels);
for (int j = 0; j < area.height; j++)
{
for (int i = 0; i < area.width; i++)
{
unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
*(unsigned int*)(dest + 4 * i + j * outputPitch) =
(argb & 0xFF00FF00) | // Keep alpha and green
(argb & 0x00FF0000) >> 16 | // Move red to blue
(argb & 0x000000FF) << 16; // Move blue to red
}
}
}
else
{
gl::Color pixelColor;
for (int j = 0; j < area.height; j++)
{
for (int i = 0; i < area.width; i++)
{
readPixelColor(source, textureDesc.Format, sourceFormat, i, j, inputPitch, &pixelColor);
writePixelColor(pixelColor, format, type, i, j, outputPitch, pixels);
}
}
}
mDeviceContext->Unmap(stagingTex, 0);
stagingTex->Release();
stagingTex = NULL;
}
bool Renderer11::blitRenderbufferRect(const gl::Rectangle &readRect, const gl::Rectangle &drawRect, RenderTarget *readRenderTarget,
RenderTarget *drawRenderTarget, bool wholeBufferCopy)
{
ASSERT(readRect.width == drawRect.width && readRect.height == drawRect.height);
RenderTarget11 *drawRenderTarget11 = RenderTarget11::makeRenderTarget11(drawRenderTarget);
if (!drawRenderTarget)
{
ERR("Failed to retrieve the draw render target from the draw framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11Texture2D *drawTexture = drawRenderTarget11->getTexture();
unsigned int drawSubresource = drawRenderTarget11->getSubresourceIndex();
RenderTarget11 *readRenderTarget11 = RenderTarget11::makeRenderTarget11(readRenderTarget);
if (!readRenderTarget)
{
ERR("Failed to retrieve the read render target from the read framebuffer.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
ID3D11Texture2D *readTexture = NULL;
unsigned int readSubresource = 0;
if (readRenderTarget->getSamples() > 0)
{
readTexture = resolveMultisampledTexture(readRenderTarget11->getTexture(), readRenderTarget11->getSubresourceIndex());
readSubresource = 0;
}
else
{
readTexture = readRenderTarget11->getTexture();
readTexture->AddRef();
readSubresource = readRenderTarget11->getSubresourceIndex();
}
if (!readTexture)
{
ERR("Failed to retrieve the read render target view from the read render target.");
return gl::error(GL_OUT_OF_MEMORY, false);
}
D3D11_BOX readBox;
readBox.left = readRect.x;
readBox.right = readRect.x + readRect.width;
readBox.top = readRect.y;
readBox.bottom = readRect.y + readRect.height;
readBox.front = 0;
readBox.back = 1;
// D3D11 needs depth-stencil CopySubresourceRegions to have a NULL pSrcBox
// We also require complete framebuffer copies for depth-stencil blit.
D3D11_BOX *pSrcBox = wholeBufferCopy ? NULL : &readBox;
mDeviceContext->CopySubresourceRegion(drawTexture, drawSubresource, drawRect.x, drawRect.y, 0,
readTexture, readSubresource, pSrcBox);
SafeRelease(readTexture);
return true;
}
ID3D11Texture2D *Renderer11::resolveMultisampledTexture(ID3D11Texture2D *source, unsigned int subresource)
{
D3D11_TEXTURE2D_DESC textureDesc;
source->GetDesc(&textureDesc);
if (textureDesc.SampleDesc.Count > 1)
{
D3D11_TEXTURE2D_DESC resolveDesc;
resolveDesc.Width = textureDesc.Width;
resolveDesc.Height = textureDesc.Height;
resolveDesc.MipLevels = 1;
resolveDesc.ArraySize = 1;
resolveDesc.Format = textureDesc.Format;
resolveDesc.SampleDesc.Count = 1;
resolveDesc.SampleDesc.Quality = 0;
resolveDesc.Usage = textureDesc.Usage;
resolveDesc.BindFlags = textureDesc.BindFlags;
resolveDesc.CPUAccessFlags = 0;
resolveDesc.MiscFlags = 0;
ID3D11Texture2D *resolveTexture = NULL;
HRESULT result = mDevice->CreateTexture2D(&resolveDesc, NULL, &resolveTexture);
if (FAILED(result))
{
ERR("Failed to create a multisample resolve texture, HRESULT: 0x%X.", result);
return NULL;
}
mDeviceContext->ResolveSubresource(resolveTexture, 0, source, subresource, textureDesc.Format);
return resolveTexture;
}
else
{
source->AddRef();
return source;
}
}
bool Renderer11::getLUID(LUID *adapterLuid) const
{
adapterLuid->HighPart = 0;
adapterLuid->LowPart = 0;
if (!mDxgiAdapter)
{
return false;
}
DXGI_ADAPTER_DESC adapterDesc;
if (FAILED(mDxgiAdapter->GetDesc(&adapterDesc)))
{
return false;
}
*adapterLuid = adapterDesc.AdapterLuid;
return true;
}
}
| [
"adzhou@hp.com"
] | adzhou@hp.com |
fb6e71811ea2b6acfe0569a9ed694f0fcecfe3fb | 28663629961c09d94d2a169635e5a9f316c9034a | /tests.h | 78751aac17c53a28088fd9b061929b84aa824c78 | [
"MIT"
] | permissive | samarasteph/compression | 14d32469d6e2f97eaf6047135bd7fd9a0f5101a2 | 6c91d7ee7189969da65721540aea7b3b1f304546 | refs/heads/master | 2020-08-29T03:21:54.203712 | 2020-02-12T22:36:43 | 2020-02-12T22:36:43 | 217,908,902 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | h |
void reset_file(const std::string& path);
void log_code(const std::string& path, int code[]);
void log_bits(const std::string& path, const char bits);
void log_file(const std::string& path, const std::string& str); | [
"aldu@mail.com"
] | aldu@mail.com |
d057a7f359d7cf7df815a4d69171788b783d6f7e | 596d4fc1ff7e87ed7945f99e92d1e8923f9dde1c | /testing_interfaces/ClientNodeTester.hpp | 021c318a4732926b2c42bffc2ceb5da61c48a1c1 | [] | no_license | khetanshu/NetDrive | 3d36e3b3ce0b23ea71214558d6ea128f3d9e3f86 | f37d3e43e453aa2f124c935e68e821a59bb564bb | refs/heads/master | 2020-04-05T19:43:59.357046 | 2018-11-26T01:58:21 | 2018-11-26T01:58:21 | 157,148,064 | 0 | 1 | null | 2018-11-25T20:17:53 | 2018-11-12T02:54:42 | C++ | UTF-8 | C++ | false | false | 305 | hpp | //
// ClientNodeTester.hpp
// NetDrive
//
//
#ifndef ClientNodeTester_hpp
#define ClientNodeTester_hpp
#include "iostream"
#include "ClientNode.hpp"
class ClientNodeTester{
protected:
//TODO : test modules for client node here....
};
#endif /* ClientNodeTester_hpp */
| [
"khetanshu.chauhan@gmail.com"
] | khetanshu.chauhan@gmail.com |
58ba273da588971e60f73c55f777b1f8137a0025 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/cc/trees/layer_tree_host_pixeltest_masks.cc | aac9b10c1947916708a0f36ed470388d81e102e9 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,260 | cc | // Copyright 2013 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 <stddef.h>
#include "base/stl_util.h"
#include "build/build_config.h"
#include "cc/layers/content_layer_client.h"
#include "cc/layers/picture_image_layer.h"
#include "cc/layers/picture_layer.h"
#include "cc/layers/solid_color_layer.h"
#include "cc/paint/paint_flags.h"
#include "cc/paint/paint_image.h"
#include "cc/paint/paint_image_builder.h"
#include "cc/paint/paint_op_buffer.h"
#include "cc/test/fake_picture_layer.h"
#include "cc/test/layer_tree_pixel_resource_test.h"
#include "cc/test/pixel_comparator.h"
#include "cc/test/solid_color_content_layer_client.h"
#include "components/viz/test/test_layer_tree_frame_sink.h"
#include "third_party/skia/include/core/SkImage.h"
#if !defined(OS_ANDROID)
namespace cc {
namespace {
using LayerTreeHostMasksPixelTest = ParameterizedPixelResourceTest;
INSTANTIATE_PIXEL_RESOURCE_TEST_SUITE_P(LayerTreeHostMasksPixelTest);
class MaskContentLayerClient : public ContentLayerClient {
public:
explicit MaskContentLayerClient(const gfx::Size& bounds) : bounds_(bounds) {}
~MaskContentLayerClient() override = default;
bool FillsBoundsCompletely() const override { return false; }
size_t GetApproximateUnsharedMemoryUsage() const override { return 0; }
gfx::Rect PaintableRegion() override { return gfx::Rect(bounds_); }
scoped_refptr<DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting picture_control) override {
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
display_list->push<SaveOp>();
display_list->push<ClipRectOp>(gfx::RectToSkRect(PaintableRegion()),
SkClipOp::kIntersect, false);
SkColor color = SK_ColorTRANSPARENT;
display_list->push<DrawColorOp>(color, SkBlendMode::kSrc);
PaintFlags flags;
flags.setStyle(PaintFlags::kStroke_Style);
flags.setStrokeWidth(SkIntToScalar(2));
flags.setColor(SK_ColorWHITE);
gfx::Rect inset_rect(bounds_);
while (!inset_rect.IsEmpty()) {
inset_rect.Inset(3, 3, 2, 2);
display_list->push<DrawRectOp>(gfx::RectToSkRect(inset_rect), flags);
inset_rect.Inset(3, 3, 2, 2);
}
display_list->push<RestoreOp>();
display_list->EndPaintOfUnpaired(PaintableRegion());
display_list->Finalize();
return display_list;
}
private:
gfx::Size bounds_;
};
TEST_P(LayerTreeHostMasksPixelTest, MaskOfLayer) {
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayerWithBorder(
gfx::Rect(25, 25, 50, 50), kCSSGreen, 1, SK_ColorBLACK);
background->AddChild(green);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
green->SetMaskLayer(mask.get());
RunPixelResourceTest(background,
base::FilePath(FILE_PATH_LITERAL("mask_of_layer.png")));
}
class LayerTreeHostLayerListPixelTest : public ParameterizedPixelResourceTest {
void InitializeSettings(LayerTreeSettings* settings) override {
settings->use_layer_lists = true;
}
};
INSTANTIATE_PIXEL_RESOURCE_TEST_SUITE_P(LayerTreeHostLayerListPixelTest);
TEST_P(LayerTreeHostLayerListPixelTest, MaskWithEffect) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 2;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
RunPixelResourceTestWithLayerList(
root_layer, base::FilePath(FILE_PATH_LITERAL("mask_with_effect.png")),
&property_trees);
}
// This tests that a solid color empty layer with mask effect works correctly.
TEST_P(LayerTreeHostLayerListPixelTest, SolidColorLayerEmptyMaskWithEffect) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 3;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
// Apply a mask that is empty and solid-color. This should result in
// the green layer being entirely clipped out.
gfx::Size mask_bounds(50, 50);
scoped_refptr<SolidColorLayer> mask =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), SK_ColorTRANSPARENT);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(
FILE_PATH_LITERAL("solid_color_empty_mask_with_effect.png")),
&property_trees);
}
class SolidColorEmptyMaskContentLayerClient : public ContentLayerClient {
public:
explicit SolidColorEmptyMaskContentLayerClient(const gfx::Size& bounds)
: bounds_(bounds) {}
~SolidColorEmptyMaskContentLayerClient() override = default;
bool FillsBoundsCompletely() const override { return false; }
size_t GetApproximateUnsharedMemoryUsage() const override { return 0; }
gfx::Rect PaintableRegion() override { return gfx::Rect(bounds_); }
scoped_refptr<DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting picture_control) override {
// Intentionally return a solid color, empty mask display list. This
// is a situation where all content should be masked out.
auto display_list = base::MakeRefCounted<DisplayItemList>();
return display_list;
}
private:
gfx::Size bounds_;
};
TEST_P(LayerTreeHostLayerListPixelTest, SolidColorEmptyMaskWithEffect) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 3;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
// Apply a mask that is empty and solid-color. This should result in
// the green layer being entirely clipped out.
gfx::Size mask_bounds(50, 50);
SolidColorEmptyMaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(
FILE_PATH_LITERAL("solid_color_empty_mask_with_effect.png")),
&property_trees);
}
// same as SolidColorEmptyMaskWithEffect, except the mask has a render surface.
TEST_P(LayerTreeHostLayerListPixelTest,
SolidColorEmptyMaskWithEffectAndRenderSurface) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 3;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
mask_effect.render_surface_reason = RenderSurfaceReason::kTest;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
// Apply a mask that is empty and solid-color. This should result in
// the green layer being entirely clipped out.
gfx::Size mask_bounds(50, 50);
SolidColorEmptyMaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(
FILE_PATH_LITERAL("solid_color_empty_mask_with_effect.png")),
&property_trees);
}
// Tests a situation in which there is no other content in the target
// render surface that the mask applies to. In this situation, the mask
// should have no effect on the rendered output.
TEST_P(LayerTreeHostLayerListPixelTest, MaskWithEffectNoContentToMask) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 2;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorRED);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(0, 0));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(FILE_PATH_LITERAL("mask_with_effect_no_content.png")),
&property_trees);
}
TEST_P(LayerTreeHostLayerListPixelTest, ScaledMaskWithEffect) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 2;
mask_effect.transform_id = 2;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
// Scale the mask with a non-integral transform. This will trigger the
// AA path in the renderer.
TransformNode transform;
transform.local = gfx::Transform();
transform.local.Scale(1.5, 1.5);
property_trees.transform_tree.Insert(transform, 1);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(2);
root_layer->AddChild(mask);
float percentage_pixels_large_error = 2.5f; // 2.5%, ~250px / (100*100)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 100.0f;
int large_error_allowed = 256;
int small_error_allowed = 0;
pixel_comparator_ = std::make_unique<FuzzyPixelComparator>(
true, // discard_alpha
percentage_pixels_large_error, percentage_pixels_small_error,
average_error_allowed_in_bad_pixels, large_error_allowed,
small_error_allowed);
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(FILE_PATH_LITERAL("scaled_mask_with_effect.png")),
&property_trees);
}
TEST_P(LayerTreeHostLayerListPixelTest, MaskWithEffectDifferentSize) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 2;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
gfx::Size mask_bounds(25, 25);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
root_layer->AddChild(mask);
// The mask is half the size of thing it's masking. In layer-list mode,
// the mask is not automatically scaled to match the other layer.
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(FILE_PATH_LITERAL("mask_with_effect_different_size.png")),
&property_trees);
}
TEST_P(LayerTreeHostLayerListPixelTest, ImageMaskWithEffect) {
PropertyTrees property_trees;
scoped_refptr<Layer> root_layer;
InitializeForLayerListMode(&root_layer, &property_trees);
EffectNode isolation_effect;
isolation_effect.clip_id = 1;
isolation_effect.stable_id = 2;
isolation_effect.render_surface_reason = RenderSurfaceReason::kTest;
isolation_effect.transform_id = 1;
property_trees.effect_tree.Insert(isolation_effect, 1);
EffectNode mask_effect;
mask_effect.clip_id = 1;
mask_effect.stable_id = 2;
mask_effect.transform_id = 1;
mask_effect.blend_mode = SkBlendMode::kDstIn;
property_trees.effect_tree.Insert(mask_effect, 2);
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
background->set_property_tree_sequence_number(property_trees.sequence_number);
background->SetClipTreeIndex(1);
background->SetEffectTreeIndex(1);
background->SetScrollTreeIndex(1);
background->SetTransformTreeIndex(1);
root_layer->AddChild(background);
scoped_refptr<SolidColorLayer> green =
CreateSolidColorLayer(gfx::Rect(25, 25, 50, 50), kCSSGreen);
green->set_property_tree_sequence_number(property_trees.sequence_number);
green->SetClipTreeIndex(1);
green->SetEffectTreeIndex(2);
green->SetScrollTreeIndex(1);
green->SetTransformTreeIndex(1);
root_layer->AddChild(green);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureImageLayer> mask = PictureImageLayer::Create();
mask->SetOffsetToTransformParent(gfx::Vector2dF(25, 25));
mask->set_property_tree_sequence_number(property_trees.sequence_number);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetClipTreeIndex(1);
mask->SetEffectTreeIndex(3);
mask->SetScrollTreeIndex(1);
mask->SetTransformTreeIndex(1);
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(200, 200);
SkCanvas* canvas = surface->getCanvas();
canvas->scale(SkIntToScalar(4), SkIntToScalar(4));
scoped_refptr<DisplayItemList> mask_display_list =
client.PaintContentsToDisplayList(
ContentLayerClient::PAINTING_BEHAVIOR_NORMAL);
mask_display_list->Raster(canvas);
mask->SetImage(PaintImageBuilder::WithDefault()
.set_id(PaintImage::GetNextId())
.set_image(surface->makeImageSnapshot(),
PaintImage::GetNextContentId())
.TakePaintImage(),
SkMatrix::I(), false);
root_layer->AddChild(mask);
// The mask is half the size of thing it's masking. In layer-list mode,
// the mask is not automatically scaled to match the other layer.
RunPixelResourceTestWithLayerList(
root_layer,
base::FilePath(FILE_PATH_LITERAL("image_mask_with_effect.png")),
&property_trees);
}
TEST_P(LayerTreeHostMasksPixelTest, ImageMaskOfLayer) {
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
gfx::Size mask_bounds(50, 50);
scoped_refptr<PictureImageLayer> mask = PictureImageLayer::Create();
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
mask->SetBounds(mask_bounds);
sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(200, 200);
SkCanvas* canvas = surface->getCanvas();
canvas->scale(SkIntToScalar(4), SkIntToScalar(4));
MaskContentLayerClient client(mask_bounds);
scoped_refptr<DisplayItemList> mask_display_list =
client.PaintContentsToDisplayList(
ContentLayerClient::PAINTING_BEHAVIOR_NORMAL);
mask_display_list->Raster(canvas);
mask->SetImage(PaintImageBuilder::WithDefault()
.set_id(PaintImage::GetNextId())
.set_image(surface->makeImageSnapshot(),
PaintImage::GetNextContentId())
.TakePaintImage(),
SkMatrix::I(), false);
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayerWithBorder(
gfx::Rect(25, 25, 50, 50), kCSSGreen, 1, SK_ColorBLACK);
green->SetMaskLayer(mask.get());
background->AddChild(green);
RunPixelResourceTest(
background, base::FilePath(FILE_PATH_LITERAL("image_mask_of_layer.png")));
}
TEST_P(LayerTreeHostMasksPixelTest, MaskOfClippedLayer) {
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
// Clip to the top half of the green layer.
scoped_refptr<Layer> clip = Layer::Create();
clip->SetPosition(gfx::PointF());
clip->SetBounds(gfx::Size(100, 50));
clip->SetMasksToBounds(true);
background->AddChild(clip);
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayerWithBorder(
gfx::Rect(25, 25, 50, 50), kCSSGreen, 1, SK_ColorBLACK);
clip->AddChild(green);
gfx::Size mask_bounds(50, 50);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
green->SetMaskLayer(mask.get());
RunPixelResourceTest(
background,
base::FilePath(FILE_PATH_LITERAL("mask_of_clipped_layer.png")));
}
TEST_P(LayerTreeHostMasksPixelTest, MaskOfLayerNonExactTextureSize) {
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(100, 100), SK_ColorWHITE);
scoped_refptr<SolidColorLayer> green = CreateSolidColorLayerWithBorder(
gfx::Rect(0, 0, 100, 100), kCSSGreen, 1, SK_ColorBLACK);
background->AddChild(green);
gfx::Size mask_bounds(100, 100);
MaskContentLayerClient client(mask_bounds);
scoped_refptr<FakePictureLayer> mask = FakePictureLayer::Create(&client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
mask->set_fixed_tile_size(gfx::Size(173, 135));
green->SetMaskLayer(mask.get());
RunPixelResourceTest(background,
base::FilePath(FILE_PATH_LITERAL(
"mask_with_non_exact_texture_size.png")));
}
class CheckerContentLayerClient : public ContentLayerClient {
public:
CheckerContentLayerClient(const gfx::Size& bounds,
SkColor color,
bool vertical)
: bounds_(bounds), color_(color), vertical_(vertical) {}
~CheckerContentLayerClient() override = default;
bool FillsBoundsCompletely() const override { return false; }
size_t GetApproximateUnsharedMemoryUsage() const override { return 0; }
gfx::Rect PaintableRegion() override { return gfx::Rect(bounds_); }
scoped_refptr<DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting picture_control) override {
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
display_list->push<SaveOp>();
display_list->push<ClipRectOp>(gfx::RectToSkRect(PaintableRegion()),
SkClipOp::kIntersect, false);
SkColor color = SK_ColorTRANSPARENT;
display_list->push<DrawColorOp>(color, SkBlendMode::kSrc);
PaintFlags flags;
flags.setStyle(PaintFlags::kStroke_Style);
flags.setStrokeWidth(SkIntToScalar(4));
flags.setColor(color_);
if (vertical_) {
for (int i = 4; i < bounds_.width(); i += 16) {
gfx::PointF p1(i, 0.f);
gfx::PointF p2(i, bounds_.height());
display_list->push<DrawLineOp>(p1.x(), p1.y(), p2.x(), p2.y(), flags);
}
} else {
for (int i = 4; i < bounds_.height(); i += 16) {
gfx::PointF p1(0.f, i);
gfx::PointF p2(bounds_.width(), i);
display_list->push<DrawLineOp>(p1.x(), p1.y(), p2.x(), p2.y(), flags);
}
}
display_list->push<RestoreOp>();
display_list->EndPaintOfUnpaired(PaintableRegion());
display_list->Finalize();
return display_list;
}
private:
gfx::Size bounds_;
SkColor color_;
bool vertical_;
};
class CircleContentLayerClient : public ContentLayerClient {
public:
explicit CircleContentLayerClient(const gfx::Size& bounds)
: bounds_(bounds) {}
~CircleContentLayerClient() override = default;
bool FillsBoundsCompletely() const override { return false; }
size_t GetApproximateUnsharedMemoryUsage() const override { return 0; }
gfx::Rect PaintableRegion() override { return gfx::Rect(bounds_); }
scoped_refptr<DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting picture_control) override {
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
display_list->push<SaveOp>();
display_list->push<ClipRectOp>(gfx::RectToSkRect(PaintableRegion()),
SkClipOp::kIntersect, false);
SkColor color = SK_ColorTRANSPARENT;
display_list->push<DrawColorOp>(color, SkBlendMode::kSrc);
PaintFlags flags;
flags.setStyle(PaintFlags::kFill_Style);
flags.setColor(SK_ColorWHITE);
float radius = bounds_.width() / 4.f;
float circle_x = bounds_.width() / 2.f;
float circle_y = bounds_.height() / 2.f;
display_list->push<DrawOvalOp>(
SkRect::MakeLTRB(circle_x - radius, circle_y - radius,
circle_x + radius, circle_y + radius),
flags);
display_list->push<RestoreOp>();
display_list->EndPaintOfUnpaired(PaintableRegion());
display_list->Finalize();
return display_list;
}
private:
gfx::Size bounds_;
};
using LayerTreeHostMasksForBackdropFiltersPixelTest =
ParameterizedPixelResourceTest;
INSTANTIATE_TEST_SUITE_P(
PixelResourceTest,
LayerTreeHostMasksForBackdropFiltersPixelTest,
::testing::Combine(
::testing::Values(SOFTWARE, GPU, ONE_COPY, ZERO_COPY),
::testing::Values(Layer::LayerMaskType::SINGLE_TEXTURE_MASK,
Layer::LayerMaskType::MULTI_TEXTURE_MASK)));
TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTest,
MaskOfLayerWithBackdropFilter) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(100, 100), SK_ColorWHITE);
gfx::Size picture_bounds(100, 100);
CheckerContentLayerClient picture_client(picture_bounds, SK_ColorGREEN, true);
scoped_refptr<PictureLayer> picture = PictureLayer::Create(&picture_client);
picture->SetBounds(picture_bounds);
picture->SetIsDrawable(true);
scoped_refptr<SolidColorLayer> blur = CreateSolidColorLayer(
gfx::Rect(100, 100), SK_ColorTRANSPARENT);
background->AddChild(picture);
background->AddChild(blur);
FilterOperations filters;
filters.Append(FilterOperation::CreateGrayscaleFilter(1.0));
gfx::RRectF backdrop_filter_bounds;
blur->SetBackdropFilters(filters);
blur->SetBackdropFilterBounds(backdrop_filter_bounds);
gfx::Size mask_bounds(100, 100);
CircleContentLayerClient mask_client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&mask_client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
blur->SetMaskLayer(mask.get());
CHECK_EQ(Layer::LayerMaskType::SINGLE_TEXTURE_MASK, mask->mask_type());
float percentage_pixels_large_error = 2.5f; // 2.5%, ~250px / (100*100)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 100.0f;
int large_error_allowed = 256;
int small_error_allowed = 0;
pixel_comparator_ = std::make_unique<FuzzyPixelComparator>(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed);
base::FilePath image_name =
(test_case_ == GPU)
? base::FilePath(FILE_PATH_LITERAL("mask_of_backdrop_filter_gpu.png"))
: base::FilePath(FILE_PATH_LITERAL("mask_of_backdrop_filter.png"));
RunPixelResourceTest(background, image_name);
}
TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTest, MaskOfLayerWithBlend) {
scoped_refptr<SolidColorLayer> background = CreateSolidColorLayer(
gfx::Rect(128, 128), SK_ColorWHITE);
gfx::Size picture_bounds(128, 128);
CheckerContentLayerClient picture_client_vertical(
picture_bounds, SK_ColorGREEN, true);
scoped_refptr<PictureLayer> picture_vertical =
PictureLayer::Create(&picture_client_vertical);
picture_vertical->SetBounds(picture_bounds);
picture_vertical->SetIsDrawable(true);
CheckerContentLayerClient picture_client_horizontal(
picture_bounds, SK_ColorMAGENTA, false);
scoped_refptr<PictureLayer> picture_horizontal =
PictureLayer::Create(&picture_client_horizontal);
picture_horizontal->SetBounds(picture_bounds);
picture_horizontal->SetIsDrawable(true);
picture_horizontal->SetContentsOpaque(false);
picture_horizontal->SetBlendMode(SkBlendMode::kMultiply);
background->AddChild(picture_vertical);
background->AddChild(picture_horizontal);
gfx::Size mask_bounds(128, 128);
CircleContentLayerClient mask_client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&mask_client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
picture_horizontal->SetMaskLayer(mask.get());
float percentage_pixels_large_error = 0.04f; // 0.04%, ~6px / (128*128)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 256.0f;
int large_error_allowed = 256;
int small_error_allowed = 0;
pixel_comparator_ = std::make_unique<FuzzyPixelComparator>(
true, // discard_alpha
percentage_pixels_large_error,
percentage_pixels_small_error,
average_error_allowed_in_bad_pixels,
large_error_allowed,
small_error_allowed);
RunPixelResourceTest(background,
base::FilePath(
FILE_PATH_LITERAL("mask_of_layer_with_blend.png")));
}
class StaticPictureLayer : private ContentLayerClient, public PictureLayer {
public:
static scoped_refptr<StaticPictureLayer> Create(
scoped_refptr<DisplayItemList> display_list) {
return base::WrapRefCounted(
new StaticPictureLayer(std::move(display_list)));
}
gfx::Rect PaintableRegion() override { return gfx::Rect(bounds()); }
scoped_refptr<DisplayItemList> PaintContentsToDisplayList(
PaintingControlSetting) override {
return display_list_;
}
bool FillsBoundsCompletely() const override { return false; }
size_t GetApproximateUnsharedMemoryUsage() const override { return 0; }
protected:
explicit StaticPictureLayer(scoped_refptr<DisplayItemList> display_list)
: PictureLayer(this), display_list_(std::move(display_list)) {}
~StaticPictureLayer() override = default;
private:
scoped_refptr<DisplayItemList> display_list_;
};
class LayerTreeHostMaskAsBlendingPixelTest
: public LayerTreeHostPixelResourceTest,
public ::testing::WithParamInterface<int> {
public:
LayerTreeHostMaskAsBlendingPixelTest()
: LayerTreeHostPixelResourceTest(
GetParam() ? ZERO_COPY : SOFTWARE,
Layer::LayerMaskType::SINGLE_TEXTURE_MASK),
use_antialiasing_(GetParam() == 2 || GetParam() == 4),
force_shaders_(GetParam() == 3 || GetParam() == 4) {
float percentage_pixels_small_error = 0.f;
float percentage_pixels_error = 0.f;
float average_error_allowed_in_bad_pixels = 0.f;
int large_error_allowed = 0;
int small_error_allowed = 0;
if (use_antialiasing_) {
percentage_pixels_small_error = 0.9f;
percentage_pixels_error = 6.7f;
average_error_allowed_in_bad_pixels = 3.5f;
large_error_allowed = 15;
small_error_allowed = 1;
} else if (test_type_ != PIXEL_TEST_SOFTWARE) {
percentage_pixels_small_error = 0.9f;
percentage_pixels_error = 6.5f;
average_error_allowed_in_bad_pixels = 3.5f;
large_error_allowed = 15;
small_error_allowed = 1;
} else {
#if defined(ARCH_CPU_ARM64)
// Differences in floating point calculation on ARM means a small
// percentage of pixels will be off by 1.
percentage_pixels_error = 0.112f;
average_error_allowed_in_bad_pixels = 1.f;
large_error_allowed = 1;
#endif
}
pixel_comparator_ = std::make_unique<FuzzyPixelComparator>(
false, // discard_alpha
percentage_pixels_error, percentage_pixels_small_error,
average_error_allowed_in_bad_pixels, large_error_allowed,
small_error_allowed);
}
static scoped_refptr<Layer> CreateCheckerboardLayer(const gfx::Size& bounds) {
constexpr int kGridSize = 8;
static const SkColor color_even = SkColorSetRGB(153, 153, 153);
static const SkColor color_odd = SkColorSetRGB(102, 102, 102);
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
display_list->push<DrawColorOp>(color_even, SkBlendMode::kSrc);
PaintFlags flags;
flags.setColor(color_odd);
for (int j = 0; j < (bounds.height() + kGridSize - 1) / kGridSize; j++) {
for (int i = 0; i < (bounds.width() + kGridSize - 1) / kGridSize; i++) {
bool is_odd_grid = (i ^ j) & 1;
if (!is_odd_grid)
continue;
display_list->push<DrawRectOp>(
SkRect::MakeXYWH(i * kGridSize, j * kGridSize, kGridSize,
kGridSize),
flags);
}
}
display_list->EndPaintOfUnpaired(gfx::Rect(bounds));
display_list->Finalize();
scoped_refptr<Layer> layer =
StaticPictureLayer::Create(std::move(display_list));
layer->SetIsDrawable(true);
layer->SetBounds(bounds);
return layer;
}
static scoped_refptr<Layer> CreateTestPatternLayer(const gfx::Size& bounds,
int grid_size) {
// Creates a layer consists of solid grids. The grids are in a mix of
// different transparency and colors (1 transparent, 3 semi-transparent,
// and 3 opaque).
static SkColor test_colors[7] = {
SkColorSetARGB(128, 255, 0, 0), SkColorSetARGB(255, 0, 0, 255),
SkColorSetARGB(128, 0, 255, 0), SkColorSetARGB(128, 0, 0, 255),
SkColorSetARGB(255, 0, 255, 0), SkColorSetARGB(0, 0, 0, 0),
SkColorSetARGB(255, 255, 0, 0)};
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
for (int j = 0; j < (bounds.height() + grid_size - 1) / grid_size; j++) {
for (int i = 0; i < (bounds.width() + grid_size - 1) / grid_size; i++) {
PaintFlags flags;
flags.setColor(test_colors[(i + j * 3) % base::size(test_colors)]);
display_list->push<DrawRectOp>(
SkRect::MakeXYWH(i * grid_size, j * grid_size, grid_size,
grid_size),
flags);
}
}
display_list->EndPaintOfUnpaired(gfx::Rect(bounds));
display_list->Finalize();
scoped_refptr<Layer> layer =
StaticPictureLayer::Create(std::move(display_list));
layer->SetIsDrawable(true);
layer->SetBounds(bounds);
return layer;
}
protected:
std::unique_ptr<viz::TestLayerTreeFrameSink> CreateLayerTreeFrameSink(
const viz::RendererSettings& renderer_settings,
double refresh_rate,
scoped_refptr<viz::ContextProvider> compositor_context_provider,
scoped_refptr<viz::RasterContextProvider> worker_context_provider)
override {
viz::RendererSettings modified_renderer_settings = renderer_settings;
modified_renderer_settings.force_antialiasing = use_antialiasing_;
modified_renderer_settings.force_blending_with_shaders = force_shaders_;
return LayerTreeHostPixelResourceTest::CreateLayerTreeFrameSink(
modified_renderer_settings, refresh_rate,
std::move(compositor_context_provider),
std::move(worker_context_provider));
}
bool use_antialiasing_;
bool force_shaders_;
};
INSTANTIATE_TEST_SUITE_P(All,
LayerTreeHostMaskAsBlendingPixelTest,
::testing::Range(0, 5));
// Instantiate 5 test modes of the following:
// 0: SOFTWARE (golden sample)
// 1: GL
// 2: GL + AA
// 3: GL + Forced Shaders
// 4: GL + Forced Shaders + AA
TEST_P(LayerTreeHostMaskAsBlendingPixelTest, PixelAlignedNoop) {
// This test verifies the degenerate case of a no-op mask doesn't affect
// the contents in any way.
scoped_refptr<Layer> root = CreateCheckerboardLayer(gfx::Size(400, 300));
scoped_refptr<Layer> mask_isolation = Layer::Create();
mask_isolation->SetPosition(gfx::PointF(20, 20));
mask_isolation->SetBounds(gfx::Size(350, 250));
mask_isolation->SetMasksToBounds(true);
mask_isolation->SetIsRootForIsolatedGroup(true);
root->AddChild(mask_isolation);
scoped_refptr<Layer> content =
CreateTestPatternLayer(gfx::Size(400, 300), 25);
content->SetPosition(gfx::PointF(-40, -40));
mask_isolation->AddChild(content);
scoped_refptr<Layer> mask_layer =
CreateSolidColorLayer(gfx::Rect(350, 250), kCSSBlack);
mask_layer->SetBlendMode(SkBlendMode::kDstIn);
mask_isolation->AddChild(mask_layer);
RunPixelResourceTest(
root, base::FilePath(FILE_PATH_LITERAL("mask_as_blending_noop.png")));
}
TEST_P(LayerTreeHostMaskAsBlendingPixelTest, PixelAlignedClippedCircle) {
// This test verifies a simple pixel aligned mask applies correctly.
scoped_refptr<Layer> root = CreateCheckerboardLayer(gfx::Size(400, 300));
scoped_refptr<Layer> mask_isolation = Layer::Create();
mask_isolation->SetPosition(gfx::PointF(20, 20));
mask_isolation->SetBounds(gfx::Size(350, 250));
mask_isolation->SetMasksToBounds(true);
mask_isolation->SetIsRootForIsolatedGroup(true);
root->AddChild(mask_isolation);
scoped_refptr<Layer> content =
CreateTestPatternLayer(gfx::Size(400, 300), 25);
content->SetPosition(gfx::PointF(-40, -40));
mask_isolation->AddChild(content);
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
PaintFlags flags;
flags.setColor(kCSSBlack);
flags.setAntiAlias(true);
display_list->push<DrawOvalOp>(SkRect::MakeXYWH(-5, -55, 360, 360), flags);
display_list->EndPaintOfUnpaired(gfx::Rect(-5, -55, 360, 360));
display_list->Finalize();
scoped_refptr<Layer> mask_layer =
StaticPictureLayer::Create(std::move(display_list));
mask_layer->SetIsDrawable(true);
mask_layer->SetBounds(gfx::Size(350, 250));
mask_layer->SetBlendMode(SkBlendMode::kDstIn);
mask_isolation->AddChild(mask_layer);
RunPixelResourceTest(
root, base::FilePath(FILE_PATH_LITERAL("mask_as_blending_circle.png")));
}
TEST_P(LayerTreeHostMaskAsBlendingPixelTest,
PixelAlignedClippedCircleUnderflow) {
// This test verifies a simple pixel aligned mask applies correctly when
// the content is smaller than the mask.
scoped_refptr<Layer> root = CreateCheckerboardLayer(gfx::Size(400, 300));
scoped_refptr<Layer> mask_isolation = Layer::Create();
mask_isolation->SetPosition(gfx::PointF(20, 20));
mask_isolation->SetBounds(gfx::Size(350, 250));
mask_isolation->SetMasksToBounds(true);
mask_isolation->SetIsRootForIsolatedGroup(true);
root->AddChild(mask_isolation);
scoped_refptr<Layer> content =
CreateTestPatternLayer(gfx::Size(330, 230), 25);
content->SetPosition(gfx::PointF(10, 10));
mask_isolation->AddChild(content);
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
PaintFlags flags;
flags.setColor(kCSSBlack);
flags.setAntiAlias(true);
display_list->push<DrawOvalOp>(SkRect::MakeXYWH(-5, -55, 360, 360), flags);
display_list->EndPaintOfUnpaired(gfx::Rect(-5, -55, 360, 360));
display_list->Finalize();
scoped_refptr<Layer> mask_layer =
StaticPictureLayer::Create(std::move(display_list));
mask_layer->SetIsDrawable(true);
mask_layer->SetBounds(gfx::Size(350, 250));
mask_layer->SetBlendMode(SkBlendMode::kDstIn);
mask_isolation->AddChild(mask_layer);
RunPixelResourceTest(root, base::FilePath(FILE_PATH_LITERAL(
"mask_as_blending_circle_underflow.png")));
}
TEST_P(LayerTreeHostMaskAsBlendingPixelTest, RotatedClippedCircle) {
// This test verifies a simple pixel aligned mask that is not pixel aligned
// to its target surface is rendered correctly.
scoped_refptr<Layer> root = CreateCheckerboardLayer(gfx::Size(400, 300));
scoped_refptr<Layer> mask_isolation = Layer::Create();
mask_isolation->SetPosition(gfx::PointF(20, 20));
{
gfx::Transform rotate;
rotate.Rotate(5.f);
mask_isolation->SetTransform(rotate);
}
mask_isolation->SetBounds(gfx::Size(350, 250));
mask_isolation->SetMasksToBounds(true);
mask_isolation->SetIsRootForIsolatedGroup(true);
root->AddChild(mask_isolation);
scoped_refptr<Layer> content =
CreateTestPatternLayer(gfx::Size(400, 300), 25);
content->SetPosition(gfx::PointF(-40, -40));
mask_isolation->AddChild(content);
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
PaintFlags flags;
flags.setColor(kCSSBlack);
flags.setAntiAlias(true);
display_list->push<DrawOvalOp>(SkRect::MakeXYWH(-5, -55, 360, 360), flags);
display_list->EndPaintOfUnpaired(gfx::Rect(-5, -55, 360, 360));
display_list->Finalize();
scoped_refptr<Layer> mask_layer =
StaticPictureLayer::Create(std::move(display_list));
mask_layer->SetIsDrawable(true);
mask_layer->SetBounds(gfx::Size(350, 250));
mask_layer->SetBlendMode(SkBlendMode::kDstIn);
mask_isolation->AddChild(mask_layer);
base::FilePath image_name =
(test_type_ == PIXEL_TEST_SOFTWARE)
? base::FilePath(
FILE_PATH_LITERAL("mask_as_blending_rotated_circle.png"))
: base::FilePath(
FILE_PATH_LITERAL("mask_as_blending_rotated_circle_gl.png"));
RunPixelResourceTest(root, image_name);
}
TEST_P(LayerTreeHostMaskAsBlendingPixelTest, RotatedClippedCircleUnderflow) {
// This test verifies a simple pixel aligned mask that is not pixel aligned
// to its target surface, and has the content smaller than the mask, is
// rendered correctly.
scoped_refptr<Layer> root = CreateCheckerboardLayer(gfx::Size(400, 300));
scoped_refptr<Layer> mask_isolation = Layer::Create();
mask_isolation->SetPosition(gfx::PointF(20, 20));
{
gfx::Transform rotate;
rotate.Rotate(5.f);
mask_isolation->SetTransform(rotate);
}
mask_isolation->SetBounds(gfx::Size(350, 250));
mask_isolation->SetMasksToBounds(true);
mask_isolation->SetIsRootForIsolatedGroup(true);
root->AddChild(mask_isolation);
scoped_refptr<Layer> content =
CreateTestPatternLayer(gfx::Size(330, 230), 25);
content->SetPosition(gfx::PointF(10, 10));
mask_isolation->AddChild(content);
auto display_list = base::MakeRefCounted<DisplayItemList>();
display_list->StartPaint();
PaintFlags flags;
flags.setColor(kCSSBlack);
flags.setAntiAlias(true);
display_list->push<DrawOvalOp>(SkRect::MakeXYWH(-5, -55, 360, 360), flags);
display_list->EndPaintOfUnpaired(gfx::Rect(-5, -55, 360, 360));
display_list->Finalize();
scoped_refptr<Layer> mask_layer =
StaticPictureLayer::Create(std::move(display_list));
mask_layer->SetIsDrawable(true);
mask_layer->SetBounds(gfx::Size(350, 250));
mask_layer->SetBlendMode(SkBlendMode::kDstIn);
mask_isolation->AddChild(mask_layer);
base::FilePath image_name =
(test_type_ == PIXEL_TEST_SOFTWARE)
? base::FilePath(FILE_PATH_LITERAL(
"mask_as_blending_rotated_circle_underflow.png"))
: base::FilePath(FILE_PATH_LITERAL(
"mask_as_blending_rotated_circle_underflow_gl.png"));
RunPixelResourceTest(root, image_name);
}
TEST_P(LayerTreeHostMasksForBackdropFiltersPixelTest,
MaskOfLayerWithBackdropFilterAndBlend) {
scoped_refptr<SolidColorLayer> background =
CreateSolidColorLayer(gfx::Rect(128, 128), SK_ColorWHITE);
gfx::Size picture_bounds(128, 128);
CheckerContentLayerClient picture_client_vertical(picture_bounds,
SK_ColorGREEN, true);
scoped_refptr<PictureLayer> picture_vertical =
PictureLayer::Create(&picture_client_vertical);
picture_vertical->SetBounds(picture_bounds);
picture_vertical->SetIsDrawable(true);
CheckerContentLayerClient picture_client_horizontal(picture_bounds,
SK_ColorMAGENTA, false);
scoped_refptr<PictureLayer> picture_horizontal =
PictureLayer::Create(&picture_client_horizontal);
picture_horizontal->SetBounds(picture_bounds);
picture_horizontal->SetIsDrawable(true);
picture_horizontal->SetContentsOpaque(false);
picture_horizontal->SetBlendMode(SkBlendMode::kMultiply);
FilterOperations filters;
filters.Append(FilterOperation::CreateGrayscaleFilter(1.0));
picture_horizontal->SetBackdropFilters(filters);
gfx::RRectF backdrop_filter_bounds;
picture_horizontal->SetBackdropFilterBounds(backdrop_filter_bounds);
background->AddChild(picture_vertical);
background->AddChild(picture_horizontal);
gfx::Size mask_bounds(128, 128);
CircleContentLayerClient mask_client(mask_bounds);
scoped_refptr<PictureLayer> mask = PictureLayer::Create(&mask_client);
mask->SetBounds(mask_bounds);
mask->SetIsDrawable(true);
mask->SetLayerMaskType(mask_type_);
picture_horizontal->SetMaskLayer(mask.get());
float percentage_pixels_large_error = 0.062f; // 0.062%, ~10px / (128*128)
float percentage_pixels_small_error = 0.0f;
float average_error_allowed_in_bad_pixels = 200.0f;
int large_error_allowed = 256;
int small_error_allowed = 0;
pixel_comparator_ = std::make_unique<FuzzyPixelComparator>(
true, // discard_alpha
percentage_pixels_large_error, percentage_pixels_small_error,
average_error_allowed_in_bad_pixels, large_error_allowed,
small_error_allowed);
RunPixelResourceTest(background,
base::FilePath(FILE_PATH_LITERAL(
"mask_of_backdrop_filter_and_blend.png")));
}
} // namespace
} // namespace cc
#endif // !defined(OS_ANDROID)
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
280254174600a3a7bd8ad6e15a018b259905e20d | d43e481b31d5f8afe1fdb6f45d55a5f8924fff01 | /InvoiceClass/Source.cpp | da19b6a263eff2ddc7e250da3eb3aec64081463c | [] | no_license | darthbatman/MCA_ECET11-InvoiceClass | 4121bb3cae6e29679e3adb4b68a0412f59b5fefa | 9211f15bf5d2660946c98375fda70c164feae4f7 | refs/heads/master | 2020-09-17T02:30:13.002385 | 2016-08-30T02:55:30 | 2016-08-30T02:55:30 | 66,900,870 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,305 | cpp | #include <iostream>;
#include <iomanip>;
#include <string>;
using namespace std;
class Invoice{
private:
string partNumber;
string partDescription;
int itemQuantity;
int pricePerItem;
public:
Invoice(string, string, int, int);
void setPartNumber(string);
void setPartDescription(string);
void setItemQuantity(int);
void setPricePerItem(int);
string getPartNumber();
string getPartDescription();
int getItemQuantity();
int getPricePerItem();
int getInvoiceAmount();
};
Invoice::Invoice(string pN, string pD, int iQ, int pPI){
partNumber = pN;
partDescription = pD;
itemQuantity = iQ;
pricePerItem = pPI;
}
void Invoice::setPartNumber(string pN){
partNumber = pN;
}
void Invoice::setPartDescription(string pD){
partDescription = pD;
}
void Invoice::setItemQuantity(int iQ){
if (iQ >= 0){
itemQuantity = iQ;
}
else {
itemQuantity = 0;
}
}
void Invoice::setPricePerItem(int pPI){
if (pPI >= 0){
pricePerItem = pPI;
}
else {
pricePerItem = 0;
}
}
string Invoice::getPartNumber(){
return partNumber;
}
string Invoice::getPartDescription(){
return partDescription;
}
int Invoice::getItemQuantity(){
return itemQuantity;
}
int Invoice::getPricePerItem(){
return pricePerItem;
}
int Invoice::getInvoiceAmount(){
return itemQuantity * pricePerItem;
}
int main(){
string tempNumber;
string tempDescription;
int tempQuantity;
int tempPricePerItem;
cout << "Enter Part Number: ";
getline(cin, tempNumber);
cout << "Enter Part Description: ";
getline(cin, tempDescription);
cout << "Enter number of items: ";
cin >> tempQuantity;
cout << "Enter price per item: $";
cin >> tempPricePerItem;
Invoice i(tempNumber, tempDescription, tempQuantity, tempPricePerItem);
cout << endl;
cout << "Invoice: " << endl;
cout << endl;
cout << setw(4) << "Part Number: " << i.getPartNumber() << endl;
cout << setw(4) << "Part Description: " << i.getPartDescription() << endl;
cout << setw(4) << "Item Quantity: " << i.getItemQuantity() << endl;
cout << setw(4) << "Price Per Item: $" << i.getPricePerItem() << endl;
cout << endl;
cout << setw(4) << "Invoice Amount: $" << i.getInvoiceAmount() << endl;
cout << endl;
return 0;
} | [
"darthanakin44@gmail.com"
] | darthanakin44@gmail.com |
a8237871347a0eb06603ba113cd399a1a34d4fdc | fee340a013f0d482034d0a5790df9bf05c0af668 | /test/3dMethods.cpp | adb06034bd571a18108e2a160d381659e4e52eb8 | [] | no_license | jdilla52/3d-methods-cpp | 69b97ec6d96a0c50c61a4405fe4e6d2630138ee6 | 3b42a5d8bbf4028fd1c23cc5b473e0b6e257f9b9 | refs/heads/main | 2023-08-28T09:02:39.012340 | 2021-10-08T14:56:24 | 2021-10-08T14:56:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 767 | cpp | //
// Created by Jacques Perrault on 10/2/21.
//
#include <catch2/catch.hpp>
#include <iostream>
#include <Eigen/Dense>
#include <3dMethods/pca.h>
using namespace Eigen;
using namespace std;
SCENARIO("pca", "[pca.h]")
{
MatrixXd mat(4, 3);
mat << 1, 1, 1, -2, -1, -1, 1.2, 1.2, 1.2, 21, 21, 21;
auto j = Pca(mat);
cout << "eigenValues:\n" << get<0>(j) << endl;
cout << "eigen vectors: \n" << get<1>(j) << endl;
// make some real test data
}
SCENARIO("findRigidTransform", "[pca.h]")
{
MatrixXd source(2, 3);
source << 1, 1, 1, -1, -1, -1;
MatrixXd target(2, 3);
target << -1, -1, -1, 2, 2, 2;
auto out = findRigidTransform(source, target);
cout << "rotation: \n" << get<0>(out) << endl;
cout << "translation: \n" << get<1>(out) << endl;
} | [
"jacques.perrault@branch.technology"
] | jacques.perrault@branch.technology |
0a5b622c1210f5fbea4c8a7c5a92b5267909ac40 | 0df48df9ed35e5995af25812137dc0d9d42f96dc | /Arduino_package/hardware/libraries/WiFi/examples/Facebook/facebook_upload_uvc_jpeg/facebook_upload_uvc_jpeg.ino | e4fcbe342945c2c2d9cc7a1ac974b0046ab4ae97 | [] | no_license | ambiot/amb1_arduino | 81539be6ba18a13cc2a33ec37021c5b27684e047 | 16720c2dcbcffa2acee0c9fe973a959cafc3ba8c | refs/heads/dev | 2023-06-08T15:27:52.848876 | 2023-06-07T02:38:24 | 2023-06-07T02:38:24 | 232,280,578 | 9 | 7 | null | 2022-06-01T08:51:01 | 2020-01-07T08:37:52 | C | UTF-8 | C++ | false | false | 3,395 | ino | /*
In this sketch, it assumed you already have a user access token with "publish_actions" scopes.
Using this token you can get a jpeg from a uvc and post it into facebook feed.
If you never use facebook graph api, please refer below tutorial as warm up:
https://www.amebaiot.com/ameba-arduino-facebook/
If you don't have access token, please reference below to get one:
https://developers.facebook.com/tools/explorer/
And you need these access right to publish on feed:
https://developers.facebook.com/docs/graph-api/reference/v2.8/user/feed
If you already have one, using link blow to check the access right:
https://developers.facebook.com/tools/debug/accesstoken
You can also extend the expire time of access token in this page.
*/
#include <WiFi.h>
#include <UVC.h>
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
char server[] = "graph.facebook.com"; // facebook graph api service
char access_token[] = "EAAEcZAcqQqtUBAPsfzwk1KxTNv2WwaasZAVvcqPXeAUwssSfUhZBen4I65BIUY7gedZC63V3wos0JFYZCcp26ZCXVwO3cZAGAeuZAOvozhBTZBoDUUZCqUCPGZARbP8gFYDQsGPz2tO8ctpTxnqCrN3YbPFyGswbhclOECXrzj1vFzstxGd2Y2ezslpKVdOYa19rp7DOHR0miNk3QZDZD";
WiFiSSLClient client;
int chunkSize = 1446;
#define BOUNDARY "-----boundary12345"
char data_file_header[] = \
"--" BOUNDARY "\r\n" \
"Content-Disposition: form-data; name=\"source\"; filename=\"test.jpg\"\r\n" \
"Content-Type: application/octet-stream\r\n\r\n";
char data_end[] = "\r\n--" BOUNDARY "--\r\n";
unsigned char jpegbuf[40 * 1024];
void setup() {
// attempt to connect to Wifi network:
while (WiFi.begin(ssid, pass) != WL_CONNECTED) {
delay(1000);
}
Serial.println("Connected to wifi");
UVC.begin(UVC_MJPEG, 320, 240, 30, 0, JPEG_CAPTURE);
// wait until UVC is ready for streaming
while (!UVC.available()) {
delay(100);
}
delay(1000);
Serial.println("UVC is ready");
}
void loop() {
int i;
int len = UVC.getJPEG(jpegbuf);
int contentlen = strlen(data_file_header) + len + strlen(data_end);
if (len > 0) {
while (1) {
if (!client.connect(server, 443)) {
Serial.println("Connect to server failed. Retry after 1s.");
client.stop();
delay(1000);
continue;
}
Serial.println("connected to server");
// Make a HTTP request:
client.print("POST /v2.9/me/photos?access_token=");
client.print(access_token);
client.println(" HTTP/1.1");
client.print("Host: ");
client.println(server);
client.println("Content-Type: multipart/form-data; boundary=" BOUNDARY);
client.print("Content-Length: ");
client.println(contentlen);
client.println();
// upload photo as file
client.write(data_file_header, strlen(data_file_header));
for (i = 0; i < len; i += chunkSize) {
client.write(jpegbuf + i, (i+chunkSize <= len) ? chunkSize : len - i);
}
client.write(data_end, strlen(data_end));
Serial.println("photo has been uploaded");
// try to get response
while (!client.available()) delay(100);
while (client.available()) {
char c = client.read();
Serial.write(c);
}
client.stop();
break;
}
}
delay(60 * 1000);
} | [
"zhangzhenwu@realtek-sg.com"
] | zhangzhenwu@realtek-sg.com |
c53b617b15e9714c3ccfb7ccac9199bf0dd6c26e | 5792b184e71a9de7779e0bd21b6833f8ddfdb4b5 | /sysvr4/svr4/cmd/sdb/inc/common/Rvalue.h | c66531205f81117709d021971546e0b581d4d28c | [] | no_license | ryanwoodsmall/oldsysv | 1637a3e62bb1b9426a224e832f44a46f1e1a31d4 | e68293af91e2dc39f5f29c20d7e429f9e0cabc75 | refs/heads/master | 2020-03-30T06:06:30.495611 | 2018-09-29T09:04:59 | 2018-09-29T09:04:59 | 150,839,670 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,593 | h | /* Copyright (c) 1990 UNIX System Laboratories, Inc. */
/* Copyright (c) 1988 AT&T */
/* All Rights Reserved */
/* THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF */
/* UNIX System Laboratories, Inc. */
/* The copyright notice above does not evidence any */
/* actual or intended publication of such source code. */
#ident "@(#)sdb:inc/common/Rvalue.h 1.4"
// Rvalue.h -- generic "R" values; objects which are the result of an
// expression evaluation. Includes fundamental types, structs, unions,
// and arrays.
//
// The bytes are held in a Itype or Vector, and the type of the value in a TYPE.
#ifndef RVALUE_H
#define RVALUE_H
#include "Vector.h"
#include "TYPE.h"
#include "Itype.h"
class Obj_info;
class Process;
class Rvalue {
TYPE _type;
Vector raw_bytes;
Stype stype; // valid if raw_bytes.size() == 0
Itype itype; // valid if stype != SINVALID
int rep; // number of instances of object, if multiple
public:
Rvalue() {}
Rvalue(Stype, Itype &);
Rvalue(void *, int, TYPE &, int rep = 1);
Rvalue(Iaddr);
Rvalue(Rvalue &);
~Rvalue();
Rvalue& operator=(Rvalue &);
int operator==(Rvalue &);
int operator!=(Rvalue &v) { return !(*this == v); }
void null() { raw_bytes.clear(); _type.null(); }
int isnull() { return _type.isnull(); }
TYPE& type() { return _type; }
unsigned char *raw();
long size();
Stype get_Itype(Itype &); // SINVALID if cannot get as Itype member.
int print(char *label = 0, char *fmt = 0, char *sep = 0);
};
#endif
| [
"rwoodsmall@gmail.com"
] | rwoodsmall@gmail.com |
d46fcf95e398256fd36ac14e23ebffdc7951234b | 67e5d8bdbbeb0d093f21d48f0e6b724339594a8e | /resip/recon/Participant.cxx | 8c61aa2c12813b464fff42cda1436ca88b8373c5 | [
"BSD-3-Clause",
"VSL-1.0",
"BSD-2-Clause"
] | permissive | heibao111728/resiprocate-1.8.14 | 7e5e46a04bfef72e95852a598774cb8d5aa0d699 | f8ddf70a6b7620fb535baec04901a4912172d4ed | refs/heads/master | 2020-04-16T01:48:14.942715 | 2019-11-09T14:29:12 | 2019-11-09T14:29:12 | 145,299,918 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,237 | cxx | #include "ConversationManager.hxx"
#include "ReconSubsystem.hxx"
#include "Participant.hxx"
#include "Conversation.hxx"
#include "UserAgent.hxx"
#include <rutil/Log.hxx>
#include <rutil/Logger.hxx>
using namespace recon;
using namespace resip;
using namespace std;
#define RESIPROCATE_SUBSYSTEM ReconSubsystem::RECON
Participant::Participant(ParticipantHandle partHandle,
ConversationManager& conversationManager)
: mHandle(partHandle),
mConversationManager(conversationManager)
{
mConversationManager.registerParticipant(this);
//InfoLog(<< "Participant created, handle=" << mHandle);
}
Participant::Participant(ConversationManager& conversationManager)
: mHandle(0),
mConversationManager(conversationManager)
{
setHandle(mConversationManager.getNewParticipantHandle());
//InfoLog(<< "Participant created, handle=" << mHandle);
}
Participant::~Participant()
{
// Note: We cannot call Conversation::unregisterParticipant here, since dynamic_cast in the fn will not work -
// thus unregister must be implemented in sub-classes destructors (see ~LocalParticipant and ~RemoteParticipant)
//InfoLog(<< "Participant destroyed, handle=" << mHandle);
if(mHandle != 0) mConversationManager.onParticipantDestroyed(mHandle);
setHandle(0); // unregister from Conversation Manager
}
void
Participant::setHandle(ParticipantHandle partHandle)
{
if(mHandle == partHandle) return; // already set
// unregister old handle if set
if(mHandle)
{
mConversationManager.unregisterParticipant(this);
}
mHandle = partHandle;
if(mHandle)
{
mConversationManager.registerParticipant(this);
}
}
void
Participant::addToConversation(Conversation* conversation, unsigned int inputGain, unsigned int outputGain)
{
assert(conversation);
if(mConversations.find(conversation->getHandle()) != mConversations.end()) return; // already present
mConversations[conversation->getHandle()] = conversation;
conversation->registerParticipant(this, inputGain, outputGain);
}
void
Participant::removeFromConversation(Conversation *conversation)
{
assert(conversation);
//InfoLog(<< "Participant handle=" << mHandle << " removed from conversation=" << conversation->getHandle());
mConversations.erase(conversation->getHandle()); // Note: this must come before next line - since unregisterParticipant may end up destroying conversation
conversation->unregisterParticipant(this);
}
void
Participant::copyConversationsToParticipant(Participant* destParticipant)
{
ConversationMap::iterator it;
for(it = mConversations.begin(); it != mConversations.end(); it++)
{
destParticipant->addToConversation(it->second); // Will over-write our entry in the conversations participant map
}
}
void
Participant::replaceWithParticipant(Participant* replacingParticipant)
{
replacingParticipant->setHandle(mHandle); // Set handle on replacing participant
copyConversationsToParticipant(replacingParticipant); // Will over-write our entry in the conversations participant map
Conversation* firstAssociatedConversation=0;
if(mConversations.size() > 0)
{
// If we are running in sipXConversationMediaInterfaceMode, then the call to applyBridgeMixWeights below must be
// passed a conversation pointer, since this participant will not be able to find the appropriate
// BridgeMixer after it's conversation list is cleared.
firstAssociatedConversation = mConversations.begin()->second;
}
mConversations.clear(); // Clear so that we won't remove replaced reference from Conversation
mHandle = 0; // Set to 0 so that we won't remove replaced reference from ConversationManager
assert(mConversationManager.getMediaInterfaceMode() == ConversationManager::sipXGlobalMediaInterfaceMode || // We are either running in sipXGlobalMediaInterfaceMode
firstAssociatedConversation != 0); // or we are running in sipXConversationMediaInterfaceMode and must have belonged to a conversation
applyBridgeMixWeights(firstAssociatedConversation); // Ensure we remove ourselves from the bridge port matrix
}
SharedPtr<MediaInterface>
Participant::getMediaInterface()
{
switch(mConversationManager.getMediaInterfaceMode())
{
case ConversationManager::sipXGlobalMediaInterfaceMode:
assert(mConversationManager.getMediaInterface() != 0);
return mConversationManager.getMediaInterface();
case ConversationManager::sipXConversationMediaInterfaceMode:
assert(mConversations.size() == 1);
assert(mConversations.begin()->second->getMediaInterface() != 0);
return mConversations.begin()->second->getMediaInterface();
default:
assert(false);
return SharedPtr<MediaInterface>((MediaInterface*)0);
}
}
void
Participant::applyBridgeMixWeights()
{
BridgeMixer* mixer=0;
switch(mConversationManager.getMediaInterfaceMode())
{
case ConversationManager::sipXGlobalMediaInterfaceMode:
assert(mConversationManager.getBridgeMixer() != 0);
mixer = mConversationManager.getBridgeMixer();
break;
case ConversationManager::sipXConversationMediaInterfaceMode:
assert(mConversations.size() == 1);
assert(mConversations.begin()->second->getBridgeMixer() != 0);
mixer = mConversations.begin()->second->getBridgeMixer();
break;
default:
break;
}
assert(mixer);
if(mixer)
{
mixer->calculateMixWeightsForParticipant(this);
}
}
// Special version of this call used only when a participant
// is removed from a conversation. Required when sipXConversationMediaInterfaceMode
// is used, in order to get a pointer to the bridge mixer
// for a participant (ie. LocalParticipant) that has no currently
// assigned conversations.
void
Participant::applyBridgeMixWeights(Conversation* removedConversation)
{
BridgeMixer* mixer=0;
switch(mConversationManager.getMediaInterfaceMode())
{
case ConversationManager::sipXGlobalMediaInterfaceMode:
assert(mConversationManager.getBridgeMixer() != 0);
mixer = mConversationManager.getBridgeMixer();
break;
case ConversationManager::sipXConversationMediaInterfaceMode:
assert(removedConversation->getBridgeMixer() != 0);
mixer = removedConversation->getBridgeMixer();
break;
default:
break;
}
assert(mixer);
if(mixer)
{
mixer->calculateMixWeightsForParticipant(this);
}
}
/* ====================================================================
Copyright (c) 2007-2008, Plantronics, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of Plantronics 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.
==================================================================== */
| [
"heibao111728@126.com"
] | heibao111728@126.com |
aa7645de9ff74de1ea91efbf43a4ebba46f8a116 | 75beb32a9c96c698eb4b56a54cace2ee6c6680c4 | /spawntele.cpp | 14fcd8f5c1811c461e751da8b0359c6a0acac0e2 | [] | no_license | jacobmain1/UWoWScripts | 450296ce033856e749e5aecd41fb58ecbbde5045 | 08e52ff67b3ceccf9338680826b1059882906b38 | refs/heads/master | 2020-12-27T12:06:44.017698 | 2013-10-13T00:39:39 | 2013-10-13T00:39:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | #include "ScriptPCH.h"
#include "Chat.h"
class item_spawn_teleporter : public ItemScript
{
public:
item_spawn_teleporter() : ItemScript("item_spawn_teleporter") { }
bool OnUse(Player* player, Item* item)
{
player->SummonCreature(481851,player->GetPositionX() ,player->GetPositionY()+10, player->GetPositionZ(), 0,TEMPSUMMON_TIMED_DESPAWN,30000);
ChatHandler(player->GetSession()).PSendSysMessage("The Teleporter has been spawened, you have 30 seconds to choose a destination.");
return true;
}
};
void AddSC_item_spawn_teleporter()
{
new item_spawn_teleporter();
}
| [
"Watcher_WoW@Outlook.com"
] | Watcher_WoW@Outlook.com |
f8fb7eed37ce93f3a572f5ea25f2944bcd155c90 | 8596d6f5c216853c43b9f716d3827e60de71918f | /STalkerLibrary/src/DataExchanged/DownstreamData/AccelerometerFrame.cpp | 6b54fbc15f57fbb469ac749703bd5146be1111e9 | [] | no_license | cezarymalek/STalker | 7d641e4517ca417c74dc8adf2205c673c5c3ae5b | 59e59ad0bf99151546ea047ad97347b9dd1b4656 | refs/heads/master | 2021-07-09T19:29:06.912356 | 2020-09-27T09:32:32 | 2020-09-27T09:32:32 | 199,929,027 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,102 | cpp | #include "AccelerometerFrame.h"
#include <boost/exception/diagnostic_information.hpp>
#include <ros/console.h>
Interface::DownstreamData::AccelerometerFrame::AccelerometerFrame()
{
potocolIndentificator = "AccelerometerFrame";
stIdentifier = 0x04;
}
Interface::DownstreamData::AccelerometerFrame::~AccelerometerFrame()
{
}
std::vector<uint8_t> Interface::DownstreamData::AccelerometerFrame::serialize()
{
std::vector<uint8_t> output(3);
output[0] = stIdentifier;
output[1] = registryAddress;
output[2] = registryValue;
return output;
}
void Interface::DownstreamData::AccelerometerFrame::deserialize(boost::property_tree::ptree& pt)
{
try
{
registryAddress = pt.get<int>("AccelerometerFrame.RegistryAddress");
registryValue = pt.get<int>("AccelerometerFrame.RegistryValue");
}
catch (const boost::exception& e)
{
std::string diag = diagnostic_information(e);
ROS_ERROR("Bad IMU frame received. Boost says: %s", diag.c_str());
}
}
void Interface::DownstreamData::AccelerometerFrame::doTheProcessing()
{
}
| [
"you@example.com"
] | you@example.com |
e3cc5150e91ddf1b585a9baeeee2a39e5a858a8e | 542a0744fc3d377af01208c19cb4cb1cee8b57e9 | /BOJ_13913/13913.cpp | 6b595ae8fc40167e0d668941fd07f3e860f1ef40 | [] | no_license | bigmtn1113/Baekjoon | 7cb38ba1af1cc4c039733220a84e8688b3ef0013 | 337a837f7292ef99c0dd4a1199bf7f584d89a82d | refs/heads/master | 2023-06-05T10:24:55.733866 | 2021-06-29T07:00:50 | 2021-06-29T07:00:50 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,134 | cpp | #include <iostream>
#include <queue>
#include <vector>
using namespace std;
int dist[100001];
int pre_position[100001]; // 이전 위치 저장
void Bfs(int n, int k) {
queue<int> q;
q.push(n);
dist[n] = 1;
while (!q.empty()) {
int current = q.front();
q.pop();
if (current == k)
break;
int next[3] = { current - 1, current + 1, current * 2 };
for (int i = 0; i < 3; ++i) {
if (next[i] < 0 || next[i] > 100000)
continue;
if (!dist[next[i]]) {
q.push(next[i]);
dist[next[i]] = dist[current] + 1;
pre_position[next[i]] = current; // 이전 위치 저장
}
}
}
}
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int n, k;
vector<int> result;
cin >> n >> k;
Bfs(n, k);
cout << dist[k] - 1 << '\n';
/*
ex) 5 17
5 -> 4 -> 8 -> 16 -> 17
k = 17 -> pre_positino[17] = 16
k = 16 -> pre_positino[16] = 8
k = 8 -> pre_positino[8] = 4
k = 4 -> pre_positino[4] = 5
*/
result.push_back(k);
while (k != n) {
k = pre_position[k];
result.push_back(k);
}
// 거꾸로 출력
for (int i = result.size() - 1; i >= 0; --i)
cout << result[i] << ' ';
} | [
"kva231@naver.com"
] | kva231@naver.com |
cf8de4d58605fdea2725bf240b412fbf4e40cc7c | 966818603978f073d4f4ed85709ec1ad0c794be4 | /INSIGHT_20191106/include/ACE_Wrappers/ace/OS_NS_stdlib.inl | 3d4728d16ed67995cecba417b9878e9b0596257c | [] | no_license | lastvangogh/YANGZE | c337743e29dafadbfb1ed532f6c9ce35ce7f24df | 870eb6066b360036a49ebe40bd9435cdd31ff5ac | refs/heads/master | 2020-09-01T13:43:02.027589 | 2019-11-06T08:40:09 | 2019-11-06T08:40:09 | 218,970,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,796 | inl | // -*- C++ -*-
#include "ace/config-all.h" /* Need ACE_TRACE */
#include "ace/Object_Manager_Base.h"
#include "ace/OS_NS_string.h"
#include "ace/Global_Macros.h"
#include "ace/os_include/os_errno.h"
#include "ace/os_include/os_search.h"
#if defined (ACE_ANDROID) && (__ANDROID_API__ < 19)
# include "ace/os_include/os_signal.h"
#endif
#if defined (ACE_WCHAR_IN_STD_NAMESPACE)
# define ACE_WCHAR_STD_NAMESPACE std
#else
# define ACE_WCHAR_STD_NAMESPACE ACE_STD_NAMESPACE
#endif /* ACE_WCHAR_IN_STD_NAMESPACE */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
// Doesn't need a macro since it *never* returns!
ACE_INLINE void
ACE_OS::_exit (int status)
{
ACE_OS_TRACE ("ACE_OS::_exit");
#if defined (ACE_VXWORKS)
::exit (status);
#elif defined (ACE_HAS_WINCE)
::TerminateProcess (::GetCurrentProcess (), status);
#elif !defined (ACE_LACKS__EXIT)
::_exit (status);
#else
ACE_UNUSED_ARG (status);
#endif /* ACE_VXWORKS */
}
ACE_INLINE void
ACE_OS::abort (void)
{
#if defined (ACE_ANDROID) && (__ANDROID_API__ < 19)
ACE_OS::_exit (128 + SIGABRT);
#elif !defined (ACE_LACKS_ABORT)
::abort ();
#elif !defined (ACE_LACKS_EXIT)
exit (1);
#endif /* !ACE_LACKS_ABORT */
}
ACE_INLINE int
ACE_OS::atexit (ACE_EXIT_HOOK func, const char* name)
{
return ACE_OS_Object_Manager::instance ()->at_exit (func, name);
}
ACE_INLINE int
ACE_OS::atoi (const char *s)
{
ACE_OSCALL_RETURN (::atoi (s), int, -1);
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE int
ACE_OS::atoi (const wchar_t *s)
{
#if defined (ACE_WIN32) && defined (ACE_HAS_WTOI)
ACE_OSCALL_RETURN (::_wtoi (s), int, -1);
#else /* ACE_WIN32 */
return ACE_OS::atoi (ACE_Wide_To_Ascii (s).char_rep ());
#endif /* ACE_WIN32 */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE long
ACE_OS::atol (const char *s)
{
ACE_OSCALL_RETURN (::atol (s), long, -1);
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE long
ACE_OS::atol (const wchar_t *s)
{
#if defined (ACE_WIN32) && defined (ACE_HAS_WTOL)
ACE_OSCALL_RETURN (::_wtol (s), long, -1);
#else /* ACE_WIN32 */
return ACE_OS::atol (ACE_Wide_To_Ascii (s).char_rep ());
#endif /* ACE_WIN32 */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE double
ACE_OS::atof (const char *s)
{
ACE_OSCALL_RETURN (::atof (s), double, -1);
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE double
ACE_OS::atof (const wchar_t *s)
{
#if !defined (ACE_HAS_WTOF)
return ACE_OS::atof (ACE_Wide_To_Ascii (s).char_rep ());
#elif defined (ACE_WTOF_EQUIVALENT)
ACE_OSCALL_RETURN (ACE_WTOF_EQUIVALENT (s), double, -1);
#else /* ACE_HAS__WTOF */
ACE_OSCALL_RETURN (::wtof (s), double, -1);
#endif /* ACE_HAS_WTOF */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE void *
ACE_OS::atop (const char *s)
{
ACE_TRACE ("ACE_OS::atop");
#if defined (ACE_WIN64)
intptr_t ip = ::_atoi64 (s);
#elif defined (ACE_OPENVMS)
# if !defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)
int ip = ::atoi (s);
# else
intptr_t ip = ::atoi (s);
# endif
#else
intptr_t ip = ::atoi (s);
#endif /* ACE_WIN64 */
void * p = reinterpret_cast<void *> (ip);
return p;
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE void *
ACE_OS::atop (const wchar_t *s)
{
# if defined (ACE_WIN64)
intptr_t ip = ::_wtoi64 (s);
# elif defined (ACE_OPENVMS)
# if !defined (__INITIAL_POINTER_SIZE) || (__INITIAL_POINTER_SIZE < 64)
int ip = ACE_OS::atoi (s);
# else
intptr_t ip = ACE_OS::atoi (s);
# endif
# else
intptr_t ip = ACE_OS::atoi (s);
# endif /* ACE_WIN64 */
void * p = reinterpret_cast<void *> (ip);
return p;
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE void *
ACE_OS::bsearch (const void *key,
const void *base,
size_t nel,
size_t size,
ACE_COMPARE_FUNC compar)
{
#if !defined (ACE_LACKS_BSEARCH)
return ::bsearch (key, base, nel, size, compar);
#else
ACE_UNUSED_ARG (key);
ACE_UNUSED_ARG (base);
ACE_UNUSED_ARG (nel);
ACE_UNUSED_ARG (size);
ACE_UNUSED_ARG (compar);
ACE_NOTSUP_RETURN (0);
#endif /* ACE_LACKS_BSEARCH */
}
ACE_INLINE char *
ACE_OS::getenv (const char *symbol)
{
ACE_OS_TRACE ("ACE_OS::getenv");
#if defined (ACE_LACKS_GETENV)
ACE_UNUSED_ARG (symbol);
ACE_NOTSUP_RETURN (0);
#else /* ACE_LACKS_GETENV */
ACE_OSCALL_RETURN (::getenv (symbol), char *, 0);
#endif /* ACE_LACKS_GETENV */
}
#if defined (ACE_HAS_WCHAR) && defined (ACE_WIN32)
ACE_INLINE wchar_t *
ACE_OS::getenv (const wchar_t *symbol)
{
#if defined (ACE_LACKS_GETENV)
ACE_UNUSED_ARG (symbol);
ACE_NOTSUP_RETURN (0);
#else
ACE_OSCALL_RETURN (::_wgetenv (symbol), wchar_t *, 0);
#endif /* ACE_LACKS_GETENV */
}
#endif /* ACE_HAS_WCHAR && ACE_WIN32 */
ACE_INLINE char *
ACE_OS::itoa (int value, char *string, int radix)
{
#if !defined (ACE_HAS_ITOA)
return ACE_OS::itoa_emulation (value, string, radix);
#elif defined (ACE_ITOA_EQUIVALENT)
return ACE_ITOA_EQUIVALENT (value, string, radix);
#else /* !ACE_HAS_ITOA */
return ::itoa (value, string, radix);
#endif /* !ACE_HAS_ITOA */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE wchar_t *
ACE_OS::itoa (int value, wchar_t *string, int radix)
{
#if defined (ACE_LACKS_ITOW)
return ACE_OS::itow_emulation (value, string, radix);
#else /* ACE_LACKS_ITOW */
return ::_itow (value, string, radix);
#endif /* ACE_LACKS_ITOW */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE ACE_HANDLE
ACE_OS::mkstemp (char *s)
{
#if !defined (ACE_LACKS_MKSTEMP)
return ::mkstemp (s);
#elif defined (ACE_USES_WCHAR)
// For wide-char filesystems, we must convert the narrow-char input to
// a wide-char string for mkstemp_emulation(), then convert the name
// back to narrow-char for the caller.
ACE_Ascii_To_Wide wide_s (s);
const ACE_HANDLE fh = ACE_OS::mkstemp_emulation (wide_s.wchar_rep ());
if (fh != ACE_INVALID_HANDLE)
{
ACE_Wide_To_Ascii narrow_s (wide_s.wchar_rep ());
ACE_OS::strcpy (s, narrow_s.char_rep ());
}
return fh;
#else
return ACE_OS::mkstemp_emulation (s);
#endif /* !ACE_LACKS_MKSTEMP */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE ACE_HANDLE
ACE_OS::mkstemp (wchar_t *s)
{
# if !defined (ACE_LACKS_MKSTEMP)
// For wide-char filesystems, we must convert the wide-char input to
// a narrow-char string for mkstemp(), then convert the name
// back to wide-char for the caller.
ACE_Wide_To_Ascii narrow_s (s);
const ACE_HANDLE fh = ::mkstemp (narrow_s.char_rep ());
if (fh != ACE_INVALID_HANDLE)
{
ACE_Ascii_To_Wide wide_s (narrow_s.char_rep ());
ACE_OS::strcpy (s, wide_s.wchar_rep ());
}
return fh;
# elif defined (ACE_USES_WCHAR)
return ACE_OS::mkstemp_emulation (s);
# else
// For wide-char filesystems, we must convert the wide-char input to
// a narrow-char string for mkstemp_emulation(), then convert the name
// back to wide-char for the caller.
ACE_Wide_To_Ascii narrow_s (s);
const ACE_HANDLE fh = ACE_OS::mkstemp_emulation (narrow_s.char_rep ());
if (fh != ACE_INVALID_HANDLE)
{
ACE_Ascii_To_Wide wide_s (narrow_s.char_rep ());
ACE_OS::strcpy (s, wide_s.wchar_rep ());
}
return fh;
# endif /* !ACE_LACKS_MKSTEMP */
}
#endif /* ACE_HAS_WCHAR */
#if !defined (ACE_DISABLE_MKTEMP)
# if !defined (ACE_LACKS_MKTEMP)
ACE_INLINE char *
ACE_OS::mktemp (char *s)
{
# if defined (ACE_WIN32)
return ::_mktemp (s);
# else /* ACE_WIN32 */
return ::mktemp (s);
# endif /* ACE_WIN32 */
}
# if defined (ACE_HAS_WCHAR)
ACE_INLINE wchar_t *
ACE_OS::mktemp (wchar_t *s)
{
# if defined (ACE_WIN32)
return ::_wmktemp (s);
# else
// For narrow-char filesystems, we must convert the wide-char input to
// a narrow-char string for mktemp (), then convert the name back to
// wide-char for the caller.
ACE_Wide_To_Ascii narrow_s (s);
if (::mktemp (narrow_s.char_rep ()) == 0)
return 0;
ACE_Ascii_To_Wide wide_s (narrow_s.char_rep ());
ACE_OS::strcpy (s, wide_s.wchar_rep ());
return s;
# endif
}
# endif /* ACE_HAS_WCHAR */
# endif /* !ACE_LACKS_MKTEMP */
#endif /* !ACE_DISABLE_MKTEMP */
ACE_INLINE int
ACE_OS::putenv (const char *string)
{
ACE_OS_TRACE ("ACE_OS::putenv");
#if defined (ACE_LACKS_PUTENV) && defined (ACE_HAS_SETENV)
int result = 0;
char *sp = ACE_OS::strchr (const_cast <char *> (string), '=');
if (sp)
{
char *stmp = ACE_OS::strdup (string);
if (stmp)
{
stmp[sp - string] = '\0';
result = ACE_OS::setenv (stmp, sp+sizeof (char), 1);
ACE_OS::free (stmp);
}
else
{
errno = ENOMEM;
result = -1;
}
}
else
{
result = ACE_OS::setenv (string, "", 1);
}
return result;
#elif defined (ACE_LACKS_PUTENV)
ACE_UNUSED_ARG (string);
ACE_NOTSUP_RETURN (0);
#elif defined (ACE_PUTENV_EQUIVALENT)
ACE_OSCALL_RETURN (ACE_PUTENV_EQUIVALENT (const_cast <char *> (string)), int, -1);
#else /* ! ACE_HAS_WINCE */
ACE_OSCALL_RETURN (ACE_STD_NAMESPACE::putenv (const_cast <char *> (string)), int, -1);
#endif /* ACE_LACKS_PUTENV && ACE_HAS_SETENV */
}
ACE_INLINE int
ACE_OS::setenv(const char *envname, const char *envval, int overwrite)
{
#if defined (ACE_LACKS_SETENV)
ACE_UNUSED_ARG (envname);
ACE_UNUSED_ARG (envval);
ACE_UNUSED_ARG (overwrite);
ACE_NOTSUP_RETURN (-1);
#else
ACE_OSCALL_RETURN (ACE_STD_NAMESPACE::setenv (envname, envval, overwrite), int, -1);
#endif
}
ACE_INLINE int
ACE_OS::unsetenv(const char *name)
{
#if defined (ACE_LACKS_UNSETENV)
ACE_UNUSED_ARG (name);
ACE_NOTSUP_RETURN (-1);
#else
# if defined (ACE_HAS_VOID_UNSETENV)
::unsetenv (name);
return 0;
#else
ACE_OSCALL_RETURN (ACE_STD_NAMESPACE::unsetenv (name), int, -1);
# endif /* ACE_HAS_VOID_UNSETENV */
#endif /* ACE_LACKS_UNSETENV */
}
#if defined (ACE_HAS_WCHAR) && defined (ACE_WIN32)
ACE_INLINE int
ACE_OS::putenv (const wchar_t *string)
{
ACE_OS_TRACE ("ACE_OS::putenv");
#if defined (ACE_LACKS_PUTENV)
ACE_UNUSED_ARG (string);
ACE_NOTSUP_RETURN (-1);
#else
ACE_OSCALL_RETURN (::_wputenv (string), int, -1);
#endif /* ACE_LACKS_PUTENV */
}
#endif /* ACE_HAS_WCHAR && ACE_WIN32 */
ACE_INLINE void
ACE_OS::qsort (void *base,
size_t nel,
size_t width,
ACE_COMPARE_FUNC compar)
{
#if !defined (ACE_LACKS_QSORT)
::qsort (base, nel, width, compar);
#else
ACE_UNUSED_ARG (base);
ACE_UNUSED_ARG (nel);
ACE_UNUSED_ARG (width);
ACE_UNUSED_ARG (compar);
#endif /* !ACE_LACKS_QSORT */
}
ACE_INLINE int
ACE_OS::rand (void)
{
ACE_OS_TRACE ("ACE_OS::rand");
#if !defined (ACE_LACKS_RAND)
ACE_OSCALL_RETURN (::rand (), int, -1);
#else
ACE_NOTSUP_RETURN (-1);
#endif /* ACE_LACKS_RAND */
}
ACE_INLINE int
ACE_OS::rand_r (unsigned int *seed)
{
ACE_OS_TRACE ("ACE_OS::rand_r");
#if defined (ACE_LACKS_RAND_R)
long new_seed = (long) *seed;
if (new_seed == 0)
new_seed = 0x12345987;
long temp = new_seed / 127773;
new_seed = 16807 * (new_seed - temp * 127773) - 2836 * temp;
if (new_seed < 0)
new_seed += 2147483647;
*seed = (unsigned int)new_seed;
return (int) (new_seed & RAND_MAX);
#else
return ace_rand_r_helper (seed);
# endif /* ACE_LACKS_RAND_R */
}
# if !defined (ACE_LACKS_REALPATH)
ACE_INLINE char *
ACE_OS::realpath (const char *file_name,
char *resolved_name)
{
# if defined (ACE_WIN32)
return ::_fullpath (resolved_name, file_name, PATH_MAX);
# else /* ACE_WIN32 */
return ::realpath (file_name, resolved_name);
# endif /* ! ACE_WIN32 */
}
# if defined (ACE_HAS_WCHAR)
ACE_INLINE wchar_t *
ACE_OS::realpath (const wchar_t *file_name,
wchar_t *resolved_name)
{
# if defined (ACE_WIN32)
return ::_wfullpath (resolved_name, file_name, PATH_MAX);
# else /* ACE_WIN32 */
ACE_Wide_To_Ascii n_file_name (file_name);
char n_resolved[PATH_MAX];
if (0 != ACE_OS::realpath (n_file_name.char_rep (), n_resolved))
{
ACE_Ascii_To_Wide w_resolved (n_resolved);
ACE_OS::strcpy (resolved_name, w_resolved.wchar_rep ());
return resolved_name;
}
return 0;
# endif /* ! ACE_WIN32 */
}
# endif /* ACE_HAS_WCHAR */
#endif /* ACE_HAS_WINCE */
ACE_INLINE ACE_EXIT_HOOK
ACE_OS::set_exit_hook (ACE_EXIT_HOOK exit_hook)
{
ACE_EXIT_HOOK old_hook = exit_hook_;
exit_hook_ = exit_hook;
return old_hook;
}
ACE_INLINE void
ACE_OS::srand (u_int seed)
{
ACE_OS_TRACE ("ACE_OS::srand");
#ifdef ACE_LACKS_SRAND
ACE_UNUSED_ARG (seed);
#else
::srand (seed);
#endif
}
#if !defined (ACE_LACKS_STRTOD)
ACE_INLINE double
ACE_OS::strtod (const char *s, char **endptr)
{
return ::strtod (s, endptr);
}
#endif /* !ACE_LACKS_STRTOD */
#if defined (ACE_HAS_WCHAR) && !defined (ACE_LACKS_WCSTOD)
ACE_INLINE double
ACE_OS::strtod (const wchar_t *s, wchar_t **endptr)
{
return ACE_WCHAR_STD_NAMESPACE::wcstod (s, endptr);
}
#endif /* ACE_HAS_WCHAR && !ACE_LACKS_WCSTOD */
ACE_INLINE long
ACE_OS::strtol (const char *s, char **ptr, int base)
{
#if defined (ACE_LACKS_STRTOL)
return ACE_OS::strtol_emulation (s, ptr, base);
#else /* ACE_LACKS_STRTOL */
return ::strtol (s, ptr, base);
#endif /* ACE_LACKS_STRTOL */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE long
ACE_OS::strtol (const wchar_t *s, wchar_t **ptr, int base)
{
#if defined (ACE_LACKS_WCSTOL)
return ACE_OS::wcstol_emulation (s, ptr, base);
#else
return ACE_WCHAR_STD_NAMESPACE::wcstol (s, ptr, base);
#endif /* ACE_LACKS_WCSTOL */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE unsigned long
ACE_OS::strtoul (const char *s, char **ptr, int base)
{
#if defined (ACE_LACKS_STRTOUL)
return ACE_OS::strtoul_emulation (s, ptr, base);
#else /* ACE_LACKS_STRTOUL */
return ::strtoul (s, ptr, base);
#endif /* ACE_LACKS_STRTOUL */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE unsigned long
ACE_OS::strtoul (const wchar_t *s, wchar_t **ptr, int base)
{
#if defined (ACE_LACKS_WCSTOUL)
return ACE_OS::wcstoul_emulation (s, ptr, base);
#else
return ACE_WCHAR_STD_NAMESPACE::wcstoul (s, ptr, base);
#endif /* ACE_LACKS_WCSTOUL */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE ACE_INT64
ACE_OS::strtoll (const char *s, char **ptr, int base)
{
#if defined (ACE_LACKS_STRTOLL)
return ACE_OS::strtoll_emulation (s, ptr, base);
#elif defined (ACE_STRTOLL_EQUIVALENT)
return ACE_STRTOLL_EQUIVALENT (s, ptr, base);
#else
return ace_strtoll_helper (s, ptr, base);
#endif /* ACE_LACKS_STRTOLL */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE ACE_INT64
ACE_OS::strtoll (const wchar_t *s, wchar_t **ptr, int base)
{
#if defined (ACE_LACKS_WCSTOLL)
return ACE_OS::wcstoll_emulation (s, ptr, base);
#elif defined (ACE_WCSTOLL_EQUIVALENT)
return ACE_WCSTOLL_EQUIVALENT (s, ptr, base);
#else
return ACE_WCHAR_STD_NAMESPACE::wcstoll (s, ptr, base);
#endif /* ACE_LACKS_WCSTOLL */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE ACE_UINT64
ACE_OS::strtoull (const char *s, char **ptr, int base)
{
#if defined (ACE_LACKS_STRTOULL)
return ACE_OS::strtoull_emulation (s, ptr, base);
#elif defined (ACE_STRTOULL_EQUIVALENT)
return ACE_STRTOULL_EQUIVALENT (s, ptr, base);
#else
return ace_strtoull_helper (s, ptr, base);
#endif /* ACE_LACKS_STRTOULL */
}
#if defined (ACE_HAS_WCHAR)
ACE_INLINE ACE_UINT64
ACE_OS::strtoull (const wchar_t *s, wchar_t **ptr, int base)
{
#if defined (ACE_LACKS_WCSTOULL)
return ACE_OS::wcstoull_emulation (s, ptr, base);
#elif defined (ACE_WCSTOULL_EQUIVALENT)
return ACE_WCSTOULL_EQUIVALENT (s, ptr, base);
#else
return ACE_WCHAR_STD_NAMESPACE::wcstoull (s, ptr, base);
#endif /* ACE_LACKS_WCSTOULL */
}
#endif /* ACE_HAS_WCHAR */
ACE_INLINE int
ACE_OS::system (const ACE_TCHAR *s)
{
// ACE_OS_TRACE ("ACE_OS::system");
#if defined (ACE_LACKS_SYSTEM)
ACE_UNUSED_ARG (s);
ACE_NOTSUP_RETURN (-1);
#elif defined (ACE_WIN32) && defined (ACE_USES_WCHAR)
ACE_OSCALL_RETURN (::_wsystem (s), int, -1);
#else
ACE_OSCALL_RETURN (::system (ACE_TEXT_ALWAYS_CHAR (s)), int, -1);
#endif /* ACE_LACKS_SYSTEM */
}
ACE_INLINE const char*
ACE_OS::getprogname ()
{
#if defined (ACE_HAS_GETPROGNAME)
return ::getprogname ();
#else
return ACE_OS::getprogname_emulation ();
#endif /* ACE_HAS_GETPROGNAME */
}
ACE_INLINE void
ACE_OS::setprogname (const char* name)
{
#if defined (ACE_HAS_SETPROGNAME)
::setprogname (name);
#else
ACE_OS::setprogname_emulation (name);
#endif /* ACE_HAS_SETPROGNAME */
}
ACE_END_VERSIONED_NAMESPACE_DECL
| [
"zhangzhuo@yangzeinvest.com"
] | zhangzhuo@yangzeinvest.com |
a0c78c2554c939e559c0d5f23760c02614312717 | 93bf4bbafe0524335ea1216f7f2941348c2cd1bd | /tensorflow/core/kernels/sequence_ops.cc | f5572a731dfec2f881c46b7c8965f048b922e831 | [
"Apache-2.0"
] | permissive | sachinpro/sachinpro.github.io | c4951734b09588cad58711a76fe657f110163c11 | c3bbd8d89818f5d8bb7296c851ed5e52c19728e3 | refs/heads/master | 2022-12-23T10:00:13.902459 | 2016-06-27T13:18:27 | 2016-06-27T13:25:58 | 25,289,839 | 1 | 1 | Apache-2.0 | 2022-12-15T00:45:03 | 2014-10-16T06:44:30 | C++ | UTF-8 | C++ | false | false | 5,834 | cc | /* Copyright 2015 Google Inc. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
// See docs in ../ops/math_ops.cc.
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/types.h"
namespace tensorflow {
int32 GetValue(int32 v) { return v; }
template <typename T>
class RangeOp : public OpKernel {
public:
explicit RangeOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& start_in = context->input(0);
const Tensor& limit_in = context->input(1);
const Tensor& delta_in = context->input(2);
OP_REQUIRES(context, IsLegacyScalar(start_in.shape()),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in.shape().DebugString()));
OP_REQUIRES(context, IsLegacyScalar(limit_in.shape()),
errors::InvalidArgument("limit must be a scalar, not shape ",
limit_in.shape().DebugString()));
OP_REQUIRES(context, IsLegacyScalar(delta_in.shape()),
errors::InvalidArgument("delta must be a scalar, not shape ",
delta_in.shape().DebugString()));
const int32 start = GetValue(start_in.scalar<T>()());
const int32 limit = GetValue(limit_in.scalar<T>()());
OP_REQUIRES(context, start <= limit,
errors::InvalidArgument("Requires start <= limit: ", start, "/",
limit));
const int32 delta = GetValue(delta_in.scalar<T>()());
OP_REQUIRES(context, delta > 0,
errors::InvalidArgument("Requires delta > 0: ", delta));
int32 size = (limit - start + delta - 1) / delta;
Tensor* out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, TensorShape({size}), &out));
auto flat = out->flat<T>();
int32 val = start;
for (int32 i = 0; i < size; ++i) {
flat(i) = T(val);
val += delta;
}
}
};
REGISTER_KERNEL_BUILDER(Name("Range")
.Device(DEVICE_CPU)
.HostMemory("start")
.HostMemory("limit")
.HostMemory("delta")
.HostMemory("output"),
RangeOp<int32>);
#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("Range")
.Device(DEVICE_GPU)
.HostMemory("start")
.HostMemory("limit")
.HostMemory("delta")
.HostMemory("output"),
RangeOp<int32>);
#endif // GOOGLE_CUDA
template <typename T>
class LinSpaceOp : public OpKernel {
public:
explicit LinSpaceOp(OpKernelConstruction* context) : OpKernel(context) {}
void Compute(OpKernelContext* context) override {
const Tensor& start_in = context->input(0);
const Tensor& stop_in = context->input(1);
const Tensor& num_in = context->input(2);
OP_REQUIRES(context, TensorShapeUtils::IsScalar(start_in.shape()),
errors::InvalidArgument("start must be a scalar, not shape ",
start_in.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsScalar(stop_in.shape()),
errors::InvalidArgument("stop must be a scalar, not shape ",
stop_in.shape().DebugString()));
OP_REQUIRES(context, TensorShapeUtils::IsScalar(num_in.shape()),
errors::InvalidArgument("num must be a scalar, not shape ",
num_in.shape().DebugString()));
const T start = start_in.scalar<T>()();
const T stop = stop_in.scalar<T>()();
const int32 num = num_in.scalar<int32>()();
OP_REQUIRES(context, num > 0,
errors::InvalidArgument("Requires num > 0: ", num));
Tensor* out = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, TensorShape({num}), &out));
auto flat = out->flat<T>();
if (num == 1) {
flat(0) = start;
} else {
const T step = (stop - start) / (num - 1);
for (int32 i = 0; i < num; ++i) flat(i) = start + step * i;
}
}
};
REGISTER_KERNEL_BUILDER(Name("LinSpace")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T")
.HostMemory("start")
.HostMemory("stop")
.HostMemory("num")
.HostMemory("output"),
LinSpaceOp<float>);
REGISTER_KERNEL_BUILDER(Name("LinSpace")
.Device(DEVICE_CPU)
.TypeConstraint<double>("T")
.HostMemory("start")
.HostMemory("stop")
.HostMemory("num")
.HostMemory("output"),
LinSpaceOp<double>);
} // namespace tensorflow
| [
"x0234443@ti.com"
] | x0234443@ti.com |
651c7cd81e2957e330765d0a07b0050024a8623c | d2e27b839614d8b23022ab12dd1c116845b2912b | /tools/gfx_d3d/GFX_Model_Cal3D.cpp | 8049a0f8a312c049c5ed4ef911336cfacade60b4 | [] | no_license | Crogarox/Mahatta | c734acd3c4779036d4232c18c98012d4eaab926e | 039a708f9cbde426a146d8b9e6bfb14ba72abb83 | refs/heads/master | 2021-12-18T00:12:26.527787 | 2012-10-03T07:09:42 | 2012-10-03T07:09:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,804 | cpp | #include "cal3d/cal3d.h"
#include "gfx_i.h"
#include "GFX\gfx_math.h"
static inline void _Cal3DSetVtxDecl(GFXVTXBUFF *vtxBuff, FLAGS flag)
{
s16 ofs = 0, ind = 0;
//now let's set the vertex declaration
D3DVERTEXELEMENT9 Declaration[MAX_FVF_DECL_SIZE];
D3DVERTEXELEMENT9 End = D3DDECL_END();
Declaration[ind].Stream = 0;
Declaration[ind].Offset = ofs; ofs += sizeof(f32)*3;
Declaration[ind].Type = D3DDECLTYPE_FLOAT3;
Declaration[ind].Method = D3DDECLMETHOD_DEFAULT;
Declaration[ind].Usage = D3DDECLUSAGE_POSITION;
Declaration[ind].UsageIndex = 0;
ind++;
Declaration[ind].Stream = 0;
Declaration[ind].Offset = ofs; ofs += sizeof(f32)*3;
Declaration[ind].Type = D3DDECLTYPE_FLOAT3;
Declaration[ind].Method = D3DDECLMETHOD_DEFAULT;
Declaration[ind].Usage = D3DDECLUSAGE_NORMAL;
Declaration[ind].UsageIndex = 0;
ind++;
Declaration[ind].Stream = 0;
Declaration[ind].Offset = ofs; ofs += sizeof(f32)*2;
Declaration[ind].Type = D3DDECLTYPE_FLOAT2;
Declaration[ind].Method = D3DDECLMETHOD_DEFAULT;
Declaration[ind].Usage = D3DDECLUSAGE_TEXCOORD;
Declaration[ind].UsageIndex = 0;
ind++;
ofs = 0;
if(TESTFLAGS(flag, MODEL_TANGENT))
{
Declaration[ind].Stream = 1;
Declaration[ind].Offset = 0; ofs += sizeof(f32)*4;
Declaration[ind].Type = D3DDECLTYPE_FLOAT4;
Declaration[ind].Method = D3DDECLMETHOD_DEFAULT;
Declaration[ind].Usage = D3DDECLUSAGE_TANGENT;
Declaration[ind].UsageIndex = 0;
ind++;
//binormals are useless without tangents
if(TESTFLAGS(flag, MODEL_BINORMAL))
{
Declaration[ind].Stream = 2;
Declaration[ind].Offset = 0; ofs += sizeof(f32)*4;
Declaration[ind].Type = D3DDECLTYPE_FLOAT4;
Declaration[ind].Method = D3DDECLMETHOD_DEFAULT;
Declaration[ind].Usage = D3DDECLUSAGE_BINORMAL;
Declaration[ind].UsageIndex = 0;
ind++;
}
}
Declaration[ind] = End;
VtxSetDecl(vtxBuff, Declaration);
}
u32 IgfxModel::_Cal3DCreateBuffer()
{
if(m_pCalCoreModel == 0)
return TRUE; //we assume pMesh
//get the maximum count for vertex and index
s32 maxInd=0, maxVert=0;
s32 maxMeshInd=0,curMeshIndC;
s32 maxMeshVert=0,curMeshVertC;
for(s32 meshID = 0; meshID < m_pCalCoreModel->getCoreMeshCount(); meshID++)
{
// get the core mesh
CalCoreMesh *pCoreMesh;
pCoreMesh = m_pCalCoreModel->getCoreMesh(meshID);
curMeshVertC = 0;
curMeshIndC = 0;
//get the maximum vertex and face count and the highest count you can get per submesh
for(s32 subMeshID = 0; subMeshID < pCoreMesh->getCoreSubmeshCount(); subMeshID++)
{
CalCoreSubmesh *pCoreSubMesh;
pCoreSubMesh = pCoreMesh->getCoreSubmesh(subMeshID);
if(pCoreSubMesh->getFaceCount()*3 > maxInd)
maxInd = pCoreSubMesh->getFaceCount()*3;
if(pCoreSubMesh->getVertexCount() > maxVert)
maxVert = pCoreSubMesh->getVertexCount();
curMeshVertC += pCoreSubMesh->getVertexCount();
curMeshIndC += pCoreSubMesh->getFaceCount()*3;
}
if(curMeshVertC > maxMeshVert)
maxMeshVert = curMeshVertC;
if(curMeshIndC > maxMeshInd)
maxMeshInd = curMeshIndC;
}
if(maxVert > 0 && maxInd > 0)
{
//create the vertex buffer
m_vtxBuff = GFXCreateVtxBuff(sizeof(f32)*8, maxVert,
GFXUSAGE_WRITEONLY|GFXUSAGE_DYNAMIC, m_fvf, GFXPOOL_DEFAULT);
if(!m_vtxBuff)
{ LogMsg(LOG_FILE, L"_MDLCal3DCreateBuffer: Error creating vertex buffer", m_name); return FALSE; }
//create index buffer
GFXCreateIndBuff(sizeof(CalIndex)*maxInd, GFXUSAGE_WRITEONLY|GFXUSAGE_DYNAMIC,
sizeof(CalIndex) == 2 ? 16 : 32, GFXPOOL_DEFAULT, &m_indBuff);
if(!m_indBuff)
{ LogMsg(LOG_FILE, L"_MDLCal3DCreateBuffer: Error creating index buffer", m_name); return FALSE; }
gfxCal3D *pCal3DS = (gfxCal3D *)m_pCalCoreModel->getUserData();
if(pCal3DS)
{
pCal3DS->numInd = maxMeshInd;
pCal3DS->numVtx = maxMeshVert;
pCal3DS->shadowVtx = (Vec3D*)MemAlloc(sizeof(Vec3D)*maxMeshVert);
pCal3DS->shadowInd = (u8*)MemAlloc(sizeof(CalIndex)*maxMeshInd);
//resize the shadow buffer if we have to
GFXShadowInit(pCal3DS->numVtx*8, pCal3DS->numVtx*2, 0);
}
m_pCalCoreModel->setUserData((Cal::UserData)pCal3DS);
}
else
{ LogMsg(LOG_FILE, L"_MDLCal3DCreateBuffer: No vertices or indices", m_name); return FALSE; }
//u32 GFXAppendVtxBuff(GFXVTXBUFF *vtx, u32 size, u32 count, u32 usage, u32 FVF, GFXPOOL pool);
//let's see if we want tangents and/or binormals
if(TESTFLAGS(m_flag, MODEL_TANGENT))
{
//at least one of them are included
//now let's append another stream to our vtx buffer
//this is a non-FVF vertex buffer
u32 vret = GFXAppendVtxBuff(m_vtxBuff, sizeof(f32)*4, maxVert,
GFXUSAGE_DYNAMIC, 0, GFXPOOL_DEFAULT);
if(TESTFLAGS(m_flag, MODEL_BINORMAL))
{
vret = GFXAppendVtxBuff(m_vtxBuff, sizeof(f32)*4, maxVert,
GFXUSAGE_DYNAMIC, 0, GFXPOOL_DEFAULT);
}
if(!vret)
{ LogMsg(LOG_FILE, L"_MDLCal3DCreateBuffer: Error creating tangent/binormal buffer", m_name); return FALSE; }
_Cal3DSetVtxDecl(m_vtxBuff, m_flag);
}
return TRUE;
}
/////////////////////////////////////
// Purpose: load cal3D model
// Output: model loaded to given model
// Return: TRUE if success
/////////////////////////////////////
u32 IgfxModel::LoadCal3D(const tCHAR *filename)
{
//TODO: MAKE CAL3D USE WIDE CHAR!!!
s32 id, matID=-1;
//default values
Vec3D scale(1.0f,1.0f,1.0f);
Vec3D rot(0.0f,0.0f,0.0f);
Vec3D trans(0.0f,0.0f,0.0f);
tCHAR errStr[MAXCHARBUFF];
hFILE fp = FSOpen(filename, L"rt");
if(!fp) { LogMsg(LOG_FILE, L"MDLLoadCal3D: Unable to load file", filename); return FALSE; }
tCHAR dir[MAXCHARBUFF]; wcscpy(dir, filename);
tCHAR *pDir = GetFilePart(dir); if(pDir) *pDir = 0;
// create a core model instance
m_pCalCoreModel = new CalCoreModel;
if(!m_pCalCoreModel)
{ LogMsg(LOG_FILE, L"MDLLoadCal3D: Unable to allocate CalCoreModel", filename); return FALSE; }
char sFilename[MAXCHARBUFF]; wcstombs(sFilename, filename, MAXCHARBUFF);
if(!m_pCalCoreModel->create(string(sFilename)))
{
mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF);
LogMsg(LOG_FILE, filename, errStr);
return FALSE;
}
//set the user data: shadow stuff
//gfxCal3D *pCal3DS = 0;
gfxCal3D *pCal3DS = (gfxCal3D *)MemAlloc(sizeof(gfxCal3D));
if(pCal3DS)
m_pCalCoreModel->setUserData((Cal::UserData)pCal3DS);
else //something went wrong!!!
{ LogMsg(LOG_FILE, L"MDLLoadCal3D: Unable to allocate gfxCal3D", filename); return FALSE; }
pCal3DS->shadowID = -1;
hFILE sfp;
wstring wPath;
tCHAR wAbsPath[MAXCHARBUFF];
char sPath[MAXCHARBUFF];
tCHAR lineS[DMAXCHARBUFF]={0}, *pLineS;
//let's parse this crap
//while(!FSEOF(fp))
for(s32 line = 1; ; line++)
{
tCHAR varS[MAXCHARBUFF]={0};
// stop if we reached the end of file
if(FSEOF(fp)) break;
//get line
ParserReadStringFile(fp, lineS, DMAXCHARBUFF, 0, '\n');
//skip comment if we find one
pLineS = lineS;
if(ParserSkipCharBuff(&pLineS, '#', FALSE) == RETCODE_SUCCESS)
continue;
//get variable and its data
pLineS = lineS;
if(ParserReadWordBuff(&pLineS, varS, MAXCHARBUFF, '=') == 0)
continue; //we reached the last of the line...
//determine what the variable is
if(wcsicmp(varS, L"LOD_Distance") == 0)
{
m_lodDist = (f32)_wtof(pLineS);
m_lodDist *= m_lodDist;
}
else if(wcsicmp(varS, L"LOD_ShadowDistance") == 0)
{
m_shadDist = (f32)_wtof(pLineS);
m_shadDist *= m_shadDist;
}
else if(wcsicmp(varS, L"scale") == 0)
{
// set rendering scale factor
scale.x = (f32)_wtof(pLineS);
scale.y = scale.z = scale.x;
}
else if(wcsicmp(varS, L"scaleEX") == 0)
{
// set rendering scale factor
swscanf(pLineS, L"%f,%f,%f", &scale.x, &scale.y, &scale.z);
}
else if(wcsicmp(varS, L"rotate") == 0)
{
// set rendering rotate factor
swscanf(pLineS, L"%f,%f,%f", &rot.x, &rot.y, &rot.z);
rot.x = TO_RAD(rot.x);
rot.y = TO_RAD(rot.y);
rot.z = TO_RAD(rot.z);
}
else if(wcsicmp(varS, L"trans") == 0)
{
// set rendering scale factor
swscanf(pLineS, L"%f,%f,%f", &trans.x, &trans.y, &trans.z);
}
else if(wcsicmp(varS, L"skeleton") == 0) // load core skeleton
{
wPath = dir;
wPath += pLineS;
sfp = FSOpen(wPath.c_str(), L"rb");
if(sfp)
{
if(FSIsArchive(sfp))
{
CalCoreSkeleton *pSkel = CalLoader::loadCoreSkeleton((void*)FSBufferGetPtr(sfp));
FSClose(sfp);
if(pSkel)
m_pCalCoreModel->setCoreSkeleton(pSkel);
else
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF);
LogMsg(LOG_FILE, filename, errStr); return FALSE; }
}
else
{
FSClose(sfp);
FSGetPath(wPath.c_str(), wAbsPath, MAXCHARBUFF);
wcstombs(sPath, wAbsPath, MAXCHARBUFF);
if(!m_pCalCoreModel->loadCoreSkeleton(sPath))
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF);
LogMsg(LOG_FILE, filename, errStr); return FALSE; }
}
}
}
else if(wcsicmp(varS, L"animation") == 0)
{
id = -1;
wPath = dir;
wPath += pLineS;
sfp = FSOpen(wPath.c_str(), L"rb");
if(sfp)
{
if(FSIsArchive(sfp) && m_pCalCoreModel->getCoreSkeleton())
{
CalCoreAnimation *pAnim = CalLoader::loadCoreAnimation((void*)FSBufferGetPtr(sfp),
m_pCalCoreModel->getCoreSkeleton());
FSClose(sfp);
if(pAnim)
id = m_pCalCoreModel->addCoreAnimation(pAnim);
}
else
{
FSClose(sfp);
FSGetPath(wPath.c_str(), wAbsPath, MAXCHARBUFF);
wcstombs(sPath, wAbsPath, MAXCHARBUFF);
// load core animation
id = m_pCalCoreModel->loadCoreAnimation(sPath);
}
}
if(id == -1)
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF); LogMsg(LOG_FILE, filename, errStr); return FALSE; }
//set helper name
tCHAR wAnimName[MAXCHARBUFF]={0};
char sAnimName[MAXCHARBUFF]={0};
GetFilename(pLineS, wAnimName, MAXCHARBUFF);
wcstombs(sAnimName, wAnimName, MAXCHARBUFF);
m_pCalCoreModel->addAnimHelper(sAnimName, id);
}
else if(wcsicmp(varS, L"mesh") == 0)
{
wPath = dir;
wPath += pLineS;
sfp = FSOpen(wPath.c_str(), L"rb");
if(sfp)
{
if(FSIsArchive(sfp))
{
CalCoreMesh *pMesh = CalLoader::loadCoreMesh((void*)FSBufferGetPtr(sfp));
FSClose(sfp);
if(pMesh)
m_pCalCoreModel->addCoreMesh(pMesh);
else
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF);
LogMsg(LOG_FILE, filename, errStr); return FALSE; }
}
else
{
FSClose(sfp);
FSGetPath(wPath.c_str(), wAbsPath, MAXCHARBUFF);
wcstombs(sPath, wAbsPath, MAXCHARBUFF);
// load core mesh
if( m_pCalCoreModel->loadCoreMesh(sPath) == -1)
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF); LogMsg(LOG_FILE, filename, errStr); return FALSE; }
}
}
}//pCal3DS
else if(wcsicmp(varS, L"meshShadow") == 0)
{
if(pCal3DS->shadowID >= 0)
{
//destroy this mesh???
continue;
}
wPath = dir;
wPath += pLineS;
sfp = FSOpen(wPath.c_str(), L"rb");
if(sfp)
{
if(FSIsArchive(sfp))
{
CalCoreMesh *pMesh = CalLoader::loadCoreMesh((void*)FSBufferGetPtr(sfp));
if(pMesh)
pCal3DS->shadowID = m_pCalCoreModel->addCoreMesh(pMesh);
else
pCal3DS->shadowID = -1;
FSClose(sfp);
}
else
{
FSClose(sfp);
FSGetPath(wPath.c_str(), wAbsPath, MAXCHARBUFF);
wcstombs(sPath, wAbsPath, MAXCHARBUFF);
// load core mesh
pCal3DS->shadowID = m_pCalCoreModel->loadCoreMesh(sPath);
}
}
if(pCal3DS->shadowID == -1)
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF); LogMsg(LOG_FILE, filename, errStr); return FALSE; }
}
else if(wcsicmp(varS, L"material") == 0)
{
wPath = dir;
wPath += pLineS;
sfp = FSOpen(wPath.c_str(), L"rb");
if(sfp)
{
if(FSIsArchive(sfp))
{
CalCoreMaterial *pMat = CalLoader::loadCoreMaterial((void*)FSBufferGetPtr(sfp));
if(pMat)
matID = m_pCalCoreModel->addCoreMaterial(pMat);
else
matID = -1;
FSClose(sfp);
}
else
{
FSClose(sfp);
FSGetPath(wPath.c_str(), wAbsPath, MAXCHARBUFF);
wcstombs(sPath, wAbsPath, MAXCHARBUFF);
// load core material
matID = m_pCalCoreModel->loadCoreMaterial(sPath);
}
}
if(matID == -1)
{ mbstowcs(errStr, CalError::getLastErrorText().c_str(), MAXCHARBUFF); LogMsg(LOG_FILE, filename, errStr); return FALSE; }
// get the core material
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(matID);
// loop through all maps of the core material
// and load each textures
s32 mapId;
for(mapId = 0; mapId < pCoreMaterial->getMapCount(); mapId++)
{
// get the filename of the texture
string strFilename;
strFilename = pCoreMaterial->getMapFilename(mapId);
// load the texture from the file
if(strFilename[0] != '\0')
{
tCHAR wTxtPath[MAXCHARBUFF]; mbstowcs(wTxtPath, strFilename.c_str(), MAXCHARBUFF);
wPath = dir; wPath += wTxtPath;
hTXT txt = TextureLoad(wPath.c_str(), FALSE, 0);
// store the texture id in the user data of the map
pCoreMaterial->setMapUserData(mapId, (Cal::UserData)txt);
}
}
}
//assume that previous key is material
else if(wcsicmp(varS, L"materialFX") == 0 && matID != -1)
{
wPath = dir;
wPath += pLineS;
hEFFECT fx = EffectLoad(wPath.c_str());
if(!fx)
{ LogMsg(LOG_FILE, L"MDLLoadCal3D: Error loading FX", filename); return FALSE; }
// get the core material and set FX as user data
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(matID);
pCoreMaterial->setUserData((Cal::UserData)fx);
}
else
{ swprintf(lineS, L"MDLLoadCal3D: (%d): Invalid syntax.", line); LogMsg(LOG_FILE, lineS, filename); }
}
FSClose(fp);
// make one material thread for each material
// NOTE: this is not the right way to do it, but this viewer can't do the right
// mapping without further information on the model etc.
for(matID = 0; matID < m_pCalCoreModel->getCoreMaterialCount(); matID++)
{
// create the a material thread
m_pCalCoreModel->createCoreMaterialThread(matID);
// initialize the material thread
m_pCalCoreModel->setCoreMaterialId(matID, 0, matID);
}
//prepare model space matrix
Matrix rotMtx, scaleMtx;
MtxScale(&scale, &scaleMtx);
MtxYawPitchRoll(rot.y, rot.x, rot.z, &rotMtx);
m_mdlMtx = rotMtx*scaleMtx;
m_mdlMtx._41 = trans.x;
m_mdlMtx._42 = trans.y;
m_mdlMtx._43 = trans.z;
//enable tangents for all submeshes, if we need them
s32 meshId;
for(meshId = 0; meshId < m_pCalCoreModel->getCoreMeshCount(); meshId++)
{
s32 submeshId;
for(submeshId = 0; submeshId < m_pCalCoreModel->getCoreMesh(meshId)->getCoreSubmeshCount() ; submeshId++)
{
CalCoreSubmesh * Submesh = m_pCalCoreModel->getCoreMesh(meshId)->getCoreSubmesh(submeshId);
s32 matThreadId = Submesh->getCoreMaterialThreadId();
CalCoreMaterial *pCoreMaterial= m_pCalCoreModel->getCoreMaterial(m_pCalCoreModel->getCoreMaterialId(matThreadId, 0));
//pCoreMaterial->setUserData
if(pCoreMaterial)
{
hEFFECT fx = (hEFFECT)pCoreMaterial->getUserData();
//check to see if we want bumpmap
if(fx)
{
FLAGS fxFlag = ((hIEFFECT)fx)->GetFlag();
if(TESTFLAGS(fxFlag, EFFECT_TANGENT))
SETFLAG(m_flag, MODEL_TANGENT);
if(TESTFLAGS(fxFlag, EFFECT_BINORMAL))
SETFLAG(m_flag, MODEL_BINORMAL);
if(TESTFLAGS(m_flag, MODEL_TANGENT))
Submesh->enableTangents(0,TRUE);
}
}
}
}
//create the buffers
m_fvf = GFXFVF_XYZ | GFXFVF_NORMAL | GFXFVF_TEX1;
return _Cal3DCreateBuffer();
}
u32 IgfxModel::Cal3DGetNumMat()
{
return m_pCalCoreModel->getCoreMaterialCount();
}
hEFFECT IgfxModel::Cal3DGetEffect(u32 ind)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial)
return (hEFFECT)pCoreMaterial->getUserData();
}
return 0;
}
void IgfxModel::Cal3DSetEffect(u32 ind, hEFFECT fx)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial)
{
if(pCoreMaterial->getUserData()) ((hEFFECT)pCoreMaterial->getUserData())->Release();
pCoreMaterial->setUserData((Cal::UserData)fx);
if(fx) fx->AddRef();
}
}
}
hTXT IgfxModel::Cal3DGetTxt(u32 ind, u32 mapInd)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial && mapInd < pCoreMaterial->getMapCount())
return (hTXT)pCoreMaterial->getMapUserData(mapInd);
}
return 0;
}
void IgfxModel::Cal3DSetTxt(u32 ind, u32 mapInd, hTXT txt)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial && mapInd < pCoreMaterial->getMapCount())
{
pCoreMaterial->setMapUserData(mapInd, (Cal::UserData)txt);
if(txt) txt->AddRef();
}
}
}
void IgfxModel::Cal3DGetMtrl(u32 ind, gfxMaterial *pMtrl)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial && pMtrl)
{
CalCoreMaterial::Color clr;
clr = pCoreMaterial->getDiffuseColor();
pMtrl->Diffuse.x = clr.red/255.0f;
pMtrl->Diffuse.y = clr.green/255.0f;
pMtrl->Diffuse.z = clr.blue/255.0f;
pMtrl->Diffuse.w = clr.alpha/255.0f;
clr = pCoreMaterial->getAmbientColor();
pMtrl->Ambient.x = clr.red/255.0f;
pMtrl->Ambient.y = clr.green/255.0f;
pMtrl->Ambient.z = clr.blue/255.0f;
pMtrl->Ambient.w = clr.alpha/255.0f;
clr = pCoreMaterial->getSpecularColor();
pMtrl->Specular.x = clr.red/255.0f;
pMtrl->Specular.y = clr.green/255.0f;
pMtrl->Specular.z = clr.blue/255.0f;
pMtrl->Specular.w = clr.alpha/255.0f;
pMtrl->Power = pCoreMaterial->getShininess();
pMtrl->Emissive.x=0.0f;pMtrl->Emissive.y=0.0f;pMtrl->Emissive.z=0.0f;pMtrl->Emissive.w=0.0f;
}
}
}
void IgfxModel::Cal3DSetMtrl(u32 ind, const gfxMaterial *pMtrl)
{
if(ind < m_pCalCoreModel->getCoreMaterialCount())
{
CalCoreMaterial *pCoreMaterial;
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(ind);
if(pCoreMaterial)
{
CalCoreMaterial::Color clr;
clr.red = (u8)(pMtrl->Ambient.x*255.0f);
clr.green = (u8)(pMtrl->Ambient.y*255.0f);
clr.blue = (u8)(pMtrl->Ambient.z*255.0f);
clr.alpha = (u8)(pMtrl->Ambient.w*255.0f);
pCoreMaterial->setAmbientColor(clr);
clr.red = (u8)(pMtrl->Diffuse.x*255.0f);
clr.green = (u8)(pMtrl->Diffuse.y*255.0f);
clr.blue = (u8)(pMtrl->Diffuse.z*255.0f);
clr.alpha = (u8)(pMtrl->Diffuse.w*255.0f);
pCoreMaterial->setDiffuseColor(clr);
clr.red = (u8)(pMtrl->Specular.x*255.0f);
clr.green = (u8)(pMtrl->Specular.y*255.0f);
clr.blue = (u8)(pMtrl->Specular.z*255.0f);
clr.alpha = (u8)(pMtrl->Specular.w*255.0f);
pCoreMaterial->setSpecularColor(clr);
pCoreMaterial->setShininess(pMtrl->Power);
}
}
}
void IgfxModel::Cal3DDestroy()
{
if(m_pCalCoreModel)
{
// get the core material
CalCoreMaterial *pCoreMaterial;
for(s32 matID = 0; matID < m_pCalCoreModel->getCoreMaterialCount(); matID++)
{
pCoreMaterial = m_pCalCoreModel->getCoreMaterial(matID);
// loop through all maps of the core material
for(s32 mapId = 0; mapId < pCoreMaterial->getMapCount(); mapId++)
{
if(pCoreMaterial->getMapUserData(mapId))
((hTXT)pCoreMaterial->getMapUserData(mapId))->Release();
}
//destroy fx
if(pCoreMaterial->getUserData())
((hEFFECT)pCoreMaterial->getUserData())->Release();
}
//destroy the shadow buffer
gfxCal3D *shadowBuff = (gfxCal3D *)m_pCalCoreModel->getUserData();
if(shadowBuff)
{
if(shadowBuff->shadowVtx)
MemFree(shadowBuff->shadowVtx);
if(shadowBuff->shadowInd)
MemFree(shadowBuff->shadowInd);
MemFree(shadowBuff);
}
delete m_pCalCoreModel;
}
} | [
"david.dionisio@lanternla.com"
] | david.dionisio@lanternla.com |
66310abe182a16c5a6898b0566867f54bed3014d | 2e543d1e0ac96540f03125ba0762b663973191ba | /sgrid/stdafx.cpp | 465093f1b7d7c7f311c0a0575fc830c0d4ad177d | [
"Apache-2.0"
] | permissive | hpcc-systems/eclide | c1ebaca1944d5d107b0d3ee58004581e1d8e8e27 | 38a6e01da20ff2c821f35a8c517f34e427b08ba5 | refs/heads/master | 2023-09-04T00:09:39.538261 | 2023-08-31T16:07:22 | 2023-08-31T16:07:22 | 2,189,986 | 10 | 16 | NOASSERTION | 2023-08-15T15:35:29 | 2011-08-11T08:33:27 | C++ | UTF-8 | C++ | false | false | 198 | cpp | // stdafx.cpp : source file that includes just the standard includes
// sgrid.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"schmoo@oceanfree.net"
] | schmoo@oceanfree.net |
1fff247f4b4b16864d62fb88d1a03282793551d7 | 8339e35782758e576a16d6f8c3e728bb46a5dd44 | /Odd Even Linked List.cpp | 66a892439f85525d17a6188f1f11946c426c4e32 | [] | no_license | arash-ha/Cpp | 019ef465703e31ce4cb1e3f976d46f872d58a360 | d403ce0e3215179cf547c3c02f5b2441d4f4abbc | refs/heads/master | 2023-09-04T11:31:41.820492 | 2023-08-28T14:17:29 | 2023-08-28T14:17:29 | 212,376,838 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | /*
Odd Even Linked List
Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.
Example 1:
Input: 1->2->3->4->5->NULL
Output: 1->3->5->2->4->NULL
Example 2:
Input: 2->1->3->5->6->4->7->NULL
Output: 2->3->6->7->1->5->4->NULL
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if(!head || !head -> next || !head -> next -> next) return head;
ListNode *odd = head, *even = head -> next, *temp = head -> next;
while(even && even -> next){
odd = odd -> next = even -> next;
even = even -> next = even -> next -> next;
}
odd -> next = temp;
return head;
}
};
| [
"54961176+arash-ha@users.noreply.github.com"
] | 54961176+arash-ha@users.noreply.github.com |
ab96e05cb9a252ceb660e66c1c91f7eaa979e39c | ebcede46cf404c5781e7681674b0e1c26a3a26f9 | /CPUT/source/CPUTParser.cpp | 7242ae4af0ee4af0361eba2f9220468f41eb8b12 | [
"Apache-2.0"
] | permissive | whztt07/FaceMapping2 | 539f0a7a0ed038f9fea41d8b13d9d09f954177e8 | a8c1125fd5f5e3a6c54c5f2f3f5b2bc6fe300be2 | refs/heads/master | 2020-07-13T15:51:57.053730 | 2017-06-05T19:35:58 | 2017-06-05T19:35:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,580 | cpp | /////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// 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 imlied.
// See the License for the specific language governing permissions and
// limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////
#include "CPUTParser.h"
#include <vector>
#include <sstream>
//
// The Command Parser class will retrieve values from a string and store them internally.
// An application can then query for different parameters. All of the query functions are
// guaranteed to not modify the return variable if the parameter was not found.
//
CommandParser::~CommandParser()
{
CleanConfigurationOptions();
}
void CommandParser::ParseConfigurationOptions(int argc, char **argv, std::string delimiter)
{
std::string commandLine;
for (int i = 0; i < argc; i++) {
commandLine.append(argv[i]);
commandLine.append(" ");
}
ParseConfigurationOptions(commandLine, delimiter);
}
//
// This function parses configuration options from a text string. Removes any previous
// options stored in the configuration list.
//
void CommandParser::ParseConfigurationOptions(std::string arguments, std::string delimiter)
{
CleanConfigurationOptions();
std::vector<std::string> argumentList;
size_t pos;
size_t nextPos = arguments.find(delimiter.c_str(), 0);
if (nextPos > 0) {
AddParameter("default", arguments.substr(0, nextPos));
}
//
// Break out parameters from command line
//
while (nextPos != std::string::npos) {
pos = nextPos + delimiter.length();
nextPos = arguments.find(delimiter.c_str(), pos);
argumentList.push_back(arguments.substr(pos, nextPos - pos));
}
//
// Remove leading spaces from arguments.
//
for (std::vector<std::string>::iterator it = argumentList.begin(); it != argumentList.end(); it++) {
std::string::size_type pos = it->find_first_not_of(' ');
if (pos != std::string::npos) {
it->erase(0, pos);
}
}
//
// Remove trailing spaces from arguments
//
for (std::vector<std::string>::iterator it = argumentList.begin(); it != argumentList.end(); it++) {
std::string::size_type pos = it->find_last_not_of(' ');
if (pos != std::string::npos) {
it->erase(pos + 1);
}
}
//
// Split the values from the parameter name
//
std::string arg;
for (std::vector<std::string>::iterator it = argumentList.begin(); it != argumentList.end(); it++) {
arg = *it;
pos = arg.find_first_of(":", 0);
if (pos != std::string::npos) {
m_Arguments.insert(std::make_pair(arg.substr(0, pos), arg.substr(pos + 1, std::string::npos)));
} else {
m_Arguments.insert(std::make_pair(arg.substr(0, pos), ""));
}
}
return;
}
void CommandParser::CleanConfigurationOptions(void)
{
m_Arguments.clear();
return;
}
bool CommandParser::GetParameter(std::string arg)
{
std::map<std::string, std::string>::iterator it;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
return true;
}
bool CommandParser::GetParameter(std::string arg, int *pOut)
{
std::map<std::string, std::string>::iterator it;
std::stringstream ss;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
ss << it->second;
ss >> *pOut;
return true;
}
bool CommandParser::GetParameter(std::string arg, double *pOut)
{
std::map<std::string, std::string>::iterator it;
std::stringstream ss;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
ss << it->second;
ss >> *pOut;
return true;
}
bool CommandParser::GetParameter(std::string arg, unsigned int *pOut)
{
std::map<std::string, std::string>::iterator it;
std::stringstream ss;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
ss << it->second;
ss >> *pOut;
return true;
}
bool CommandParser::GetParameter(std::string arg, std::string *pOut)
{
std::map<std::string, std::string>::iterator it;
std::stringstream ss;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
ss << it->second;
*pOut = ss.str();
return true;
}
// buffer pointed to by pOut must be large enough for data
bool CommandParser::GetParameter(std::string arg, char *pOut)
{
std::map<std::string, std::string>::iterator it;
std::stringstream ss;
it = m_Arguments.find(arg);
if (it == m_Arguments.end())
return false;
ss << it->second;
ss >> pOut;
return true;
}
void CommandParser::AddParameter(std::string paramName, std::string paramValue)
{
m_Arguments.insert(std::make_pair(paramName, paramValue));
}
| [
"marissa@galacticsoft.net"
] | marissa@galacticsoft.net |
94a69cd9a52161f66496258f04cc84201ff0960e | 1b3b7fe9d90cb1933b675b46dfa9aae1a5202da8 | /Bit Manipulation/unique_number_2.cpp | 850f41bc07d40cbdba7fe2edb0b0f8d69845776a | [] | no_license | AJ-54/Coding-BLocks-CP-Solutions | d923725419bee837f49ac6caee8ce81a11d2652b | 9b735d73a2b288878ee6d8d2e67558d57a2d3d48 | refs/heads/master | 2022-12-17T07:08:37.745944 | 2020-09-17T14:47:23 | 2020-09-17T14:47:23 | 296,355,829 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | #include<iostream>
#include<bits/stdc++.h>
#include<cstring>
using namespace std;
int arr[100000]={0};
int main() {
long int n,ans=0,ans1=0,ans2=0;
cin >> n;
for(long int j=0;j<n;j++) {
cin>>arr[j];
ans^=arr[j];
}
ans=ans&~(ans-1);
for (long int j=0;j<n;j++){
if (arr[j]&ans) ans1^=arr[j];
else ans2^=arr[j];
}
cout<<ans2<<' '<<ans1<<endl;
} | [
"ayushjai@iitg.ac.in"
] | ayushjai@iitg.ac.in |
c737c9e849b589036783bfcd585046ebac6ead08 | 5c7a6c37cf471d05f2813723e34bc1a016d8b06d | /M5Stack_MultiApp_Firmware/Apps/Tools/DhtReader.cpp | 065e4ac0a079fee309cec397b2f5acb9c10fca7d | [] | no_license | PartsandCircuits/M5Stack_MultiApp_Firmware | 575b2623c36604a4aabc88bb7f1036cfd136bc2a | 71c44176790e0206c771081833ebe164076a1bf2 | refs/heads/master | 2020-03-13T13:39:27.571405 | 2018-04-26T11:52:59 | 2018-04-26T11:52:59 | 131,143,251 | 1 | 0 | null | 2018-04-26T11:03:56 | 2018-04-26T11:03:56 | null | UTF-8 | C++ | false | false | 1,546 | cpp | #include "../../apps.h"
unsigned int dhtPin = 17;
unsigned long past = 0;
float temperature, humidity, oldtemperature, oldhumidity;
DHTesp dht;
void Dht_Run()
{
M5.Lcd.fillScreen(BLACK);
M5.Lcd.drawCentreString("Pin 17 to DHT Signal Pin", 155, 120, 4);
delay(5000);
dht.setup(dhtPin, DHTesp::AUTO_DETECT);
MyMenu.drawAppMenu(F("DHT Reader"), F("ESC"), F(""), F(""));
while (!M5.BtnA.wasPressed())
{
unsigned long start = millis();
if (start - past >= 3000)
{
temperature = dht.getTemperature();
humidity = dht.getHumidity();
if (temperature != oldtemperature || humidity != oldhumidity)
{
M5.Lcd.drawCentreString("Temperature", 60, 80, 2);
M5.Lcd.drawCentreString(String(temperature), 60, 100, 4);
M5.Lcd.drawCentreString("'C", 60, 125, 2);
M5.Lcd.drawCentreString("Humidity", 260, 80, 2);
M5.Lcd.drawCentreString(String(humidity), 260, 100, 4);
M5.Lcd.drawCentreString("%RH", 260, 125, 2);
M5.Lcd.VprogressBar(120, 50, 20, 100, RED, int(dht.getTemperature()));
M5.Lcd.fillCircle(129, 160, 20, RED);
M5.Lcd.VprogressBar(180, 50, 20, 100, BLUE, int(dht.getHumidity()));
M5.Lcd.fillCircle(189, 160, 20, BLUE);
oldtemperature = temperature;
oldhumidity = humidity;
}
past = start;
}
M5.update();
}
return;
} | [
"botofancalin@gmail.com"
] | botofancalin@gmail.com |
7777d3e7c6c78638b7178769dd16fcd3874a76b4 | 76e493f8aa37ea2793f3091e4e245aef045ecce1 | /data/tplcache/ad3253c5165c55d7311d969a6906bdab.inc | bf7fea758e11a052a75f3d8b1702b302edbc581b | [] | no_license | z342526265/baobei | a311a6759ce7c441a2bf1968bed102005fa34d4f | 87babdc1e150372eb6af4ecd1ea89f8acd17861f | refs/heads/master | 2020-05-28T04:33:00.634380 | 2013-03-27T01:06:42 | 2013-03-27T01:06:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | inc | {dede:pagestyle maxwidth='800' pagepicnum='12' ddmaxwidth='200' row='3' col='4' value='2'/}
{dede:img ddimg='/uploads/allimg/130322/1-130322154617.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154617.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154622.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154622.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154623.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154623.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154623-50.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154623-50.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154623-51.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154623-51.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154624.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154624.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154625.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154625.jpg {/dede:img}
{dede:img ddimg='/uploads/allimg/130322/1-130322154625-50.jpg' text='' width='1123' height='1685'} /uploads/allimg/130322/1-130322154625-50.jpg {/dede:img}
| [
"ubuntu@ubuntu.(none)"
] | ubuntu@ubuntu.(none) |
75045c92b72043ba46bd30f7e79e1f5afacd7302 | f5a6a91529f78a1ba4a32b98df67148921f213dc | /src/Component/Cube.hpp | 4785702f7f9123e93d5e79bedc98190412e40c75 | [] | no_license | study-game-engines/merlin | 70e525ffb0274162793872b8a0f09e4cec3b2eae | d41fa8007121a5a0a27180350c978377b03d444c | refs/heads/master | 2023-03-16T01:32:03.828464 | 2018-05-30T23:35:04 | 2018-05-30T23:35:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | hpp | #pragma once
#include <glm/vec3.hpp>
#include "Object.hpp"
namespace Component {
class Cube {
public:
Cube(Object*);
~Cube();
Object *getObject() const;
void setObject(Object *object);
const glm::vec3 &getPosition() const;
void setPosition(const glm::vec3 &position);
const glm::vec3 &getVelocity() const;
void setVelocity(const glm::vec3 &velocity);
float getMass() const;
void setMass(float mass);
double distanceTo(glm::vec3);
private:
Object *object;
glm::vec3 position;
glm::vec3 velocity;
float mass;
};
} | [
"vlad-negura@mail.ru"
] | vlad-negura@mail.ru |
0e0df821958907066009c757cfa44607f08cb1ae | 75769bea756af71dd3359711c0d96a08849ae7b8 | /cn/localhost01/lteenodeb/lte_rrc/rrc/asn/include/rtsrc/ASN1CGeneralizedTime.h | a7e1fe3887ce9cbcd32741398daecc15f776ead2 | [] | no_license | windy-zzf/C_code_annalyze | ed986c6c24b7e410eae9790736209f8b0dbf15a8 | da038bcc9eda6a853f13bb39313917a16694271b | refs/heads/master | 2023-03-27T04:09:28.453216 | 2021-03-29T05:47:41 | 2021-03-29T05:47:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,922 | h | /*
* Copyright (c) 1997-2017 Objective Systems, Inc.
*
* This software is furnished under a license and may be used and copied
* only in accordance with the terms of such license and with the
* inclusion of the above copyright notice. This software or any other
* copies thereof may not be provided or otherwise made available to any
* other person. No title to and ownership of the software is hereby
* transferred.
*
* The information in this software is subject to change without notice
* and should not be construed as a commitment by Objective Systems, Inc.
*
* PROPRIETARY NOTICE
*
* This software is an unpublished work subject to a confidentiality agreement
* and is protected by copyright and trade secret law. Unauthorized copying,
* redistribution or other use of this work is prohibited.
*
* The above notice of copyright on this source code product does not indicate
* any actual or intended publication of such source code.
*
*****************************************************************************/
#ifndef __ASN1CGENTIME_H__
#define __ASN1CGENTIME_H__
#include "rtsrc/ASN1CTime.h"
/**
* @file rtsrc/ASN1CGeneralizedTime.h
* GeneralizedTime control class definition.
*/
/**
* @addtogroup asn1ctrl
* @{
*/
/**
* @addtogroup asn1ctime
* @{
*/
//////////////////////////////////////////////////////////////////////
//
// ASN1CGeneralizedTime
//
// ISO 8601 time and date for ITU-T X.680.
//
// Author Artem Bolgar.
// version 3.00 03 Sep, 2004 (refactored to use ASN1TGeneralizedTime)
//
// version 2.13 11 Jul, 2003 (2038 year problem fixed + some other fixes)
// version 1.11 03 Aug, 2002
//
#ifndef _NO_UTILS_CLASSES
/**
* ASN.1 GeneralizedTime control class.
* The ASN1CGeneralizedTime class is derived from the ASN1CTime base class. It
* is used as the base class for generated control classes for the ASN.1
* Generalized Time ([UNIVERSAL 24] IMPLICIT VisibleString) type. This class
* provides utility methods for operating on the time information referenced by
* the generated class. This class can also be used inline to operate on the
* times within generated time string elements in a SEQUENCE, SET, or CHOICE
* construct. The time string generally is encoded according to ISO 8601 format
* with some exceptions (see X.680).
*/
class EXTRTCLASS ASN1CGeneralizedTime : public ASN1CTime {
protected:
ASN1TGeneralizedTime timeObj;
virtual ASN1TTime& getTimeObj () { return timeObj; }
virtual const ASN1TTime& getTimeObj () const { return timeObj; }
EXTRTMETHOD ASN1CGeneralizedTime(char*& buf, int bufSize, OSBOOL useDerRules = FALSE);
EXTRTMETHOD ASN1CGeneralizedTime(ASN1GeneralizedTime& buf,
OSBOOL useDerRules = FALSE);
public:
/**
* This constructor creates a time string from a buffer. It does not deep-copy
* the data, it just assigns the passed array to an internal reference
* variable. The object will then directly operate on the given data variable.
*
* @param msgBuf Reference to an OSRTMessage buffer derived object (for
* example, an ASN1BEREncodeBuffer).
* @param buf A reference pointer to the time string buffer.
* @param bufSize The size of the passed buffer, in bytes.
* @param useDerRules An OSBOOL value.
*/
EXTRTMETHOD ASN1CGeneralizedTime(OSRTMessageBufferIF& msgBuf, char*& buf, int bufSize,
OSBOOL useDerRules = FALSE);
/**
* This constructor creates a time string using the ASN1GeneralizedTime
* argument. The constructor does not deep-copy the variable, it assigns a
* reference to it to an internal variable. The object will then directly
* operate on the given data variable. This form of the constructor is used
* with a complier-generated time string variable.
*
* @param msgBuf Reference to an OSRTMessage buffer derived object (for
* example, an ASN1BEREncodeBuffer).
* @param buf A reference pointer to the time string buffer.
* @param useDerRules An OSBOOL value.
*/
EXTRTMETHOD ASN1CGeneralizedTime(OSRTMessageBufferIF& msgBuf, ASN1GeneralizedTime& buf,
OSBOOL useDerRules = FALSE);
/**
* This constructor creates a time string from buffer.
*
* It does not deep-copy the data; it just assigns the passed array to an
* internal reference variable. The object will then directly operate on the
* given data variable.
*
* @param ctxt Reference to an ::OSRTContext data structure.
* @param buf Reference to a pointer to a time string buffer.
* @param bufSize Size of buffer in bytes.
* @param useDerRules Use the Distinguished Encoding Rules (DER) to operate
* on this time value.
*/
EXTRTMETHOD ASN1CGeneralizedTime(OSRTContext& ctxt, char*& buf, int bufSize,
OSBOOL useDerRules = FALSE);
/**
* This constructor creates a time string from an ::ASN1GeneralizedTime
* object.
*
* It does not deep-copy the data; it just assigns the passed array to an
* internal reference variable. The object will then directly operate on the
* given data variable.
*
* @param ctxt Reference to an ::OSRTContext data structure.
* @param buf Reference to a pointer to a time string buffer.
* @param useDerRules Use the Distinguished Encoding Rules (DER) to operate
* on this time value.
*/
EXTRTMETHOD ASN1CGeneralizedTime(OSRTContext& ctxt, ASN1GeneralizedTime& buf,
OSBOOL useDerRules = FALSE);
// copy ctor
/**
* The copy constructor. This does not deep-copy the original value.
* Instead, it assigns references to the internal components.
*
* @param original The original time string object value.
*/
ASN1CGeneralizedTime (const ASN1CGeneralizedTime& original) :
ASN1CTime (original) {}
/**
* This method returns the century part (first two digits) of the year
* component of the time value.
*
* @param - none
* @return Century part (first two digits) of the year component
* is returned if the operation is sucessful. If the
* operation fails, one of the negative status codes is
* returned.
*/
EXTRTMETHOD int getCentury();
/**
* This method sets the century part (first two digits) of the year component
* of the time value.
*
* @param century Century part (first two digits) of the year component.
* @return Completion status of operation:
* - 0 (0) = success,
* - negative return value is error.
*/
EXTRTMETHOD int setCentury(short century);
/**
* This converts the value of the C built-in type time_t to a time string.
*
* The value is the number of seconds from January 1, 1970. Note that the
* action of this method may differ for different inherited ASN1CTime
* Classes.
*
* @param time The time value, expressed as a number of seconds from
* January 1, 1970.
* @param diffTime TRUE means the difference between local time and UTC
* time will be calculated; in other case, only local
* time will be stored.
* @return Completion status of operation:
* - 0 (0) = success,
* - negative return value is error.
*/
EXTRTMETHOD int setTime(time_t time, OSBOOL diffTime);
const ASN1CGeneralizedTime& operator = (const ASN1CGeneralizedTime& tm) {
return (const ASN1CGeneralizedTime&) ASN1CTime::operator = (tm);
}
protected:
/**
* Compiles new time string accoring X.680 (clause 41) and ISO 8601.
* Returns 0, if succeed, or error code, if error.
*
* @return 0 on success, or an error code otherwise.
*/
EXTRTMETHOD int compileString();
} ;
#else
typedef class _ASN1CGeneralizedTime : public _ASN1CTime {
protected:
_ASN1CGeneralizedTime(char*& buf, int bufSize, OSBOOL useDerRules) {}
_ASN1CGeneralizedTime(ASN1VisibleString& buf, OSBOOL useDerRules) {}
public:
_ASN1CGeneralizedTime (OSRTMessageBufferIF& msgBuf, char*& buf, int sz,
OSBOOL useDerRules = FALSE) :
_ASN1CTime (msgBuf, buf, sz, useDerRules) {}
_ASN1CGeneralizedTime (OSRTMessageBufferIF& msgBuf, ASN1VisibleString& buf,
OSBOOL useDerRules = FALSE) :
_ASN1CTime (msgBuf, buf, useDerRules) {}
_ASN1CGeneralizedTime(OSRTContext& ctxt, char*& buf, int bufSize,
OSBOOL useDerRules) : _ASN1CTime (ctxt, buf, bufSize, useDerRules) {}
_ASN1CGeneralizedTime(OSRTContext& ctxt, ASN1VisibleString& buf,
OSBOOL useDerRules) : _ASN1CTime (ctxt, buf, bufSize, useDerRules) {}
} ASN1CGeneralizedTime;
#endif // _NO_UTILS_CLASSES
/**
* @}ASN1CGeneralizedTime
*/
/**
* @} asn1ctrl
*/
#endif //__ASN1CGENTIME_H__
| [
"820713556@qq.com"
] | 820713556@qq.com |
0be5ce8823bd26f5974fc8b380ee1d7312853f37 | a85a1e6c776e0433c30aa5830aa353a82f4c8833 | /coregame/soundfx_type.h | be135bf1fc1a2879ef47363cd6bff50881b46b78 | [] | no_license | IceCube-22/darkreign2 | fe97ccb194b9eacf849d97b2657e7bd1c52d2916 | 9ce9da5f21604310a997f0c41e9cd383f5e292c3 | refs/heads/master | 2023-03-20T02:27:03.321950 | 2018-10-04T10:06:38 | 2018-10-04T10:06:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,762 | h | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright 1997-1999 Pandemic Studios, Dark Reign II
//
// Sound Effects
//
// 08-FEB-1999
//
#ifndef __SOUNDFX_TYPE_H
#define __SOUNDFX_TYPE_H
///////////////////////////////////////////////////////////////////////////////
//
// Includes
//
#include "fscope.h"
#include "utiltypes.h"
#include "mapobjdec.h"
///////////////////////////////////////////////////////////////////////////////
//
// NameSpace SoundFX
//
namespace SoundFX
{
///////////////////////////////////////////////////////////////////////////////
//
// Forward Declarations
//
class Object;
///////////////////////////////////////////////////////////////////////////////
//
// Struct CallBackData
//
struct CallBackData
{
// Volume
F32 volume;
// Constructor
CallBackData();
};
///////////////////////////////////////////////////////////////////////////////
//
// Class Type
//
class Type
{
private:
// Wave file
GameIdent file;
// Priority of the sound effect
F32 priority;
// Distance where sound is maxed
F32 maxDistance;
// Distance where sond is minimum
F32 minDistance;
// Flags
U8 useOwner : 1, // Use owner (to prevent talking out of both sides of mouth)
alwaysHear : 1, // Hear the sound regardless of wether its out of sight
loop : 1; // Loop the sound around and around and around and around
public:
// Constructor and Destructor
Type(FScope *fScope)
{
Setup( fScope);
}
~Type();
void Setup(FScope *fScope);
// Post Load
void PostLoad(MapObjType *mapObjType);
// Friends
friend class Object;
};
}
#endif | [
"eider@protonmail.com"
] | eider@protonmail.com |
4b701154e5e10f40331ba3bf96d39baf2460ebdc | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/libs/dll/test/cpp_load_test.cpp | 4b6d9b5cbc5db9aec2062df52637bceb067ba43f | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,648 | cpp | // Copyright 2016 Klemens Morgenstern
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
// For more information, see http://www.boost.org
#include <sstd/boost/predef.h>
#if (__cplusplus >= 201402L) || (BOOST_COMP_MSVC >= BOOST_VERSION_NUMBER(14,0,0))
#include "../example/b2_workarounds.hpp"
#include <sstd/boost/dll/smart_library.hpp>
#include <sstd/boost/core/lightweight_test.hpp>
#include <sstd/boost/filesystem.hpp>
#include <sstd/boost/variant.hpp>
#include <iostream>
struct override_class
{
int arr[32];
};
int main(int argc, char* argv[])
{
using namespace boost::dll;
using namespace boost::dll::experimental;
boost::filesystem::path pt = b2_workarounds::first_lib_from_argv(argc, argv);
BOOST_TEST(!pt.empty());
std::cout << "Library: " << pt << std::endl;
smart_library sm(pt);
auto& unscoped_var = sm.get_variable<int>("unscoped_var");
BOOST_TEST(unscoped_var == 42);
auto& unscoped_c_var = sm.get_variable<const double>("unscoped_c_var");
BOOST_TEST(unscoped_c_var == 1.234);
auto& sp_variable = sm.get_variable<double>("some_space::variable");
BOOST_TEST(sp_variable == 0.2);
auto scoped_fun = sm.get_function<const int&()>("some_space::scoped_fun");
BOOST_TEST(scoped_fun != nullptr);
{
auto &res = scoped_fun();
const int expected = 0xDEADBEEF;
BOOST_TEST(res == expected);
}
auto ovl1 = sm.get_function<void(int)> ("overloaded");
auto ovl2 = sm.get_function<void(double)>("overloaded");
BOOST_TEST(ovl1 != nullptr);
BOOST_TEST(ovl2 != nullptr);
BOOST_TEST(reinterpret_cast<void*>(ovl1) != reinterpret_cast<void*>(ovl2));
ovl1(12);
BOOST_TEST(unscoped_var == 12);
ovl2(5.0);
BOOST_TEST(sp_variable == 5.0);
auto var1 = sm.get_function<void(boost::variant<int, double> &)>("use_variant");
auto var2 = sm.get_function<void(boost::variant<double, int> &)>("use_variant");
BOOST_TEST(var1 != nullptr);
BOOST_TEST(var2 != nullptr);
BOOST_TEST(reinterpret_cast<void*>(var1) != reinterpret_cast<void*>(var2));
{
boost::variant<int, double> v1 = 232.22;
boost::variant<double, int> v2 = -1;
var1(v1);
var2(v2);
struct : boost::static_visitor<void>
{
void operator()(double) {BOOST_TEST(false);}
void operator()(int i) {BOOST_TEST(i == 42);}
} vis1;
struct : boost::static_visitor<void>
{
void operator()(double d) {BOOST_TEST(d == 3.124);}
void operator()(int ) {BOOST_TEST(false);}
} vis2;
boost::apply_visitor(vis1, v1);
boost::apply_visitor(vis2, v2);
}
/* now test the class stuff */
//first we import and test the global variables
auto& father_val = sm.get_variable<int>("some_space::father_value");
auto& static_val = sm.get_variable<int>("some_space::some_class::value");
BOOST_TEST(father_val == 12);
BOOST_TEST(static_val == -1);
//now get the static function.
auto set_value = sm.get_function<void(const int &)>("some_space::some_class::set_value");
BOOST_TEST(set_value != nullptr);
set_value(42);
BOOST_TEST(static_val == 42); //alright, static method works.
//alright, now import the class members
//first add the type alias.
sm.add_type_alias<override_class>("some_space::some_class");
auto set = sm.get_mem_fn<override_class, void(int)>("set");
try {
sm.get_mem_fn<override_class, int()>("get");
BOOST_TEST(false);
} catch(boost::system::system_error &) {}
auto get = sm.get_mem_fn<const override_class, int()>("get");
BOOST_TEST(get != nullptr);
BOOST_TEST(set != nullptr);
auto func_dd = sm.get_mem_fn<override_class, double(double, double)>("func");
auto func_ii = sm.get_mem_fn<override_class, int(int, int)> ("func");
auto func_iiv = sm.get_mem_fn<volatile override_class, int(int, int)> ("func");
auto func_ddc = sm.get_mem_fn<const volatile override_class, double(double, double)>("func");
BOOST_TEST(func_dd != nullptr);
BOOST_TEST(func_ii != nullptr);
auto ctor_v = sm.get_constructor<override_class()>();
auto ctor_i = sm.get_constructor<override_class(int)>();
auto dtor = sm.get_destructor<override_class>();
//actually never used.
if (ctor_v.has_allocating())
{
//allocate
auto p = ctor_v.call_allocating();
//assert it works
auto val = (p->*get)();
BOOST_TEST(val == 123);
//deallocate
dtor.call_deleting(p);
//now i cannot assert that it deletes, since it would crash.
}
//More tests to assure the correct this-ptr
typedef override_class * override_class_p;
override_class_p &this_dll = sm.shared_lib().get<override_class_p>("this_");
//ok, now load the ctor/dtor
override_class oc;
override_class_p this_exe = &oc;
for (auto& i : oc.arr) {
i = 0;
}
BOOST_TEST((oc.*get)() == 0); BOOST_TEST(this_dll == this_exe);
ctor_i.call_standard(&oc, 12); BOOST_TEST(this_dll == this_exe);
BOOST_TEST(static_val == 12);
BOOST_TEST((oc.*get)() == 456); BOOST_TEST(this_dll == this_exe);
(oc.*set)(42);
BOOST_TEST((oc.*get)() == 42); BOOST_TEST(this_dll == this_exe);
BOOST_TEST((oc.*func_dd)(3,2) == 6); BOOST_TEST(this_dll == this_exe);
BOOST_TEST((oc.*func_ii)(1,2) == 3); BOOST_TEST(this_dll == this_exe);
BOOST_TEST((oc.*func_ddc)(10,2) == 5); BOOST_TEST(this_dll == this_exe);
BOOST_TEST((oc.*func_iiv)(9,2) == 7); BOOST_TEST(this_dll == this_exe);
dtor.call_standard(&oc); BOOST_TEST(this_dll == this_exe);
BOOST_TEST(static_val == 0);
const auto& ti = sm.get_type_info<override_class>();
BOOST_TEST(ti.name() != nullptr);
//test the ovls helper.
{
namespace ex = boost::dll::experimental;
auto &var = ex::get<double>(sm, "some_space::variable");
BOOST_TEST(&var == &sp_variable);
auto fun = ex::get<void(int)>(sm, "overloaded");
BOOST_TEST(fun == ovl1);
auto func_ii = sm.get_mem_fn<override_class, int(int, int)> ("func");
auto mem_fn = ex::get<override_class, int(int, int)>(sm, "func");
BOOST_TEST(mem_fn == func_ii);
}
return boost::report_errors();
}
#else
int main() {return 0;}
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
a89ef760b73d831dece1997d9a7d9dd47676e6df | 7ddf927418bb3c1db7b144f1f54ab840427994bf | /src/backend/cpu/kernel/fftconvolve.hpp | ca192f5626681455fbcb478227f15ba88fd9edc3 | [
"BSD-3-Clause",
"MIT",
"Zlib",
"BSL-1.0",
"Apache-2.0"
] | permissive | bkloppenborg/arrayfire | bddc3280ede7958b2ccfc41442192be8aa7f80ea | 4d625e70852fe923dd35f324f6f24d9553c649f2 | refs/heads/devel | 2021-01-18T01:34:12.743154 | 2016-05-09T04:05:26 | 2016-05-09T04:05:26 | 27,399,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,287 | hpp | /*******************************************************
* Copyright (c) 2015, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#pragma once
#include <Array.hpp>
#include <convolve_common.hpp>
namespace cpu
{
namespace kernel
{
template<typename To, typename Ti>
void packData(Array<To> out, const af::dim4 od, const af::dim4 os, Array<Ti> const in)
{
To* out_ptr = out.get();
const af::dim4 id = in.dims();
const af::dim4 is = in.strides();
const Ti* in_ptr = in.get();
int id0_half = divup(id[0], 2);
bool odd_id0 = (id[0] % 2 == 1);
for (int d3 = 0; d3 < (int)od[3]; d3++) {
for (int d2 = 0; d2 < (int)od[2]; d2++) {
for (int d1 = 0; d1 < (int)od[1]; d1++) {
for (int d0 = 0; d0 < (int)od[0] / 2; d0++) {
const dim_t oidx = d3*os[3] + d2*os[2] + d1*os[1] + d0*2;
if (d0 < (int)id0_half && d1 < (int)id[1] && d2 < (int)id[2] && d3 < (int)id[3]) {
const dim_t iidx = d3*is[3] + d2*is[2] + d1*is[1] + d0;
out_ptr[oidx] = (To)in_ptr[iidx];
if (d0 == id0_half-1 && odd_id0)
out_ptr[oidx+1] = (To)0;
else
out_ptr[oidx+1] = (To)in_ptr[iidx+id0_half];
}
else {
// Pad remaining elements with 0s
out_ptr[oidx] = (To)0;
out_ptr[oidx+1] = (To)0;
}
}
}
}
}
}
template<typename To, typename Ti>
void padArray(Array<To> out, const af::dim4 od, const af::dim4 os,
Array<Ti> const in, const dim_t offset)
{
To* out_ptr = out.get() + offset;
const af::dim4 id = in.dims();
const af::dim4 is = in.strides();
const Ti* in_ptr = in.get();
for (int d3 = 0; d3 < (int)od[3]; d3++) {
for (int d2 = 0; d2 < (int)od[2]; d2++) {
for (int d1 = 0; d1 < (int)od[1]; d1++) {
for (int d0 = 0; d0 < (int)od[0] / 2; d0++) {
const dim_t oidx = d3*os[3] + d2*os[2] + d1*os[1] + d0*2;
if (d0 < (int)id[0] && d1 < (int)id[1] && d2 < (int)id[2] && d3 < (int)id[3]) {
// Copy input elements to real elements, set imaginary elements to 0
const dim_t iidx = d3*is[3] + d2*is[2] + d1*is[1] + d0;
out_ptr[oidx] = (To)in_ptr[iidx];
out_ptr[oidx+1] = (To)0;
}
else {
// Pad remaining of the matrix to 0s
out_ptr[oidx] = (To)0;
out_ptr[oidx+1] = (To)0;
}
}
}
}
}
}
template<typename T>
void complexMultiply(Array<T> packed, const af::dim4 sig_dims, const af::dim4 sig_strides,
const af::dim4 fit_dims, const af::dim4 fit_strides,
ConvolveBatchKind kind, const dim_t offset)
{
T* out_ptr = packed.get() + (kind==CONVOLVE_BATCH_KERNEL? offset : 0);
T* in1_ptr = packed.get();
T* in2_ptr = packed.get() + offset;
const af::dim4& od = (kind==CONVOLVE_BATCH_KERNEL ? fit_dims : sig_dims);
const af::dim4& os = (kind==CONVOLVE_BATCH_KERNEL ? fit_strides : sig_strides);
const af::dim4& i1d = sig_dims;
const af::dim4& i2d = fit_dims;
const af::dim4& i1s = sig_strides;
const af::dim4& i2s = fit_strides;
for (int d3 = 0; d3 < (int)od[3]; d3++) {
for (int d2 = 0; d2 < (int)od[2]; d2++) {
for (int d1 = 0; d1 < (int)od[1]; d1++) {
for (int d0 = 0; d0 < (int)od[0] / 2; d0++) {
if (kind == CONVOLVE_BATCH_NONE || kind == CONVOLVE_BATCH_SAME) {
// Complex multiply each signal to equivalent filter
const int ridx = d3*os[3] + d2*os[2] + d1*os[1] + d0*2;
const int iidx = ridx + 1;
T a = in1_ptr[ridx];
T b = in1_ptr[iidx];
T c = in2_ptr[ridx];
T d = in2_ptr[iidx];
T ac = a*c;
T bd = b*d;
out_ptr[ridx] = ac - bd;
out_ptr[iidx] = (a+b) * (c+d) - ac - bd;
}
else if (kind == CONVOLVE_BATCH_SIGNAL) {
// Complex multiply all signals to filter
const int ridx1 = d3*os[3] + d2*os[2] + d1*os[1] + d0*2;
const int iidx1 = ridx1 + 1;
const int ridx2 = ridx1 % (i2s[3] * i2d[3]);
const int iidx2 = iidx1 % (i2s[3] * i2d[3]);
T a = in1_ptr[ridx1];
T b = in1_ptr[iidx1];
T c = in2_ptr[ridx2];
T d = in2_ptr[iidx2];
T ac = a*c;
T bd = b*d;
out_ptr[ridx1] = ac - bd;
out_ptr[iidx1] = (a+b) * (c+d) - ac - bd;
}
else if (kind == CONVOLVE_BATCH_KERNEL) {
// Complex multiply signal to all filters
const int ridx2 = d3*os[3] + d2*os[2] + d1*os[1] + d0*2;
const int iidx2 = ridx2 + 1;
const int ridx1 = ridx2 % (i1s[3] * i1d[3]);
const int iidx1 = iidx2 % (i1s[3] * i1d[3]);
T a = in1_ptr[ridx1];
T b = in1_ptr[iidx1];
T c = in2_ptr[ridx2];
T d = in2_ptr[iidx2];
T ac = a*c;
T bd = b*d;
out_ptr[ridx2] = ac - bd;
out_ptr[iidx2] = (a+b) * (c+d) - ac - bd;
}
}
}
}
}
}
template<typename To, typename Ti, bool roundOut>
void reorderHelper(To* out_ptr, const af::dim4& od, const af::dim4& os,
const Ti* in_ptr, const af::dim4& id, const af::dim4& is,
const af::dim4& fd, const int half_di0, const int baseDim,
const int fftScale, const bool expand)
{
for (int d3 = 0; d3 < (int)od[3]; d3++) {
for (int d2 = 0; d2 < (int)od[2]; d2++) {
for (int d1 = 0; d1 < (int)od[1]; d1++) {
for (int d0 = 0; d0 < (int)od[0]; d0++) {
int id0, id1, id2, id3;
if (expand) {
id0 = d0;
id1 = d1 * is[1];
id2 = d2 * is[2];
id3 = d3 * is[3];
}
else {
id0 = d0 + fd[0]/2;
id1 = (d1 + (baseDim > 1)*(fd[1]/2)) * is[1];
id2 = (d2 + (baseDim > 2)*(fd[2]/2)) * is[2];
id3 = d3 * is[3];
}
int oidx = d3*os[3] + d2*os[2] + d1*os[1] + d0;
// Divide output elements to cuFFT resulting scale, round result if output
// type is single or double precision floating-point
if (id0 < half_di0) {
// Copy top elements
int iidx = id3 + id2 + id1 + id0 * 2;
if (roundOut)
out_ptr[oidx] = (To)roundf((float)(in_ptr[iidx] / fftScale));
else
out_ptr[oidx] = (To)(in_ptr[iidx] / fftScale);
}
else if (id0 < half_di0 + (int)fd[0] - 1) {
// Add signal and filter elements to central part
int iidx1 = id3 + id2 + id1 + id0 * 2;
int iidx2 = id3 + id2 + id1 + (id0 - half_di0) * 2 + 1;
if (roundOut)
out_ptr[oidx] = (To)roundf((float)((in_ptr[iidx1] + in_ptr[iidx2]) / fftScale));
else
out_ptr[oidx] = (To)((in_ptr[iidx1] + in_ptr[iidx2]) / fftScale);
}
else {
// Copy bottom elements
const int iidx = id3 + id2 + id1 + (id0 - half_di0) * 2 + 1;
if (roundOut)
out_ptr[oidx] = (To)roundf((float)(in_ptr[iidx] / fftScale));
else
out_ptr[oidx] = (To)(in_ptr[iidx] / fftScale);
}
}
}
}
}
}
template<typename T, typename convT, bool roundOut, int baseDim>
void reorder(Array<T> out, Array<convT> packed,
const Array<T> filter, const dim_t sig_half_d0, const dim_t fftScale,
const dim4 sig_tmp_dims, const dim4 sig_tmp_strides,
const dim4 filter_tmp_dims, const dim4 filter_tmp_strides,
bool expand, ConvolveBatchKind kind)
{
T* out_ptr = out.get();
const af::dim4 out_dims = out.dims();
const af::dim4 out_strides = out.strides();
const af::dim4 filter_dims = filter.dims();
convT* packed_ptr = packed.get();
convT* sig_tmp_ptr = packed_ptr;
convT* filter_tmp_ptr = packed_ptr + sig_tmp_strides[3] * sig_tmp_dims[3];
// Reorder the output
if (kind == CONVOLVE_BATCH_KERNEL) {
reorderHelper<T, convT, roundOut>(out_ptr, out_dims, out_strides,
filter_tmp_ptr, filter_tmp_dims, filter_tmp_strides,
filter_dims, sig_half_d0, baseDim, fftScale, expand);
} else {
reorderHelper<T, convT, roundOut>(out_ptr, out_dims, out_strides,
sig_tmp_ptr, sig_tmp_dims, sig_tmp_strides,
filter_dims, sig_half_d0, baseDim, fftScale, expand);
}
}
}
}
| [
"pradeep@arrayfire.com"
] | pradeep@arrayfire.com |
4b3ae7a0bb8c7652dd57dab41505e27915376368 | e4811f3907453ecd25f0ca03ca9c78e8b0cac96c | /CPP/7zip/Compress/BZip2Encoder.h | bf05f59fd45a4f8a5f78a49286d2e1ad700e04e1 | [] | no_license | keithjjones/7z | 9ddff9b524851be04452fdd72e761f0a26e216d2 | 174a5af5960d2bbebc7deb3b7bc622f5f62b9a3e | refs/heads/master | 2021-01-10T08:48:04.232649 | 2016-03-17T20:28:37 | 2016-03-17T20:28:37 | 48,259,207 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,373 | h | // BZip2Encoder.h
#ifndef __COMPRESS_BZIP2_ENCODER_H
#define __COMPRESS_BZIP2_ENCODER_H
#include "../../Common/Defs.h"
#include "../../Common/MyCom.h"
#ifndef _7ZIP_ST
#include "../../Windows/Synchronization.h"
#include "../../Windows/Thread.h"
#endif
#include "../ICoder.h"
#include "../Common/InBuffer.h"
#include "../Common/OutBuffer.h"
#include "BitmEncoder.h"
#include "BZip2Const.h"
#include "BZip2Crc.h"
namespace NCompress {
namespace NBZip2 {
class CMsbfEncoderTemp
{
UInt32 _pos;
unsigned _bitPos;
Byte _curByte;
Byte *_buf;
public:
void SetStream(Byte *buf) { _buf = buf; }
Byte *GetStream() const { return _buf; }
void Init()
{
_pos = 0;
_bitPos = 8;
_curByte = 0;
}
void Flush()
{
if (_bitPos < 8)
WriteBits(0, _bitPos);
}
void WriteBits(UInt32 value, unsigned numBits)
{
while (numBits > 0)
{
unsigned numNewBits = MyMin(numBits, _bitPos);
numBits -= numNewBits;
_curByte <<= numNewBits;
UInt32 newBits = value >> numBits;
_curByte |= Byte(newBits);
value -= (newBits << numBits);
_bitPos -= numNewBits;
if (_bitPos == 0)
{
_buf[_pos++] = _curByte;
_bitPos = 8;
}
}
}
UInt32 GetBytePos() const { return _pos ; }
UInt32 GetPos() const { return _pos * 8 + (8 - _bitPos); }
Byte GetCurByte() const { return _curByte; }
void SetPos(UInt32 bitPos)
{
_pos = bitPos >> 3;
_bitPos = 8 - ((unsigned)bitPos & 7);
}
void SetCurState(unsigned bitPos, Byte curByte)
{
_bitPos = 8 - bitPos;
_curByte = curByte;
}
};
class CEncoder;
const unsigned kNumPassesMax = 10;
class CThreadInfo
{
public:
Byte *m_Block;
private:
Byte *m_MtfArray;
Byte *m_TempArray;
UInt32 *m_BlockSorterIndex;
CMsbfEncoderTemp *m_OutStreamCurrent;
Byte Lens[kNumTablesMax][kMaxAlphaSize];
UInt32 Freqs[kNumTablesMax][kMaxAlphaSize];
UInt32 Codes[kNumTablesMax][kMaxAlphaSize];
Byte m_Selectors[kNumSelectorsMax];
UInt32 m_CRCs[1 << kNumPassesMax];
UInt32 m_NumCrcs;
UInt32 m_BlockIndex;
void WriteBits2(UInt32 value, unsigned numBits);
void WriteByte2(Byte b);
void WriteBit2(Byte v);
void WriteCrc2(UInt32 v);
void EncodeBlock(const Byte *block, UInt32 blockSize);
UInt32 EncodeBlockWithHeaders(const Byte *block, UInt32 blockSize);
void EncodeBlock2(const Byte *block, UInt32 blockSize, UInt32 numPasses);
public:
bool m_OptimizeNumTables;
CEncoder *Encoder;
#ifndef _7ZIP_ST
NWindows::CThread Thread;
NWindows::NSynchronization::CAutoResetEvent StreamWasFinishedEvent;
NWindows::NSynchronization::CAutoResetEvent WaitingWasStartedEvent;
// it's not member of this thread. We just need one event per thread
NWindows::NSynchronization::CAutoResetEvent CanWriteEvent;
UInt64 m_PackSize;
Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size.
HRESULT Create();
void FinishStream(bool needLeave);
DWORD ThreadFunc();
#endif
CThreadInfo(): m_BlockSorterIndex(0), m_Block(0) {}
~CThreadInfo() { Free(); }
bool Alloc();
void Free();
HRESULT EncodeBlock3(UInt32 blockSize);
};
struct CEncProps
{
UInt32 BlockSizeMult;
UInt32 NumPasses;
CEncProps()
{
BlockSizeMult = (UInt32)(Int32)-1;
NumPasses = (UInt32)(Int32)-1;
}
void Normalize(int level);
bool DoOptimizeNumTables() const { return NumPasses > 1; }
};
class CEncoder :
public ICompressCoder,
public ICompressSetCoderProperties,
#ifndef _7ZIP_ST
public ICompressSetCoderMt,
#endif
public CMyUnknownImp
{
UInt32 m_NumThreadsPrev;
public:
CInBuffer m_InStream;
Byte MtPad[1 << 8]; // It's pad for Multi-Threading. Must be >= Cache_Line_Size.
CBitmEncoder<COutBuffer> m_OutStream;
CEncProps _props;
CBZip2CombinedCrc CombinedCrc;
#ifndef _7ZIP_ST
CThreadInfo *ThreadsInfo;
NWindows::NSynchronization::CManualResetEvent CanProcessEvent;
NWindows::NSynchronization::CCriticalSection CS;
UInt32 NumThreads;
bool MtMode;
UInt32 NextBlockIndex;
bool CloseThreads;
bool StreamWasFinished;
NWindows::NSynchronization::CManualResetEvent CanStartWaitingEvent;
HRESULT Result;
ICompressProgressInfo *Progress;
#else
CThreadInfo ThreadsInfo;
#endif
UInt32 ReadRleBlock(Byte *buf);
void WriteBytes(const Byte *data, UInt32 sizeInBits, Byte lastByte);
void WriteBits(UInt32 value, unsigned numBits);
void WriteByte(Byte b);
// void WriteBit(Byte v);
void WriteCrc(UInt32 v);
#ifndef _7ZIP_ST
HRESULT Create();
void Free();
#endif
public:
CEncoder();
#ifndef _7ZIP_ST
~CEncoder();
#endif
HRESULT Flush() { return m_OutStream.Flush(); }
#ifndef _7ZIP_ST
MY_UNKNOWN_IMP2(ICompressSetCoderMt, ICompressSetCoderProperties)
#else
MY_UNKNOWN_IMP1(ICompressSetCoderProperties)
#endif
HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
#ifndef _7ZIP_ST
STDMETHOD(SetNumberOfThreads)(UInt32 numThreads);
#endif
};
}}
#endif
| [
"keith@keithjjones.com"
] | keith@keithjjones.com |
057f43a98fedb52553ed41c828d71c3c931baf14 | 5e2d56ad488957d6cfdb04b7a54aa8dc29b78fee | /BookManage/BookManage/Book.cpp | 6f161b68e3b9fabc0ff2858a78ee3d2af9283a48 | [] | no_license | ProChen/BookManage | 151ef5c69d28125341be738b33d77faa01885c8c | 68f1acdccd1d4ab1cfa6ea991187600507e6f8ab | refs/heads/master | 2021-01-20T20:14:57.496277 | 2016-07-03T08:00:34 | 2016-07-03T08:00:34 | 62,486,766 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,855 | cpp | #include "Book.h"
#include <string>
#include <fstream>
#include <iostream>
#include <iomanip>
using namespace std;
CBook::CBook(char* cName,char* cIsbn,char* cPrice,char* cAuthor)
{
strncpy(m_cName,cName,NUM1);
strncpy(m_cIsbn,cIsbn,NUM1);
strncpy(m_cPrice,cPrice,NUM2);
strncpy(m_cAuthor,cAuthor,NUM2);
}
char* CBook::GetName()
{
return m_cName;
}
void CBook::SetName(char* cName)
{
strncpy(m_cName,cName,NUM1);
}
char* CBook::GetIsbn()
{
return m_cIsbn;
}
void CBook::SetIsbn(char* cIsbn)
{
strncpy(m_cIsbn,cIsbn,NUM1);
}
char* CBook::GetPrice()
{
return m_cPrice;
}
void CBook::SetPrice(char* cPrice)
{
strncpy(m_cPrice,cPrice,NUM2);
}
char* CBook::GetAuthor()
{
return m_cAuthor;
}
void CBook::SetAuthor(char* cAuthor)
{
strncpy(m_cAuthor,cAuthor,NUM2);
}
void CBook::WriteData()
{
ofstream ofile;
ofile.open("book.dat",ios::binary|ios::app);
try
{
ofile.write(m_cName,NUM1);
ofile.write(m_cIsbn,NUM1);
ofile.write(m_cPrice,NUM2);
ofile.write(m_cAuthor,NUM2);
}
catch(...)
{
throw "file error occurred";
ofile.close();
}
ofile.close();
}
void CBook::GetBookFromFile(int iCount)
{
char cName[NUM1];
char cIsbn[NUM1];
char cPrice[NUM2];
char cAuthor[NUM2];
ifstream ifile;
ifile.open("book.dat",ios::binary);
try
{
ifile.seekg(iCount*(NUM1+NUM1+NUM2+NUM2),ios::beg);
ifile.read(cName,NUM1);
if(ifile.tellg()>0)
strncpy(m_cName,cName,NUM1);
ifile.read(cIsbn,NUM1);
if(ifile.tellg()>0)
strncpy(m_cIsbn,cIsbn,NUM1);
ifile.read(cPrice,NUM2);
if(ifile.tellg()>0)
strncpy(m_cIsbn,cIsbn,NUM2);
ifile.read(cAuthor,NUM2);
if(ifile.tellg()>0)
strncpy(m_cAuthor,cAuthor,NUM2);
}
catch(...)
{
throw "file error occurred";
ifile.close();
}
ifile.close();
}
void CBook::DeleteData(int iCount)
{
long respos;
int iDataCount=0;
fstream file;
fstream tmpfile;
ofstream ofile;
char cTempBuf[NUM1+NUM1+NUM2+NUM2];
file.open("book.dat",ios::binary|ios::in|ios::out);
tmpfile.open("temp.dat",ios::binary|ios::in|ios::out|ios::trunc);
file.seekg(0,ios::end);
respos=file.tellg();
iDataCount=respos/(NUM1+NUM1+NUM2+NUM2);
if(iCount < 0 && iCount > iDataCount)
{
throw "Input number error";
}
else
{
file.seekg((iCount)*(NUM1+NUM1+NUM2+NUM2),ios::beg);
for(int j=0;j<(iDataCount-iCount);j++)
{
memset(cTempBuf,0,NUM1+NUM1+NUM2+NUM2);
file.read(cTempBuf,NUM1+NUM1+NUM2+NUM2);
tmpfile.write(cTempBuf,NUM1+NUM1+NUM2+NUM2);
}
file.close();
tmpfile.seekg(0,ios::beg);
ofile.open("book.dat");
ofile.seekp((iCount-1)*(NUM1+NUM1+NUM2+NUM2),ios::beg);
for(int i=0;i<(iDataCount-iCount);i++)
{
memset(cTempBuf,0,NUM1+NUM1+NUM2+NUM2);
tmpfile.read(cTempBuf,NUM1+NUM1+NUM2+NUM2);
ofile.write(cTempBuf,NUM1+NUM1+NUM2+NUM2);
}
}
tmpfile.close();
ofile.close();
remove("temp.dat");
}
| [
"1224532706@qq.com"
] | 1224532706@qq.com |
895a1ed25dbeec7910081d42861044a30e5cd68f | 846a7668ac964632bdb6db639ab381be11c13b77 | /android/hardware/qcom/display/sdm845/sdm/libs/hwc/hwc_buffer_sync_handler.cpp | 784e91b5145bc84c37c043c45bcf5ac6e2bc50e8 | [] | no_license | BPI-SINOVOIP/BPI-A64-Android8 | f2900965e96fd6f2a28ced68af668a858b15ebe1 | 744c72c133b9bf5d2e9efe0ab33e01e6e51d5743 | refs/heads/master | 2023-05-21T08:02:23.364495 | 2020-07-15T11:27:51 | 2020-07-15T11:27:51 | 143,945,191 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,051 | cpp | /*
* Copyright (c) 2015, The Linux Foundation. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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 <sync/sync.h>
#include <utils/constants.h>
#include <utils/debug.h>
#include "hwc_debugger.h"
#include "hwc_buffer_sync_handler.h"
#define __CLASS__ "HWCBufferSyncHandler"
namespace sdm {
DisplayError HWCBufferSyncHandler::SyncWait(int fd) {
int error = 0;
if (fd >= 0) {
error = sync_wait(fd, 1000);
if (error < 0) {
DLOGE("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
return kErrorTimeOut;
}
}
return kErrorNone;
}
DisplayError HWCBufferSyncHandler::SyncMerge(int fd1, int fd2, int *merged_fd) {
DisplayError error = kErrorNone;
// Merge the two fences. In the case where one of the fences is not a
// valid fence (e.g. NO_FENCE) merge the one valid fence with itself so
// that a new fence with the given name is created.
// TODO(user): "SyncMerge"string should be replaced with user-defined string to represent
// why it is merged.
if (fd1 >= 0 && fd2 >= 0) {
*merged_fd = sync_merge("SyncMerge", fd1, fd2);
} else if (fd1 >= 0) {
*merged_fd = sync_merge("SyncMerge", fd1, fd1);
} else if (fd2 >= 0) {
*merged_fd = sync_merge("SyncMerge", fd2, fd2);
} else {
*merged_fd = -1;
return kErrorNone;
}
if (*merged_fd == -1) {
DLOGE("Sync merge error! fd1 %d fd2 %d", fd1, fd2);
error = kErrorFileDescriptor;
}
return error;
}
bool HWCBufferSyncHandler::IsSyncSignaled(int fd) {
if (sync_wait(fd, 0) < 0) {
return false;
} else {
return true;
}
}
} // namespace sdm
| [
"mingxin.android@gmail.com"
] | mingxin.android@gmail.com |
e79cc389a908e16531978fe92f022c329eac4830 | beb0f80259be767ebe81a07b6c5e67fa0e28c12b | /android/build/generated/jni/com.yallaya.fragments.FragmentFrameProxy.h | c61af54bae54cc248c2941d6b0264c3d1d2af72d | [
"Apache-2.0"
] | permissive | darknos/com.yallaya.fragments | c8be88e43f003dd3fa7bc877441b2a8135c64862 | aba87fc644176917d7c3dd1b4182ea702154b69f | refs/heads/master | 2021-05-28T18:40:50.765474 | 2015-04-01T14:12:12 | 2015-04-01T14:12:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,151 | h | /**
* Appcelerator Titanium Mobile
* Copyright (c) 2011-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*/
/** This is generated, do not edit by hand. **/
#include <jni.h>
#include "Proxy.h"
namespace com {
namespace yallaya {
namespace fragments {
namespace fragments {
class FragmentFrameProxy : public titanium::Proxy
{
public:
explicit FragmentFrameProxy(jobject javaObject);
static void bindProxy(v8::Handle<v8::Object> exports);
static v8::Handle<v8::FunctionTemplate> getProxyTemplate();
static void dispose();
static v8::Persistent<v8::FunctionTemplate> proxyTemplate;
static jclass javaClass;
private:
// Methods -----------------------------------------------------------
static v8::Handle<v8::Value> getUid(const v8::Arguments&);
// Dynamic property accessors ----------------------------------------
static v8::Handle<v8::Value> getter_uid(v8::Local<v8::String> property, const v8::AccessorInfo& info);
};
} // namespace fragments
} // fragments
} // yallaya
} // com
| [
"Nimrod@Nimrods-MacBook-Air.local"
] | Nimrod@Nimrods-MacBook-Air.local |
a1c003c7baec2505943835156467f08bb49a3b3e | 4ec6bc3779261b73164a73c361de26cb0a724676 | /include/NumCpp/Functions/minimum.hpp | 0a3159ec8cca4f11ad65fcb8d8fbc815a77289fe | [
"MIT"
] | permissive | kontramind/NumCpp | 3efc6673e0cc69b3fcb93f8b7c801abc6d9419cf | eba08fc5b97b338bc1ca9d1f9e2d3d76c2431cd1 | refs/heads/master | 2020-12-26T19:32:05.328636 | 2020-04-12T11:26:35 | 2020-04-12T11:26:35 | 237,615,461 | 0 | 0 | MIT | 2020-02-01T12:59:35 | 2020-02-01T12:59:35 | null | UTF-8 | C++ | false | false | 2,552 | hpp | /// @file
/// @author David Pilger <dpilger26@gmail.com>
/// [GitHub Repository](https://github.com/dpilger26/NumCpp)
/// @version 1.3
///
/// @section License
/// Copyright 2020 David Pilger
///
/// 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.
///
/// @section Description
/// Functions for working with NdArrays
///
#pragma once
#include "NumCpp/NdArray.hpp"
#include "NumCpp/Core/Error.hpp"
#include "NumCpp/Core/StlAlgorithms.hpp"
#include <cmath>
#include <string>
namespace nc
{
//============================================================================
// Method Description:
/// Element-wise minimum of array elements.
///
/// NumPy Reference: https://www.numpy.org/devdocs/reference/generated/numpy.minimum.html
///
/// @param inArray1
/// @param inArray2
///
/// @return
/// NdArray
///
template<typename dtype>
NdArray<dtype> minimum(const NdArray<dtype>& inArray1, const NdArray<dtype>& inArray2)
{
if (inArray1.shape() != inArray2.shape())
{
THROW_INVALID_ARGUMENT_ERROR("input array shapes are not consistant.");
}
NdArray<dtype> returnArray(inArray1.shape());
stl_algorithms::transform(inArray1.cbegin(), inArray1.cend(), inArray2.cbegin(), returnArray.begin(),
[](dtype inValue1, dtype inValue2) noexcept -> dtype
{
return std::min(inValue1, inValue2);
});
return returnArray;
}
}
| [
"dpilger26@gmail.com"
] | dpilger26@gmail.com |
efa657e5f3ba1ce4b9503ba8bafab98b9645a150 | 8209f14e1949031e0023a04ab366bb49817237a6 | /src/core/imgui/imgui.cpp | 4699e6735fa8677369238b0fed36e02f686c314f | [
"MIT"
] | permissive | WilliamLewww/Thane | 3fdb6220c603c4dd3b65ceaad77ef2e922427049 | c9fc1ea7780e51e78e3362670a08b1764843ed7e | refs/heads/master | 2021-01-20T07:15:37.438212 | 2019-02-08T04:35:06 | 2019-02-08T04:35:06 | 101,527,318 | 0 | 0 | MIT | 2018-08-30T18:16:27 | 2017-08-27T03:27:00 | C++ | UTF-8 | C++ | false | false | 621,428 | cpp | // dear imgui, v1.60 WIP
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// This library is free but I need your support to sustain development and maintenance.
// If you work for a company, please consider financial support, see Readme. For individuals: https://www.patreon.com/imgui
/*
Index
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
- Read first
- How to update to a newer version of Dear ImGui
- Getting started with integrating Dear ImGui in your code/engine
- Using gamepad/keyboard navigation controls [BETA]
- API BREAKING CHANGES (read me when you update!)
- ISSUES & TODO LIST
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- How can I display an image? What is ImTextureID, how does it works?
- How can I have multiple widgets with the same label? Can I have widget without a label? (Yes). A primer on labels and the ID stack.
- How can I load a different font than the default?
- How can I easily use icons in my application?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- I integrated Dear ImGui in my engine and the text or lines are blurry..
- I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- How can I help?
- ISSUES & TODO-LIST
- CODE
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools
- Easy to hack and improve
- Minimize screen real-estate usage
- Minimize setup and maintenance
- Minimize state storage on user side
- Portable, minimize dependencies, run on target (consoles, phones, etc.)
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window, opening a tree node
for the first time, etc. but a typical frame won't allocate anything)
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate
- Limited layout features, intricate layouts are typically crafted in code
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at goo.gl/9LgVZW.
PROGRAMMER GUIDE
================
READ FIRST
- Read the FAQ below this section!
- Your code creates the UI, if your code doesn't run the UI is gone! == very dynamic UI, no construction/destructions steps, less data retention
on your side, no state duplication, less sync, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- You can learn about immediate-mode gui principles at http://www.johno.se/book/imgui.html or watch http://mollyrocket.com/861
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed from the public API.
If you have a problem with a missing function/symbols, search for its name in the code, there will likely be a comment about it.
Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
- Add the Dear ImGui source files to your projects, using your preferred build system.
It is recommended you build the .cpp files as part of your project and not as a library.
- You can later customize the imconfig.h file to tweak some compilation time behavior, such as integrating imgui types with your own maths types.
- See examples/ folder for standalone sample applications.
- You may be able to grab and copy a ready made imgui_impl_*** file from the examples/.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Init: retrieve the ImGuiIO structure with ImGui::GetIO() and fill the fields marked 'Settings': at minimum you need to set io.DisplaySize
(application resolution). Later on you will fill your keyboard mapping, clipboard handlers, and other advanced features but for a basic
integration you don't need to worry about it all.
- Init: call io.Fonts->GetTexDataAsRGBA32(...), it will build the font atlas texture, then load the texture pixels into graphics memory.
- Every frame:
- In your main loop as early a possible, fill the IO fields marked 'Input' (e.g. mouse position, buttons, keyboard info, etc.)
- Call ImGui::NewFrame() to begin the frame
- You can use any ImGui function you want between NewFrame() and Render()
- Call ImGui::Render() as late as you can to end the frame and finalize render data. it will call your io.RenderDrawListFn handler.
(Even if you don't render, call Render() and ignore the callback, or call EndFrame() instead. Otherwhise some features will break)
- All rendering information are stored into command-lists until ImGui::Render() is called.
- Dear ImGui never touches or knows about your GPU state. the only function that knows about GPU is the RenderDrawListFn handler that you provide.
- Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render" phases
of your own application.
- Refer to the examples applications in the examples/ folder for instruction on how to setup your code.
- A minimal application skeleton may be:
// Application init
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize.x = 1920.0f;
io.DisplaySize.y = 1280.0f;
// TODO: Fill others settings of the io structure later.
// Load texture atlas (there is a default font so you don't need to care about choosing a font yet)
unsigned char* pixels;
int width, height;
io.Fonts->GetTexDataAsRGBA32(pixels, &width, &height);
// TODO: At this points you've got the texture data and you need to upload that your your graphic system:
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA)
// TODO: Store your texture pointer/identifier (whatever your engine uses) in 'io.Fonts->TexID'. This will be passed back to your via the renderer.
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs (e.g. on Win32, GetKeyboardState(), or write to those fields from your Windows message loop handlers, etc.)
ImGuiIO& io = ImGui::GetIO();
io.DeltaTime = 1.0f/60.0f;
io.MousePos = mouse_pos;
io.MouseDown[0] = mouse_button_0;
io.MouseDown[1] = mouse_button_1;
// Call NewFrame(), after this point you can use ImGui::* functions anytime
ImGui::NewFrame();
// Most of your application code here
MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any ImGui functions as well!
// Render & swap video buffers
ImGui::Render();
MyImGuiRenderFunction(ImGui::GetDrawData());
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
- A minimal render function skeleton may be:
void void MyRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport, orthographic projection matrix
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls with use the imgui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture(pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API supports it.
// If your engine doesn't support scissoring yet, you will get some small glitches (some elements outside their bounds) which you can fix later.
MyEngineScissor((int)pcmd->ClipRect.x, (int)pcmd->ClipRect.y, (int)(pcmd->ClipRect.z - pcmd->ClipRect.x), (int)(pcmd->ClipRect.w - pcmd->ClipRect.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits if your engine doesn't support 16-bits indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many functional implementation of the pseudo-code above.
- When calling NewFrame(), the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags are updated.
They tell you if ImGui intends to use your inputs. So for example, if 'io.WantCaptureMouse' is set you would typically want to hide
mouse inputs from the rest of your application. Read the FAQ below for more information about those flags.
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS [BETA]
- The gamepad/keyboard navigation is in Beta. Ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable. NewFrame() will automatically fill io.NavInputs[] based on your io.KeyDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag will be set.
For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame(). Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo to toggle the target.
Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. The breakage are generally minor and easy to fix.
Here is a change-log of API breaking changes, if you are using one of the functions listed, expect to have to fix some code.
Also read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2018/03/20 (1.60) - Renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - Removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - Changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - Renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwhise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
However if your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
{
float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
}
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDraw::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
argument: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
(1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
font init: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>
became: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier;
you now more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
it is now recommended that you sample the font texture with bilinear interpolation.
(1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
(1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
(1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
ISSUES & TODO-LIST
==================
See TODO.txt
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
A: You can read the 'io.WantCaptureMouse'/'io.WantCaptureKeyboard'/'io.WantTextInput' flags from the ImGuiIO structure.
- When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
perfectly fine, as the bool toggle fairly rarely.
(Advanced note: text input releases focus on Return 'KeyDown', so the following Return 'KeyUp' event that your application receive will typically
have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
were for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
Q: How can I display an image? What is ImTextureID, how does it works?
A: ImTextureID is a void* used to pass renderer-agnostic texture references around until it hits your render function.
Dear ImGui knows nothing about what those bits represent, it just passes them around. It is up to you to decide what you want the void* to carry!
It could be an identifier to your OpenGL texture (cast GLuint to void*), a pointer to your custom engine material (cast MyMaterial* to void*), etc.
At the end of the chain, your renderer takes this void* to cast it back into whatever it needs to select a current texture to render.
Refer to examples applications, where each renderer (in a imgui_impl_xxxx.cpp file) is treating ImTextureID as a different thing.
(c++ tip: OpenGL uses integers to identify textures. You can safely store an integer into a void*, just cast it to void*, don't take it's address!)
To display a custom image/texture within an ImGui window, you may use ImGui::Image(), ImGui::ImageButton(), ImDrawList::AddImage() functions.
Dear ImGui will generate the geometry and draw calls using the ImTextureID that you passed and which your renderer can use.
You may call ImGui::ShowMetricsWindow() to explore active draw lists and visualize/understand how the draw data is generated.
It is your responsibility to get textures uploaded to your GPU.
Q: Can I have multiple widgets with the same label? Can I have widget without a label?
A: Yes. A primer on labels and the ID stack...
- Elements that are typically not clickable, such as Text() items don't need an ID.
- Interactive widgets require state to be carried over multiple frames (most typically Dear ImGui often needs to remember what is
the "active" widget). to do so they need a unique ID. unique ID are typically derived from a string label, an integer index or a pointer.
Button("OK"); // Label = "OK", ID = hash of "OK"
Button("Cancel"); // Label = "Cancel", ID = hash of "Cancel"
- ID are uniquely scoped within windows, tree nodes, etc. so no conflict can happen if you have two buttons called "OK"
in two different windows or in two different locations of a tree.
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Both buttons will be treated as the same.
Fear not! this is easy to solve and there are many ways to solve it!
- When passing a label you can optionally specify extra unique ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know which items are going to be created.
Button("Play"); // Label = "Play", ID = hash of "Play"
Button("Play##foo1"); // Label = "Play", ID = hash of "Play##foo1" (different from above)
Button("Play##foo2"); // Label = "Play", ID = hash of "Play##foo2" (different from above)
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of "##On" (no label!)
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows you to animate labels.
For example you may want to include varying information in a window title bar, but windows are uniquely identified by their ID..
Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"; // Label = "Hello", ID = hash of "ID"
Button("World###ID"; // Label = "World", ID = hash of "ID" (same as above)
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable label, ID = hash of "MyGame"
- Use PushID() / PopID() to create scopes and avoid ID conflicts within the same Window.
This is the most convenient way of distinguishing ID if you are iterating and creating many UI elements.
You can push a pointer, a string or an integer value. Remember that ID are formed from the concatenation of _everything_ in the ID stack!
for (int i = 0; i < 100; i++)
{
PushID(i);
Button("Click"); // Label = "Click", ID = hash of integer + "label" (unique)
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of pointer + "label" (unique)
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of string + "label" (unique)
PopID();
}
- More example showing that you can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of "Click"
PushID("node");
Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of "node" + ptr + "Click"
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of "Click"
if (TreeNode("node"))
{
Button("Click"); // Label = "Click", ID = hash of "node" + "Click"
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when displaying a single object that may change over time (dynamic 1-1 relationship), using a static string as ID will preserve your
node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the node open/closed state differently.
experiment and see what makes more sense!
Q: How can I load a different font than the default? (default is an embedded version of ProggyClean.ttf, rendered at size 13)
A: Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
New programmers: remember that in C/C++ and most programming languages if you want to use a backslash \ in a string literal you need to write a double backslash "\\":
io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG
io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
Q: How can I easily use icons in my application?
A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you main font. Then you can refer to icons within your
strings. Read 'How can I load multiple fonts?' and the file 'misc/fonts/README.txt' for instructions and useful header files.
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
(Read misc/fonts/README.txt and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
// the first loaded font gets used by default
// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
// Options
ImFontConfig config;
config.OversampleH = 3;
config.OversampleV = 1;
config.GlyphOffset.y -= 2.0f; // Move everything by 2 pixels up
config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->LoadFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
io.Fonts->LoadFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
// Add default Japanese ranges
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
// Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
ImVector<ImWchar> ranges;
ImFontAtlas::GlyphRangesBuilder builder;
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
builder.AddChar(0x7262); // Add a specific character
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8 by using the u8"hello" syntax.
Specifying literal in your source code using a local code page (such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
Text input: it is up to your application to pass the right character code to io.AddInputCharacter(). The applications in examples/ are doing that.
For languages using IME, on Windows you can copy the Hwnd of your application to io.ImeWindowHandle.
The default implementation of io.ImeSetInputScreenPosFn() on Windows will set your IME position correctly.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
A: - You can create a dummy window. Call SetNextWindowBgAlpha(0.0f), call Begin() with NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs flags.
Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows.
- You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create your own ImDrawListSharedData.
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
A: You are probably mishandling the clipping rectangles in your render function.
Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
Q: How can I help?
A: - If you are experienced with Dear ImGui and C++, look at the github issues, or TODO.txt and see how you want/can help!
- Convince your company to fund development time! Individual users: you can also become a Patron (patreon.com/imgui) or donate on PayPal! See README.
- Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1269). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
this is also useful to set yourself in the context of another window (to get/set other settings)
- tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui_internal.h"
#include <ctype.h> // toupper, isprint
#include <stdlib.h> // NULL, malloc, free, qsort, atoi
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
#define IMGUI_DEBUG_NAV_SCORING 0
#define IMGUI_DEBUG_NAV_RECTS 0
// 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
#endif
// Clang warnings with -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#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 (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int' //
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#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 "-Wcast-qual" // warning: cast from type 'xxxx' to type 'xxxx' casts away qualifiers
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#endif
// Enforce cdecl calling convention for functions called by the standard library, in case compilation settings changed the default to e.g. __vectorcall
#ifdef _MSC_VER
#define IMGUI_CDECL __cdecl
#else
#define IMGUI_CDECL
#endif
//-------------------------------------------------------------------------
// Forward Declarations
//-------------------------------------------------------------------------
static bool IsKeyPressedMap(ImGuiKey key, bool repeat = true);
static ImFont* GetDefaultFont();
static void SetCurrentWindow(ImGuiWindow* window);
static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x);
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y);
static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond);
static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond);
static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond);
static ImGuiWindow* FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_list, ImGuiWindow* window);
static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
static ImGuiWindowSettings* AddWindowSettings(const char* name);
static void LoadIniSettingsFromDisk(const char* ini_filename);
static void LoadIniSettingsFromMemory(const char* buf);
static void SaveIniSettingsToDisk(const char* ini_filename);
static void SaveIniSettingsToMemory(ImVector<char>& out_buf);
static void MarkIniSettingsDirty(ImGuiWindow* window);
static ImRect GetViewportRect();
static void ClosePopupToLevel(int remaining);
static ImGuiWindow* GetFrontMostModalRootWindow();
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data);
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end);
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining = NULL, ImVec2* out_offset = NULL, bool stop_on_new_line = false);
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size);
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size);
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg_1, const void* arg_2);
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format);
namespace ImGui
{
static void NavUpdate();
static void NavUpdateWindowing();
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
static void UpdateMovingWindow();
static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void FocusFrontMostActiveWindow(ImGuiWindow* ignore_window);
}
//-----------------------------------------------------------------------------
// Platform dependent default implementations
//-----------------------------------------------------------------------------
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y);
//-----------------------------------------------------------------------------
// Context
//-----------------------------------------------------------------------------
// Current context pointer. Implicitely used by all ImGui functions. Always assumed to be != NULL.
// CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// If you use DLL hotreloading you might need to call SetCurrentContext() after reloading code from this file.
// ImGui functions are not thread-safe because of this pointer. If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage. You may #define GImGui in imconfig.h for that purpose. Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - Having multiple instances of the ImGui code compiled inside different namespace (easiest/safest, if you have a finite number of contexts)
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { (void)user_data; (void)size; IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { (void)user_data; (void)ptr; IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
static size_t GImAllocatorActiveAllocationsCount = 0;
//-----------------------------------------------------------------------------
// User facing structures
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
DisplayWindowPadding = ImVec2(22,22); // Window positions are clamped to be visible within the display area by at least this amount. Only covers regular windows.
DisplaySafeAreaPadding = ImVec2(4,4); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
ImGui::StyleColorsClassic(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
// Settings
ConfigFlags = 0x00;
BackendFlags = 0x00;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
DisplayVisibleMin = DisplayVisibleMax = ImVec2(0.0f, 0.0f);
// Advanced/subtle behaviors
#ifdef __APPLE__
OptMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
OptMacOSXBehaviors = false;
#endif
OptCursorBlink = true;
// Settings (User Functions)
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(ImWchar c)
{
const int n = ImStrlenW(InputCharacters);
if (n + 1 < IM_ARRAYSIZE(InputCharacters))
{
InputCharacters[n] = c;
InputCharacters[n+1] = '\0';
}
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
// We can't pass more wchars than ImGuiIO::InputCharacters[] can hold so don't convert more
const int wchars_buf_len = sizeof(ImGuiIO::InputCharacters) / sizeof(ImWchar);
ImWchar wchars[wchars_buf_len];
ImTextStrFromUtf8(wchars, wchars_buf_len, utf8_chars, NULL);
for (int i = 0; i < wchars_buf_len && wchars[i] != 0; i++)
AddInputCharacter(wchars[i]);
}
//-----------------------------------------------------------------------------
// HELPERS
//-----------------------------------------------------------------------------
#define IM_F32_TO_INT8_UNBOUND(_VAL) ((int)((_VAL) * 255.0f + ((_VAL)>=0 ? 0.5f : -0.5f))) // Unsaturated, for display purpose
#define IM_F32_TO_INT8_SAT(_VAL) ((int)(ImSaturate(_VAL) * 255.0f + 0.5f)) // Saturated, always output 0..255
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1) return;
strncpy(dst, src, count);
dst[count-1] = 0;
}
char* ImStrdup(const char *str)
{
size_t len = strlen(str) + 1;
void* buf = ImGui::MemAlloc(len);
return (char*)memcpy(buf, (const void*)str, len);
}
char* ImStrchrRange(const char* str, const char* str_end, char c)
{
for ( ; str < str_end; str++)
if (*str == c)
return (char*)str;
return NULL;
}
int ImStrlenW(const ImWchar* str)
{
int n = 0;
while (*str++) n++;
return n;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
static const char* ImAtoi(const char* src, int* output)
{
int negative = 0;
if (*src == '-') { negative = 1; src++; }
if (*src == '+') { src++; }
int v = 0;
while (*src >= '0' && *src <= '9')
v = (v * 10) + (*src++ - '0');
*output = negative ? -v : v;
return src;
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
int w = vsnprintf(buf, buf_size, fmt, args);
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
int w = vsnprintf(buf, buf_size, fmt, args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
// Pass data_size==0 for zero-terminated strings
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHash(const void* data, int data_size, ImU32 seed)
{
static ImU32 crc32_lut[256] = { 0 };
if (!crc32_lut[1])
{
const ImU32 polynomial = 0xEDB88320;
for (ImU32 i = 0; i < 256; i++)
{
ImU32 crc = i;
for (ImU32 j = 0; j < 8; j++)
crc = (crc >> 1) ^ (ImU32(-int(crc & 1)) & polynomial);
crc32_lut[i] = crc;
}
}
seed = ~seed;
ImU32 crc = seed;
const unsigned char* current = (const unsigned char*)data;
if (data_size > 0)
{
// Known size
while (data_size--)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *current++];
}
else
{
// Zero-terminated string
while (unsigned char c = *current++)
{
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller.
if (c == '#' && current[0] == '#' && current[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// ImText* helpers
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bits character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000)
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c >= 0xdc00 && c < 0xe000)
{
return 0;
}
if (c >= 0xd800 && c < 0xdc00)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
//else if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c >= 0xdc00 && c < 0xe000) return 0;
if (c >= 0xd800 && c < 0xdc00) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
float style_alpha = GImGui->Style.Alpha;
if (style_alpha >= 1.0f)
return col;
int a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (int)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = fabsf(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = fmodf(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
FILE* ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// Load file content into memory
// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, int* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && file_open_mode);
if (out_file_size)
*out_file_size = 0;
FILE* f;
if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
return NULL;
long file_size_signed;
if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
{
fclose(f);
return NULL;
}
int file_size = (int)file_size_signed;
void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
if (file_data == NULL)
{
fclose(f);
return NULL;
}
if (fread(file_data, 1, (size_t)file_size, f) != (size_t)file_size)
{
fclose(f);
ImGui::MemFree(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void *)(((char*)file_data) + file_size), 0, padding_bytes);
fclose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImVector<ImGuiStorage::Pair>::iterator LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
{
ImVector<ImGuiStorage::Pair>::iterator first = data.begin();
ImVector<ImGuiStorage::Pair>::iterator last = data.end();
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImVector<ImGuiStorage::Pair>::iterator mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
qsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImVector<Pair>::iterator it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImVector<Pair>::iterator it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::PushItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (width != 0.0f)
ImGui::PopItemWidth();
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>& out)
{
out.resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out.push_back(TextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out.push_back(TextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
Filters[i].trim_blanks();
if (Filters[i].empty())
continue;
if (Filters[i].front() != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const TextRange& f = Filters[i];
if (f.empty())
continue;
if (f.front() == '-')
{
// Subtract
if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#define va_copy(dest, src) (dest = src)
#endif
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
return;
const int write_off = Buf.Size;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int double_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > double_capacity ? needed_sz : double_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], len + 1, fmt, args_copy);
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// ImGuiSimpleColumns (internal use only)
//-----------------------------------------------------------------------------
ImGuiMenuColumns::ImGuiMenuColumns()
{
Count = 0;
Spacing = Width = NextWidth = 0.0f;
memset(Pos, 0, sizeof(Pos));
memset(NextWidths, 0, sizeof(NextWidths));
}
void ImGuiMenuColumns::Update(int count, float spacing, bool clear)
{
IM_ASSERT(Count <= IM_ARRAYSIZE(Pos));
Count = count;
Width = NextWidth = 0.0f;
Spacing = spacing;
if (clear) memset(NextWidths, 0, sizeof(NextWidths));
for (int i = 0; i < Count; i++)
{
if (i > 0 && NextWidths[i] > 0.0f)
Width += Spacing;
Pos[i] = (float)(int)Width;
Width += NextWidths[i];
NextWidths[i] = 0.0f;
}
}
float ImGuiMenuColumns::DeclColumns(float w0, float w1, float w2) // not using va_arg because they promote float to double
{
NextWidth = 0.0f;
NextWidths[0] = ImMax(NextWidths[0], w0);
NextWidths[1] = ImMax(NextWidths[1], w1);
NextWidths[2] = ImMax(NextWidths[2], w2);
for (int i = 0; i < 3; i++)
NextWidth += NextWidths[i] + ((i > 0 && NextWidths[i] > 0.0f) ? Spacing : 0.0f);
return ImMax(Width, NextWidth);
}
float ImGuiMenuColumns::CalcExtraSpace(float avail_w)
{
return ImMax(0.0f, avail_w - Width);
}
//-----------------------------------------------------------------------------
// ImGuiListClipper
//-----------------------------------------------------------------------------
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHere() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGui::SetCursorPosY(pos_y);
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHere() can properly function after the end of our clipper usage.
window->DC.PrevLineHeight = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (window->DC.ColumnsSet)
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
StartPosY = ImGui::GetCursorPosY();
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = ImGui::GetCursorPosY();
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = ImGui::GetCursorPosY() - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount-1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// ImGuiWindow
//-----------------------------------------------------------------------------
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
{
Name = ImStrdup(name);
ID = ImHash(name, 0);
IDStack.push_back(ID);
Flags = 0;
PosFloat = Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarX = ScrollbarY = false;
ScrollbarSizes = ImVec2(0.0f, 0.0f);
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
CollapseToggleWanted = false;
SkipItems = false;
Appearing = false;
CloseButton = false;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
BeginCount = 0;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
AutoFitChildAxises = 0x00;
AutoPosLastDirection = ImGuiDir_None;
HiddenFrames = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = 1.0f;
DrawList = IM_NEW(ImDrawList)(&context->DrawListSharedData);
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForTabbing = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
FocusIdxAllCounter = FocusIdxTabCounter = -1;
FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
}
ImGuiWindow::~ImGuiWindow()
{
IM_DELETE(DrawList);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumnsSet();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHash(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHash(str, str_end ? (int)(str_end - str) : 0, seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHash(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
//-----------------------------------------------------------------------------
// Internal API exposed in imgui_internal.h
//-----------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
static void SetNavID(ImGuiID id, int nav_layer)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
static void SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
g.ActiveIdTimer = 0.0f;
g.ActiveId = id;
g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
if (id)
{
g.ActiveIdIsAlive = true;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
}
ImGuiID ImGui::GetActiveID()
{
ImGuiContext& g = *GImGui;
return g.ActiveId;
}
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
const int nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavId = id;
g.NavWindow = window;
g.NavLayer = nav_layer;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
g.HoveredIdTimer = (id != 0 && g.HoveredIdPreviousFrame == id) ? (g.HoveredIdTimer + g.IO.DeltaTime) : 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = true;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
return true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
const float line_height = ImMax(window->DC.CurrentLineHeight, size.y);
const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
window->DC.CursorPos = ImVec2((float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX), (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y));
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineHeight = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrentLineHeight = window->DC.CurrentLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
{
ItemSize(bb.GetSize(), text_offset_y);
}
static ImGuiDir NavScoreItemGetQuadrant(float dx, float dy)
{
if (fabsf(dx) > fabsf(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// We perform scoring on items bounding box clipped by their parent window on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
{
cand.Min.y = ImClamp(cand.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
cand.Max.y = ImClamp(cand.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y);
}
else
{
cand.Min.x = ImClamp(cand.Min.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
cand.Max.x = ImClamp(cand.Max.x, window->ClipRect.Min.x, window->ClipRect.Max.x);
}
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = fabsf(dbx) + fabsf(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = fabsf(dcx) + fabsf(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = NavScoreItemGetQuadrant(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = NavScoreItemGetQuadrant(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
g.OverlayDrawList.AddRect(curr.Min, curr.Max, IM_COL32(255, 200, 0, 100));
g.OverlayDrawList.AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
g.OverlayDrawList.AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
g.OverlayDrawList.AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
g.OverlayDrawList.AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may however lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
static void NavSaveLastChildNavWindow(ImGuiWindow* child_window)
{
ImGuiWindow* parent_window = child_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != child_window)
parent_window->NavLastChildNavWindow = child_window;
}
// Call when we are expected to land on Layer 0 after FocusWindow()
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(int layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
if (layer == 0 && g.NavWindow->NavLastIds[0] != 0)
SetNavIDWithRectRel(g.NavWindow->NavLastIds[0], layer, g.NavWindow->NavRectRel[0]);
else
ImGui::NavInitWindow(g.NavWindow, true);
}
static inline void NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
static bool NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Scoring for navigation
if (g.NavId != id && !(item_flags & ImGuiItemFlags_NoNav))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->ID = id;
result->ParentID = window->IDStack.back();
result->Window = window;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->FocusIdxTabCounter;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
// it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = 0;
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
// Special handling for the 1st item after Begin() which represent the title bar. When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect tht case.
if (window->DC.LastItemId == window->MoveId && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_Default))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
{
ImGuiContext& g = *GImGui;
const bool allow_keyboard_focus = (window->DC.ItemFlags & (ImGuiItemFlags_AllowKeyboardFocus | ImGuiItemFlags_Disabled)) == ImGuiItemFlags_AllowKeyboardFocus;
window->FocusIdxAllCounter++;
if (allow_keyboard_focus)
window->FocusIdxTabCounter++;
// Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
// Note that we can always TAB out of a widget that doesn't allow tabbing in.
if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (allow_keyboard_focus ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
if (allow_keyboard_focus && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
{
g.NavJustTabbedId = id;
return true;
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->FocusIdxAllCounter--;
window->FocusIdxTabCounter--;
}
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
{
ImGuiContext& g = *GImGui;
ImVec2 content_max;
if (size.x < 0.0f || size.y < 0.0f)
content_max = g.CurrentWindow->Pos + GetContentRegionMax();
if (size.x <= 0.0f)
size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
if (size.y <= 0.0f)
size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
return size;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GetCurrentWindowRead();
if (wrap_pos_x == 0.0f)
wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
//-----------------------------------------------------------------------------
void* ImGui::MemAlloc(size_t sz)
{
GImAllocatorActiveAllocationsCount++;
return GImAllocatorAllocFunc(sz, GImAllocatorUserData);
}
void ImGui::MemFree(void* ptr)
{
if (ptr) GImAllocatorActiveAllocationsCount--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
if (GImGui->IO.SetClipboardTextFn)
GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void(*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->IO;
}
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->Style;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.DrawData.Valid ? &g.DrawData : NULL;
}
float ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetOverlayDrawList()
{
return &GImGui->OverlayDrawList;
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
if (init_for_nav)
{
SetNavID(0, g.NavLayer);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
}
}
static ImVec2 NavCalcPreferredMousePos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.NavWindow;
if (!window)
return g.IO.MousePos;
const ImRect& rect_rel = window->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x*4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = GetViewportRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
static int FindWindowIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size-1; i >= 0; i--)
if (g.Windows[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavigable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.Windows.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.Windows[i]))
return g.Windows[i];
return NULL;
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
// Equivalent of IsKeyDown() for NavInputs[]
static bool IsNavInputDown(ImGuiNavInput n)
{
return GImGui->IO.NavInputs[n] > 0.0f;
}
// Equivalent of IsKeyPressed() for NavInputs[]
static bool IsNavInputPressed(ImGuiNavInput n, ImGuiInputReadMode mode)
{
return ImGui::GetNavInputAmount(n, mode) > 0.0f;
}
static bool IsNavInputPressedAnyOfTwo(ImGuiNavInput n1, ImGuiNavInput n2, ImGuiInputReadMode mode)
{
return (ImGui::GetNavInputAmount(n1, mode) + ImGui::GetNavInputAmount(n2, mode)) > 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = FindWindowIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavigable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavigable((focus_change_dir < 0) ? (g.Windows.Size - 1) : 0, i_current, focus_change_dir);
g.NavWindowingTarget = window_target;
g.NavWindowingToggleLayer = false;
}
// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavigable(g.Windows.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = window->RootWindowForTabbing;
g.NavWindowingHighlightTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingHighlightTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.20f) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingHighlightTimer - 0.15f) / 0.04f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingTarget->PosFloat += move_delta * move_speed;
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowForTabbing))
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << 1))
g.NavLayer = 1;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
ImGuiWindow* new_nav_window = g.NavWindow;
while ((new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0 && (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
NavRestoreLayer((g.NavWindow->DC.NavLayerActiveMask & (1 << 1)) ? (g.NavLayer ^ 1) : 0);
}
}
// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
static void NavScrollToBringItemIntoView(ImGuiWindow* window, ImRect& item_rect_rel)
{
// Scroll to keep newly navigated item fully into view
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1, 1), window->InnerRect.Max - window->Pos + ImVec2(1, 1));
//g.OverlayDrawList.AddRect(window->Pos + window_rect_rel.Min, window->Pos + window_rect_rel.Max, IM_COL32_WHITE); // [DEBUG]
if (window_rect_rel.Contains(item_rect_rel))
return;
ImGuiContext& g = *GImGui;
if (window->ScrollbarX && item_rect_rel.Min.x < window_rect_rel.Min.x)
{
window->ScrollTarget.x = item_rect_rel.Min.x + window->Scroll.x - g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
else if (window->ScrollbarX && item_rect_rel.Max.x >= window_rect_rel.Max.x)
{
window->ScrollTarget.x = item_rect_rel.Max.x + window->Scroll.x + g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 1.0f;
}
if (item_rect_rel.Min.y < window_rect_rel.Min.y)
{
window->ScrollTarget.y = item_rect_rel.Min.y + window->Scroll.y - g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
else if (item_rect_rel.Max.y >= window_rect_rel.Max.y)
{
window->ScrollTarget.y = item_rect_rel.Max.y + window->Scroll.y + g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 1.0f;
}
// Estimate upcoming scroll so we can offset our relative mouse position so mouse position can be applied immediately (under this block)
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
item_rect_rel.Translate(window->Scroll - next_scroll);
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) printf("[%05d] NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad))
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
IM_ASSERT(g.NavWindow);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest && (g.NavMoveResultLocal.ID != 0 || g.NavMoveResultOther.ID != 0))
{
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
if (g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow) // Maybe entering a flattened child? In this case solve the tie using the regular scoring rules
if ((g.NavMoveResultOther.DistBox < g.NavMoveResultLocal.DistBox) || (g.NavMoveResultOther.DistBox == g.NavMoveResultLocal.DistBox && g.NavMoveResultOther.DistCenter < g.NavMoveResultLocal.DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view
if (g.NavLayer == 0)
NavScrollToBringItemIntoView(result->Window, result->RectRel);
// Apply result from previous frame navigation directional move request
ClearActiveID();
g.NavWindow = result->Window;
SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
g.NavJustMovedToId = result->ID;
g.NavMoveFromClampedRefRect = false;
}
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the nav widget position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredMousePos();
g.IO.WantSetMousePos = true;
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindow(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
NavUpdateWindowing();
// Set output flags for user application
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL) || g.NavInitRequest;
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0);
g.NavIdIsAlive = false;
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(0);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
}
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveRequest && g.NavId == 0)
{
g.NavInitRequest = g.NavInitRequestFromMove = true;
g.NavInitResultId = 0;
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with NavUp/NavDown when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerRect.Min - window->Pos - ImVec2(1,1), window->InnerRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : GetViewportRect();
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous fabsf() calls in NavScoreItem().
//g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) g.OverlayDrawList.AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (g.NavWindow) { ImU32 col = (g.NavWindow->HiddenFrames <= 0) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredMousePos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); g.OverlayDrawList.AddCircleFilled(p, 3.0f, col); g.OverlayDrawList.AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
#endif
}
static void ImGui::UpdateMovingWindow()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow && g.MovingWindow->MoveId == g.ActiveId && g.ActiveIdSource == ImGuiInputSource_Mouse)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0])
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->PosFloat.x != pos.x || moving_window->PosFloat.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
moving_window->PosFloat = pos;
}
FocusWindow(g.MovingWindow);
}
else
{
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
g.MovingWindow = NULL;
}
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
ImGuiContext& g = *GImGui;
// Check user data
// (We pass an error message in the assert expression as a trick to get it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT(g.IO.DeltaTime >= 0.0f && "Need a positive DeltaTime (zero is tolerated but will cause some timing issues)");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Do a simple check for required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was super recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Load settings on first frame
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
g.Time += g.IO.DeltaTime;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.OverlayDrawList.Clear();
g.OverlayDrawList.PushTextureID(g.IO.Fonts->TexID);
g.OverlayDrawList.PushClipRectFullScreen();
g.OverlayDrawList.Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
// Mark rendering data as invalid to prevent user who may have a handle on it to use it
g.DrawData.Clear();
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (!g.ActiveIdIsAlive && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
g.ScalarAsInputTextId = 0;
// Elapse drag & drop payload
if (g.DragDropActive && g.DragDropPayload.DataFrameCount + 1 < g.FrameCount)
{
ClearDragDrop();
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX component, but in reality we test for -256000.0f) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if (g.Time - g.IO.MouseClickedTime[i] < g.IO.MouseDoubleClickTime)
{
if (ImLengthSqr(g.IO.MousePos - g.IO.MouseClickedPos[i]) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
ImVec2 mouse_delta = g.IO.MousePos - g.IO.MouseClickedPos[i];
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, mouse_delta.x < 0.0f ? -mouse_delta.x : mouse_delta.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, mouse_delta.y < 0.0f ? -mouse_delta.y : mouse_delta.y);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(mouse_delta));
}
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = 1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame));
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMovingWindow();
// Delay saving settings so we don't spam disk too much
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
SaveIniSettingsToDisk(g.IO.IniFilename);
}
// Find the window we are hovering
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
g.HoveredWindow = (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoInputs)) ? g.MovingWindow : FindHoveredWindow();
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
ImGuiWindow* modal_window = GetFrontMostModalRootWindow();
if (modal_window != NULL)
{
g.ModalWindowDarkeningRatio = ImMin(g.ModalWindowDarkeningRatio + g.IO.DeltaTime * 6.0f, 1.0f);
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredRootWindow = g.HoveredWindow = NULL;
}
else
{
g.ModalWindowDarkeningRatio = 0.0f;
}
// Update the WantCaptureMouse/WantCaptureKeyboard flags, so user can capture/discard the inputs away from the rest of their application.
// When clicking outside of a window we assume the click is owned by the application and won't request capture. We need to track click ownership.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : 0;
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.OsImePosRequest = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = NULL;
// Mouse wheel scrolling, scale
if (g.HoveredWindow && !g.HoveredWindow->Collapsed && (g.IO.MouseWheel != 0.0f || g.IO.MouseWheelH != 0.0f))
{
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
ImGuiWindow* window = g.HoveredWindow;
ImGuiWindow* scroll_window = window;
while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs) && scroll_window->ParentWindow)
scroll_window = scroll_window->ParentWindow;
const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoInputs);
if (g.IO.MouseWheel != 0.0f)
{
if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
// Zoom / Scale window
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
window->Pos += offset;
window->PosFloat += offset;
window->Size *= scale;
window->SizeFull *= scale;
}
else if (!g.IO.KeyCtrl && scroll_allowed)
{
// Mouse wheel vertical scrolling
float scroll_amount = 5 * scroll_window->CalcFontSize();
scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
}
}
if (g.IO.MouseWheelH != 0.0f && scroll_allowed)
{
// Mouse wheel horizontal scrolling (for hardware that supports it)
float scroll_amount = scroll_window->CalcFontSize();
if (!g.IO.KeyCtrl && !(window->Flags & ImGuiWindowFlags_NoScrollWithMouse))
SetWindowScrollX(window, window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
}
}
// Pressing TAB activate widget focus
if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
{
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
}
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->Active = false;
window->WriteAccessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusFrontMostActiveWindow(NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.CurrentPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow);
// Create implicit window - we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
}
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHash(name, 0));
if (!settings)
settings = AddWindowSettings(name);
return (void*)settings;
}
static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
float x, y;
int i;
if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) settings->Pos = ImVec2(x, y);
else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize);
else if (sscanf(line, "Collapsed=%d", &i) == 1) settings->Collapsed = (i != 0);
}
static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
ImGuiContext& g = *imgui_ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID);
if (!settings)
settings = AddWindowSettings(window->Name);
settings->Pos = window->Pos;
settings->Size = window->SizeFull;
settings->Collapsed = window->Collapsed;
}
// Write a buffer
// If a window wasn't opened in this session we preserve its settings
buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
for (int i = 0; i != g.SettingsWindows.Size; i++)
{
const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
if (settings->Pos.x == FLT_MAX)
continue;
const char* name = settings->Name;
if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
name = p;
buf->appendf("[%s][%s]\n", handler->TypeName, name);
buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->appendf("\n");
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
g.LogClipboard = IM_NEW(ImGuiTextBuffer)();
// Add .ini handle for ImGuiWindow type
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHash("Window", 0, 0);
ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
g.SettingsHandlers.push_front(ini_handler);
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
ImGuiContext& g = *context;
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
IM_DELETE(g.IO.Fonts);
// Cleanup of other data are conditional on actually having initialize ImGui.
if (!g.Initialized)
return;
SaveIniSettingsToDisk(g.IO.IniFilename);
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = NULL;
g.HoveredRootWindow = NULL;
g.ActiveIdWindow = NULL;
g.MovingWindow = NULL;
for (int i = 0; i < g.SettingsWindows.Size; i++)
IM_DELETE(g.SettingsWindows[i].Name);
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.CurrentPopupStack.clear();
g.DrawDataBuilder.ClearFreeMemory();
g.OverlayDrawList.ClearFreeMemory();
g.PrivateClipboard.clear();
g.InputTextState.Text.clear();
g.InputTextState.InitialText.clear();
g.InputTextState.TempTextBuffer.clear();
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard)
IM_DELETE(g.LogClipboard);
g.Initialized = false;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (int i = 0; i != g.SettingsWindows.Size; i++)
if (g.SettingsWindows[i].Id == id)
return &g.SettingsWindows[i];
return NULL;
}
static ImGuiWindowSettings* AddWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
g.SettingsWindows.push_back(ImGuiWindowSettings());
ImGuiWindowSettings* settings = &g.SettingsWindows.back();
settings->Name = ImStrdup(name);
settings->Id = ImHash(name, 0);
return settings;
}
static void LoadIniSettingsFromDisk(const char* ini_filename)
{
if (!ini_filename)
return;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", NULL, +1);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data);
ImGui::MemFree(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHash(type_name, 0, 0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
static void LoadIniSettingsFromMemory(const char* buf_readonly)
{
// For convenience and to make the code simpler, we'll write zero terminators inside the buffer. So let's create a writable copy.
char* buf = ImStrdup(buf_readonly);
char* buf_end = buf + strlen(buf);
ImGuiContext& g = *GImGui;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
{
name_start = type_start; // Import legacy entries that have no type
type_start = "Window";
}
else
{
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
}
entry_handler = ImGui::FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
ImGui::MemFree(buf);
g.SettingsLoaded = true;
}
static void SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
ImVector<char> buf;
SaveIniSettingsToMemory(buf);
FILE* f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
fwrite(buf.Data, sizeof(char), (size_t)buf.Size, f);
fclose(f);
}
static void SaveIniSettingsToMemory(ImVector<char>& out_buf)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
ImGuiTextBuffer buf;
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &buf);
}
buf.Buf.pop_back(); // Remove extra zero-terminator used by ImGuiTextBuffer
out_buf.swap(buf.Buf);
}
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
static void MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* a = *(const ImGuiWindow**)lhs;
const ImGuiWindow* b = *(const ImGuiWindow**)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortedBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
qsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortedBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_render_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
// B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
// You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
// C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_render_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImVector<ImDrawList*>* out_render_list, ImGuiWindow* window)
{
AddDrawListToDrawData(out_render_list, window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active && child->HiddenFrames <= 0) // clipped children may have been marked not active
AddWindowToDrawData(out_render_list, child);
}
}
static void AddWindowToDrawDataSelectLayer(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsActiveWindows++;
if (window->Flags & ImGuiWindowFlags_Tooltip)
AddWindowToDrawData(&g.DrawDataBuilder.Layers[1], window);
else
AddWindowToDrawData(&g.DrawDataBuilder.Layers[0], window);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupDrawData(ImVector<ImDrawList*>* draw_lists, ImDrawData* out_draw_data)
{
out_draw_data->Valid = true;
out_draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
out_draw_data->CmdListsCount = draw_lists->Size;
out_draw_data->TotalVtxCount = out_draw_data->TotalIdxCount = 0;
for (int n = 0; n < draw_lists->Size; n++)
{
out_draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
out_draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && ImLengthSqr(g.OsImePosRequest - g.OsImePosSet) > 0.0001f)
{
g.IO.ImeSetInputScreenPosFn((int)g.OsImePosRequest.x, (int)g.OsImePosRequest.y);
g.OsImePosSet = g.OsImePosRequest;
}
// Hide implicit "Debug" window if it hasn't been used
IM_ASSERT(g.CurrentWindowStack.Size == 1); // Mismatched Begin()/End() calls
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
if (g.ActiveId == 0 && g.HoveredId == 0)
{
if (!g.NavWindow || !g.NavWindow->Appearing) // Unless we just made a window/popup appear
{
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
// Set ActiveId even if the _NoMove flag is set, without it dragging away from a window with _NoMove would activate hover on other windows.
FocusWindow(g.HoveredWindow);
SetActiveID(g.HoveredWindow->MoveId, g.HoveredWindow);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - g.HoveredRootWindow->Pos;
if (!(g.HoveredWindow->Flags & ImGuiWindowFlags_NoMove) && !(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoMove))
g.MovingWindow = g.HoveredWindow;
}
else if (g.NavWindow != NULL && GetFrontMostModalRootWindow() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus
// (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the front most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetFrontMostModalRootWindow();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
}
}
}
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsSortBuffer.resize(0);
g.WindowsSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortedBuffer(&g.WindowsSortBuffer, window);
}
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size); // we done something wrong
g.Windows.swap(g.WindowsSortBuffer);
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
g.FrameCountEnded = g.FrameCount;
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
if (g.FrameCountEnded != g.FrameCount)
ImGui::EndFrame();
g.FrameCountRendered = g.FrameCount;
// Gather windows to render
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsActiveWindows = 0;
g.DrawDataBuilder.Clear();
ImGuiWindow* window_to_render_front_most = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget : NULL;
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (window->Active && window->HiddenFrames <= 0 && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != window_to_render_front_most)
AddWindowToDrawDataSelectLayer(window);
}
if (window_to_render_front_most && window_to_render_front_most->Active && window_to_render_front_most->HiddenFrames <= 0) // NavWindowingTarget is always temporarily displayed as the front-most window
AddWindowToDrawDataSelectLayer(window_to_render_front_most);
g.DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested
ImVec2 offset, size, uv[4];
if (g.IO.MouseDrawCursor && g.IO.Fonts->GetMouseCursorTexData(g.MouseCursor, &offset, &size, &uv[0], &uv[2]))
{
const ImVec2 pos = g.IO.MousePos - offset;
const ImTextureID tex_id = g.IO.Fonts->TexID;
const float sc = g.Style.MouseCursorScale;
g.OverlayDrawList.PushTextureID(tex_id);
g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(1,0)*sc, pos+ImVec2(1,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
g.OverlayDrawList.AddImage(tex_id, pos + ImVec2(2,0)*sc, pos+ImVec2(2,0)*sc + size*sc, uv[2], uv[3], IM_COL32(0,0,0,48)); // Shadow
g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[2], uv[3], IM_COL32(0,0,0,255)); // Black border
g.OverlayDrawList.AddImage(tex_id, pos, pos + size*sc, uv[0], uv[1], IM_COL32(255,255,255,255)); // White fill
g.OverlayDrawList.PopTextureID();
}
if (!g.OverlayDrawList.VtxBuffer.empty())
AddDrawListToDrawData(&g.DrawDataBuilder.Layers[0], &g.OverlayDrawList);
// Setup ImDrawData structure for end-user
SetupDrawData(&g.DrawDataBuilder.Layers[0], &g.DrawData);
g.IO.MetricsRenderVertices = g.DrawData.TotalVtxCount;
g.IO.MetricsRenderIndices = g.DrawData.TotalIdxCount;
// Render. If user hasn't set a callback then they may retrieve the draw data via GetDrawData()
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.DrawData.CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(&g.DrawData);
#endif
}
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
{
vfprintf(g.LogFile, fmt, args);
}
else
{
g.LogClipboard->appendfv(fmt, args);
}
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
static void LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end = NULL)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = ImGui::FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
if (ref_pos)
window->DC.LogLinePosY = ref_pos->y;
const char* text_remaining = text;
if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogStartDepth = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
const char* line_end = text_remaining;
while (line_end < text_end)
if (*line_end == '\n')
break;
else
line_end++;
if (line_end >= text_end)
line_end = NULL;
const bool is_first_line = (text == text_remaining);
bool is_last_line = false;
if (line_end == NULL)
{
is_last_line = true;
line_end = text_end;
}
if (line_end != NULL && !(is_last_line && (line_end - text_remaining)==0))
{
const int char_count = (int)(line_end - text_remaining);
if (log_new_line || !is_first_line)
ImGui::LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, text_remaining);
else
ImGui::LogText(" %.*s", char_count, text_remaining);
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
const int text_len = (int)(text_display_end - text);
if (text_len > 0)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
const int text_len = (int)(text_end - text);
if (text_len > 0)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render a triangle to denote expanded/collapsed state
void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float h = g.FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = p_min + 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;
center.y -= r * 0.25f;
a = ImVec2(0,1) * r;
b = ImVec2(-0.866f,-0.5f) * r;
c = ImVec2(+0.866f,-0.5f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
center.x -= r * 0.25f;
a = ImVec2(1,0) * r;
b = ImVec2(-0.500f,+0.866f) * r;
c = ImVec2(-0.500f,-0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
window->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
}
void ImGui::RenderBullet(ImVec2 pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddCircleFilled(pos, GImGui->FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
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;
window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
window->DrawList->PathLineTo(ImVec2(bx, by));
window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
window->DrawList->PathStroke(col, false, thickness);
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = ImGui::GetCurrentWindow();
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Cancel out character spacing for the last character of a line (it is baked into glyph->AdvanceX field)
const float font_scale = font_size / font->FontSize;
const float character_spacing_x = 1.0f * font_scale;
if (text_size.x > 0.0f)
text_size.x -= character_spacing_x;
text_size.x = (float)(int)(text_size.x + 0.95f);
return text_size;
}
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((window->ClipRect.Min.y - pos.y) / items_height);
int end = (int)((window->ClipRect.Max.y - pos.y) / items_height);
if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Up) // When performing a navigation request, ensure we have one item extra in the direction we are moving to
start--;
if (g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
// Find window given position, search front-to-back
// FIXME: Note that we have a lag here because WindowRectClipped is updated in Begin() so windows moved by user via SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is called, aka before the next Begin(). Moving window thankfully isn't affected.
static ImGuiWindow* FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active)
continue;
if (window->Flags & ImGuiWindowFlags_NoInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->WindowRectClipped.Min - g.Style.TouchExtraPadding, window->WindowRectClipped.Max + g.Style.TouchExtraPadding);
if (bb.Contains(g.IO.MousePos))
return window;
}
return NULL;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(window->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
return rect_for_touch.Contains(g.IO.MousePos);
}
static bool IsKeyPressedMap(ImGuiKey key, bool repeat)
{
const int key_index = GImGui->IO.KeyMap[key];
return (key_index >= 0) ? ImGui::IsKeyPressed(key_index, repeat) : false;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
return GImGui->IO.KeyMap[imgui_key];
}
// Note that imgui doesn't know the semantic of each entry of io.KeyDown[]. Use your own indices/enums according to how your back-end/engine stored them into KeyDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
return GImGui->IO.KeysDown[user_key_index];
}
int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
{
if (t == 0.0f)
return 1;
if (t <= repeat_delay || repeat_rate <= 0.0f)
return 0;
const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
return (count > 0) ? count : 0;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0) return false;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
bool ImGui::IsMouseClicked(int button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
if ((fmodf(t - delay, rate) > rate*0.5f) != (fmodf(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
return true;
}
return false;
}
bool ImGui::IsMouseReleased(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
bool ImGui::IsMouseDragging(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
ImVec2 ImGui::GetMousePos()
{
return GImGui->IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.CurrentPopupStack.Size > 0)
return g.OpenPopupStack[g.CurrentPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
if (mouse_pos == NULL)
mouse_pos = &GImGui->IO.MousePos;
const float MOUSE_INVALID = -256000.0f;
return mouse_pos->x >= MOUSE_INVALID && mouse_pos->y >= MOUSE_INVALID;
}
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId && !g.NavDisableHighlight && g.NavId == g.CurrentWindow->DC.LastItemId;
}
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_Default);
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static ImRect GetViewportRect()
{
ImGuiContext& g = *GImGui;
if (g.IO.DisplayVisibleMin.x != g.IO.DisplayVisibleMax.x && g.IO.DisplayVisibleMin.y != g.IO.DisplayVisibleMax.y)
return ImRect(g.IO.DisplayVisibleMin, g.IO.DisplayVisibleMax);
return ImRect(0.0f, 0.0f, g.IO.DisplaySize.x, g.IO.DisplaySize.y);
}
// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
{
ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (override_previous_tooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltips. We can't easily "reset" the content of a window so we create a new one.
window->HiddenFrames = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoNav;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
BeginTooltipEx(0, true);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
void ImGui::BeginTooltip()
{
BeginTooltipEx(0, false);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.CurrentPopupStack.Size;
ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.ParentWindow = parent_window;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenMousePos = g.IO.MousePos;
popup_ref.OpenPopupPos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Close child popups if any
g.OpenPopupStack.resize(current_stack_size + 1);
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
else
g.OpenPopupStack[current_stack_size] = popup_ref;
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int n = 0;
if (ref_window)
{
for (n = 0; n < g.OpenPopupStack.Size; n++)
{
ImGuiPopupRef& popup = g.OpenPopupStack[n];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
bool has_focus = false;
for (int m = n; m < g.OpenPopupStack.Size && !has_focus; m++)
has_focus = (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow);
if (!has_focus)
break;
}
}
if (n < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the block below
ClosePopupToLevel(n);
}
static ImGuiWindow* GetFrontMostModalRootWindow()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
static void ClosePopupToLevel(int remaining)
{
IM_ASSERT(remaining >= 0);
ImGuiContext& g = *GImGui;
ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
if (g.NavLayer == 0)
focus_window = NavRestoreLastChildNavWindow(focus_window);
ImGui::FocusWindow(focus_window);
focus_window->DC.NavHideHighlightOneFrame = true;
g.OpenPopupStack.resize(remaining);
}
void ImGui::ClosePopup(ImGuiID id)
{
if (!IsPopupOpen(id))
return;
ImGuiContext& g = *GImGui;
ClosePopupToLevel(g.OpenPopupStack.Size - 1);
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.CurrentPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.CurrentPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
while (popup_idx > 0 && g.OpenPopupStack[popup_idx].Window && (g.OpenPopupStack[popup_idx].Window->Flags & ImGuiWindowFlags_ChildMenu))
popup_idx--;
ClosePopupToLevel(popup_idx);
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (extra_flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.CurrentPopupStack.Size) // Early out for performance
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if (g.NextWindowData.PosCond == 0)
SetNextWindowPos(g.IO.DisplaySize * 0.5f, ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
bool is_open = Begin(name, p_open, flags | ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopup(id);
return false;
}
return is_open;
}
static void NavProcessMoveRequestWrapAround(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow == window && NavMoveRequestButNoResultYet())
if ((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == 0)
{
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
ImGui::NavMoveRequestCancel();
g.NavWindow->NavRectRel[0].Min.y = g.NavWindow->NavRectRel[0].Max.y = ((g.NavMoveDir == ImGuiDir_Up) ? ImMax(window->SizeFull.y, window->SizeContents.y) : 0.0f) - window->Scroll.y;
}
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui; (void)g;
IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.CurrentPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavProcessMoveRequestWrapAround(g.CurrentWindow);
End();
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // However, you cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = ImGui::GetCurrentWindow();
ImGuiWindowFlags flags = ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
const ImVec2 content_avail = ImGui::GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
flags |= extra_flags;
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
ImGui::SetNextWindowSize(size);
bool ret = ImGui::Begin(title, NULL, flags);
ImGuiWindow* child_window = ImGui::GetCurrentWindow();
child_window->ChildId = id;
child_window->AutoFitChildAxises = auto_fit_axises;
g.Style.ChildBorderSize = backup_border_size;
// Process navigation-in immediately so NavInit can run on first frame
if (!(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll) && g.NavActivateId == id)
{
ImGui::FocusWindow(child_window);
ImGui::NavInitWindow(child_window, false);
ImGui::SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if (window->BeginCount > 1)
{
End();
}
else
{
// When using auto-filling child window, we don't provide full width/height to ItemSize so that it doesn't feed back into automatic size-fitting.
ImVec2 sz = GetWindowSize();
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
return BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
}
void ImGui::EndChildFrame()
{
EndChild();
PopStyleVar(3);
PopStyleColor();
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
static void CheckStacksSize(ImGuiWindow* window, bool write)
{
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
ImGuiContext& g = *GImGui;
int* p_backup = &window->DC.StackSizesBackup[0];
{ int current = window->IDStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
{ int current = window->DC.GroupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
{ int current = g.CurrentPopupStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
{ int current = g.ColorModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
{ int current = g.StyleModifiers.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
{ int current = g.FontStack.Size; if (write) *p_backup = current; else IM_ASSERT(*p_backup == current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
enum ImGuiPopupPositionPolicy
{
ImGuiPopupPositionPolicy_Default,
ImGuiPopupPositionPolicy_ComboBox
};
static ImVec2 FindBestWindowPosForPopup(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy = ImGuiPopupPositionPolicy_Default)
{
const ImGuiStyle& style = GImGui->Style;
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
ImVec2 safe_padding = style.DisplaySafeAreaPadding;
ImRect r_outer(GetViewportRect());
r_outer.Expand(ImVec2((size.x - r_outer.GetWidth() > safe_padding.x*2) ? -safe_padding.x : 0.0f, (size.y - r_outer.GetHeight() > safe_padding.y*2) ? -safe_padding.y : 0.0f));
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiContext& g = *GImGui;
ImGuiID id = ImHash(name, 0);
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
{
// Retrieve settings from .ini file
// Use SetWindowPos() or SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
window->Pos = window->PosFloat = ImVec2(60, 60);
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
window->PosFloat = settings->Pos;
window->Pos = ImFloor(window->PosFloat);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = settings->Size;
}
}
window->Size = window->SizeFull = window->SizeFullAtLastBegin = size;
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.insert(g.Windows.begin(), window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.SizeConstraintCond != 0)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window->TitleBarHeight() + window->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcSizeContents(ImGuiWindow* window)
{
ImVec2 sz;
sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
return sz + window->WindowPadding;
}
static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
ImVec2 size_auto_fit;
if ((flags & ImGuiWindowFlags_Tooltip) != 0)
{
// Tooltip always resize. We keep the spacing symmetric on both axises for aesthetic purpose.
size_auto_fit = size_contents;
}
else
{
// When the window cannot fit all contents (either because of constraints, either because screen is too small): we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than DisplaySize-WindowPadding.
size_auto_fit = ImClamp(size_contents, style.WindowMinSize, ImMax(style.WindowMinSize, g.IO.DisplaySize - g.Style.DisplaySafeAreaPadding));
ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
if (size_auto_fit_after_constraint.x < size_contents.x && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar))
size_auto_fit.y += style.ScrollbarSize;
if (size_auto_fit_after_constraint.y < size_contents.y && !(flags & ImGuiWindowFlags_NoScrollbar))
size_auto_fit.x += style.ScrollbarSize;
}
return size_auto_fit;
}
static float GetScrollMaxX(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
}
static float GetScrollMaxY(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
}
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
{
ImVec2 scroll = window->Scroll;
float cr_x = window->ScrollTargetCenterRatio.x;
float cr_y = window->ScrollTargetCenterRatio.y;
if (window->ScrollTarget.x < FLT_MAX)
scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
if (window->ScrollTarget.y < FLT_MAX)
scroll.y = window->ScrollTarget.y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, GetScrollMaxX(window));
scroll.y = ImMin(scroll.y, GetScrollMaxY(window));
}
return scroll;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPos;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
};
static ImRect GetBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y, rect.Max.x - perp_padding, rect.Min.y + thickness);
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x, rect.Max.y - perp_padding);
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y);
if (border_n == 3) return ImRect(rect.Min.x, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding);
IM_ASSERT(0);
return ImRect();
}
// Handle resize for: Resize Grips, Borders, Gamepad
static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return;
const int resize_border_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 4 : 0;
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
const float grip_hover_size = (float)(int)(grip_draw_size * 0.75f);
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner, corner + grip.InnerDir * grip_hover_size);
resize_rect.FixInverted();
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (g.HoveredWindow == window && held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcSizeAfterConstraint(window, size_auto_fit);
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + resize_rect.GetSize() * grip.CornerPos; // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPos, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
const float BORDER_SIZE = 5.0f; // FIXME: Only works _inside_ window because of HoveredWindow check.
const float BORDER_APPEAR_TIMER = 0.05f; // Reduce visual noise
bool hovered, held;
ImRect border_rect = GetBorderRect(window, border_n, grip_hover_size, BORDER_SIZE);
ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
if ((hovered && g.HoveredIdTimer > BORDER_APPEAR_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held) *border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y); }
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + BORDER_SIZE); }
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + BORDER_SIZE); }
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x); }
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = window->PosFloat = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
}
// Push a new ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL); // Window name required
IM_ASSERT(g.Initialized); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
if (!window)
{
ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if (flags & ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
if (first_begin_of_the_frame)
window->Flags = (ImGuiWindowFlags)flags;
else
flags = window->Flags;
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFrames == 1);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
window->CloseButton = (p_open != NULL);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// Add to stack
g.CurrentWindowStack.push_back(window);
SetCurrentWindow(window);
CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.CurrentPopupStack.Size];
popup_ref.Window = window;
g.CurrentPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.PosCond)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
g.NextWindowData.PosCond = 0;
}
if (g.NextWindowData.SizeCond)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
g.NextWindowData.SizeCond = 0;
}
if (g.NextWindowData.ContentSizeCond)
{
// Adjust passed "client size" to become a "window size"
window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
if (window->SizeContentsExplicit.y != 0.0f)
window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
g.NextWindowData.ContentSizeCond = 0;
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
if (g.NextWindowData.CollapsedCond)
{
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
g.NextWindowData.CollapsedCond = 0;
}
if (g.NextWindowData.FocusCond)
{
SetWindowFocus();
g.NextWindowData.FocusCond = 0;
}
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
// Initialize
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !window_is_child_tooltip)
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = window->RootWindowForTabbing = parent_window->RootWindowForTitleBarHighlight; // Same value in master branch, will differ for docking
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
window->Active = true;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = g.WindowsActiveCount++;
window->BeginCount = 0;
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->LastFrameActive = current_frame;
window->IDStack.resize(1);
// Lock window rounding, border size and rounding so that altering the border sizes for children doesn't have side-effects.
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
window->WindowBorderSize = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildBorderSize : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
window->WindowPadding = style.WindowPadding;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse))
{
ImRect title_bar_rect = window->TitleBarRect();
if (window->CollapseToggleWanted || (g.HoveredWindow == window && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0]))
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->CollapseToggleWanted = false;
// SIZE
// Update contents size from last frame for auto-fitting (unless explicitly specified)
window->SizeContents = CalcSizeContents(window);
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
if (window->HiddenFrames > 0)
window->HiddenFrames--;
if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0 && window_just_activated_by_user)
{
window->HiddenFrames = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->SizeContents = ImVec2(0.f, 0.f);
}
}
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
if (flags & ImGuiWindowFlags_AlwaysAutoResize && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
if (!window_size_y_set_by_api)
window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit only grows during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// SCROLLBAR STATUS
// Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied
float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = window->PosFloat = g.CurrentPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
window->BeginOrderWithinParent = parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = window->PosFloat = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFrames == 0);
if (window_pos_with_pivot)
{
// Position given a pivot (e.g. for centering)
SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0);
}
else if (flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then our FindBestPopupWindowPos() function will move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
IM_ASSERT(window_pos_set_by_api);
float horizontal_overlap = style.ItemSpacing.x; // We want some overlap to convey the relative depth of each popup (currently the amount of overlap it is hard-coded to style.ItemSpacing.x, may need to introduce another style value).
ImGuiWindow* parent_menu = parent_window_in_stack;
ImRect rect_to_avoid;
if (parent_menu->DC.MenuBarAppending)
rect_to_avoid = ImRect(-FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight(), FLT_MAX, parent_menu->Pos.y + parent_menu->TitleBarHeight() + parent_menu->MenuBarHeight());
else
rect_to_avoid = ImRect(parent_menu->Pos.x + horizontal_overlap, -FLT_MAX, parent_menu->Pos.x + parent_menu->Size.x - horizontal_overlap - parent_menu->ScrollbarSizes.x, FLT_MAX);
window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
{
ImRect rect_to_avoid(window->PosFloat.x - 1, window->PosFloat.y - 1, window->PosFloat.x + 1, window->PosFloat.y + 1);
window->PosFloat = FindBestWindowPosForPopup(window->PosFloat, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
}
// Position tooltip (always follows mouse)
if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
{
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = (!g.NavDisableHighlight && g.NavDisableMouseHover) ? NavCalcPreferredMousePos() : g.IO.MousePos;
ImRect rect_to_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
rect_to_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
window->PosFloat = FindBestWindowPosForPopup(ref_pos, window->Size, &window->AutoPosLastDirection, rect_to_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
window->PosFloat = ref_pos + ImVec2(2,2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
}
// Clamp position so it stays visible
if (!(flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
{
if (!window_pos_set_by_api && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && g.IO.DisplaySize.x > 0.0f && g.IO.DisplaySize.y > 0.0f) // Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
{
ImVec2 padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
window->PosFloat = ImMax(window->PosFloat + window->Size, padding) - window->Size;
window->PosFloat = ImMin(window->PosFloat, g.IO.DisplaySize - padding);
}
}
window->Pos = ImFloor(window->PosFloat);
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
else
window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
// Prepare for focus requests
window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// Apply focus, new windows appears in front
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
if (!(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) || (flags & ImGuiWindowFlags_Popup))
want_focus = true;
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = { 0 };
const int resize_grip_count = (flags & ImGuiWindowFlags_ResizeFromAnySide) ? 2 : 1; // 4
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
if (!window->Collapsed)
UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
ImRect viewport_rect(GetViewportRect());
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
else
PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
// Draw modal window background (darkens what is behind them)
if ((flags & ImGuiWindowFlags_Modal) != 0 && window == GetFrontMostModalRootWindow())
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, GetColorU32(ImGuiCol_ModalWindowDarkening, g.ModalWindowDarkeningRatio));
// Draw navigation selection/windowing rectangle background
if (g.NavWindowingTarget == window)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Draw window + handle manual resize
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
const bool title_bar_is_highlight = want_focus || (g.NavWindow && window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
const ImRect title_bar_rect = window->TitleBarRect();
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
if (g.NextWindowData.BgAlphaCond != 0)
{
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(g.NextWindowData.BgAlphaVal) << IM_COL32_A_SHIFT);
g.NextWindowData.BgAlphaCond = 0;
}
window->DrawList->AddRectFilled(window->Pos+ImVec2(0,window->TitleBarHeight()), window->Pos+window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
// Title bar
ImU32 title_bar_col = GetColorU32(window->Collapsed ? ImGuiCol_TitleBgCollapsed : title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
if (!(flags & ImGuiWindowFlags_NoTitleBar))
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min, menu_bar_rect.Max, GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiLayoutType_Horizontal);
if (window->ScrollbarY)
Scrollbar(ImGuiLayoutType_Vertical);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (!(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPos);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders
if (window_border_size > 0.0f)
window->DrawList->AddRect(window->Pos, window->Pos+window->Size, GetColorU32(ImGuiCol_Border), window_rounding, ImDrawCornerFlags_All, window_border_size);
if (border_held != -1)
{
ImRect border = GetBorderRect(window, border_held, grip_draw_size, 0.0f);
window->DrawList->AddLine(border.Min, border.Max, GetColorU32(ImGuiCol_SeparatorActive), ImMax(1.0f, window_border_size));
}
if (style.FrameBorderSize > 0 && !(flags & ImGuiWindowFlags_NoTitleBar))
window->DrawList->AddLine(title_bar_rect.GetBL() + ImVec2(style.WindowBorderSize, -1), title_bar_rect.GetBR() + ImVec2(-style.WindowBorderSize,-1), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTarget == window)
{
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(viewport_rect)) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
}
// Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
window->SizeFullAtLastBegin = window->SizeFull;
// Update ContentsRegionMax. All the variable it depends on are set above in this function.
window->ContentsRegionRect.Min.x = -window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = -window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
window->ContentsRegionRect.Max.x = -window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
window->ContentsRegionRect.Max.y = -window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.IndentX = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffsetX = 0.0f;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.IndentX + window->DC.ColumnsOffsetX, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrentLineHeight = window->DC.PrevLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (GetScrollMaxY() > 0.0f);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
window->DC.MenuBarOffsetX = ImMax(window->WindowPadding.x, style.ItemSpacing.x);
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.ItemFlags = ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.ColumnsSet = NULL;
window->DC.TreeDepth = 0;
window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
window->DC.ItemFlags = parent_window->DC.ItemFlags;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
// Close & collapse button are on layer 1 (same as menus) and don't default focus
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent++;
window->DC.NavLayerCurrentMask <<= 1;
// Collapse button
if (!(flags & ImGuiWindowFlags_NoCollapse))
{
ImGuiID id = window->GetID("#COLLAPSE");
ImRect bb(window->Pos + style.FramePadding + ImVec2(1,1), window->Pos + style.FramePadding + ImVec2(g.FontSize,g.FontSize) - ImVec2(1,1));
ItemAdd(bb, id); // To allow navigation
if (ButtonBehavior(bb, id, NULL, NULL))
window->CollapseToggleWanted = true; // Defer collapsing to next frame as we are too far in the Begin() function
RenderNavHighlight(bb, id);
RenderArrow(window->Pos + style.FramePadding, window->Collapsed ? ImGuiDir_Right : ImGuiDir_Down, 1.0f);
}
// Close button
if (p_open != NULL)
{
const float pad = style.FramePadding.y;
const float rad = g.FontSize * 0.5f;
if (CloseButton(window->GetID("#CLOSE"), window->Rect().GetTR() + ImVec2(-pad - rad, pad + rad), rad + 1))
*p_open = false;
}
window->DC.NavLayerCurrent--;
window->DC.NavLayerCurrentMask >>= 1;
window->DC.ItemFlags = item_flags_backup;
// Title text (FIXME: refactor text alignment facilities along with RenderText helpers)
ImVec2 text_size = CalcTextSize(name, NULL, true);
ImRect text_r = title_bar_rect;
float pad_left = (flags & ImGuiWindowFlags_NoCollapse) == 0 ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
float pad_right = (p_open != NULL) ? (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x) : style.FramePadding.x;
if (style.WindowTitleAlign.x > 0.0f) pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
text_r.Min.x += pad_left;
text_r.Max.x -= pad_right;
ImRect clip_rect = text_r;
clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
}
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
window->WindowRectClipped = window->Rect();
window->WindowRectClipped.ClipWith(window->ClipRect);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
ImGui::LogToClipboard();
*/
// Inner rectangle
// We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
// Note that if our window is collapsed we will end up with a null clipping rectangle which is the correct behavior.
window->InnerRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
window->InnerRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
//window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
// Inner clipping rectangle
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y);
// After Begin() we fill the last item / hovered data using the title bar data. Make that a standard behavior (to allow usage of context menus on title bar only, etc.).
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
}
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.SizeConstraintCond = 0;
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse because they have no title bar).
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
window->Collapsed = parent_window && parent_window->Collapsed;
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
window->Collapsed |= (window->WindowRectClipped.Min.x >= window->WindowRectClipped.Max.x || window->WindowRectClipped.Min.y >= window->WindowRectClipped.Max.y);
// We also hide the window from rendering because we've already added its border to the command list.
// (we could perform the check earlier in the function but it is simpler at this point)
if (window->Collapsed)
window->Active = false;
}
if (style.Alpha <= 0.0f)
window->Active = false;
// Return false if we don't intend to display anything to allow user to perform an early out optimization
window->SkipItems = (window->Collapsed || !window->Active) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0;
return !window->SkipItems;
}
// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
{
// Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
ImGui::SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
// Old API feature: override the window background alpha with a parameter.
if (bg_alpha_override >= 0.0f)
ImGui::SetNextWindowBgAlpha(bg_alpha_override);
return ImGui::Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.ColumnsSet != NULL)
EndColumns();
PopClipRect(); // Inner window clip rectangle
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.CurrentPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
// Vertical scrollbar
// The entire piece of code below is rather confusing because:
// - We handle absolute seeking (when first clicking outside the grab) and relative manipulation (afterward or when clicking inside the grab)
// - We store values as normalized ratio and in a form that allows the window content to change while we are holding on a scrollbar
// - We handle both horizontal and vertical scrollbars, which makes the terminology not ideal.
void ImGui::Scrollbar(ImGuiLayoutType direction)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const bool horizontal = (direction == ImGuiLayoutType_Horizontal);
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(horizontal ? "#SCROLLX" : "#SCROLLY");
// Render background
bool other_scrollbar = (horizontal ? window->ScrollbarY : window->ScrollbarX);
float other_scrollbar_size_w = other_scrollbar ? style.ScrollbarSize : 0.0f;
const ImRect window_rect = window->Rect();
const float border_size = window->WindowBorderSize;
ImRect bb = horizontal
? ImRect(window->Pos.x + border_size, window_rect.Max.y - style.ScrollbarSize, window_rect.Max.x - other_scrollbar_size_w - border_size, window_rect.Max.y - border_size)
: ImRect(window_rect.Max.x - style.ScrollbarSize, window->Pos.y + border_size, window_rect.Max.x - border_size, window_rect.Max.y - other_scrollbar_size_w - border_size);
if (!horizontal)
bb.Min.y += window->TitleBarHeight() + ((window->Flags & ImGuiWindowFlags_MenuBar) ? window->MenuBarHeight() : 0.0f);
if (bb.GetWidth() <= 0.0f || bb.GetHeight() <= 0.0f)
return;
int window_rounding_corners;
if (horizontal)
window_rounding_corners = ImDrawCornerFlags_BotLeft | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
else
window_rounding_corners = (((window->Flags & ImGuiWindowFlags_NoTitleBar) && !(window->Flags & ImGuiWindowFlags_MenuBar)) ? ImDrawCornerFlags_TopRight : 0) | (other_scrollbar ? 0 : ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_ScrollbarBg), window->WindowRounding, window_rounding_corners);
bb.Expand(ImVec2(-ImClamp((float)(int)((bb.Max.x - bb.Min.x - 2.0f) * 0.5f), 0.0f, 3.0f), -ImClamp((float)(int)((bb.Max.y - bb.Min.y - 2.0f) * 0.5f), 0.0f, 3.0f)));
// V denote the main, longer axis of the scrollbar (= height for a vertical scrollbar)
float scrollbar_size_v = horizontal ? bb.GetWidth() : bb.GetHeight();
float scroll_v = horizontal ? window->Scroll.x : window->Scroll.y;
float win_size_avail_v = (horizontal ? window->SizeFull.x : window->SizeFull.y) - other_scrollbar_size_w;
float win_size_contents_v = horizontal ? window->SizeContents.x : window->SizeContents.y;
// Calculate the height of our grabbable box. It generally represent the amount visible (vs the total scrollable amount)
// But we maintain a minimum size in pixel to allow for the user to still aim inside.
IM_ASSERT(ImMax(win_size_contents_v, win_size_avail_v) > 0.0f); // Adding this assert to check if the ImMax(XXX,1.0f) is still needed. PLEASE CONTACT ME if this triggers.
const float win_size_v = ImMax(ImMax(win_size_contents_v, win_size_avail_v), 1.0f);
const float grab_h_pixels = ImClamp(scrollbar_size_v * (win_size_avail_v / win_size_v), style.GrabMinSize, scrollbar_size_v);
const float grab_h_norm = grab_h_pixels / scrollbar_size_v;
// Handle input right away. None of the code of Begin() is relying on scrolling position before calling Scrollbar().
bool held = false;
bool hovered = false;
const bool previously_held = (g.ActiveId == id);
ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_NoNavFocus);
float scroll_max = ImMax(1.0f, win_size_contents_v - win_size_avail_v);
float scroll_ratio = ImSaturate(scroll_v / scroll_max);
float grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
if (held && grab_h_norm < 1.0f)
{
float scrollbar_pos_v = horizontal ? bb.Min.x : bb.Min.y;
float mouse_pos_v = horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
float* click_delta_to_grab_center_v = horizontal ? &g.ScrollbarClickDeltaToGrabCenter.x : &g.ScrollbarClickDeltaToGrabCenter.y;
// Click position in scrollbar normalized space (0.0f->1.0f)
const float clicked_v_norm = ImSaturate((mouse_pos_v - scrollbar_pos_v) / scrollbar_size_v);
SetHoveredID(id);
bool seek_absolute = false;
if (!previously_held)
{
// On initial click calculate the distance between mouse and the center of the grab
if (clicked_v_norm >= grab_v_norm && clicked_v_norm <= grab_v_norm + grab_h_norm)
{
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
else
{
seek_absolute = true;
*click_delta_to_grab_center_v = 0.0f;
}
}
// Apply scroll
// It is ok to modify Scroll here because we are being called in Begin() after the calculation of SizeContents and before setting up our starting position
const float scroll_v_norm = ImSaturate((clicked_v_norm - *click_delta_to_grab_center_v - grab_h_norm*0.5f) / (1.0f - grab_h_norm));
scroll_v = (float)(int)(0.5f + scroll_v_norm * scroll_max);//(win_size_contents_v - win_size_v));
if (horizontal)
window->Scroll.x = scroll_v;
else
window->Scroll.y = scroll_v;
// Update values for rendering
scroll_ratio = ImSaturate(scroll_v / scroll_max);
grab_v_norm = scroll_ratio * (scrollbar_size_v - grab_h_pixels) / scrollbar_size_v;
// Update distance to grab now that we have seeked and saturated
if (seek_absolute)
*click_delta_to_grab_center_v = clicked_v_norm - grab_v_norm - grab_h_norm*0.5f;
}
// Render
const ImU32 grab_col = GetColorU32(held ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_ScrollbarGrab);
ImRect grab_rect;
if (horizontal)
grab_rect = ImRect(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm), bb.Min.y, ImMin(ImLerp(bb.Min.x, bb.Max.x, grab_v_norm) + grab_h_pixels, window_rect.Max.x), bb.Max.y);
else
grab_rect = ImRect(bb.Min.x, ImLerp(bb.Min.y, bb.Max.y, grab_v_norm), bb.Max.x, ImMin(ImLerp(bb.Min.y, bb.Max.y, grab_v_norm) + grab_h_pixels, window_rect.Max.y));
window->DrawList->AddRectFilled(grab_rect.Min, grab_rect.Max, grab_col, style.ScrollbarRounding);
}
void ImGui::BringWindowToFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.Windows[i] == window)
{
g.Windows.erase(g.Windows.Data + i);
g.Windows.push_back(window);
break;
}
}
void ImGui::BringWindowToBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavIdIsAlive = false;
g.NavLayer = 0;
}
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Move the root window to the top of the pile
if (window->RootWindow)
window = window->RootWindow;
// Steal focus on active widgets
if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
ClearActiveID();
// Bring to front
if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
BringWindowToFront(window);
}
void ImGui::FocusFrontMostActiveWindow(ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size - 1; i >= 0; i--)
if (g.Windows[i] != ignore_window && g.Windows[i]->WasActive && !(g.Windows[i]->Flags & ImGuiWindowFlags_ChildWindow))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(g.Windows[i]);
FocusWindow(focus_window);
return;
}
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = GImGui->Style;
if (w_full <= 0.0f)
w_full = CalcItemWidth();
const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
float ImGui::CalcItemWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
float w = window->DC.ItemWidth;
if (w < 0.0f)
{
// Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
float width_to_right_edge = GetContentRegionAvail().x;
w = ImMax(1.0f, width_to_right_edge + w);
}
w = (float)(int)w;
return w;
}
static ImFont* GetDefaultFont()
{
ImGuiContext& g = *GImGui;
return g.IO.FontDefault ? g.IO.FontDefault : g.IO.Fonts->Fonts[0];
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale;
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_AllowKeyboardFocus, allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_ModalWindowDarkening: return "ModalWindowDarkening";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredRootWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindow;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
return window->Active && window == window->RootWindowForTabbing && (!(window->Flags & ImGuiWindowFlags_NoNavFocus) || window == g.NavWindow);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
static void SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.x = new_scroll_x;
window->DC.CursorMaxPos.x -= window->Scroll.x;
}
static void SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.y = new_scroll_y;
window->DC.CursorMaxPos.y -= window->Scroll.y;
}
static void SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->PosFloat = pos;
window->Pos = ImFloor(pos);
window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
static void SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = size.x;
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = size.y;
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
static void SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.BgAlphaVal = alpha;
g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
// In window space (not screen space!)
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImVec2 mx = window->ContentsRegionRect.Max;
if (window->DC.ColumnsSet)
mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GetCurrentWindowRead();
return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
}
float ImGui::GetContentRegionAvailWidth()
{
return GetContentRegionAvail().x;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Min;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max.x - window->ContentsRegionRect.Min.x;
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& screen_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = screen_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
float ImGui::GetScrollX()
{
return GImGui->CurrentWindow->Scroll.x;
}
float ImGui::GetScrollY()
{
return GImGui->CurrentWindow->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
return GetScrollMaxX(GImGui->CurrentWindow);
}
float ImGui::GetScrollMaxY()
{
return GetScrollMaxY(GImGui->CurrentWindow);
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosY(float pos_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
window->ScrollTarget.y = (float)(int)(pos_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
// Minor hack to to make scrolling to top/bottom of window take account of WindowPadding, it looks more right to the user this way
if (center_y_ratio <= 0.0f && window->ScrollTarget.y <= window->WindowPadding.y)
window->ScrollTarget.y = 0.0f;
else if (center_y_ratio >= 1.0f && window->ScrollTarget.y >= window->SizeContents.y - window->WindowPadding.y + GImGui->Style.ItemSpacing.y)
window->ScrollTarget.y = window->SizeContents.y;
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHere(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineHeight * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiWindow* window = GetCurrentWindow();
window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
window->FocusIdxTabRequestNext = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHere();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.StateStorage;
}
void ImGui::TextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const char* text_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
TextUnformatted(g.TempBuffer, text_end);
}
void ImGui::Text(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextV(fmt, args);
va_end(args);
}
void ImGui::TextColoredV(const ImVec4& col, const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, col);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextColored(const ImVec4& col, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextColoredV(col, fmt, args);
va_end(args);
}
void ImGui::TextDisabledV(const char* fmt, va_list args)
{
PushStyleColor(ImGuiCol_Text, GImGui->Style.Colors[ImGuiCol_TextDisabled]);
TextV(fmt, args);
PopStyleColor();
}
void ImGui::TextDisabled(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextDisabledV(fmt, args);
va_end(args);
}
void ImGui::TextWrappedV(const char* fmt, va_list args)
{
bool need_wrap = (GImGui->CurrentWindow->DC.TextWrapPos < 0.0f); // Keep existing wrap position is one ia already set
if (need_wrap) PushTextWrapPos(0.0f);
TextV(fmt, args);
if (need_wrap) PopTextWrapPos();
}
void ImGui::TextWrapped(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
TextWrappedV(fmt, args);
va_end(args);
}
void ImGui::TextUnformatted(const char* text, const char* text_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
IM_ASSERT(text != NULL);
const char* text_begin = text;
if (text_end == NULL)
text_end = text + strlen(text); // FIXME-OPT
const ImVec2 text_pos(window->DC.CursorPos.x, window->DC.CursorPos.y + window->DC.CurrentLineTextBaseOffset);
const float wrap_pos_x = window->DC.TextWrapPos;
const bool wrap_enabled = wrap_pos_x >= 0.0f;
if (text_end - text > 2000 && !wrap_enabled)
{
// Long text!
// Perform manual coarse clipping to optimize for long multi-line text
// From this point we will only compute the width of lines that are visible. Optimization only available when word-wrapping is disabled.
// We also don't vertically center the text within the line full height, which is unlikely to matter because we are likely the biggest and only item on the line.
const char* line = text;
const float line_height = GetTextLineHeight();
const ImRect clip_rect = window->ClipRect;
ImVec2 text_size(0,0);
if (text_pos.y <= clip_rect.Max.y)
{
ImVec2 pos = text_pos;
// Lines to skip (can't skip when logging text)
if (!g.LogEnabled)
{
int lines_skippable = (int)((clip_rect.Min.y - text_pos.y) / line_height);
if (lines_skippable > 0)
{
int lines_skipped = 0;
while (line < text_end && lines_skipped < lines_skippable)
{
const char* line_end = strchr(line, '\n');
if (!line_end)
line_end = text_end;
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
}
// Lines to render
if (line < text_end)
{
ImRect line_rect(pos, pos + ImVec2(FLT_MAX, line_height));
while (line < text_end)
{
const char* line_end = strchr(line, '\n');
if (IsClippedEx(line_rect, 0, false))
break;
const ImVec2 line_size = CalcTextSize(line, line_end, false);
text_size.x = ImMax(text_size.x, line_size.x);
RenderText(pos, line, line_end, false);
if (!line_end)
line_end = text_end;
line = line_end + 1;
line_rect.Min.y += line_height;
line_rect.Max.y += line_height;
pos.y += line_height;
}
// Count remaining lines
int lines_skipped = 0;
while (line < text_end)
{
const char* line_end = strchr(line, '\n');
if (!line_end)
line_end = text_end;
line = line_end + 1;
lines_skipped++;
}
pos.y += lines_skipped * line_height;
}
text_size.y += (pos - text_pos).y;
}
ImRect bb(text_pos, text_pos + text_size);
ItemSize(bb);
ItemAdd(bb, 0);
}
else
{
const float wrap_width = wrap_enabled ? CalcWrapWidthForPos(window->DC.CursorPos, wrap_pos_x) : 0.0f;
const ImVec2 text_size = CalcTextSize(text_begin, text_end, false, wrap_width);
// Account of baseline offset
ImRect bb(text_pos, text_pos + text_size);
ItemSize(text_size);
if (!ItemAdd(bb, 0))
return;
// Render (we don't hide text after ## in this end-user function)
RenderTextWrapped(bb.Min, text_begin, text_end, wrap_width);
}
}
void ImGui::AlignTextToFramePadding()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
window->DC.CurrentLineHeight = ImMax(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y * 2);
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.CurrentLineTextBaseOffset, g.Style.FramePadding.y);
}
// Add a label+text combo aligned to other label+value widgets
void ImGui::LabelTextV(const char* label, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect value_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2));
const ImRect total_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w + (label_size.x > 0.0f ? style.ItemInnerSpacing.x : 0.0f), style.FramePadding.y*2) + label_size);
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0))
return;
// Render
const char* value_text_begin = &g.TempBuffer[0];
const char* value_text_end = value_text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
RenderTextClipped(value_bb.Min, value_bb.Max, value_text_begin, value_text_end, NULL, ImVec2(0.0f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(value_bb.Max.x + style.ItemInnerSpacing.x, value_bb.Min.y + style.FramePadding.y), label);
}
void ImGui::LabelText(const char* label, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
LabelTextV(label, fmt, args);
va_end(args);
}
bool ImGui::ButtonBehavior(const ImRect& bb, ImGuiID id, bool* out_hovered, bool* out_held, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
if (flags & ImGuiButtonFlags_Disabled)
{
if (out_hovered) *out_hovered = false;
if (out_held) *out_held = false;
if (g.ActiveId == id) ClearActiveID();
return false;
}
// Default behavior requires click+release on same spot
if ((flags & (ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnRelease | ImGuiButtonFlags_PressedOnDoubleClick)) == 0)
flags |= ImGuiButtonFlags_PressedOnClickRelease;
ImGuiWindow* backup_hovered_window = g.HoveredWindow;
if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
g.HoveredWindow = window;
bool pressed = false;
bool hovered = ItemHoverable(bb, id);
// Special mode for Drag and Drop where holding button pressed for a long time while dragging another item triggers the button
if ((flags & ImGuiButtonFlags_PressedOnDragDropHold) && g.DragDropActive && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoHoldToOpenOthers))
if (IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
hovered = true;
SetHoveredID(id);
if (CalcTypematicPressedRepeatAmount(g.HoveredIdTimer + 0.0001f, g.HoveredIdTimer + 0.0001f - g.IO.DeltaTime, 0.01f, 0.70f)) // FIXME: Our formula for CalcTypematicPressedRepeatAmount() is fishy
{
pressed = true;
FocusWindow(window);
}
}
if ((flags & ImGuiButtonFlags_FlattenChildren) && g.HoveredRootWindow == window)
g.HoveredWindow = backup_hovered_window;
// AllowOverlap mode (rarely used) requires previous frame HoveredId to be null or to match. This allows using patterns where a later submitted widget overlaps a previous one.
if (hovered && (flags & ImGuiButtonFlags_AllowItemOverlap) && (g.HoveredIdPreviousFrame != id && g.HoveredIdPreviousFrame != 0))
hovered = false;
// Mouse
if (hovered)
{
if (!(flags & ImGuiButtonFlags_NoKeyModifiers) || (!g.IO.KeyCtrl && !g.IO.KeyShift && !g.IO.KeyAlt))
{
// | CLICKING | HOLDING with ImGuiButtonFlags_Repeat
// PressedOnClickRelease | <on release>* | <on repeat> <on repeat> .. (NOT on release) <-- MOST COMMON! (*) only if both click/release were over bounds
// PressedOnClick | <on click> | <on click> <on repeat> <on repeat> ..
// PressedOnRelease | <on release> | <on repeat> <on repeat> .. (NOT on release)
// PressedOnDoubleClick | <on dclick> | <on dclick> <on repeat> <on repeat> ..
// FIXME-NAV: We don't honor those different behaviors.
if ((flags & ImGuiButtonFlags_PressedOnClickRelease) && g.IO.MouseClicked[0])
{
SetActiveID(id, window);
if (!(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
FocusWindow(window);
}
if (((flags & ImGuiButtonFlags_PressedOnClick) && g.IO.MouseClicked[0]) || ((flags & ImGuiButtonFlags_PressedOnDoubleClick) && g.IO.MouseDoubleClicked[0]))
{
pressed = true;
if (flags & ImGuiButtonFlags_NoHoldingActiveID)
ClearActiveID();
else
SetActiveID(id, window); // Hold on ID
FocusWindow(window);
}
if ((flags & ImGuiButtonFlags_PressedOnRelease) && g.IO.MouseReleased[0])
{
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
pressed = true;
ClearActiveID();
}
// 'Repeat' mode acts when held regardless of _PressedOn flags (see table above).
// Relies on repeat logic of IsMouseClicked() but we may as well do it ourselves if we end up exposing finer RepeatDelay/RepeatRate settings.
if ((flags & ImGuiButtonFlags_Repeat) && g.ActiveId == id && g.IO.MouseDownDuration[0] > 0.0f && IsMouseClicked(0, true))
pressed = true;
}
if (pressed)
g.NavDisableHighlight = true;
}
// Gamepad/Keyboard navigation
// We report navigated item as hovered but we don't set g.HoveredId to not interfere with mouse.
if (g.NavId == id && !g.NavDisableHighlight && g.NavDisableMouseHover && (g.ActiveId == 0 || g.ActiveId == id || g.ActiveId == window->MoveId))
hovered = true;
if (g.NavActivateDownId == id)
{
bool nav_activated_by_code = (g.NavActivateId == id);
bool nav_activated_by_inputs = IsNavInputPressed(ImGuiNavInput_Activate, (flags & ImGuiButtonFlags_Repeat) ? ImGuiInputReadMode_Repeat : ImGuiInputReadMode_Pressed);
if (nav_activated_by_code || nav_activated_by_inputs)
pressed = true;
if (nav_activated_by_code || nav_activated_by_inputs || g.ActiveId == id)
{
// Set active id so it can be queried by user via IsItemActive(), equivalent of holding the mouse button.
g.NavActivateId = id; // This is so SetActiveId assign a Nav source
SetActiveID(id, window);
if (!(flags & ImGuiButtonFlags_NoNavFocus))
SetFocusID(id, window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right) | (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
}
}
bool held = false;
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (g.ActiveIdIsJustActivated)
g.ActiveIdClickOffset = g.IO.MousePos - bb.Min;
if (g.IO.MouseDown[0])
{
held = true;
}
else
{
if (hovered && (flags & ImGuiButtonFlags_PressedOnClickRelease))
if (!((flags & ImGuiButtonFlags_Repeat) && g.IO.MouseDownDurationPrev[0] >= g.IO.KeyRepeatDelay)) // Repeat mode trumps <on release>
if (!g.DragDropActive)
pressed = true;
ClearActiveID();
}
if (!(flags & ImGuiButtonFlags_NoNavFocus))
g.NavDisableHighlight = true;
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
if (g.NavActivateDownId != id)
ClearActiveID();
}
}
if (out_hovered) *out_hovered = hovered;
if (out_held) *out_held = held;
return pressed;
}
bool ImGui::ButtonEx(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 pos = window->DC.CursorPos;
if ((flags & ImGuiButtonFlags_AlignTextBaseLine) && style.FramePadding.y < window->DC.CurrentLineTextBaseOffset) // Try to vertically align buttons that are smaller/have no padding so that text baseline matches (bit hacky, since it shouldn't be a flag)
pos.y += window->DC.CurrentLineTextBaseOffset - style.FramePadding.y;
ImVec2 size = CalcItemSize(size_arg, label_size.x + style.FramePadding.x * 2.0f, label_size.y + style.FramePadding.y * 2.0f);
const ImRect bb(pos, pos + size);
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, id))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_ButtonRepeat)
flags |= ImGuiButtonFlags_Repeat;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding, bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup();
return pressed;
}
bool ImGui::Button(const char* label, const ImVec2& size_arg)
{
return ButtonEx(label, size_arg, 0);
}
// Small buttons fits within text without additional vertical spacing.
bool ImGui::SmallButton(const char* label)
{
ImGuiContext& g = *GImGui;
float backup_padding_y = g.Style.FramePadding.y;
g.Style.FramePadding.y = 0.0f;
bool pressed = ButtonEx(label, ImVec2(0,0), ImGuiButtonFlags_AlignTextBaseLine);
g.Style.FramePadding.y = backup_padding_y;
return pressed;
}
bool ImGui::ArrowButton(const char* str_id, ImGuiDir dir)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(str_id);
float sz = ImGui::GetFrameHeight();
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(sz, sz));
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, g.Style.FrameRounding);
RenderArrow(bb.Min + g.Style.FramePadding, dir);
return pressed;
}
// Tip: use ImGui::PushID()/PopID() to push indices or pointers in the ID stack.
// Then you can keep 'str_id' empty or the same for all your buttons (instead of creating a string based on a non-string id)
bool ImGui::InvisibleButton(const char* str_id, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiID id = window->GetID(str_id);
ImVec2 size = CalcItemSize(size_arg, 0.0f, 0.0f);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
return pressed;
}
// Button to close a window
bool ImGui::CloseButton(ImGuiID id, const ImVec2& pos, float radius)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We intentionally allow interaction when clipped so that a mechanical Alt,Right,Validate sequence close a window.
// (this isn't the regular behavior of buttons, but it doesn't affect the user much because navigation tends to keep items visible).
const ImRect bb(pos - ImVec2(radius,radius), pos + ImVec2(radius,radius));
bool is_clipped = !ItemAdd(bb, id);
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (is_clipped)
return pressed;
// Render
ImVec2 center = bb.GetCenter();
if (hovered)
window->DrawList->AddCircleFilled(center, ImMax(2.0f, radius), GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : ImGuiCol_ButtonHovered), 9);
float cross_extent = (radius * 0.7071f) - 1.0f;
ImU32 cross_col = GetColorU32(ImGuiCol_Text);
center -= ImVec2(0.5f, 0.5f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,+cross_extent), center + ImVec2(-cross_extent,-cross_extent), cross_col, 1.0f);
window->DrawList->AddLine(center + ImVec2(+cross_extent,-cross_extent), center + ImVec2(-cross_extent,+cross_extent), cross_col, 1.0f);
return pressed;
}
// [Internal]
bool ImGui::ArrowButton(ImGuiID id, ImGuiDir dir, ImVec2 padding, ImGuiButtonFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return false;
const ImGuiStyle& style = g.Style;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + padding.x * 2.0f, g.FontSize + padding.y * 2.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, flags);
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderArrow(bb.Min + padding, dir, 1.0f);
return pressed;
}
void ImGui::Image(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, const ImVec4& tint_col, const ImVec4& border_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
if (border_col.w > 0.0f)
bb.Max += ImVec2(2,2);
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
if (border_col.w > 0.0f)
{
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(border_col), 0.0f);
window->DrawList->AddImage(user_texture_id, bb.Min+ImVec2(1,1), bb.Max-ImVec2(1,1), uv0, uv1, GetColorU32(tint_col));
}
else
{
window->DrawList->AddImage(user_texture_id, bb.Min, bb.Max, uv0, uv1, GetColorU32(tint_col));
}
}
// frame_padding < 0: uses FramePadding from style (default)
// frame_padding = 0: no framing
// frame_padding > 0: set framing size
// The color used are the button colors.
bool ImGui::ImageButton(ImTextureID user_texture_id, const ImVec2& size, const ImVec2& uv0, const ImVec2& uv1, int frame_padding, const ImVec4& bg_col, const ImVec4& tint_col)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Default to using texture ID as ID. User can still push string/integer prefixes.
// We could hash the size/uv to create a unique ID but that would prevent the user from animating UV.
PushID((void *)user_texture_id);
const ImGuiID id = window->GetID("#image");
PopID();
const ImVec2 padding = (frame_padding >= 0) ? ImVec2((float)frame_padding, (float)frame_padding) : style.FramePadding;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size + padding*2);
const ImRect image_bb(window->DC.CursorPos + padding, window->DC.CursorPos + padding + size);
ItemSize(bb);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render
const ImU32 col = GetColorU32((hovered && held) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, ImClamp((float)ImMin(padding.x, padding.y), 0.0f, style.FrameRounding));
if (bg_col.w > 0.0f)
window->DrawList->AddRectFilled(image_bb.Min, image_bb.Max, GetColorU32(bg_col));
window->DrawList->AddImage(user_texture_id, image_bb.Min, image_bb.Max, uv0, uv1, GetColorU32(tint_col));
return pressed;
}
// Start logging ImGui output to TTY
void ImGui::LogToTTY(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogFile == NULL);
g.LogFile = stdout;
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to given file
void ImGui::LogToFile(int max_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
if (!filename)
{
filename = g.IO.LogFilename;
if (!filename)
return;
}
IM_ASSERT(g.LogFile == NULL);
g.LogFile = ImFileOpen(filename, "ab");
if (!g.LogFile)
{
IM_ASSERT(g.LogFile != NULL); // Consider this an error
return;
}
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to clipboard
void ImGui::LogToClipboard(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogFile == NULL);
g.LogFile = NULL;
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
if (g.LogFile != NULL)
{
if (g.LogFile == stdout)
fflush(g.LogFile);
else
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard->size() > 1)
{
SetClipboardText(g.LogClipboard->begin());
g.LogClipboard->clear();
}
g.LogEnabled = false;
}
// Helper to display logging buttons
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
const bool log_to_tty = Button("Log To TTY"); SameLine();
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushItemWidth(80.0f);
PushAllowKeyboardFocus(false);
SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
PopAllowKeyboardFocus();
PopItemWidth();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY(g.LogAutoExpandMaxDepth);
if (log_to_file)
LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
if (log_to_clipboard)
LogToClipboard(g.LogAutoExpandMaxDepth);
}
bool ImGui::TreeNodeBehaviorIsOpen(ImGuiID id, ImGuiTreeNodeFlags flags)
{
if (flags & ImGuiTreeNodeFlags_Leaf)
return true;
// We only write to the tree storage if the user clicks (or explicitely use SetNextTreeNode*** functions)
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiStorage* storage = window->DC.StateStorage;
bool is_open;
if (g.NextTreeNodeOpenCond != 0)
{
if (g.NextTreeNodeOpenCond & ImGuiCond_Always)
{
is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
// We treat ImGuiCond_Once and ImGuiCond_FirstUseEver the same because tree node state are not saved persistently.
const int stored_value = storage->GetInt(id, -1);
if (stored_value == -1)
{
is_open = g.NextTreeNodeOpenVal;
storage->SetInt(id, is_open);
}
else
{
is_open = stored_value != 0;
}
}
g.NextTreeNodeOpenCond = 0;
}
else
{
is_open = storage->GetInt(id, (flags & ImGuiTreeNodeFlags_DefaultOpen) ? 1 : 0) != 0;
}
// When logging is enabled, we automatically expand tree nodes (but *NOT* collapsing headers.. seems like sensible behavior).
// NB- If we are above max depth we still allow manually opened nodes to be logged.
if (g.LogEnabled && !(flags & ImGuiTreeNodeFlags_NoAutoOpenOnLog) && window->DC.TreeDepth < g.LogAutoExpandMaxDepth)
is_open = true;
return is_open;
}
bool ImGui::TreeNodeBehavior(ImGuiID id, ImGuiTreeNodeFlags flags, const char* label, const char* label_end)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const bool display_frame = (flags & ImGuiTreeNodeFlags_Framed) != 0;
const ImVec2 padding = (display_frame || (flags & ImGuiTreeNodeFlags_FramePadding)) ? style.FramePadding : ImVec2(style.FramePadding.x, 0.0f);
if (!label_end)
label_end = FindRenderedTextEnd(label);
const ImVec2 label_size = CalcTextSize(label, label_end, false);
// We vertically grow up to current line height up the typical widget height.
const float text_base_offset_y = ImMax(padding.y, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float frame_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + style.FramePadding.y*2), label_size.y + padding.y*2);
ImRect frame_bb = ImRect(window->DC.CursorPos, ImVec2(window->Pos.x + GetContentRegionMax().x, window->DC.CursorPos.y + frame_height));
if (display_frame)
{
// Framed header expand a little outside the default padding
frame_bb.Min.x -= (float)(int)(window->WindowPadding.x*0.5f) - 1;
frame_bb.Max.x += (float)(int)(window->WindowPadding.x*0.5f) - 1;
}
const float text_offset_x = (g.FontSize + (display_frame ? padding.x*3 : padding.x*2)); // Collapser arrow width + Spacing
const float text_width = g.FontSize + (label_size.x > 0.0f ? label_size.x + padding.x*2 : 0.0f); // Include collapser
ItemSize(ImVec2(text_width, frame_height), text_base_offset_y);
// For regular tree nodes, we arbitrary allow to click past 2 worth of ItemSpacing
// (Ideally we'd want to add a flag for the user to specify if we want the hit test to be done up to the right side of the content or not)
const ImRect interact_bb = display_frame ? frame_bb : ImRect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + text_width + style.ItemSpacing.x*2, frame_bb.Max.y);
bool is_open = TreeNodeBehaviorIsOpen(id, flags);
// Store a flag for the current depth to tell if we will allow closing this node when navigating one of its child.
// For this purpose we essentially compare if g.NavIdIsAlive went from 0 to 1 between TreeNode() and TreePop().
// This is currently only support 32 level deep and we are fine with (1 << Depth) overflowing into a zero.
if (is_open && !g.NavIdIsAlive && (flags & ImGuiTreeNodeFlags_NavLeftJumpsBackHere) && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
window->DC.TreeDepthMayJumpToParentOnPop |= (1 << window->DC.TreeDepth);
bool item_add = ItemAdd(interact_bb, id);
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDisplayRect;
window->DC.LastItemDisplayRect = frame_bb;
if (!item_add)
{
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
// Flags that affects opening behavior:
// - 0(default) ..................... single-click anywhere to open
// - OpenOnDoubleClick .............. double-click anywhere to open
// - OpenOnArrow .................... single-click on arrow to open
// - OpenOnDoubleClick|OpenOnArrow .. single-click on arrow or double-click anywhere to open
ImGuiButtonFlags button_flags = ImGuiButtonFlags_NoKeyModifiers | ((flags & ImGuiTreeNodeFlags_AllowItemOverlap) ? ImGuiButtonFlags_AllowItemOverlap : 0);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
button_flags |= ImGuiButtonFlags_PressedOnDragDropHold;
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
button_flags |= ImGuiButtonFlags_PressedOnDoubleClick | ((flags & ImGuiTreeNodeFlags_OpenOnArrow) ? ImGuiButtonFlags_PressedOnClickRelease : 0);
bool hovered, held, pressed = ButtonBehavior(interact_bb, id, &hovered, &held, button_flags);
if (!(flags & ImGuiTreeNodeFlags_Leaf))
{
bool toggled = false;
if (pressed)
{
toggled = !(flags & (ImGuiTreeNodeFlags_OpenOnArrow | ImGuiTreeNodeFlags_OpenOnDoubleClick)) || (g.NavActivateId == id);
if (flags & ImGuiTreeNodeFlags_OpenOnArrow)
toggled |= IsMouseHoveringRect(interact_bb.Min, ImVec2(interact_bb.Min.x + text_offset_x, interact_bb.Max.y)) && (!g.NavDisableMouseHover);
if (flags & ImGuiTreeNodeFlags_OpenOnDoubleClick)
toggled |= g.IO.MouseDoubleClicked[0];
if (g.DragDropActive && is_open) // When using Drag and Drop "hold to open" we keep the node highlighted after opening, but never close it again.
toggled = false;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Left && is_open)
{
toggled = true;
NavMoveRequestCancel();
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right && !is_open) // If there's something upcoming on the line we may want to give it the priority?
{
toggled = true;
NavMoveRequestCancel();
}
if (toggled)
{
is_open = !is_open;
window->DC.StateStorage->SetInt(id, is_open);
}
}
if (flags & ImGuiTreeNodeFlags_AllowItemOverlap)
SetItemAllowOverlap();
// Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
const ImVec2 text_pos = frame_bb.Min + ImVec2(text_offset_x, text_base_offset_y);
if (display_frame)
{
// Framed type
RenderFrame(frame_bb.Min, frame_bb.Max, col, true, style.FrameRounding);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
RenderArrow(frame_bb.Min + ImVec2(padding.x, text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 1.0f);
if (g.LogEnabled)
{
// NB: '##' is normally used to hide text (as a library-wide feature), so we need to specify the text range to make sure the ## aren't stripped out here.
const char log_prefix[] = "\n##";
const char log_suffix[] = "##";
LogRenderedText(&text_pos, log_prefix, log_prefix+3);
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
LogRenderedText(&text_pos, log_suffix+1, log_suffix+3);
}
else
{
RenderTextClipped(text_pos, frame_bb.Max, label, label_end, &label_size);
}
}
else
{
// Unframed typed for tree nodes
if (hovered || (flags & ImGuiTreeNodeFlags_Selected))
{
RenderFrame(frame_bb.Min, frame_bb.Max, col, false);
RenderNavHighlight(frame_bb, id, ImGuiNavHighlightFlags_TypeThin);
}
if (flags & ImGuiTreeNodeFlags_Bullet)
RenderBullet(frame_bb.Min + ImVec2(text_offset_x * 0.5f, g.FontSize*0.50f + text_base_offset_y));
else if (!(flags & ImGuiTreeNodeFlags_Leaf))
RenderArrow(frame_bb.Min + ImVec2(padding.x, g.FontSize*0.15f + text_base_offset_y), is_open ? ImGuiDir_Down : ImGuiDir_Right, 0.70f);
if (g.LogEnabled)
LogRenderedText(&text_pos, ">");
RenderText(text_pos, label, label_end, false);
}
if (is_open && !(flags & ImGuiTreeNodeFlags_NoTreePushOnOpen))
TreePushRawID(id);
return is_open;
}
// CollapsingHeader returns true when opened but do not indent nor push into the ID stack (because of the ImGuiTreeNodeFlags_NoTreePushOnOpen flag).
// This is basically the same as calling TreeNodeEx(label, ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen). You can remove the _NoTreePushOnOpen flag if you want behavior closer to normal TreeNode().
bool ImGui::CollapsingHeader(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen, label);
}
bool ImGui::CollapsingHeader(const char* label, bool* p_open, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (p_open && !*p_open)
return false;
ImGuiID id = window->GetID(label);
bool is_open = TreeNodeBehavior(id, flags | ImGuiTreeNodeFlags_CollapsingHeader | ImGuiTreeNodeFlags_NoTreePushOnOpen | (p_open ? ImGuiTreeNodeFlags_AllowItemOverlap : 0), label);
if (p_open)
{
// Create a small overlapping close button // FIXME: We can evolve this into user accessible helpers to add extra buttons on title bars, headers, etc.
ImGuiContext& g = *GImGui;
float button_sz = g.FontSize * 0.5f;
ImGuiItemHoveredDataBackup last_item_backup;
if (CloseButton(window->GetID((void*)(intptr_t)(id+1)), ImVec2(ImMin(window->DC.LastItemRect.Max.x, window->ClipRect.Max.x) - g.Style.FramePadding.x - button_sz, window->DC.LastItemRect.Min.y + g.Style.FramePadding.y + button_sz), button_sz))
*p_open = false;
last_item_backup.Restore();
}
return is_open;
}
bool ImGui::TreeNodeEx(const char* label, ImGuiTreeNodeFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), flags, label, NULL);
}
bool ImGui::TreeNodeExV(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(str_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeExV(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const char* label_end = g.TempBuffer + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
return TreeNodeBehavior(window->GetID(ptr_id), flags, g.TempBuffer, label_end);
}
bool ImGui::TreeNodeV(const char* str_id, const char* fmt, va_list args)
{
return TreeNodeExV(str_id, 0, fmt, args);
}
bool ImGui::TreeNodeV(const void* ptr_id, const char* fmt, va_list args)
{
return TreeNodeExV(ptr_id, 0, fmt, args);
}
bool ImGui::TreeNodeEx(const char* str_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNodeEx(const void* ptr_id, ImGuiTreeNodeFlags flags, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, flags, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const char* str_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(str_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const void* ptr_id, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
bool is_open = TreeNodeExV(ptr_id, 0, fmt, args);
va_end(args);
return is_open;
}
bool ImGui::TreeNode(const char* label)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
return TreeNodeBehavior(window->GetID(label), 0, label, NULL);
}
void ImGui::TreeAdvanceToLabelPos()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DC.CursorPos.x += GetTreeNodeToLabelSpacing();
}
// Horizontal distance preceding label when using TreeNode() or Bullet()
float ImGui::GetTreeNodeToLabelSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + (g.Style.FramePadding.x * 2.0f);
}
void ImGui::SetNextTreeNodeOpen(bool is_open, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindow->SkipItems)
return;
g.NextTreeNodeOpenVal = is_open;
g.NextTreeNodeOpenCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PushID(int int_id)
{
const void* ptr_id = (void*)(intptr_t)int_id;
ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.push_back(window->GetID(ptr_id));
}
void ImGui::PopID()
{
ImGuiWindow* window = GetCurrentWindowRead();
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
return GImGui->CurrentWindow->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
return GImGui->CurrentWindow->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
return GImGui->CurrentWindow->GetID(ptr_id);
}
void ImGui::Bullet()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize, line_height));
ItemSize(bb);
if (!ItemAdd(bb, 0))
{
SameLine(0, style.FramePadding.x*2);
return;
}
// Render and stay on same line
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
SameLine(0, style.FramePadding.x*2);
}
// Text with a little bullet aligned to the typical tree node.
void ImGui::BulletTextV(const char* fmt, va_list args)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const char* text_begin = g.TempBuffer;
const char* text_end = text_begin + ImFormatStringV(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), fmt, args);
const ImVec2 label_size = CalcTextSize(text_begin, text_end, false);
const float text_base_offset_y = ImMax(0.0f, window->DC.CurrentLineTextBaseOffset); // Latch before ItemSize changes it
const float line_height = ImMax(ImMin(window->DC.CurrentLineHeight, g.FontSize + g.Style.FramePadding.y*2), g.FontSize);
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(g.FontSize + (label_size.x > 0.0f ? (label_size.x + style.FramePadding.x*2) : 0.0f), ImMax(line_height, label_size.y))); // Empty text doesn't add padding
ItemSize(bb);
if (!ItemAdd(bb, 0))
return;
// Render
RenderBullet(bb.Min + ImVec2(style.FramePadding.x + g.FontSize*0.5f, line_height*0.5f));
RenderText(bb.Min+ImVec2(g.FontSize + style.FramePadding.x*2, text_base_offset_y), text_begin, text_end, false);
}
void ImGui::BulletText(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
BulletTextV(fmt, args);
va_end(args);
}
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, const char* display_format, char* buf, int buf_size)
{
if (data_type == ImGuiDataType_Int)
ImFormatString(buf, buf_size, display_format, *(int*)data_ptr);
else if (data_type == ImGuiDataType_Float)
ImFormatString(buf, buf_size, display_format, *(float*)data_ptr);
else if (data_type == ImGuiDataType_Double)
ImFormatString(buf, buf_size, display_format, *(double*)data_ptr);
}
static inline void DataTypeFormatString(ImGuiDataType data_type, void* data_ptr, int decimal_precision, char* buf, int buf_size)
{
if (data_type == ImGuiDataType_Int)
{
if (decimal_precision < 0)
ImFormatString(buf, buf_size, "%d", *(int*)data_ptr);
else
ImFormatString(buf, buf_size, "%.*d", decimal_precision, *(int*)data_ptr);
}
else if (data_type == ImGuiDataType_Float)
{
if (decimal_precision < 0)
ImFormatString(buf, buf_size, "%f", *(float*)data_ptr); // Ideally we'd have a minimum decimal precision of 1 to visually denote that it is a float, while hiding non-significant digits?
else
ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(float*)data_ptr);
}
else if (data_type == ImGuiDataType_Double)
{
if (decimal_precision < 0)
ImFormatString(buf, buf_size, "%f", *(double*)data_ptr);
else
ImFormatString(buf, buf_size, "%.*f", decimal_precision, *(double*)data_ptr);
}
}
static void DataTypeApplyOp(ImGuiDataType data_type, int op, void* output, void* arg1, const void* arg2)
{
IM_ASSERT(op == '+' || op == '-');
if (data_type == ImGuiDataType_Int)
{
if (op == '+') *(int*)output = *(int*)arg1 + *(const int*)arg2;
else if (op == '-') *(int*)output = *(int*)arg1 - *(const int*)arg2;
}
else if (data_type == ImGuiDataType_Float)
{
if (op == '+') *(float*)output = *(float*)arg1 + *(const float*)arg2;
else if (op == '-') *(float*)output = *(float*)arg1 - *(const float*)arg2;
}
else if (data_type == ImGuiDataType_Double)
{
if (op == '+') *(double*)output = *(double*)arg1 + *(const double*)arg2;
else if (op == '-') *(double*)output = *(double*)arg1 - *(const double*)arg2;
}
}
static size_t GDataTypeSize[ImGuiDataType_COUNT] =
{
sizeof(int),
sizeof(float),
sizeof(double)
};
// User can input math operators (e.g. +100) to edit a numerical values.
// NB: This is _not_ a full expression evaluator. We should probably add one though..
static bool DataTypeApplyOpFromText(const char* buf, const char* initial_value_buf, ImGuiDataType data_type, void* data_ptr, const char* scalar_format)
{
while (ImCharIsSpace(*buf))
buf++;
// We don't support '-' op because it would conflict with inputing negative value.
// Instead you can use +-100 to subtract from an existing value
char op = buf[0];
if (op == '+' || op == '*' || op == '/')
{
buf++;
while (ImCharIsSpace(*buf))
buf++;
}
else
{
op = 0;
}
if (!buf[0])
return false;
IM_ASSERT(data_type < ImGuiDataType_COUNT);
int data_backup[2];
IM_ASSERT(GDataTypeSize[data_type] <= sizeof(data_backup));
memcpy(data_backup, data_ptr, GDataTypeSize[data_type]);
if (data_type == ImGuiDataType_Int)
{
if (!scalar_format)
scalar_format = "%d";
int* v = (int*)data_ptr;
int arg0i = *v;
if (op && sscanf(initial_value_buf, scalar_format, &arg0i) < 1)
return false;
// Store operand in a float so we can use fractional value for multipliers (*1.1), but constant always parsed as integer so we can fit big integers (e.g. 2000000003) past float precision
float arg1f = 0.0f;
if (op == '+') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i + arg1f); } // Add (use "+-" to subtract)
else if (op == '*') { if (sscanf(buf, "%f", &arg1f) == 1) *v = (int)(arg0i * arg1f); } // Multiply
else if (op == '/') { if (sscanf(buf, "%f", &arg1f) == 1 && arg1f != 0.0f) *v = (int)(arg0i / arg1f); }// Divide
else { if (sscanf(buf, scalar_format, &arg0i) == 1) *v = arg0i; } // Assign integer constant
}
else if (data_type == ImGuiDataType_Float)
{
// For floats we have to ignore format with precision (e.g. "%.2f") because sscanf doesn't take them in
scalar_format = "%f";
float* v = (float*)data_ptr;
float arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
return false;
if (sscanf(buf, scalar_format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
else if (data_type == ImGuiDataType_Double)
{
scalar_format = "%lf";
double* v = (double*)data_ptr;
double arg0f = *v, arg1f = 0.0f;
if (op && sscanf(initial_value_buf, scalar_format, &arg0f) < 1)
return false;
if (sscanf(buf, scalar_format, &arg1f) < 1)
return false;
if (op == '+') { *v = arg0f + arg1f; } // Add (use "+-" to subtract)
else if (op == '*') { *v = arg0f * arg1f; } // Multiply
else if (op == '/') { if (arg1f != 0.0f) *v = arg0f / arg1f; } // Divide
else { *v = arg1f; } // Assign constant
}
return memcmp(data_backup, data_ptr, GDataTypeSize[data_type]) != 0;
}
// Create text input in place of a slider (when CTRL+Clicking on slider)
// FIXME: Logic is messy and confusing.
bool ImGui::InputScalarAsWidgetReplacement(const ImRect& aabb, const char* label, ImGuiDataType data_type, void* data_ptr, ImGuiID id, int decimal_precision)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
// Our replacement widget will override the focus ID (registered previously to allow for a TAB focus to happen)
// On the first frame, g.ScalarAsInputTextId == 0, then on subsequent frames it becomes == id
SetActiveID(g.ScalarAsInputTextId, window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
SetHoveredID(0);
FocusableItemUnregister(window);
char buf[32];
DataTypeFormatString(data_type, data_ptr, decimal_precision, buf, IM_ARRAYSIZE(buf));
bool text_value_changed = InputTextEx(label, buf, IM_ARRAYSIZE(buf), aabb.GetSize(), ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_AutoSelectAll);
if (g.ScalarAsInputTextId == 0) // First frame we started displaying the InputText widget
{
IM_ASSERT(g.ActiveId == id); // InputText ID expected to match the Slider ID (else we'd need to store them both, which is also possible)
g.ScalarAsInputTextId = g.ActiveId;
SetHoveredID(id);
}
if (text_value_changed)
return DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, NULL);
return false;
}
// Parse display precision back from the display format string
int ImGui::ParseFormatPrecision(const char* fmt, int default_precision)
{
int precision = default_precision;
while ((fmt = strchr(fmt, '%')) != NULL)
{
fmt++;
if (fmt[0] == '%') { fmt++; continue; } // Ignore "%%"
while (*fmt >= '0' && *fmt <= '9')
fmt++;
if (*fmt == '.')
{
fmt = ImAtoi(fmt + 1, &precision);
if (precision < 0 || precision > 10)
precision = default_precision;
}
if (*fmt == 'e' || *fmt == 'E') // Maximum precision with scientific notation
precision = -1;
break;
}
return precision;
}
static float GetMinimumStepAtDecimalPrecision(int decimal_precision)
{
static const float min_steps[10] = { 1.0f, 0.1f, 0.01f, 0.001f, 0.0001f, 0.00001f, 0.000001f, 0.0000001f, 0.00000001f, 0.000000001f };
return (decimal_precision >= 0 && decimal_precision < 10) ? min_steps[decimal_precision] : powf(10.0f, (float)-decimal_precision);
}
float ImGui::RoundScalar(float value, int decimal_precision)
{
// Round past decimal precision
// So when our value is 1.99999 with a precision of 0.001 we'll end up rounding to 2.0
// FIXME: Investigate better rounding methods
if (decimal_precision < 0)
return value;
const float min_step = GetMinimumStepAtDecimalPrecision(decimal_precision);
bool negative = value < 0.0f;
value = fabsf(value);
float remainder = fmodf(value, min_step);
if (remainder <= min_step*0.5f)
value -= remainder;
else
value += (min_step - remainder);
return negative ? -value : value;
}
static inline float SliderBehaviorCalcRatioFromValue(float v, float v_min, float v_max, float power, float linear_zero_pos)
{
if (v_min == v_max)
return 0.0f;
const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
const float v_clamped = (v_min < v_max) ? ImClamp(v, v_min, v_max) : ImClamp(v, v_max, v_min);
if (is_non_linear)
{
if (v_clamped < 0.0f)
{
const float f = 1.0f - (v_clamped - v_min) / (ImMin(0.0f,v_max) - v_min);
return (1.0f - powf(f, 1.0f/power)) * linear_zero_pos;
}
else
{
const float f = (v_clamped - ImMax(0.0f,v_min)) / (v_max - ImMax(0.0f,v_min));
return linear_zero_pos + powf(f, 1.0f/power) * (1.0f - linear_zero_pos);
}
}
// Linear slider
return (v_clamped - v_min) / (v_max - v_min);
}
bool ImGui::SliderBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_min, float v_max, float power, int decimal_precision, ImGuiSliderFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = g.Style;
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
const bool is_non_linear = (power < 1.0f-0.00001f) || (power > 1.0f+0.00001f);
const bool is_horizontal = (flags & ImGuiSliderFlags_Vertical) == 0;
const float grab_padding = 2.0f;
const float slider_sz = is_horizontal ? (frame_bb.GetWidth() - grab_padding * 2.0f) : (frame_bb.GetHeight() - grab_padding * 2.0f);
float grab_sz;
if (decimal_precision != 0)
grab_sz = ImMin(style.GrabMinSize, slider_sz);
else
grab_sz = ImMin(ImMax(1.0f * (slider_sz / ((v_min < v_max ? v_max - v_min : v_min - v_max) + 1.0f)), style.GrabMinSize), slider_sz); // Integer sliders, if possible have the grab size represent 1 unit
const float slider_usable_sz = slider_sz - grab_sz;
const float slider_usable_pos_min = (is_horizontal ? frame_bb.Min.x : frame_bb.Min.y) + grab_padding + grab_sz*0.5f;
const float slider_usable_pos_max = (is_horizontal ? frame_bb.Max.x : frame_bb.Max.y) - grab_padding - grab_sz*0.5f;
// For logarithmic sliders that cross over sign boundary we want the exponential increase to be symmetric around 0.0f
float linear_zero_pos = 0.0f; // 0.0->1.0f
if (v_min * v_max < 0.0f)
{
// Different sign
const float linear_dist_min_to_0 = powf(fabsf(0.0f - v_min), 1.0f/power);
const float linear_dist_max_to_0 = powf(fabsf(v_max - 0.0f), 1.0f/power);
linear_zero_pos = linear_dist_min_to_0 / (linear_dist_min_to_0+linear_dist_max_to_0);
}
else
{
// Same sign
linear_zero_pos = v_min < 0.0f ? 1.0f : 0.0f;
}
// Process interacting with the slider
bool value_changed = false;
if (g.ActiveId == id)
{
bool set_new_value = false;
float clicked_t = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse)
{
if (!g.IO.MouseDown[0])
{
ClearActiveID();
}
else
{
const float mouse_abs_pos = is_horizontal ? g.IO.MousePos.x : g.IO.MousePos.y;
clicked_t = (slider_usable_sz > 0.0f) ? ImClamp((mouse_abs_pos - slider_usable_pos_min) / slider_usable_sz, 0.0f, 1.0f) : 0.0f;
if (!is_horizontal)
clicked_t = 1.0f - clicked_t;
set_new_value = true;
}
}
else if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
const ImVec2 delta2 = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard | ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 0.0f, 0.0f);
float delta = is_horizontal ? delta2.x : -delta2.y;
if (g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
{
ClearActiveID();
}
else if (delta != 0.0f)
{
clicked_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
if (decimal_precision == 0 && !is_non_linear)
{
if (fabsf(v_max - v_min) <= 100.0f || IsNavInputDown(ImGuiNavInput_TweakSlow))
delta = ((delta < 0.0f) ? -1.0f : +1.0f) / (v_max - v_min); // Gamepad/keyboard tweak speeds in integer steps
else
delta /= 100.0f;
}
else
{
delta /= 100.0f; // Gamepad/keyboard tweak speeds in % of slider bounds
if (IsNavInputDown(ImGuiNavInput_TweakSlow))
delta /= 10.0f;
}
if (IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= 10.0f;
set_new_value = true;
if ((clicked_t >= 1.0f && delta > 0.0f) || (clicked_t <= 0.0f && delta < 0.0f)) // This is to avoid applying the saturation when already past the limits
set_new_value = false;
else
clicked_t = ImSaturate(clicked_t + delta);
}
}
if (set_new_value)
{
float new_value;
if (is_non_linear)
{
// Account for logarithmic scale on both sides of the zero
if (clicked_t < linear_zero_pos)
{
// Negative: rescale to the negative range before powering
float a = 1.0f - (clicked_t / linear_zero_pos);
a = powf(a, power);
new_value = ImLerp(ImMin(v_max,0.0f), v_min, a);
}
else
{
// Positive: rescale to the positive range before powering
float a;
if (fabsf(linear_zero_pos - 1.0f) > 1.e-6f)
a = (clicked_t - linear_zero_pos) / (1.0f - linear_zero_pos);
else
a = clicked_t;
a = powf(a, power);
new_value = ImLerp(ImMax(v_min,0.0f), v_max, a);
}
}
else
{
// Linear slider
new_value = ImLerp(v_min, v_max, clicked_t);
}
// Round past decimal precision
new_value = RoundScalar(new_value, decimal_precision);
if (*v != new_value)
{
*v = new_value;
value_changed = true;
}
}
}
// Draw
float grab_t = SliderBehaviorCalcRatioFromValue(*v, v_min, v_max, power, linear_zero_pos);
if (!is_horizontal)
grab_t = 1.0f - grab_t;
const float grab_pos = ImLerp(slider_usable_pos_min, slider_usable_pos_max, grab_t);
ImRect grab_bb;
if (is_horizontal)
grab_bb = ImRect(ImVec2(grab_pos - grab_sz*0.5f, frame_bb.Min.y + grab_padding), ImVec2(grab_pos + grab_sz*0.5f, frame_bb.Max.y - grab_padding));
else
grab_bb = ImRect(ImVec2(frame_bb.Min.x + grab_padding, grab_pos - grab_sz*0.5f), ImVec2(frame_bb.Max.x - grab_padding, grab_pos + grab_sz*0.5f));
window->DrawList->AddRectFilled(grab_bb.Min, grab_bb.Max, GetColorU32(g.ActiveId == id ? ImGuiCol_SliderGrabActive : ImGuiCol_SliderGrab), style.GrabRounding);
return value_changed;
}
// Use power!=1.0 for logarithmic sliders.
// Adjust display_format to decorate the value with a prefix or a suffix.
// "%.3f" 1.234
// "%5.2f secs" 01.23 secs
// "Gold: %.0f" Gold: 1
bool ImGui::SliderFloat(const char* label, float* v, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
// Tabbing or CTRL-clicking on Slider turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, id);
if (tab_focus_requested || (hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (tab_focus_requested || g.IO.KeyCtrl || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
// Actual slider behavior + render grab
ItemSize(total_bb, style.FramePadding.y);
const bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
return value_changed;
}
bool ImGui::VSliderFloat(const char* label, const ImVec2& size, float* v, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(frame_bb, id))
return false;
const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
if ((hovered && g.IO.MouseClicked[0]) || g.NavActivateId == id || g.NavInputId == id)
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Left) | (1 << ImGuiDir_Right);
}
// Actual slider behavior + render grab
bool value_changed = SliderBehavior(frame_bb, id, v, v_min, v_max, power, decimal_precision, ImGuiSliderFlags_Vertical);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
// For the vertical slider we allow centered text to overlap the frame padding
char value_buf[64];
char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
return value_changed;
}
bool ImGui::SliderAngle(const char* label, float* v_rad, float v_degrees_min, float v_degrees_max)
{
float v_deg = (*v_rad) * 360.0f / (2*IM_PI);
bool value_changed = SliderFloat(label, &v_deg, v_degrees_min, v_degrees_max, "%.0f deg", 1.0f);
*v_rad = v_deg * (2*IM_PI) / 360.0f;
return value_changed;
}
bool ImGui::SliderInt(const char* label, int* v, int v_min, int v_max, const char* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = SliderFloat(label, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
*v = (int)v_f;
return value_changed;
}
bool ImGui::VSliderInt(const char* label, const ImVec2& size, int* v, int v_min, int v_max, const char* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = VSliderFloat(label, size, &v_f, (float)v_min, (float)v_max, display_format, 1.0f);
*v = (int)v_f;
return value_changed;
}
// Add multiple sliders on 1 line for compact edition of multiple components
bool ImGui::SliderFloatN(const char* label, float* v, int components, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= SliderFloat("##v", &v[i], v_min, v_max, display_format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::SliderFloat2(const char* label, float v[2], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 2, v_min, v_max, display_format, power);
}
bool ImGui::SliderFloat3(const char* label, float v[3], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 3, v_min, v_max, display_format, power);
}
bool ImGui::SliderFloat4(const char* label, float v[4], float v_min, float v_max, const char* display_format, float power)
{
return SliderFloatN(label, v, 4, v_min, v_max, display_format, power);
}
bool ImGui::SliderIntN(const char* label, int* v, int components, int v_min, int v_max, const char* display_format)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= SliderInt("##v", &v[i], v_min, v_max, display_format);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::SliderInt2(const char* label, int v[2], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 2, v_min, v_max, display_format);
}
bool ImGui::SliderInt3(const char* label, int v[3], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 3, v_min, v_max, display_format);
}
bool ImGui::SliderInt4(const char* label, int v[4], int v_min, int v_max, const char* display_format)
{
return SliderIntN(label, v, 4, v_min, v_max, display_format);
}
bool ImGui::DragBehavior(const ImRect& frame_bb, ImGuiID id, float* v, float v_speed, float v_min, float v_max, int decimal_precision, float power)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
// Draw frame
const ImU32 frame_col = GetColorU32(g.ActiveId == id ? ImGuiCol_FrameBgActive : g.HoveredId == id ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
RenderFrame(frame_bb.Min, frame_bb.Max, frame_col, true, style.FrameRounding);
bool value_changed = false;
// Process interacting with the drag
if (g.ActiveId == id)
{
if (g.ActiveIdSource == ImGuiInputSource_Mouse && !g.IO.MouseDown[0])
ClearActiveID();
else if (g.ActiveIdSource == ImGuiInputSource_Nav && g.NavActivatePressedId == id && !g.ActiveIdIsJustActivated)
ClearActiveID();
}
if (g.ActiveId == id)
{
if (g.ActiveIdIsJustActivated)
{
// Lock current value on click
g.DragCurrentValue = *v;
g.DragLastMouseDelta = ImVec2(0.f, 0.f);
}
if (v_speed == 0.0f && (v_max - v_min) != 0.0f && (v_max - v_min) < FLT_MAX)
v_speed = (v_max - v_min) * g.DragSpeedDefaultRatio;
float v_cur = g.DragCurrentValue;
const ImVec2 mouse_drag_delta = GetMouseDragDelta(0, 1.0f);
float adjust_delta = 0.0f;
if (g.ActiveIdSource == ImGuiInputSource_Mouse && IsMousePosValid())
{
adjust_delta = mouse_drag_delta.x - g.DragLastMouseDelta.x;
if (g.IO.KeyShift && g.DragSpeedScaleFast >= 0.0f)
adjust_delta *= g.DragSpeedScaleFast;
if (g.IO.KeyAlt && g.DragSpeedScaleSlow >= 0.0f)
adjust_delta *= g.DragSpeedScaleSlow;
g.DragLastMouseDelta.x = mouse_drag_delta.x;
}
if (g.ActiveIdSource == ImGuiInputSource_Nav)
{
adjust_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard|ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_RepeatFast, 1.0f/10.0f, 10.0f).x;
if (v_min < v_max && ((v_cur >= v_max && adjust_delta > 0.0f) || (v_cur <= v_min && adjust_delta < 0.0f))) // This is to avoid applying the saturation when already past the limits
adjust_delta = 0.0f;
v_speed = ImMax(v_speed, GetMinimumStepAtDecimalPrecision(decimal_precision));
}
adjust_delta *= v_speed;
if (fabsf(adjust_delta) > 0.0f)
{
if (fabsf(power - 1.0f) > 0.001f)
{
// Logarithmic curve on both side of 0.0
float v0_abs = v_cur >= 0.0f ? v_cur : -v_cur;
float v0_sign = v_cur >= 0.0f ? 1.0f : -1.0f;
float v1 = powf(v0_abs, 1.0f / power) + (adjust_delta * v0_sign);
float v1_abs = v1 >= 0.0f ? v1 : -v1;
float v1_sign = v1 >= 0.0f ? 1.0f : -1.0f; // Crossed sign line
v_cur = powf(v1_abs, power) * v0_sign * v1_sign; // Reapply sign
}
else
{
v_cur += adjust_delta;
}
// Clamp
if (v_min < v_max)
v_cur = ImClamp(v_cur, v_min, v_max);
g.DragCurrentValue = v_cur;
}
// Round to user desired precision, then apply
v_cur = RoundScalar(v_cur, decimal_precision);
if (*v != v_cur)
{
*v = v_cur;
value_changed = true;
}
}
return value_changed;
}
bool ImGui::DragFloat(const char* label, float* v, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float w = CalcItemWidth();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
// NB- we don't call ItemSize() yet because we may turn into a text edit box below
if (!ItemAdd(total_bb, id, &frame_bb))
{
ItemSize(total_bb, style.FramePadding.y);
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (!display_format)
display_format = "%.3f";
int decimal_precision = ParseFormatPrecision(display_format, 3);
// Tabbing or CTRL-clicking on Drag turns it into an input box
bool start_text_input = false;
const bool tab_focus_requested = FocusableItemRegister(window, id);
if (tab_focus_requested || (hovered && (g.IO.MouseClicked[0] || g.IO.MouseDoubleClicked[0])) || g.NavActivateId == id || (g.NavInputId == id && g.ScalarAsInputTextId != id))
{
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
g.ActiveIdAllowNavDirFlags = (1 << ImGuiDir_Up) | (1 << ImGuiDir_Down);
if (tab_focus_requested || g.IO.KeyCtrl || g.IO.MouseDoubleClicked[0] || g.NavInputId == id)
{
start_text_input = true;
g.ScalarAsInputTextId = 0;
}
}
if (start_text_input || (g.ActiveId == id && g.ScalarAsInputTextId == id))
return InputScalarAsWidgetReplacement(frame_bb, label, ImGuiDataType_Float, v, id, decimal_precision);
// Actual drag behavior
ItemSize(total_bb, style.FramePadding.y);
const bool value_changed = DragBehavior(frame_bb, id, v, v_speed, v_min, v_max, decimal_precision, power);
// Display value using user-provided display format so user can add prefix/suffix/decorations to the value.
char value_buf[64];
const char* value_buf_end = value_buf + ImFormatString(value_buf, IM_ARRAYSIZE(value_buf), display_format, *v);
RenderTextClipped(frame_bb.Min, frame_bb.Max, value_buf, value_buf_end, NULL, ImVec2(0.5f,0.5f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
return value_changed;
}
bool ImGui::DragFloatN(const char* label, float* v, int components, float v_speed, float v_min, float v_max, const char* display_format, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= DragFloat("##v", &v[i], v_speed, v_min, v_max, display_format, power);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::DragFloat2(const char* label, float v[2], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 2, v_speed, v_min, v_max, display_format, power);
}
bool ImGui::DragFloat3(const char* label, float v[3], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 3, v_speed, v_min, v_max, display_format, power);
}
bool ImGui::DragFloat4(const char* label, float v[4], float v_speed, float v_min, float v_max, const char* display_format, float power)
{
return DragFloatN(label, v, 4, v_speed, v_min, v_max, display_format, power);
}
bool ImGui::DragFloatRange2(const char* label, float* v_current_min, float* v_current_max, float v_speed, float v_min, float v_max, const char* display_format, const char* display_format_max, float power)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
bool value_changed = DragFloat("##min", v_current_min, v_speed, (v_min >= v_max) ? -FLT_MAX : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragFloat("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? FLT_MAX : v_max, display_format_max ? display_format_max : display_format, power);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
// NB: v_speed is float to allow adjusting the drag speed with more precision
bool ImGui::DragInt(const char* label, int* v, float v_speed, int v_min, int v_max, const char* display_format)
{
if (!display_format)
display_format = "%.0f";
float v_f = (float)*v;
bool value_changed = DragFloat(label, &v_f, v_speed, (float)v_min, (float)v_max, display_format);
*v = (int)v_f;
return value_changed;
}
bool ImGui::DragIntN(const char* label, int* v, int components, float v_speed, int v_min, int v_max, const char* display_format)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= DragInt("##v", &v[i], v_speed, v_min, v_max, display_format);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::DragInt2(const char* label, int v[2], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 2, v_speed, v_min, v_max, display_format);
}
bool ImGui::DragInt3(const char* label, int v[3], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 3, v_speed, v_min, v_max, display_format);
}
bool ImGui::DragInt4(const char* label, int v[4], float v_speed, int v_min, int v_max, const char* display_format)
{
return DragIntN(label, v, 4, v_speed, v_min, v_max, display_format);
}
bool ImGui::DragIntRange2(const char* label, int* v_current_min, int* v_current_max, float v_speed, int v_min, int v_max, const char* display_format, const char* display_format_max)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
PushID(label);
BeginGroup();
PushMultiItemsWidths(2);
bool value_changed = DragInt("##min", v_current_min, v_speed, (v_min >= v_max) ? INT_MIN : v_min, (v_min >= v_max) ? *v_current_max : ImMin(v_max, *v_current_max), display_format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
value_changed |= DragInt("##max", v_current_max, v_speed, (v_min >= v_max) ? *v_current_min : ImMax(v_min, *v_current_min), (v_min >= v_max) ? INT_MAX : v_max, display_format_max ? display_format_max : display_format);
PopItemWidth();
SameLine(0, g.Style.ItemInnerSpacing.x);
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
PopID();
return value_changed;
}
void ImGui::PlotEx(ImGuiPlotType plot_type, const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImVec2 label_size = CalcTextSize(label, NULL, true);
if (graph_size.x == 0.0f)
graph_size.x = CalcItemWidth();
if (graph_size.y == 0.0f)
graph_size.y = label_size.y + (style.FramePadding.y * 2);
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(graph_size.x, graph_size.y));
const ImRect inner_bb(frame_bb.Min + style.FramePadding, frame_bb.Max - style.FramePadding);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, 0, &frame_bb))
return;
const bool hovered = ItemHoverable(inner_bb, 0);
// Determine scale from values if not specified
if (scale_min == FLT_MAX || scale_max == FLT_MAX)
{
float v_min = FLT_MAX;
float v_max = -FLT_MAX;
for (int i = 0; i < values_count; i++)
{
const float v = values_getter(data, i);
v_min = ImMin(v_min, v);
v_max = ImMax(v_max, v);
}
if (scale_min == FLT_MAX)
scale_min = v_min;
if (scale_max == FLT_MAX)
scale_max = v_max;
}
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
if (values_count > 0)
{
int res_w = ImMin((int)graph_size.x, values_count) + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
int item_count = values_count + ((plot_type == ImGuiPlotType_Lines) ? -1 : 0);
// Tooltip on hover
int v_hovered = -1;
if (hovered)
{
const float t = ImClamp((g.IO.MousePos.x - inner_bb.Min.x) / (inner_bb.Max.x - inner_bb.Min.x), 0.0f, 0.9999f);
const int v_idx = (int)(t * item_count);
IM_ASSERT(v_idx >= 0 && v_idx < values_count);
const float v0 = values_getter(data, (v_idx + values_offset) % values_count);
const float v1 = values_getter(data, (v_idx + 1 + values_offset) % values_count);
if (plot_type == ImGuiPlotType_Lines)
SetTooltip("%d: %8.4g\n%d: %8.4g", v_idx, v0, v_idx+1, v1);
else if (plot_type == ImGuiPlotType_Histogram)
SetTooltip("%d: %8.4g", v_idx, v0);
v_hovered = v_idx;
}
const float t_step = 1.0f / (float)res_w;
const float inv_scale = (scale_min == scale_max) ? 0.0f : (1.0f / (scale_max - scale_min));
float v0 = values_getter(data, (0 + values_offset) % values_count);
float t0 = 0.0f;
ImVec2 tp0 = ImVec2( t0, 1.0f - ImSaturate((v0 - scale_min) * inv_scale) ); // Point in the normalized space of our target rectangle
float histogram_zero_line_t = (scale_min * scale_max < 0.0f) ? (-scale_min * inv_scale) : (scale_min < 0.0f ? 0.0f : 1.0f); // Where does the zero line stands
const ImU32 col_base = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLines : ImGuiCol_PlotHistogram);
const ImU32 col_hovered = GetColorU32((plot_type == ImGuiPlotType_Lines) ? ImGuiCol_PlotLinesHovered : ImGuiCol_PlotHistogramHovered);
for (int n = 0; n < res_w; n++)
{
const float t1 = t0 + t_step;
const int v1_idx = (int)(t0 * item_count + 0.5f);
IM_ASSERT(v1_idx >= 0 && v1_idx < values_count);
const float v1 = values_getter(data, (v1_idx + values_offset + 1) % values_count);
const ImVec2 tp1 = ImVec2( t1, 1.0f - ImSaturate((v1 - scale_min) * inv_scale) );
// NB: Draw calls are merged together by the DrawList system. Still, we should render our batch are lower level to save a bit of CPU.
ImVec2 pos0 = ImLerp(inner_bb.Min, inner_bb.Max, tp0);
ImVec2 pos1 = ImLerp(inner_bb.Min, inner_bb.Max, (plot_type == ImGuiPlotType_Lines) ? tp1 : ImVec2(tp1.x, histogram_zero_line_t));
if (plot_type == ImGuiPlotType_Lines)
{
window->DrawList->AddLine(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
else if (plot_type == ImGuiPlotType_Histogram)
{
if (pos1.x >= pos0.x + 2.0f)
pos1.x -= 1.0f;
window->DrawList->AddRectFilled(pos0, pos1, v_hovered == v1_idx ? col_hovered : col_base);
}
t0 = t1;
tp0 = tp1;
}
}
// Text overlay
if (overlay_text)
RenderTextClipped(ImVec2(frame_bb.Min.x, frame_bb.Min.y + style.FramePadding.y), frame_bb.Max, overlay_text, NULL, NULL, ImVec2(0.5f,0.0f));
if (label_size.x > 0.0f)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, inner_bb.Min.y), label);
}
struct ImGuiPlotArrayGetterData
{
const float* Values;
int Stride;
ImGuiPlotArrayGetterData(const float* values, int stride) { Values = values; Stride = stride; }
};
static float Plot_ArrayGetter(void* data, int idx)
{
ImGuiPlotArrayGetterData* plot_data = (ImGuiPlotArrayGetterData*)data;
const float v = *(float*)(void*)((unsigned char*)plot_data->Values + (size_t)idx * plot_data->Stride);
return v;
}
void ImGui::PlotLines(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Lines, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotLines(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Lines, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, const float* values, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size, int stride)
{
ImGuiPlotArrayGetterData data(values, stride);
PlotEx(ImGuiPlotType_Histogram, label, &Plot_ArrayGetter, (void*)&data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
void ImGui::PlotHistogram(const char* label, float (*values_getter)(void* data, int idx), void* data, int values_count, int values_offset, const char* overlay_text, float scale_min, float scale_max, ImVec2 graph_size)
{
PlotEx(ImGuiPlotType_Histogram, label, values_getter, data, values_count, values_offset, overlay_text, scale_min, scale_max, graph_size);
}
// size_arg (for each axis) < 0.0f: align to end, 0.0f: auto, > 0.0f: specified size
void ImGui::ProgressBar(float fraction, const ImVec2& size_arg, const char* overlay)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImRect bb(pos, pos + CalcItemSize(size_arg, CalcItemWidth(), g.FontSize + style.FramePadding.y*2.0f));
ItemSize(bb, style.FramePadding.y);
if (!ItemAdd(bb, 0))
return;
// Render
fraction = ImSaturate(fraction);
RenderFrame(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
bb.Expand(ImVec2(-style.FrameBorderSize, -style.FrameBorderSize));
const ImVec2 fill_br = ImVec2(ImLerp(bb.Min.x, bb.Max.x, fraction), bb.Max.y);
RenderRectFilledRangeH(window->DrawList, bb, GetColorU32(ImGuiCol_PlotHistogram), 0.0f, fraction, style.FrameRounding);
// Default displaying the fraction as percentage string, but user can override it
char overlay_buf[32];
if (!overlay)
{
ImFormatString(overlay_buf, IM_ARRAYSIZE(overlay_buf), "%.0f%%", fraction*100+0.01f);
overlay = overlay_buf;
}
ImVec2 overlay_size = CalcTextSize(overlay, NULL);
if (overlay_size.x > 0.0f)
RenderTextClipped(ImVec2(ImClamp(fill_br.x + style.ItemSpacing.x, bb.Min.x, bb.Max.x - overlay_size.x - style.ItemInnerSpacing.x), bb.Min.y), bb.Max, overlay, NULL, &overlay_size, ImVec2(0.0f,0.5f), &bb);
}
bool ImGui::Checkbox(const char* label, bool* v)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2, label_size.y + style.FramePadding.y*2)); // We want a square shape to we use Y twice
ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
if (label_size.x > 0)
SameLine(0, style.ItemInnerSpacing.x);
const ImRect text_bb(window->DC.CursorPos + ImVec2(0,style.FramePadding.y), window->DC.CursorPos + ImVec2(0,style.FramePadding.y) + label_size);
if (label_size.x > 0)
{
ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
total_bb = ImRect(ImMin(check_bb.Min, text_bb.Min), ImMax(check_bb.Max, text_bb.Max));
}
if (!ItemAdd(total_bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
if (pressed)
*v = !(*v);
RenderNavHighlight(total_bb, id);
RenderFrame(check_bb.Min, check_bb.Max, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), true, style.FrameRounding);
if (*v)
{
const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
RenderCheckMark(check_bb.Min + ImVec2(pad,pad), GetColorU32(ImGuiCol_CheckMark), check_bb.GetWidth() - pad*2.0f);
}
if (g.LogEnabled)
LogRenderedText(&text_bb.Min, *v ? "[x]" : "[ ]");
if (label_size.x > 0.0f)
RenderText(text_bb.Min, label);
return pressed;
}
bool ImGui::CheckboxFlags(const char* label, unsigned int* flags, unsigned int flags_value)
{
bool v = ((*flags & flags_value) == flags_value);
bool pressed = Checkbox(label, &v);
if (pressed)
{
if (v)
*flags |= flags_value;
else
*flags &= ~flags_value;
}
return pressed;
}
bool ImGui::RadioButton(const char* label, bool active)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const ImRect check_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(label_size.y + style.FramePadding.y*2-1, label_size.y + style.FramePadding.y*2-1));
ItemSize(check_bb, style.FramePadding.y);
ImRect total_bb = check_bb;
if (label_size.x > 0)
SameLine(0, style.ItemInnerSpacing.x);
const ImRect text_bb(window->DC.CursorPos + ImVec2(0, style.FramePadding.y), window->DC.CursorPos + ImVec2(0, style.FramePadding.y) + label_size);
if (label_size.x > 0)
{
ItemSize(ImVec2(text_bb.GetWidth(), check_bb.GetHeight()), style.FramePadding.y);
total_bb.Add(text_bb);
}
if (!ItemAdd(total_bb, id))
return false;
ImVec2 center = check_bb.GetCenter();
center.x = (float)(int)center.x + 0.5f;
center.y = (float)(int)center.y + 0.5f;
const float radius = check_bb.GetHeight() * 0.5f;
bool hovered, held;
bool pressed = ButtonBehavior(total_bb, id, &hovered, &held);
RenderNavHighlight(total_bb, id);
window->DrawList->AddCircleFilled(center, radius, GetColorU32((held && hovered) ? ImGuiCol_FrameBgActive : hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg), 16);
if (active)
{
const float check_sz = ImMin(check_bb.GetWidth(), check_bb.GetHeight());
const float pad = ImMax(1.0f, (float)(int)(check_sz / 6.0f));
window->DrawList->AddCircleFilled(center, radius-pad, GetColorU32(ImGuiCol_CheckMark), 16);
}
if (style.FrameBorderSize > 0.0f)
{
window->DrawList->AddCircle(center+ImVec2(1,1), radius, GetColorU32(ImGuiCol_BorderShadow), 16, style.FrameBorderSize);
window->DrawList->AddCircle(center, radius, GetColorU32(ImGuiCol_Border), 16, style.FrameBorderSize);
}
if (g.LogEnabled)
LogRenderedText(&text_bb.Min, active ? "(x)" : "( )");
if (label_size.x > 0.0f)
RenderText(text_bb.Min, label);
return pressed;
}
bool ImGui::RadioButton(const char* label, int* v, int v_button)
{
const bool pressed = RadioButton(label, *v == v_button);
if (pressed)
{
*v = v_button;
}
return pressed;
}
static int InputTextCalcTextLenAndLineCount(const char* text_begin, const char** out_text_end)
{
int line_count = 0;
const char* s = text_begin;
while (char c = *s++) // We are only matching for \n so we can ignore UTF-8 decoding
if (c == '\n')
line_count++;
s--;
if (s[0] != '\n' && s[0] != '\r')
line_count++;
*out_text_end = s;
return line_count;
}
static ImVec2 InputTextCalcTextSizeW(const ImWchar* text_begin, const ImWchar* text_end, const ImWchar** remaining, ImVec2* out_offset, bool stop_on_new_line)
{
ImFont* font = GImGui->Font;
const float line_height = GImGui->FontSize;
const float scale = line_height / font->FontSize;
ImVec2 text_size = ImVec2(0,0);
float line_width = 0.0f;
const ImWchar* s = text_begin;
while (s < text_end)
{
unsigned int c = (unsigned int)(*s++);
if (c == '\n')
{
text_size.x = ImMax(text_size.x, line_width);
text_size.y += line_height;
line_width = 0.0f;
if (stop_on_new_line)
break;
continue;
}
if (c == '\r')
continue;
const float char_width = font->GetCharAdvance((unsigned short)c) * scale;
line_width += char_width;
}
if (text_size.x < line_width)
text_size.x = line_width;
if (out_offset)
*out_offset = ImVec2(line_width, text_size.y + line_height); // offset allow for the possibility of sitting after a trailing \n
if (line_width > 0 || text_size.y == 0.0f) // whereas size.y will ignore the trailing \n
text_size.y += line_height;
if (remaining)
*remaining = s;
return text_size;
}
// Wrapper for stb_textedit.h to edit text (our wrapper is for: statically sized buffer, single-line, wchar characters. InputText converts between UTF-8 and wchar)
namespace ImGuiStb
{
static int STB_TEXTEDIT_STRINGLEN(const STB_TEXTEDIT_STRING* obj) { return obj->CurLenW; }
static ImWchar STB_TEXTEDIT_GETCHAR(const STB_TEXTEDIT_STRING* obj, int idx) { return obj->Text[idx]; }
static float STB_TEXTEDIT_GETWIDTH(STB_TEXTEDIT_STRING* obj, int line_start_idx, int char_idx) { ImWchar c = obj->Text[line_start_idx+char_idx]; if (c == '\n') return STB_TEXTEDIT_GETWIDTH_NEWLINE; return GImGui->Font->GetCharAdvance(c) * (GImGui->FontSize / GImGui->Font->FontSize); }
static int STB_TEXTEDIT_KEYTOTEXT(int key) { return key >= 0x10000 ? 0 : key; }
static ImWchar STB_TEXTEDIT_NEWLINE = '\n';
static void STB_TEXTEDIT_LAYOUTROW(StbTexteditRow* r, STB_TEXTEDIT_STRING* obj, int line_start_idx)
{
const ImWchar* text = obj->Text.Data;
const ImWchar* text_remaining = NULL;
const ImVec2 size = InputTextCalcTextSizeW(text + line_start_idx, text + obj->CurLenW, &text_remaining, NULL, true);
r->x0 = 0.0f;
r->x1 = size.x;
r->baseline_y_delta = size.y;
r->ymin = 0.0f;
r->ymax = size.y;
r->num_chars = (int)(text_remaining - (text + line_start_idx));
}
static bool is_separator(unsigned int c) { return ImCharIsSpace(c) || c==',' || c==';' || c=='(' || c==')' || c=='{' || c=='}' || c=='[' || c==']' || c=='|'; }
static int is_word_boundary_from_right(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (is_separator( obj->Text[idx-1] ) && !is_separator( obj->Text[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDLEFT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx--; while (idx >= 0 && !is_word_boundary_from_right(obj, idx)) idx--; return idx < 0 ? 0 : idx; }
#ifdef __APPLE__ // FIXME: Move setting to IO structure
static int is_word_boundary_from_left(STB_TEXTEDIT_STRING* obj, int idx) { return idx > 0 ? (!is_separator( obj->Text[idx-1] ) && is_separator( obj->Text[idx] ) ) : 1; }
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_left(obj, idx)) idx++; return idx > len ? len : idx; }
#else
static int STB_TEXTEDIT_MOVEWORDRIGHT_IMPL(STB_TEXTEDIT_STRING* obj, int idx) { idx++; int len = obj->CurLenW; while (idx < len && !is_word_boundary_from_right(obj, idx)) idx++; return idx > len ? len : idx; }
#endif
#define STB_TEXTEDIT_MOVEWORDLEFT STB_TEXTEDIT_MOVEWORDLEFT_IMPL // They need to be #define for stb_textedit.h
#define STB_TEXTEDIT_MOVEWORDRIGHT STB_TEXTEDIT_MOVEWORDRIGHT_IMPL
static void STB_TEXTEDIT_DELETECHARS(STB_TEXTEDIT_STRING* obj, int pos, int n)
{
ImWchar* dst = obj->Text.Data + pos;
// We maintain our buffer length in both UTF-8 and wchar formats
obj->CurLenA -= ImTextCountUtf8BytesFromStr(dst, dst + n);
obj->CurLenW -= n;
// Offset remaining text
const ImWchar* src = obj->Text.Data + pos + n;
while (ImWchar c = *src++)
*dst++ = c;
*dst = '\0';
}
static bool STB_TEXTEDIT_INSERTCHARS(STB_TEXTEDIT_STRING* obj, int pos, const ImWchar* new_text, int new_text_len)
{
const int text_len = obj->CurLenW;
IM_ASSERT(pos <= text_len);
if (new_text_len + text_len + 1 > obj->Text.Size)
return false;
const int new_text_len_utf8 = ImTextCountUtf8BytesFromStr(new_text, new_text + new_text_len);
if (new_text_len_utf8 + obj->CurLenA + 1 > obj->BufSizeA)
return false;
ImWchar* text = obj->Text.Data;
if (pos != text_len)
memmove(text + pos + new_text_len, text + pos, (size_t)(text_len - pos) * sizeof(ImWchar));
memcpy(text + pos, new_text, (size_t)new_text_len * sizeof(ImWchar));
obj->CurLenW += new_text_len;
obj->CurLenA += new_text_len_utf8;
obj->Text[obj->CurLenW] = '\0';
return true;
}
// We don't use an enum so we can build even with conflicting symbols (if another user of stb_textedit.h leak their STB_TEXTEDIT_K_* symbols)
#define STB_TEXTEDIT_K_LEFT 0x10000 // keyboard input to move cursor left
#define STB_TEXTEDIT_K_RIGHT 0x10001 // keyboard input to move cursor right
#define STB_TEXTEDIT_K_UP 0x10002 // keyboard input to move cursor up
#define STB_TEXTEDIT_K_DOWN 0x10003 // keyboard input to move cursor down
#define STB_TEXTEDIT_K_LINESTART 0x10004 // keyboard input to move cursor to start of line
#define STB_TEXTEDIT_K_LINEEND 0x10005 // keyboard input to move cursor to end of line
#define STB_TEXTEDIT_K_TEXTSTART 0x10006 // keyboard input to move cursor to start of text
#define STB_TEXTEDIT_K_TEXTEND 0x10007 // keyboard input to move cursor to end of text
#define STB_TEXTEDIT_K_DELETE 0x10008 // keyboard input to delete selection or character under cursor
#define STB_TEXTEDIT_K_BACKSPACE 0x10009 // keyboard input to delete selection or character left of cursor
#define STB_TEXTEDIT_K_UNDO 0x1000A // keyboard input to perform undo
#define STB_TEXTEDIT_K_REDO 0x1000B // keyboard input to perform redo
#define STB_TEXTEDIT_K_WORDLEFT 0x1000C // keyboard input to move cursor left one word
#define STB_TEXTEDIT_K_WORDRIGHT 0x1000D // keyboard input to move cursor right one word
#define STB_TEXTEDIT_K_SHIFT 0x20000
#define STB_TEXTEDIT_IMPLEMENTATION
#include "stb_textedit.h"
}
void ImGuiTextEditState::OnKeyPressed(int key)
{
stb_textedit_key(this, &StbState, key);
CursorFollow = true;
CursorAnimReset();
}
// Public API to manipulate UTF-8 text
// We expose UTF-8 to the user (unlike the STB_TEXTEDIT_* functions which are manipulating wchar)
// FIXME: The existence of this rarely exercised code path is a bit of a nuisance.
void ImGuiTextEditCallbackData::DeleteChars(int pos, int bytes_count)
{
IM_ASSERT(pos + bytes_count <= BufTextLen);
char* dst = Buf + pos;
const char* src = Buf + pos + bytes_count;
while (char c = *src++)
*dst++ = c;
*dst = '\0';
if (CursorPos + bytes_count >= pos)
CursorPos -= bytes_count;
else if (CursorPos >= pos)
CursorPos = pos;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen -= bytes_count;
}
void ImGuiTextEditCallbackData::InsertChars(int pos, const char* new_text, const char* new_text_end)
{
const int new_text_len = new_text_end ? (int)(new_text_end - new_text) : (int)strlen(new_text);
if (new_text_len + BufTextLen + 1 >= BufSize)
return;
if (BufTextLen != pos)
memmove(Buf + pos + new_text_len, Buf + pos, (size_t)(BufTextLen - pos));
memcpy(Buf + pos, new_text, (size_t)new_text_len * sizeof(char));
Buf[BufTextLen + new_text_len] = '\0';
if (CursorPos >= pos)
CursorPos += new_text_len;
SelectionStart = SelectionEnd = CursorPos;
BufDirty = true;
BufTextLen += new_text_len;
}
// Return false to discard a character.
static bool InputTextFilterCharacter(unsigned int* p_char, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
unsigned int c = *p_char;
if (c < 128 && c != ' ' && !isprint((int)(c & 0xFF)))
{
bool pass = false;
pass |= (c == '\n' && (flags & ImGuiInputTextFlags_Multiline));
pass |= (c == '\t' && (flags & ImGuiInputTextFlags_AllowTabInput));
if (!pass)
return false;
}
if (c >= 0xE000 && c <= 0xF8FF) // Filter private Unicode range. I don't imagine anybody would want to input them. GLFW on OSX seems to send private characters for special keys like arrow keys.
return false;
if (flags & (ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase | ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_CharsScientific))
{
if (flags & ImGuiInputTextFlags_CharsDecimal)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/'))
return false;
if (flags & ImGuiInputTextFlags_CharsScientific)
if (!(c >= '0' && c <= '9') && (c != '.') && (c != '-') && (c != '+') && (c != '*') && (c != '/') && (c != 'e') && (c != 'E'))
return false;
if (flags & ImGuiInputTextFlags_CharsHexadecimal)
if (!(c >= '0' && c <= '9') && !(c >= 'a' && c <= 'f') && !(c >= 'A' && c <= 'F'))
return false;
if (flags & ImGuiInputTextFlags_CharsUppercase)
if (c >= 'a' && c <= 'z')
*p_char = (c += (unsigned int)('A'-'a'));
if (flags & ImGuiInputTextFlags_CharsNoBlank)
if (ImCharIsSpace(c))
return false;
}
if (flags & ImGuiInputTextFlags_CallbackCharFilter)
{
ImGuiTextEditCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
callback_data.EventFlag = ImGuiInputTextFlags_CallbackCharFilter;
callback_data.EventChar = (ImWchar)c;
callback_data.Flags = flags;
callback_data.UserData = user_data;
if (callback(&callback_data) != 0)
return false;
*p_char = callback_data.EventChar;
if (!callback_data.EventChar)
return false;
}
return true;
}
// Edit a string of text
// NB: when active, hold on a privately held copy of the text (and apply back to 'buf'). So changing 'buf' while active has no effect.
// FIXME: Rather messy function partly because we are doing UTF8 > u16 > UTF8 conversions on the go to more easily handle stb_textedit calls. Ideally we should stay in UTF-8 all the time. See https://github.com/nothings/stb/issues/188
bool ImGui::InputTextEx(const char* label, char* buf, int buf_size, const ImVec2& size_arg, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackHistory) && (flags & ImGuiInputTextFlags_Multiline))); // Can't use both together (they both use up/down keys)
IM_ASSERT(!((flags & ImGuiInputTextFlags_CallbackCompletion) && (flags & ImGuiInputTextFlags_AllowTabInput))); // Can't use both together (they both use tab key)
ImGuiContext& g = *GImGui;
const ImGuiIO& io = g.IO;
const ImGuiStyle& style = g.Style;
const bool is_multiline = (flags & ImGuiInputTextFlags_Multiline) != 0;
const bool is_editable = (flags & ImGuiInputTextFlags_ReadOnly) == 0;
const bool is_password = (flags & ImGuiInputTextFlags_Password) != 0;
const bool is_undoable = (flags & ImGuiInputTextFlags_NoUndoRedo) == 0;
if (is_multiline) // Open group before calling GetID() because groups tracks id created during their spawn
BeginGroup();
const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), (is_multiline ? GetTextLineHeight() * 8.0f : label_size.y) + style.FramePadding.y*2.0f); // Arbitrary default of 8 lines high for multi-line
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + size);
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? (style.ItemInnerSpacing.x + label_size.x) : 0.0f, 0.0f));
ImGuiWindow* draw_window = window;
if (is_multiline)
{
ItemAdd(total_bb, id, &frame_bb);
if (!BeginChildFrame(id, frame_bb.GetSize()))
{
EndChildFrame();
EndGroup();
return false;
}
draw_window = GetCurrentWindow();
size.x -= draw_window->ScrollbarSizes.x;
}
else
{
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
}
const bool hovered = ItemHoverable(frame_bb, id);
if (hovered)
g.MouseCursor = ImGuiMouseCursor_TextInput;
// Password pushes a temporary font with only a fallback glyph
if (is_password)
{
const ImFontGlyph* glyph = g.Font->FindGlyph('*');
ImFont* password_font = &g.InputTextPasswordFont;
password_font->FontSize = g.Font->FontSize;
password_font->Scale = g.Font->Scale;
password_font->DisplayOffset = g.Font->DisplayOffset;
password_font->Ascent = g.Font->Ascent;
password_font->Descent = g.Font->Descent;
password_font->ContainerAtlas = g.Font->ContainerAtlas;
password_font->FallbackGlyph = glyph;
password_font->FallbackAdvanceX = glyph->AdvanceX;
IM_ASSERT(password_font->Glyphs.empty() && password_font->IndexAdvanceX.empty() && password_font->IndexLookup.empty());
PushFont(password_font);
}
// NB: we are only allowed to access 'edit_state' if we are the active widget.
ImGuiTextEditState& edit_state = g.InputTextState;
const bool focus_requested = FocusableItemRegister(window, id, (flags & (ImGuiInputTextFlags_CallbackCompletion|ImGuiInputTextFlags_AllowTabInput)) == 0); // Using completion callback disable keyboard tabbing
const bool focus_requested_by_code = focus_requested && (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent);
const bool focus_requested_by_tab = focus_requested && !focus_requested_by_code;
const bool user_clicked = hovered && io.MouseClicked[0];
const bool user_scrolled = is_multiline && g.ActiveId == 0 && edit_state.Id == id && g.ActiveIdPreviousFrame == draw_window->GetIDNoKeepAlive("#SCROLLY");
const bool user_nav_input_start = (g.ActiveId != id) && ((g.NavInputId == id) || (g.NavActivateId == id && g.NavInputSource == ImGuiInputSource_NavKeyboard));
bool clear_active_id = false;
bool select_all = (g.ActiveId != id) && ((flags & ImGuiInputTextFlags_AutoSelectAll) != 0 || user_nav_input_start) && (!is_multiline);
if (focus_requested || user_clicked || user_scrolled || user_nav_input_start)
{
if (g.ActiveId != id)
{
// Start edition
// Take a copy of the initial buffer value (both in original UTF-8 format and converted to wchar)
// From the moment we focused we are ignoring the content of 'buf' (unless we are in read-only mode)
const int prev_len_w = edit_state.CurLenW;
edit_state.Text.resize(buf_size+1); // wchar count <= UTF-8 count. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
edit_state.InitialText.resize(buf_size+1); // UTF-8. we use +1 to make sure that .Data isn't NULL so it doesn't crash.
ImStrncpy(edit_state.InitialText.Data, buf, edit_state.InitialText.Size);
const char* buf_end = NULL;
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
edit_state.CurLenA = (int)(buf_end - buf); // We can't get the result from ImFormatString() above because it is not UTF-8 aware. Here we'll cut off malformed UTF-8.
edit_state.CursorAnimReset();
// Preserve cursor position and undo/redo stack if we come back to same widget
// FIXME: We should probably compare the whole buffer to be on the safety side. Comparing buf (utf8) and edit_state.Text (wchar).
const bool recycle_state = (edit_state.Id == id) && (prev_len_w == edit_state.CurLenW);
if (recycle_state)
{
// Recycle existing cursor/selection/undo stack but clamp position
// Note a single mouse click will override the cursor/position immediately by calling stb_textedit_click handler.
edit_state.CursorClamp();
}
else
{
edit_state.Id = id;
edit_state.ScrollX = 0.0f;
stb_textedit_initialize_state(&edit_state.StbState, !is_multiline);
if (!is_multiline && focus_requested_by_code)
select_all = true;
}
if (flags & ImGuiInputTextFlags_AlwaysInsertMode)
edit_state.StbState.insert_mode = true;
if (!is_multiline && (focus_requested_by_tab || (user_clicked && io.KeyCtrl)))
select_all = true;
}
SetActiveID(id, window);
SetFocusID(id, window);
FocusWindow(window);
if (!is_multiline && !(flags & ImGuiInputTextFlags_CallbackHistory))
g.ActiveIdAllowNavDirFlags |= ((1 << ImGuiDir_Up) | (1 << ImGuiDir_Down));
}
else if (io.MouseClicked[0])
{
// Release focus when we click outside
clear_active_id = true;
}
bool value_changed = false;
bool enter_pressed = false;
if (g.ActiveId == id)
{
if (!is_editable && !g.ActiveIdIsJustActivated)
{
// When read-only we always use the live data passed to the function
edit_state.Text.resize(buf_size+1);
const char* buf_end = NULL;
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, buf, NULL, &buf_end);
edit_state.CurLenA = (int)(buf_end - buf);
edit_state.CursorClamp();
}
edit_state.BufSizeA = buf_size;
// Although we are active we don't prevent mouse from hovering other elements unless we are interacting right now with the widget.
// Down the line we should have a cleaner library-wide concept of Selected vs Active.
g.ActiveIdAllowOverlap = !io.MouseDown[0];
g.WantTextInputNextFrame = 1;
// Edit in progress
const float mouse_x = (io.MousePos.x - frame_bb.Min.x - style.FramePadding.x) + edit_state.ScrollX;
const float mouse_y = (is_multiline ? (io.MousePos.y - draw_window->DC.CursorPos.y - style.FramePadding.y) : (g.FontSize*0.5f));
const bool osx_double_click_selects_words = io.OptMacOSXBehaviors; // OS X style: Double click selects by word instead of selecting whole text
if (select_all || (hovered && !osx_double_click_selects_words && io.MouseDoubleClicked[0]))
{
edit_state.SelectAll();
edit_state.SelectedAllMouseLock = true;
}
else if (hovered && osx_double_click_selects_words && io.MouseDoubleClicked[0])
{
// Select a word only, OS X style (by simulating keystrokes)
edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT);
edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDRIGHT | STB_TEXTEDIT_K_SHIFT);
}
else if (io.MouseClicked[0] && !edit_state.SelectedAllMouseLock)
{
if (hovered)
{
stb_textedit_click(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
edit_state.CursorAnimReset();
}
}
else if (io.MouseDown[0] && !edit_state.SelectedAllMouseLock && (io.MouseDelta.x != 0.0f || io.MouseDelta.y != 0.0f))
{
stb_textedit_drag(&edit_state, &edit_state.StbState, mouse_x, mouse_y);
edit_state.CursorAnimReset();
edit_state.CursorFollow = true;
}
if (edit_state.SelectedAllMouseLock && !io.MouseDown[0])
edit_state.SelectedAllMouseLock = false;
if (io.InputCharacters[0])
{
// Process text input (before we check for Return because using some IME will effectively send a Return?)
// We ignore CTRL inputs, but need to allow ALT+CTRL as some keyboards (e.g. German) use AltGR (which _is_ Alt+Ctrl) to input certain characters.
if (!(io.KeyCtrl && !io.KeyAlt) && is_editable && !user_nav_input_start)
for (int n = 0; n < IM_ARRAYSIZE(io.InputCharacters) && io.InputCharacters[n]; n++)
{
// Insert character if they pass filtering
unsigned int c = (unsigned int)io.InputCharacters[n];
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
// Consume characters
memset(g.IO.InputCharacters, 0, sizeof(g.IO.InputCharacters));
}
}
bool cancel_edit = false;
if (g.ActiveId == id && !g.ActiveIdIsJustActivated && !clear_active_id)
{
// Handle key-presses
const int k_mask = (io.KeyShift ? STB_TEXTEDIT_K_SHIFT : 0);
const bool is_shortcut_key_only = (io.OptMacOSXBehaviors ? (io.KeySuper && !io.KeyCtrl) : (io.KeyCtrl && !io.KeySuper)) && !io.KeyAlt && !io.KeyShift; // OS X style: Shortcuts using Cmd/Super instead of Ctrl
const bool is_wordmove_key_down = io.OptMacOSXBehaviors ? io.KeyAlt : io.KeyCtrl; // OS X style: Text editing cursor movement using Alt instead of Ctrl
const bool is_startend_key_down = io.OptMacOSXBehaviors && io.KeySuper && !io.KeyCtrl && !io.KeyAlt; // OS X style: Line/Text Start and End using Cmd+Arrows instead of Home/End
const bool is_ctrl_key_only = io.KeyCtrl && !io.KeyShift && !io.KeyAlt && !io.KeySuper;
const bool is_shift_key_only = io.KeyShift && !io.KeyCtrl && !io.KeyAlt && !io.KeySuper;
const bool is_cut = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_X)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Delete))) && is_editable && !is_password && (!is_multiline || edit_state.HasSelection());
const bool is_copy = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_C)) || (is_ctrl_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && !is_password && (!is_multiline || edit_state.HasSelection());
const bool is_paste = ((is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_V)) || (is_shift_key_only && IsKeyPressedMap(ImGuiKey_Insert))) && is_editable;
if (IsKeyPressedMap(ImGuiKey_LeftArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINESTART : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDLEFT : STB_TEXTEDIT_K_LEFT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_RightArrow)) { edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_LINEEND : is_wordmove_key_down ? STB_TEXTEDIT_K_WORDRIGHT : STB_TEXTEDIT_K_RIGHT) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_UpArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMax(draw_window->Scroll.y - g.FontSize, 0.0f)); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTSTART : STB_TEXTEDIT_K_UP) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_DownArrow) && is_multiline) { if (io.KeyCtrl) SetWindowScrollY(draw_window, ImMin(draw_window->Scroll.y + g.FontSize, GetScrollMaxY())); else edit_state.OnKeyPressed((is_startend_key_down ? STB_TEXTEDIT_K_TEXTEND : STB_TEXTEDIT_K_DOWN) | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Home)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTSTART | k_mask : STB_TEXTEDIT_K_LINESTART | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_End)) { edit_state.OnKeyPressed(io.KeyCtrl ? STB_TEXTEDIT_K_TEXTEND | k_mask : STB_TEXTEDIT_K_LINEEND | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Delete) && is_editable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_DELETE | k_mask); }
else if (IsKeyPressedMap(ImGuiKey_Backspace) && is_editable)
{
if (!edit_state.HasSelection())
{
if (is_wordmove_key_down) edit_state.OnKeyPressed(STB_TEXTEDIT_K_WORDLEFT|STB_TEXTEDIT_K_SHIFT);
else if (io.OptMacOSXBehaviors && io.KeySuper && !io.KeyAlt && !io.KeyCtrl) edit_state.OnKeyPressed(STB_TEXTEDIT_K_LINESTART|STB_TEXTEDIT_K_SHIFT);
}
edit_state.OnKeyPressed(STB_TEXTEDIT_K_BACKSPACE | k_mask);
}
else if (IsKeyPressedMap(ImGuiKey_Enter))
{
bool ctrl_enter_for_new_line = (flags & ImGuiInputTextFlags_CtrlEnterForNewLine) != 0;
if (!is_multiline || (ctrl_enter_for_new_line && !io.KeyCtrl) || (!ctrl_enter_for_new_line && io.KeyCtrl))
{
enter_pressed = clear_active_id = true;
}
else if (is_editable)
{
unsigned int c = '\n'; // Insert new line
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
}
else if ((flags & ImGuiInputTextFlags_AllowTabInput) && IsKeyPressedMap(ImGuiKey_Tab) && !io.KeyCtrl && !io.KeyShift && !io.KeyAlt && is_editable)
{
unsigned int c = '\t'; // Insert TAB
if (InputTextFilterCharacter(&c, flags, callback, user_data))
edit_state.OnKeyPressed((int)c);
}
else if (IsKeyPressedMap(ImGuiKey_Escape)) { clear_active_id = cancel_edit = true; }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Z) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_UNDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_Y) && is_editable && is_undoable) { edit_state.OnKeyPressed(STB_TEXTEDIT_K_REDO); edit_state.ClearSelection(); }
else if (is_shortcut_key_only && IsKeyPressedMap(ImGuiKey_A)) { edit_state.SelectAll(); edit_state.CursorFollow = true; }
else if (is_cut || is_copy)
{
// Cut, Copy
if (io.SetClipboardTextFn)
{
const int ib = edit_state.HasSelection() ? ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end) : 0;
const int ie = edit_state.HasSelection() ? ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end) : edit_state.CurLenW;
edit_state.TempTextBuffer.resize((ie-ib) * 4 + 1);
ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data+ib, edit_state.Text.Data+ie);
SetClipboardText(edit_state.TempTextBuffer.Data);
}
if (is_cut)
{
if (!edit_state.HasSelection())
edit_state.SelectAll();
edit_state.CursorFollow = true;
stb_textedit_cut(&edit_state, &edit_state.StbState);
}
}
else if (is_paste)
{
// Paste
if (const char* clipboard = GetClipboardText())
{
// Filter pasted buffer
const int clipboard_len = (int)strlen(clipboard);
ImWchar* clipboard_filtered = (ImWchar*)ImGui::MemAlloc((clipboard_len+1) * sizeof(ImWchar));
int clipboard_filtered_len = 0;
for (const char* s = clipboard; *s; )
{
unsigned int c;
s += ImTextCharFromUtf8(&c, s, NULL);
if (c == 0)
break;
if (c >= 0x10000 || !InputTextFilterCharacter(&c, flags, callback, user_data))
continue;
clipboard_filtered[clipboard_filtered_len++] = (ImWchar)c;
}
clipboard_filtered[clipboard_filtered_len] = 0;
if (clipboard_filtered_len > 0) // If everything was filtered, ignore the pasting operation
{
stb_textedit_paste(&edit_state, &edit_state.StbState, clipboard_filtered, clipboard_filtered_len);
edit_state.CursorFollow = true;
}
ImGui::MemFree(clipboard_filtered);
}
}
}
if (g.ActiveId == id)
{
if (cancel_edit)
{
// Restore initial value
if (is_editable)
{
ImStrncpy(buf, edit_state.InitialText.Data, buf_size);
value_changed = true;
}
}
// When using 'ImGuiInputTextFlags_EnterReturnsTrue' as a special case we reapply the live buffer back to the input buffer before clearing ActiveId, even though strictly speaking it wasn't modified on this frame.
// If we didn't do that, code like InputInt() with ImGuiInputTextFlags_EnterReturnsTrue would fail. Also this allows the user to use InputText() with ImGuiInputTextFlags_EnterReturnsTrue without maintaining any user-side storage.
bool apply_edit_back_to_user_buffer = !cancel_edit || (enter_pressed && (flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0);
if (apply_edit_back_to_user_buffer)
{
// Apply new value immediately - copy modified buffer back
// Note that as soon as the input box is active, the in-widget value gets priority over any underlying modification of the input buffer
// FIXME: We actually always render 'buf' when calling DrawList->AddText, making the comment above incorrect.
// FIXME-OPT: CPU waste to do this every time the widget is active, should mark dirty state from the stb_textedit callbacks.
if (is_editable)
{
edit_state.TempTextBuffer.resize(edit_state.Text.Size * 4);
ImTextStrToUtf8(edit_state.TempTextBuffer.Data, edit_state.TempTextBuffer.Size, edit_state.Text.Data, NULL);
}
// User callback
if ((flags & (ImGuiInputTextFlags_CallbackCompletion | ImGuiInputTextFlags_CallbackHistory | ImGuiInputTextFlags_CallbackAlways)) != 0)
{
IM_ASSERT(callback != NULL);
// The reason we specify the usage semantic (Completion/History) is that Completion needs to disable keyboard TABBING at the moment.
ImGuiInputTextFlags event_flag = 0;
ImGuiKey event_key = ImGuiKey_COUNT;
if ((flags & ImGuiInputTextFlags_CallbackCompletion) != 0 && IsKeyPressedMap(ImGuiKey_Tab))
{
event_flag = ImGuiInputTextFlags_CallbackCompletion;
event_key = ImGuiKey_Tab;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_UpArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_UpArrow;
}
else if ((flags & ImGuiInputTextFlags_CallbackHistory) != 0 && IsKeyPressedMap(ImGuiKey_DownArrow))
{
event_flag = ImGuiInputTextFlags_CallbackHistory;
event_key = ImGuiKey_DownArrow;
}
else if (flags & ImGuiInputTextFlags_CallbackAlways)
event_flag = ImGuiInputTextFlags_CallbackAlways;
if (event_flag)
{
ImGuiTextEditCallbackData callback_data;
memset(&callback_data, 0, sizeof(ImGuiTextEditCallbackData));
callback_data.EventFlag = event_flag;
callback_data.Flags = flags;
callback_data.UserData = user_data;
callback_data.ReadOnly = !is_editable;
callback_data.EventKey = event_key;
callback_data.Buf = edit_state.TempTextBuffer.Data;
callback_data.BufTextLen = edit_state.CurLenA;
callback_data.BufSize = edit_state.BufSizeA;
callback_data.BufDirty = false;
// We have to convert from wchar-positions to UTF-8-positions, which can be pretty slow (an incentive to ditch the ImWchar buffer, see https://github.com/nothings/stb/issues/188)
ImWchar* text = edit_state.Text.Data;
const int utf8_cursor_pos = callback_data.CursorPos = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.cursor);
const int utf8_selection_start = callback_data.SelectionStart = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_start);
const int utf8_selection_end = callback_data.SelectionEnd = ImTextCountUtf8BytesFromStr(text, text + edit_state.StbState.select_end);
// Call user code
callback(&callback_data);
// Read back what user may have modified
IM_ASSERT(callback_data.Buf == edit_state.TempTextBuffer.Data); // Invalid to modify those fields
IM_ASSERT(callback_data.BufSize == edit_state.BufSizeA);
IM_ASSERT(callback_data.Flags == flags);
if (callback_data.CursorPos != utf8_cursor_pos) edit_state.StbState.cursor = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.CursorPos);
if (callback_data.SelectionStart != utf8_selection_start) edit_state.StbState.select_start = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionStart);
if (callback_data.SelectionEnd != utf8_selection_end) edit_state.StbState.select_end = ImTextCountCharsFromUtf8(callback_data.Buf, callback_data.Buf + callback_data.SelectionEnd);
if (callback_data.BufDirty)
{
IM_ASSERT(callback_data.BufTextLen == (int)strlen(callback_data.Buf)); // You need to maintain BufTextLen if you change the text!
edit_state.CurLenW = ImTextStrFromUtf8(edit_state.Text.Data, edit_state.Text.Size, callback_data.Buf, NULL);
edit_state.CurLenA = callback_data.BufTextLen; // Assume correct length and valid UTF-8 from user, saves us an extra strlen()
edit_state.CursorAnimReset();
}
}
}
// Copy back to user buffer
if (is_editable && strcmp(edit_state.TempTextBuffer.Data, buf) != 0)
{
ImStrncpy(buf, edit_state.TempTextBuffer.Data, buf_size);
value_changed = true;
}
}
}
// Release active ID at the end of the function (so e.g. pressing Return still does a final application of the value)
if (clear_active_id && g.ActiveId == id)
ClearActiveID();
// Render
// Select which buffer we are going to display. When ImGuiInputTextFlags_NoLiveEdit is set 'buf' might still be the old value. We set buf to NULL to prevent accidental usage from now on.
const char* buf_display = (g.ActiveId == id && is_editable) ? edit_state.TempTextBuffer.Data : buf; buf = NULL;
RenderNavHighlight(frame_bb, id);
if (!is_multiline)
RenderFrame(frame_bb.Min, frame_bb.Max, GetColorU32(ImGuiCol_FrameBg), true, style.FrameRounding);
const ImVec4 clip_rect(frame_bb.Min.x, frame_bb.Min.y, frame_bb.Min.x + size.x, frame_bb.Min.y + size.y); // Not using frame_bb.Max because we have adjusted size
ImVec2 render_pos = is_multiline ? draw_window->DC.CursorPos : frame_bb.Min + style.FramePadding;
ImVec2 text_size(0.f, 0.f);
const bool is_currently_scrolling = (edit_state.Id == id && is_multiline && g.ActiveId == draw_window->GetIDNoKeepAlive("#SCROLLY"));
if (g.ActiveId == id || is_currently_scrolling)
{
edit_state.CursorAnim += io.DeltaTime;
// This is going to be messy. We need to:
// - Display the text (this alone can be more easily clipped)
// - Handle scrolling, highlight selection, display cursor (those all requires some form of 1d->2d cursor position calculation)
// - Measure text height (for scrollbar)
// We are attempting to do most of that in **one main pass** to minimize the computation cost (non-negligible for large amount of text) + 2nd pass for selection rendering (we could merge them by an extra refactoring effort)
// FIXME: This should occur on buf_display but we'd need to maintain cursor/select_start/select_end for UTF-8.
const ImWchar* text_begin = edit_state.Text.Data;
ImVec2 cursor_offset, select_start_offset;
{
// Count lines + find lines numbers straddling 'cursor' and 'select_start' position.
const ImWchar* searches_input_ptr[2];
searches_input_ptr[0] = text_begin + edit_state.StbState.cursor;
searches_input_ptr[1] = NULL;
int searches_remaining = 1;
int searches_result_line_number[2] = { -1, -999 };
if (edit_state.StbState.select_start != edit_state.StbState.select_end)
{
searches_input_ptr[1] = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
searches_result_line_number[1] = -1;
searches_remaining++;
}
// Iterate all lines to find our line numbers
// In multi-line mode, we never exit the loop until all lines are counted, so add one extra to the searches_remaining counter.
searches_remaining += is_multiline ? 1 : 0;
int line_count = 0;
for (const ImWchar* s = text_begin; *s != 0; s++)
if (*s == '\n')
{
line_count++;
if (searches_result_line_number[0] == -1 && s >= searches_input_ptr[0]) { searches_result_line_number[0] = line_count; if (--searches_remaining <= 0) break; }
if (searches_result_line_number[1] == -1 && s >= searches_input_ptr[1]) { searches_result_line_number[1] = line_count; if (--searches_remaining <= 0) break; }
}
line_count++;
if (searches_result_line_number[0] == -1) searches_result_line_number[0] = line_count;
if (searches_result_line_number[1] == -1) searches_result_line_number[1] = line_count;
// Calculate 2d position by finding the beginning of the line and measuring distance
cursor_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[0], text_begin), searches_input_ptr[0]).x;
cursor_offset.y = searches_result_line_number[0] * g.FontSize;
if (searches_result_line_number[1] >= 0)
{
select_start_offset.x = InputTextCalcTextSizeW(ImStrbolW(searches_input_ptr[1], text_begin), searches_input_ptr[1]).x;
select_start_offset.y = searches_result_line_number[1] * g.FontSize;
}
// Store text height (note that we haven't calculated text width at all, see GitHub issues #383, #1224)
if (is_multiline)
text_size = ImVec2(size.x, line_count * g.FontSize);
}
// Scroll
if (edit_state.CursorFollow)
{
// Horizontal scroll in chunks of quarter width
if (!(flags & ImGuiInputTextFlags_NoHorizontalScroll))
{
const float scroll_increment_x = size.x * 0.25f;
if (cursor_offset.x < edit_state.ScrollX)
edit_state.ScrollX = (float)(int)ImMax(0.0f, cursor_offset.x - scroll_increment_x);
else if (cursor_offset.x - size.x >= edit_state.ScrollX)
edit_state.ScrollX = (float)(int)(cursor_offset.x - size.x + scroll_increment_x);
}
else
{
edit_state.ScrollX = 0.0f;
}
// Vertical scroll
if (is_multiline)
{
float scroll_y = draw_window->Scroll.y;
if (cursor_offset.y - g.FontSize < scroll_y)
scroll_y = ImMax(0.0f, cursor_offset.y - g.FontSize);
else if (cursor_offset.y - size.y >= scroll_y)
scroll_y = cursor_offset.y - size.y;
draw_window->DC.CursorPos.y += (draw_window->Scroll.y - scroll_y); // To avoid a frame of lag
draw_window->Scroll.y = scroll_y;
render_pos.y = draw_window->DC.CursorPos.y;
}
}
edit_state.CursorFollow = false;
const ImVec2 render_scroll = ImVec2(edit_state.ScrollX, 0.0f);
// Draw selection
if (edit_state.StbState.select_start != edit_state.StbState.select_end)
{
const ImWchar* text_selected_begin = text_begin + ImMin(edit_state.StbState.select_start, edit_state.StbState.select_end);
const ImWchar* text_selected_end = text_begin + ImMax(edit_state.StbState.select_start, edit_state.StbState.select_end);
float bg_offy_up = is_multiline ? 0.0f : -1.0f; // FIXME: those offsets should be part of the style? they don't play so well with multi-line selection.
float bg_offy_dn = is_multiline ? 0.0f : 2.0f;
ImU32 bg_color = GetColorU32(ImGuiCol_TextSelectedBg);
ImVec2 rect_pos = render_pos + select_start_offset - render_scroll;
for (const ImWchar* p = text_selected_begin; p < text_selected_end; )
{
if (rect_pos.y > clip_rect.w + g.FontSize)
break;
if (rect_pos.y < clip_rect.y)
{
while (p < text_selected_end)
if (*p++ == '\n')
break;
}
else
{
ImVec2 rect_size = InputTextCalcTextSizeW(p, text_selected_end, &p, NULL, true);
if (rect_size.x <= 0.0f) rect_size.x = (float)(int)(g.Font->GetCharAdvance((unsigned short)' ') * 0.50f); // So we can see selected empty lines
ImRect rect(rect_pos + ImVec2(0.0f, bg_offy_up - g.FontSize), rect_pos +ImVec2(rect_size.x, bg_offy_dn));
rect.ClipWith(clip_rect);
if (rect.Overlaps(clip_rect))
draw_window->DrawList->AddRectFilled(rect.Min, rect.Max, bg_color);
}
rect_pos.x = render_pos.x - render_scroll.x;
rect_pos.y += g.FontSize;
}
}
draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos - render_scroll, GetColorU32(ImGuiCol_Text), buf_display, buf_display + edit_state.CurLenA, 0.0f, is_multiline ? NULL : &clip_rect);
// Draw blinking cursor
bool cursor_is_visible = (!g.IO.OptCursorBlink) || (g.InputTextState.CursorAnim <= 0.0f) || fmodf(g.InputTextState.CursorAnim, 1.20f) <= 0.80f;
ImVec2 cursor_screen_pos = render_pos + cursor_offset - render_scroll;
ImRect cursor_screen_rect(cursor_screen_pos.x, cursor_screen_pos.y-g.FontSize+0.5f, cursor_screen_pos.x+1.0f, cursor_screen_pos.y-1.5f);
if (cursor_is_visible && cursor_screen_rect.Overlaps(clip_rect))
draw_window->DrawList->AddLine(cursor_screen_rect.Min, cursor_screen_rect.GetBL(), GetColorU32(ImGuiCol_Text));
// Notify OS of text input position for advanced IME (-1 x offset so that Windows IME can cover our cursor. Bit of an extra nicety.)
if (is_editable)
g.OsImePosRequest = ImVec2(cursor_screen_pos.x - 1, cursor_screen_pos.y - g.FontSize);
}
else
{
// Render text only
const char* buf_end = NULL;
if (is_multiline)
text_size = ImVec2(size.x, InputTextCalcTextLenAndLineCount(buf_display, &buf_end) * g.FontSize); // We don't need width
draw_window->DrawList->AddText(g.Font, g.FontSize, render_pos, GetColorU32(ImGuiCol_Text), buf_display, buf_end, 0.0f, is_multiline ? NULL : &clip_rect);
}
if (is_multiline)
{
Dummy(text_size + ImVec2(0.0f, g.FontSize)); // Always add room to scroll an extra line
EndChildFrame();
EndGroup();
}
if (is_password)
PopFont();
// Log as text
if (g.LogEnabled && !is_password)
LogRenderedText(&render_pos, buf_display, NULL);
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((flags & ImGuiInputTextFlags_EnterReturnsTrue) != 0)
return enter_pressed;
else
return value_changed;
}
bool ImGui::InputText(const char* label, char* buf, size_t buf_size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
IM_ASSERT(!(flags & ImGuiInputTextFlags_Multiline)); // call InputTextMultiline()
return InputTextEx(label, buf, (int)buf_size, ImVec2(0,0), flags, callback, user_data);
}
bool ImGui::InputTextMultiline(const char* label, char* buf, size_t buf_size, const ImVec2& size, ImGuiInputTextFlags flags, ImGuiTextEditCallback callback, void* user_data)
{
return InputTextEx(label, buf, (int)buf_size, size, flags | ImGuiInputTextFlags_Multiline, callback, user_data);
}
// NB: scalar_format here must be a simple "%xx" format string with no prefix/suffix (unlike the Drag/Slider functions "display_format" argument)
bool ImGui::InputScalarEx(const char* label, ImGuiDataType data_type, void* data_ptr, void* step_ptr, void* step_fast_ptr, const char* scalar_format, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImVec2 label_size = CalcTextSize(label, NULL, true);
BeginGroup();
PushID(label);
const ImVec2 button_sz = ImVec2(GetFrameHeight(), GetFrameHeight());
if (step_ptr)
PushItemWidth(ImMax(1.0f, CalcItemWidth() - (button_sz.x + style.ItemInnerSpacing.x)*2));
char buf[64];
DataTypeFormatString(data_type, data_ptr, scalar_format, buf, IM_ARRAYSIZE(buf));
bool value_changed = false;
if ((extra_flags & (ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsScientific)) == 0)
extra_flags |= ImGuiInputTextFlags_CharsDecimal;
extra_flags |= ImGuiInputTextFlags_AutoSelectAll;
if (InputText("", buf, IM_ARRAYSIZE(buf), extra_flags)) // PushId(label) + "" gives us the expected ID from outside point of view
value_changed = DataTypeApplyOpFromText(buf, GImGui->InputTextState.InitialText.begin(), data_type, data_ptr, scalar_format);
// Step buttons
if (step_ptr)
{
PopItemWidth();
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("-", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
DataTypeApplyOp(data_type, '-', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
SameLine(0, style.ItemInnerSpacing.x);
if (ButtonEx("+", button_sz, ImGuiButtonFlags_Repeat | ImGuiButtonFlags_DontClosePopups))
{
DataTypeApplyOp(data_type, '+', data_ptr, data_ptr, g.IO.KeyCtrl && step_fast_ptr ? step_fast_ptr : step_ptr);
value_changed = true;
}
}
PopID();
if (label_size.x > 0)
{
SameLine(0, style.ItemInnerSpacing.x);
RenderText(ImVec2(window->DC.CursorPos.x, window->DC.CursorPos.y + style.FramePadding.y), label);
ItemSize(label_size, style.FramePadding.y);
}
EndGroup();
return value_changed;
}
bool ImGui::InputFloat(const char* label, float* v, float step, float step_fast, int decimal_precision, ImGuiInputTextFlags extra_flags)
{
extra_flags |= ImGuiInputTextFlags_CharsScientific;
if (decimal_precision < 0)
{
// Ideally we'd have a minimum decimal precision of 1 to visually denote that this is a float, while hiding non-significant digits? %f doesn't have a minimum of 1
return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), "%f", extra_flags);
}
else
{
char display_format[16];
ImFormatString(display_format, IM_ARRAYSIZE(display_format), "%%.%df", decimal_precision);
return InputScalarEx(label, ImGuiDataType_Float, (void*)v, (void*)(step>0.0f ? &step : NULL), (void*)(step_fast>0.0f ? &step_fast : NULL), display_format, extra_flags);
}
}
bool ImGui::InputDouble(const char* label, double* v, double step, double step_fast, const char* display_format, ImGuiInputTextFlags extra_flags)
{
extra_flags |= ImGuiInputTextFlags_CharsScientific;
return InputScalarEx(label, ImGuiDataType_Double, (void*)v, (void*)(step>0.0 ? &step : NULL), (void*)(step_fast>0.0 ? &step_fast : NULL), display_format, extra_flags);
}
bool ImGui::InputInt(const char* label, int* v, int step, int step_fast, ImGuiInputTextFlags extra_flags)
{
// Hexadecimal input provided as a convenience but the flag name is awkward. Typically you'd use InputText() to parse your own data, if you want to handle prefixes.
const char* scalar_format = (extra_flags & ImGuiInputTextFlags_CharsHexadecimal) ? "%08X" : "%d";
return InputScalarEx(label, ImGuiDataType_Int, (void*)v, (void*)(step>0 ? &step : NULL), (void*)(step_fast>0 ? &step_fast : NULL), scalar_format, extra_flags);
}
bool ImGui::InputFloatN(const char* label, float* v, int components, int decimal_precision, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= InputFloat("##v", &v[i], 0, 0, decimal_precision, extra_flags);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::InputFloat2(const char* label, float v[2], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 2, decimal_precision, extra_flags);
}
bool ImGui::InputFloat3(const char* label, float v[3], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 3, decimal_precision, extra_flags);
}
bool ImGui::InputFloat4(const char* label, float v[4], int decimal_precision, ImGuiInputTextFlags extra_flags)
{
return InputFloatN(label, v, 4, decimal_precision, extra_flags);
}
bool ImGui::InputIntN(const char* label, int* v, int components, ImGuiInputTextFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
bool value_changed = false;
BeginGroup();
PushID(label);
PushMultiItemsWidths(components);
for (int i = 0; i < components; i++)
{
PushID(i);
value_changed |= InputInt("##v", &v[i], 0, 0, extra_flags);
SameLine(0, g.Style.ItemInnerSpacing.x);
PopID();
PopItemWidth();
}
PopID();
TextUnformatted(label, FindRenderedTextEnd(label));
EndGroup();
return value_changed;
}
bool ImGui::InputInt2(const char* label, int v[2], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 2, extra_flags);
}
bool ImGui::InputInt3(const char* label, int v[3], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 3, extra_flags);
}
bool ImGui::InputInt4(const char* label, int v[4], ImGuiInputTextFlags extra_flags)
{
return InputIntN(label, v, 4, extra_flags);
}
static float CalcMaxPopupHeightFromItemCount(int items_count)
{
ImGuiContext& g = *GImGui;
if (items_count <= 0)
return FLT_MAX;
return (g.FontSize + g.Style.ItemSpacing.y) * items_count - g.Style.ItemSpacing.y + (g.Style.WindowPadding.y * 2);
}
bool ImGui::BeginCombo(const char* label, const char* preview_value, ImGuiComboFlags flags)
{
// Always consume the SetNextWindowSizeConstraint() call in our early return paths
ImGuiContext& g = *GImGui;
ImGuiCond backup_next_window_size_constraint = g.NextWindowData.SizeConstraintCond;
g.NextWindowData.SizeConstraintCond = 0;
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
IM_ASSERT((flags & (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)) != (ImGuiComboFlags_NoArrowButton | ImGuiComboFlags_NoPreview)); // Can't use both flags together
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
const float arrow_size = (flags & ImGuiComboFlags_NoArrowButton) ? 0.0f : GetFrameHeight();
const ImVec2 label_size = CalcTextSize(label, NULL, true);
const float w = (flags & ImGuiComboFlags_NoPreview) ? arrow_size : CalcItemWidth();
const ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + ImVec2(w, label_size.y + style.FramePadding.y*2.0f));
const ImRect total_bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
ItemSize(total_bb, style.FramePadding.y);
if (!ItemAdd(total_bb, id, &frame_bb))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(frame_bb, id, &hovered, &held);
bool popup_open = IsPopupOpen(id);
const ImRect value_bb(frame_bb.Min, frame_bb.Max - ImVec2(arrow_size, 0.0f));
const ImU32 frame_col = GetColorU32(hovered ? ImGuiCol_FrameBgHovered : ImGuiCol_FrameBg);
RenderNavHighlight(frame_bb, id);
if (!(flags & ImGuiComboFlags_NoPreview))
window->DrawList->AddRectFilled(frame_bb.Min, ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Max.y), frame_col, style.FrameRounding, ImDrawCornerFlags_Left);
if (!(flags & ImGuiComboFlags_NoArrowButton))
{
window->DrawList->AddRectFilled(ImVec2(frame_bb.Max.x - arrow_size, frame_bb.Min.y), frame_bb.Max, GetColorU32((popup_open || hovered) ? ImGuiCol_ButtonHovered : ImGuiCol_Button), style.FrameRounding, (w <= arrow_size) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Right);
RenderArrow(ImVec2(frame_bb.Max.x - arrow_size + style.FramePadding.y, frame_bb.Min.y + style.FramePadding.y), ImGuiDir_Down);
}
RenderFrameBorder(frame_bb.Min, frame_bb.Max, style.FrameRounding);
if (preview_value != NULL && !(flags & ImGuiComboFlags_NoPreview))
RenderTextClipped(frame_bb.Min + style.FramePadding, value_bb.Max, preview_value, NULL, NULL, ImVec2(0.0f,0.0f));
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
if ((pressed || g.NavActivateId == id) && !popup_open)
{
if (window->DC.NavLayerCurrent == 0)
window->NavLastIds[0] = id;
OpenPopupEx(id);
popup_open = true;
}
if (!popup_open)
return false;
if (backup_next_window_size_constraint)
{
g.NextWindowData.SizeConstraintCond = backup_next_window_size_constraint;
g.NextWindowData.SizeConstraintRect.Min.x = ImMax(g.NextWindowData.SizeConstraintRect.Min.x, w);
}
else
{
if ((flags & ImGuiComboFlags_HeightMask_) == 0)
flags |= ImGuiComboFlags_HeightRegular;
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiComboFlags_HeightMask_)); // Only one
int popup_max_height_in_items = -1;
if (flags & ImGuiComboFlags_HeightRegular) popup_max_height_in_items = 8;
else if (flags & ImGuiComboFlags_HeightSmall) popup_max_height_in_items = 4;
else if (flags & ImGuiComboFlags_HeightLarge) popup_max_height_in_items = 20;
SetNextWindowSizeConstraints(ImVec2(w, 0.0f), ImVec2(FLT_MAX, CalcMaxPopupHeightFromItemCount(popup_max_height_in_items)));
}
char name[16];
ImFormatString(name, IM_ARRAYSIZE(name), "##Combo_%02d", g.CurrentPopupStack.Size); // Recycle windows based on depth
// Peak into expected window size so we can position it
if (ImGuiWindow* popup_window = FindWindowByName(name))
if (popup_window->WasActive)
{
ImVec2 size_contents = CalcSizeContents(popup_window);
ImVec2 size_expected = CalcSizeAfterConstraint(popup_window, CalcSizeAutoFit(popup_window, size_contents));
if (flags & ImGuiComboFlags_PopupAlignLeft)
popup_window->AutoPosLastDirection = ImGuiDir_Left;
ImVec2 pos = FindBestWindowPosForPopup(frame_bb.GetBL(), size_expected, &popup_window->AutoPosLastDirection, frame_bb, ImGuiPopupPositionPolicy_ComboBox);
SetNextWindowPos(pos);
}
ImGuiWindowFlags window_flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_Popup | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings;
if (!Begin(name, NULL, window_flags))
{
EndPopup();
IM_ASSERT(0); // This should never happen as we tested for IsPopupOpen() above
return false;
}
// Horizontally align ourselves with the framed text
if (style.FramePadding.x != style.WindowPadding.x)
Indent(style.FramePadding.x - style.WindowPadding.x);
return true;
}
void ImGui::EndCombo()
{
const ImGuiStyle& style = GImGui->Style;
if (style.FramePadding.x != style.WindowPadding.x)
Unindent(style.FramePadding.x - style.WindowPadding.x);
EndPopup();
}
// Old API, prefer using BeginCombo() nowadays if you can.
bool ImGui::Combo(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int popup_max_height_in_items)
{
ImGuiContext& g = *GImGui;
const char* preview_text = NULL;
if (*current_item >= 0 && *current_item < items_count)
items_getter(data, *current_item, &preview_text);
// The old Combo() API exposed "popup_max_height_in_items", however the new more general BeginCombo() API doesn't, so we emulate it here.
if (popup_max_height_in_items != -1 && !g.NextWindowData.SizeConstraintCond)
{
float popup_max_height = CalcMaxPopupHeightFromItemCount(popup_max_height_in_items);
SetNextWindowSizeConstraints(ImVec2(0,0), ImVec2(FLT_MAX, popup_max_height));
}
if (!BeginCombo(label, preview_text, 0))
return false;
// Display items
// FIXME-OPT: Use clipper (but we need to disable it on the appearing frame to make sure our call to SetItemDefaultFocus() is processed)
bool value_changed = false;
for (int i = 0; i < items_count; i++)
{
PushID((void*)(intptr_t)i);
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
if (Selectable(item_text, item_selected))
{
value_changed = true;
*current_item = i;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
EndCombo();
return value_changed;
}
static bool Items_ArrayGetter(void* data, int idx, const char** out_text)
{
const char* const* items = (const char* const*)data;
if (out_text)
*out_text = items[idx];
return true;
}
static bool Items_SingleStringGetter(void* data, int idx, const char** out_text)
{
// FIXME-OPT: we could pre-compute the indices to fasten this. But only 1 active combo means the waste is limited.
const char* items_separated_by_zeros = (const char*)data;
int items_count = 0;
const char* p = items_separated_by_zeros;
while (*p)
{
if (idx == items_count)
break;
p += strlen(p) + 1;
items_count++;
}
if (!*p)
return false;
if (out_text)
*out_text = p;
return true;
}
// Combo box helper allowing to pass an array of strings.
bool ImGui::Combo(const char* label, int* current_item, const char* const items[], int items_count, int height_in_items)
{
const bool value_changed = Combo(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_in_items);
return value_changed;
}
// Combo box helper allowing to pass all items in a single string.
bool ImGui::Combo(const char* label, int* current_item, const char* items_separated_by_zeros, int height_in_items)
{
int items_count = 0;
const char* p = items_separated_by_zeros; // FIXME-OPT: Avoid computing this, or at least only when combo is open
while (*p)
{
p += strlen(p) + 1;
items_count++;
}
bool value_changed = Combo(label, current_item, Items_SingleStringGetter, (void*)items_separated_by_zeros, items_count, height_in_items);
return value_changed;
}
// Tip: pass an empty label (e.g. "##dummy") then you can use the space to draw other text or image.
// But you need to make sure the ID is unique, e.g. enclose calls in PushID/PopID.
bool ImGui::Selectable(const char* label, bool selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet) // FIXME-OPT: Avoid if vertically clipped.
PopClipRect();
ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImVec2 size(size_arg.x != 0.0f ? size_arg.x : label_size.x, size_arg.y != 0.0f ? size_arg.y : label_size.y);
ImVec2 pos = window->DC.CursorPos;
pos.y += window->DC.CurrentLineTextBaseOffset;
ImRect bb(pos, pos + size);
ItemSize(bb);
// Fill horizontal space.
ImVec2 window_padding = window->WindowPadding;
float max_x = (flags & ImGuiSelectableFlags_SpanAllColumns) ? GetWindowContentRegionMax().x : GetContentRegionMax().x;
float w_draw = ImMax(label_size.x, window->Pos.x + max_x - window_padding.x - window->DC.CursorPos.x);
ImVec2 size_draw((size_arg.x != 0 && !(flags & ImGuiSelectableFlags_DrawFillAvailWidth)) ? size_arg.x : w_draw, size_arg.y != 0.0f ? size_arg.y : size.y);
ImRect bb_with_spacing(pos, pos + size_draw);
if (size_arg.x == 0.0f || (flags & ImGuiSelectableFlags_DrawFillAvailWidth))
bb_with_spacing.Max.x += window_padding.x;
// Selectables are tightly packed together, we extend the box to cover spacing between selectable.
float spacing_L = (float)(int)(style.ItemSpacing.x * 0.5f);
float spacing_U = (float)(int)(style.ItemSpacing.y * 0.5f);
float spacing_R = style.ItemSpacing.x - spacing_L;
float spacing_D = style.ItemSpacing.y - spacing_U;
bb_with_spacing.Min.x -= spacing_L;
bb_with_spacing.Min.y -= spacing_U;
bb_with_spacing.Max.x += spacing_R;
bb_with_spacing.Max.y += spacing_D;
if (!ItemAdd(bb_with_spacing, (flags & ImGuiSelectableFlags_Disabled) ? 0 : id))
{
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
PushColumnClipRect();
return false;
}
ImGuiButtonFlags button_flags = 0;
if (flags & ImGuiSelectableFlags_Menu) button_flags |= ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_NoHoldingActiveID;
if (flags & ImGuiSelectableFlags_MenuItem) button_flags |= ImGuiButtonFlags_PressedOnRelease;
if (flags & ImGuiSelectableFlags_Disabled) button_flags |= ImGuiButtonFlags_Disabled;
if (flags & ImGuiSelectableFlags_AllowDoubleClick) button_flags |= ImGuiButtonFlags_PressedOnClickRelease | ImGuiButtonFlags_PressedOnDoubleClick;
bool hovered, held;
bool pressed = ButtonBehavior(bb_with_spacing, id, &hovered, &held, button_flags);
if (flags & ImGuiSelectableFlags_Disabled)
selected = false;
// Hovering selectable with mouse updates NavId accordingly so navigation can be resumed with gamepad/keyboard (this doesn't happen on most widgets)
if (pressed || hovered)// && (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f))
if (!g.NavDisableMouseHover && g.NavWindow == window && g.NavLayer == window->DC.NavLayerActiveMask)
{
g.NavDisableHighlight = true;
SetNavID(id, window->DC.NavLayerCurrent);
}
// Render
if (hovered || selected)
{
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
RenderFrame(bb_with_spacing.Min, bb_with_spacing.Max, col, false, 0.0f);
RenderNavHighlight(bb_with_spacing, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
}
if ((flags & ImGuiSelectableFlags_SpanAllColumns) && window->DC.ColumnsSet)
{
PushColumnClipRect();
bb_with_spacing.Max.x -= (GetContentRegionMax().x - max_x);
}
if (flags & ImGuiSelectableFlags_Disabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderTextClipped(bb.Min, bb_with_spacing.Max, label, NULL, &label_size, ImVec2(0.0f,0.0f));
if (flags & ImGuiSelectableFlags_Disabled) PopStyleColor();
// Automatically close popups
if (pressed && (window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiSelectableFlags_DontClosePopups) && !(window->DC.ItemFlags & ImGuiItemFlags_SelectableDontClosePopup))
CloseCurrentPopup();
return pressed;
}
bool ImGui::Selectable(const char* label, bool* p_selected, ImGuiSelectableFlags flags, const ImVec2& size_arg)
{
if (Selectable(label, *p_selected, flags, size_arg))
{
*p_selected = !*p_selected;
return true;
}
return false;
}
// Helper to calculate the size of a listbox and display a label on the right.
// Tip: To have a list filling the entire window width, PushItemWidth(-1) and pass an empty label "##empty"
bool ImGui::ListBoxHeader(const char* label, const ImVec2& size_arg)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
const ImGuiStyle& style = GetStyle();
const ImGuiID id = GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true);
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
ImVec2 size = CalcItemSize(size_arg, CalcItemWidth(), GetTextLineHeightWithSpacing() * 7.4f + style.ItemSpacing.y);
ImVec2 frame_size = ImVec2(size.x, ImMax(size.y, label_size.y));
ImRect frame_bb(window->DC.CursorPos, window->DC.CursorPos + frame_size);
ImRect bb(frame_bb.Min, frame_bb.Max + ImVec2(label_size.x > 0.0f ? style.ItemInnerSpacing.x + label_size.x : 0.0f, 0.0f));
window->DC.LastItemRect = bb; // Forward storage for ListBoxFooter.. dodgy.
BeginGroup();
if (label_size.x > 0)
RenderText(ImVec2(frame_bb.Max.x + style.ItemInnerSpacing.x, frame_bb.Min.y + style.FramePadding.y), label);
BeginChildFrame(id, frame_bb.GetSize());
return true;
}
bool ImGui::ListBoxHeader(const char* label, int items_count, int height_in_items)
{
// Size default to hold ~7 items. Fractional number of items helps seeing that we can scroll down/up without looking at scrollbar.
// However we don't add +0.40f if items_count <= height_in_items. It is slightly dodgy, because it means a dynamic list of items will make the widget resize occasionally when it crosses that size.
// I am expecting that someone will come and complain about this behavior in a remote future, then we can advise on a better solution.
if (height_in_items < 0)
height_in_items = ImMin(items_count, 7);
float height_in_items_f = height_in_items < items_count ? (height_in_items + 0.40f) : (height_in_items + 0.00f);
// We include ItemSpacing.y so that a list sized for the exact number of items doesn't make a scrollbar appears. We could also enforce that by passing a flag to BeginChild().
ImVec2 size;
size.x = 0.0f;
size.y = GetTextLineHeightWithSpacing() * height_in_items_f + GetStyle().ItemSpacing.y;
return ListBoxHeader(label, size);
}
void ImGui::ListBoxFooter()
{
ImGuiWindow* parent_window = GetCurrentWindow()->ParentWindow;
const ImRect bb = parent_window->DC.LastItemRect;
const ImGuiStyle& style = GetStyle();
EndChildFrame();
// Redeclare item size so that it includes the label (we have stored the full size in LastItemRect)
// We call SameLine() to restore DC.CurrentLine* data
SameLine();
parent_window->DC.CursorPos = bb.Min;
ItemSize(bb, style.FramePadding.y);
EndGroup();
}
bool ImGui::ListBox(const char* label, int* current_item, const char* const items[], int items_count, int height_items)
{
const bool value_changed = ListBox(label, current_item, Items_ArrayGetter, (void*)items, items_count, height_items);
return value_changed;
}
bool ImGui::ListBox(const char* label, int* current_item, bool (*items_getter)(void*, int, const char**), void* data, int items_count, int height_in_items)
{
if (!ListBoxHeader(label, items_count, height_in_items))
return false;
// Assume all items have even height (= 1 line of text). If you need items of different or variable sizes you can create a custom version of ListBox() in your code without using the clipper.
bool value_changed = false;
ImGuiListClipper clipper(items_count, GetTextLineHeightWithSpacing()); // We know exactly our line height here so we pass it as a minor optimization, but generally you don't need to.
while (clipper.Step())
for (int i = clipper.DisplayStart; i < clipper.DisplayEnd; i++)
{
const bool item_selected = (i == *current_item);
const char* item_text;
if (!items_getter(data, i, &item_text))
item_text = "*Unknown item*";
PushID(i);
if (Selectable(item_text, item_selected))
{
*current_item = i;
value_changed = true;
}
if (item_selected)
SetItemDefaultFocus();
PopID();
}
ListBoxFooter();
return value_changed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool selected, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImVec2 pos = window->DC.CursorPos;
ImVec2 label_size = CalcTextSize(label, NULL, true);
ImGuiSelectableFlags flags = ImGuiSelectableFlags_MenuItem | (enabled ? 0 : ImGuiSelectableFlags_Disabled);
bool pressed;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Mimic the exact layout spacing of BeginMenu() to allow MenuItem() inside a menu bar, which is a little misleading but may be useful
// Note that in this situation we render neither the shortcut neither the selected tick mark
float w = label_size.x;
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
pressed = Selectable(label, false, flags, ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
ImVec2 shortcut_size = shortcut ? CalcTextSize(shortcut, NULL) : ImVec2(0.0f, 0.0f);
float w = window->MenuColumns.DeclColumns(label_size.x, shortcut_size.x, (float)(int)(g.FontSize * 1.20f)); // Feedback for next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, false, flags | ImGuiSelectableFlags_DrawFillAvailWidth, ImVec2(w, 0.0f));
if (shortcut_size.x > 0.0f)
{
PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderText(pos + ImVec2(window->MenuColumns.Pos[1] + extra_w, 0.0f), shortcut, NULL, false);
PopStyleColor();
}
if (selected)
RenderCheckMark(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.40f, g.FontSize * 0.134f * 0.5f), GetColorU32(enabled ? ImGuiCol_Text : ImGuiCol_TextDisabled), g.FontSize * 0.866f);
}
return pressed;
}
bool ImGui::MenuItem(const char* label, const char* shortcut, bool* p_selected, bool enabled)
{
if (MenuItem(label, shortcut, p_selected ? *p_selected : false, enabled))
{
if (p_selected)
*p_selected = !*p_selected;
return true;
}
return false;
}
bool ImGui::BeginMainMenuBar()
{
ImGuiContext& g = *GImGui;
SetNextWindowPos(ImVec2(0.0f, 0.0f));
SetNextWindowSize(ImVec2(g.IO.DisplaySize.x, g.FontBaseSize + g.Style.FramePadding.y * 2.0f));
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowMinSize, ImVec2(0,0));
if (!Begin("##MainMenuBar", NULL, ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoScrollbar|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_MenuBar)
|| !BeginMenuBar())
{
End();
PopStyleVar(2);
return false;
}
g.CurrentWindow->DC.MenuBarOffsetX += g.Style.DisplaySafeAreaPadding.x;
return true;
}
void ImGui::EndMainMenuBar()
{
EndMenuBar();
// When the user has left the menu layer (typically: closed menus through activation of an item), we restore focus to the previous window
ImGuiContext& g = *GImGui;
if (g.CurrentWindow == g.NavWindow && g.NavLayer == 0)
FocusFrontMostActiveWindow(g.NavWindow);
End();
PopStyleVar(2);
}
bool ImGui::BeginMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
if (!(window->Flags & ImGuiWindowFlags_MenuBar))
return false;
IM_ASSERT(!window->DC.MenuBarAppending);
BeginGroup(); // Save position
PushID("##menubar");
// We don't clip with regular window clipping rectangle as it is already set to the area below. However we clip with window full rect.
// We remove 1 worth of rounding to Max.x to that text in long menus don't tend to display over the lower-right rounded area, which looks particularly glitchy.
ImRect bar_rect = window->MenuBarRect();
ImRect clip_rect(ImFloor(bar_rect.Min.x + 0.5f), ImFloor(bar_rect.Min.y + window->WindowBorderSize + 0.5f), ImFloor(ImMax(bar_rect.Min.x, bar_rect.Max.x - window->WindowRounding) + 0.5f), ImFloor(bar_rect.Max.y + 0.5f));
clip_rect.ClipWith(window->WindowRectClipped);
PushClipRect(clip_rect.Min, clip_rect.Max, false);
window->DC.CursorPos = ImVec2(bar_rect.Min.x + window->DC.MenuBarOffsetX, bar_rect.Min.y);// + g.Style.FramePadding.y);
window->DC.LayoutType = ImGuiLayoutType_Horizontal;
window->DC.NavLayerCurrent++;
window->DC.NavLayerCurrentMask <<= 1;
window->DC.MenuBarAppending = true;
AlignTextToFramePadding();
return true;
}
void ImGui::EndMenuBar()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
// Nav: When a move request within one of our child menu failed, capture the request to navigate among our siblings.
if (NavMoveRequestButNoResultYet() && (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right) && (g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
{
ImGuiWindow* nav_earliest_child = g.NavWindow;
while (nav_earliest_child->ParentWindow && (nav_earliest_child->ParentWindow->Flags & ImGuiWindowFlags_ChildMenu))
nav_earliest_child = nav_earliest_child->ParentWindow;
if (nav_earliest_child->ParentWindow == window && nav_earliest_child->DC.ParentLayoutType == ImGuiLayoutType_Horizontal && g.NavMoveRequestForward == ImGuiNavForward_None)
{
// To do so we claim focus back, restore NavId and then process the movement request for yet another frame.
// This involve a one-frame delay which isn't very problematic in this situation. We could remove it by scoring in advance for multiple window (probably not worth the hassle/cost)
IM_ASSERT(window->DC.NavLayerActiveMaskNext & 0x02); // Sanity check
FocusWindow(window);
SetNavIDWithRectRel(window->NavLastIds[1], 1, window->NavRectRel[1]);
g.NavLayer = 1;
g.NavDisableHighlight = true; // Hide highlight for the current frame so we don't see the intermediary selection.
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
NavMoveRequestCancel();
}
}
IM_ASSERT(window->Flags & ImGuiWindowFlags_MenuBar);
IM_ASSERT(window->DC.MenuBarAppending);
PopClipRect();
PopID();
window->DC.MenuBarOffsetX = window->DC.CursorPos.x - window->MenuBarRect().Min.x;
window->DC.GroupStack.back().AdvanceCursor = false;
EndGroup();
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.NavLayerCurrent--;
window->DC.NavLayerCurrentMask >>= 1;
window->DC.MenuBarAppending = false;
}
bool ImGui::BeginMenu(const char* label, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(label, NULL, true);
bool pressed;
bool menu_is_open = IsPopupOpen(id);
bool menuset_is_open = !(window->Flags & ImGuiWindowFlags_Popup) && (g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].OpenParentId == window->IDStack.back());
ImGuiWindow* backed_nav_window = g.NavWindow;
if (menuset_is_open)
g.NavWindow = window; // Odd hack to allow hovering across menus of a same menu-set (otherwise we wouldn't be able to hover parent)
// The reference position stored in popup_pos will be used by Begin() to find a suitable position for the child menu (using FindBestPopupWindowPos).
ImVec2 popup_pos, pos = window->DC.CursorPos;
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
{
// Menu inside an horizontal menu bar
// Selectable extend their highlight by half ItemSpacing in each direction.
// For ChildMenu, the popup position will be overwritten by the call to FindBestPopupWindowPos() in Begin()
popup_pos = ImVec2(pos.x - window->WindowPadding.x, pos.y - style.FramePadding.y + window->MenuBarHeight());
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * 0.5f);
PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing * 2.0f);
float w = label_size.x;
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
PopStyleVar();
window->DC.CursorPos.x += (float)(int)(style.ItemSpacing.x * (-1.0f + 0.5f)); // -1 spacing to compensate the spacing added when Selectable() did a SameLine(). It would also work to call SameLine() ourselves after the PopStyleVar().
}
else
{
// Menu inside a menu
popup_pos = ImVec2(pos.x, pos.y - style.WindowPadding.y);
float w = window->MenuColumns.DeclColumns(label_size.x, 0.0f, (float)(int)(g.FontSize * 1.20f)); // Feedback to next frame
float extra_w = ImMax(0.0f, GetContentRegionAvail().x - w);
pressed = Selectable(label, menu_is_open, ImGuiSelectableFlags_Menu | ImGuiSelectableFlags_DontClosePopups | ImGuiSelectableFlags_DrawFillAvailWidth | (!enabled ? ImGuiSelectableFlags_Disabled : 0), ImVec2(w, 0.0f));
if (!enabled) PushStyleColor(ImGuiCol_Text, g.Style.Colors[ImGuiCol_TextDisabled]);
RenderArrow(pos + ImVec2(window->MenuColumns.Pos[2] + extra_w + g.FontSize * 0.30f, 0.0f), ImGuiDir_Right);
if (!enabled) PopStyleColor();
}
const bool hovered = enabled && ItemHoverable(window->DC.LastItemRect, id);
if (menuset_is_open)
g.NavWindow = backed_nav_window;
bool want_open = false, want_close = false;
if (window->DC.LayoutType == ImGuiLayoutType_Vertical) // (window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu))
{
// Implement http://bjk5.com/post/44698559168/breaking-down-amazons-mega-dropdown to avoid using timers, so menus feels more reactive.
bool moving_within_opened_triangle = false;
if (g.HoveredWindow == window && g.OpenPopupStack.Size > g.CurrentPopupStack.Size && g.OpenPopupStack[g.CurrentPopupStack.Size].ParentWindow == window && !(window->Flags & ImGuiWindowFlags_MenuBar))
{
if (ImGuiWindow* next_window = g.OpenPopupStack[g.CurrentPopupStack.Size].Window)
{
ImRect next_window_rect = next_window->Rect();
ImVec2 ta = g.IO.MousePos - g.IO.MouseDelta;
ImVec2 tb = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetTL() : next_window_rect.GetTR();
ImVec2 tc = (window->Pos.x < next_window->Pos.x) ? next_window_rect.GetBL() : next_window_rect.GetBR();
float extra = ImClamp(fabsf(ta.x - tb.x) * 0.30f, 5.0f, 30.0f); // add a bit of extra slack.
ta.x += (window->Pos.x < next_window->Pos.x) ? -0.5f : +0.5f; // to avoid numerical issues
tb.y = ta.y + ImMax((tb.y - extra) - ta.y, -100.0f); // triangle is maximum 200 high to limit the slope and the bias toward large sub-menus // FIXME: Multiply by fb_scale?
tc.y = ta.y + ImMin((tc.y + extra) - ta.y, +100.0f);
moving_within_opened_triangle = ImTriangleContainsPoint(ta, tb, tc, g.IO.MousePos);
//window->DrawList->PushClipRectFullScreen(); window->DrawList->AddTriangleFilled(ta, tb, tc, moving_within_opened_triangle ? IM_COL32(0,128,0,128) : IM_COL32(128,0,0,128)); window->DrawList->PopClipRect(); // Debug
}
}
want_close = (menu_is_open && !hovered && g.HoveredWindow == window && g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrame != id && !moving_within_opened_triangle);
want_open = (!menu_is_open && hovered && !moving_within_opened_triangle) || (!menu_is_open && hovered && pressed);
if (g.NavActivateId == id)
{
want_close = menu_is_open;
want_open = !menu_is_open;
}
if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Right) // Nav-Right to open
{
want_open = true;
NavMoveRequestCancel();
}
}
else
{
// Menu bar
if (menu_is_open && pressed && menuset_is_open) // Click an open menu again to close it
{
want_close = true;
want_open = menu_is_open = false;
}
else if (pressed || (hovered && menuset_is_open && !menu_is_open)) // First click to open, then hover to open others
{
want_open = true;
}
else if (g.NavId == id && g.NavMoveRequest && g.NavMoveDir == ImGuiDir_Down) // Nav-Down to open
{
want_open = true;
NavMoveRequestCancel();
}
}
if (!enabled) // explicitly close if an open menu becomes disabled, facilitate users code a lot in pattern such as 'if (BeginMenu("options", has_object)) { ..use object.. }'
want_close = true;
if (want_close && IsPopupOpen(id))
ClosePopupToLevel(g.CurrentPopupStack.Size);
if (!menu_is_open && want_open && g.OpenPopupStack.Size > g.CurrentPopupStack.Size)
{
// Don't recycle same menu level in the same frame, first close the other menu and yield for a frame.
OpenPopup(label);
return false;
}
menu_is_open |= want_open;
if (want_open)
OpenPopup(label);
if (menu_is_open)
{
SetNextWindowPos(popup_pos, ImGuiCond_Always);
ImGuiWindowFlags flags = ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ((window->Flags & (ImGuiWindowFlags_Popup|ImGuiWindowFlags_ChildMenu)) ? ImGuiWindowFlags_ChildMenu|ImGuiWindowFlags_ChildWindow : ImGuiWindowFlags_ChildMenu);
menu_is_open = BeginPopupEx(id, flags); // menu_is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
}
return menu_is_open;
}
void ImGui::EndMenu()
{
// Nav: When a left move request _within our child menu_ failed, close the menu.
// A menu doesn't close itself because EndMenuBar() wants the catch the last Left<>Right inputs.
// However it means that with the current code, a BeginMenu() from outside another menu or a menu-bar won't be closable with the Left direction.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavWindow && g.NavWindow->ParentWindow == window && g.NavMoveDir == ImGuiDir_Left && NavMoveRequestButNoResultYet() && window->DC.LayoutType == ImGuiLayoutType_Vertical)
{
ClosePopupToLevel(g.OpenPopupStack.Size - 1);
NavMoveRequestCancel();
}
EndPopup();
}
// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
void ImGui::ColorTooltip(const char* text, const float* col, ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
BeginTooltipEx(0, true);
const char* text_end = text ? FindRenderedTextEnd(text, NULL) : text;
if (text_end > text)
{
TextUnformatted(text, text_end);
Separator();
}
ImVec2 sz(g.FontSize * 3 + g.Style.FramePadding.y * 2, g.FontSize * 3 + g.Style.FramePadding.y * 2);
ColorButton("##preview", ImVec4(col[0], col[1], col[2], col[3]), (flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf)) | ImGuiColorEditFlags_NoTooltip, sz);
SameLine();
if (flags & ImGuiColorEditFlags_NoAlpha)
Text("#%02X%02X%02X\nR: %d, G: %d, B: %d\n(%.3f, %.3f, %.3f)", cr, cg, cb, cr, cg, cb, col[0], col[1], col[2]);
else
Text("#%02X%02X%02X%02X\nR:%d, G:%d, B:%d, A:%d\n(%.3f, %.3f, %.3f, %.3f)", cr, cg, cb, ca, cr, cg, cb, ca, col[0], col[1], col[2], col[3]);
EndTooltip();
}
static inline ImU32 ImAlphaBlendColor(ImU32 col_a, ImU32 col_b)
{
float t = ((col_b >> IM_COL32_A_SHIFT) & 0xFF) / 255.f;
int r = ImLerp((int)(col_a >> IM_COL32_R_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_R_SHIFT) & 0xFF, t);
int g = ImLerp((int)(col_a >> IM_COL32_G_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_G_SHIFT) & 0xFF, t);
int b = ImLerp((int)(col_a >> IM_COL32_B_SHIFT) & 0xFF, (int)(col_b >> IM_COL32_B_SHIFT) & 0xFF, t);
return IM_COL32(r, g, b, 0xFF);
}
// 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.
// I 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 alltogether.
void ImGui::RenderColorRectWithAlphaCheckerboard(ImVec2 p_min, ImVec2 p_max, ImU32 col, float grid_step, ImVec2 grid_off, float rounding, int rounding_corners_flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (((col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT) < 0xFF)
{
ImU32 col_bg1 = GetColorU32(ImAlphaBlendColor(IM_COL32(204,204,204,255), col));
ImU32 col_bg2 = GetColorU32(ImAlphaBlendColor(IM_COL32(128,128,128,255), col));
window->DrawList->AddRectFilled(p_min, p_max, col_bg1, rounding, rounding_corners_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;
int rounding_corners_flags_cell = 0;
if (y1 <= p_min.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_TopRight; }
if (y2 >= p_max.y) { if (x1 <= p_min.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotLeft; if (x2 >= p_max.x) rounding_corners_flags_cell |= ImDrawCornerFlags_BotRight; }
rounding_corners_flags_cell &= rounding_corners_flags;
window->DrawList->AddRectFilled(ImVec2(x1,y1), ImVec2(x2,y2), col_bg2, rounding_corners_flags_cell ? rounding : 0.0f, rounding_corners_flags_cell);
}
}
}
else
{
window->DrawList->AddRectFilled(p_min, p_max, col, rounding, rounding_corners_flags);
}
}
void ImGui::SetColorEditOptions(ImGuiColorEditFlags flags)
{
ImGuiContext& g = *GImGui;
if ((flags & ImGuiColorEditFlags__InputsMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__InputsMask;
if ((flags & ImGuiColorEditFlags__DataTypeMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__DataTypeMask;
if ((flags & ImGuiColorEditFlags__PickerMask) == 0)
flags |= ImGuiColorEditFlags__OptionsDefault & ImGuiColorEditFlags__PickerMask;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__InputsMask))); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__DataTypeMask))); // Check only 1 option is selected
IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check only 1 option is selected
g.ColorEditOptions = flags;
}
// A little colored square. Return true when clicked.
// FIXME: May want to display/ignore the alpha component in the color display? Yet show it in the tooltip.
// 'desc_id' is not called 'label' because we don't display it next to the button, but only in the tooltip.
bool ImGui::ColorButton(const char* desc_id, const ImVec4& col, ImGuiColorEditFlags flags, ImVec2 size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiID id = window->GetID(desc_id);
float default_size = GetFrameHeight();
if (size.x == 0.0f)
size.x = default_size;
if (size.y == 0.0f)
size.y = default_size;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb, (size.y >= default_size) ? g.Style.FramePadding.y : 0.0f);
if (!ItemAdd(bb, id))
return false;
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held);
if (flags & ImGuiColorEditFlags_NoAlpha)
flags &= ~(ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf);
ImVec4 col_without_alpha(col.x, col.y, col.z, 1.0f);
float grid_step = ImMin(size.x, size.y) / 2.99f;
float rounding = ImMin(g.Style.FrameRounding, grid_step * 0.5f);
ImRect bb_inner = bb;
float off = -0.75f; // The border (using Col_FrameBg) tends to look off when color is near-opaque and rounding is enabled. This offset seemed like a good middle ground to reduce those artifacts.
bb_inner.Expand(off);
if ((flags & ImGuiColorEditFlags_AlphaPreviewHalf) && col.w < 1.0f)
{
float mid_x = (float)(int)((bb_inner.Min.x + bb_inner.Max.x) * 0.5f + 0.5f);
RenderColorRectWithAlphaCheckerboard(ImVec2(bb_inner.Min.x + grid_step, bb_inner.Min.y), bb_inner.Max, GetColorU32(col), grid_step, ImVec2(-grid_step + off, off), rounding, ImDrawCornerFlags_TopRight| ImDrawCornerFlags_BotRight);
window->DrawList->AddRectFilled(bb_inner.Min, ImVec2(mid_x, bb_inner.Max.y), GetColorU32(col_without_alpha), rounding, ImDrawCornerFlags_TopLeft|ImDrawCornerFlags_BotLeft);
}
else
{
// Because GetColorU32() multiplies by the global style Alpha and we don't want to display a checkerboard if the source code had no alpha
ImVec4 col_source = (flags & ImGuiColorEditFlags_AlphaPreview) ? col : col_without_alpha;
if (col_source.w < 1.0f)
RenderColorRectWithAlphaCheckerboard(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), grid_step, ImVec2(off, off), rounding);
else
window->DrawList->AddRectFilled(bb_inner.Min, bb_inner.Max, GetColorU32(col_source), rounding, ImDrawCornerFlags_All);
}
RenderNavHighlight(bb, id);
if (g.Style.FrameBorderSize > 0.0f)
RenderFrameBorder(bb.Min, bb.Max, rounding);
else
window->DrawList->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_FrameBg), rounding); // Color button are often in need of some sort of border
// Drag and Drop Source
if (g.ActiveId == id && BeginDragDropSource()) // NB: The ActiveId test is merely an optional micro-optimization
{
if (flags & ImGuiColorEditFlags_NoAlpha)
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F, &col, sizeof(float) * 3, ImGuiCond_Once);
else
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F, &col, sizeof(float) * 4, ImGuiCond_Once);
ColorButton(desc_id, col, flags);
SameLine();
TextUnformatted("Color");
EndDragDropSource();
hovered = false;
}
// Tooltip
if (!(flags & ImGuiColorEditFlags_NoTooltip) && hovered)
ColorTooltip(desc_id, &col.x, flags & (ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf));
return pressed;
}
bool ImGui::ColorEdit3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
return ColorEdit4(label, col, flags | ImGuiColorEditFlags_NoAlpha);
}
void ImGui::ColorEditOptionsPopup(const float* col, ImGuiColorEditFlags flags)
{
bool allow_opt_inputs = !(flags & ImGuiColorEditFlags__InputsMask);
bool allow_opt_datatype = !(flags & ImGuiColorEditFlags__DataTypeMask);
if ((!allow_opt_inputs && !allow_opt_datatype) || !BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
ImGuiColorEditFlags opts = g.ColorEditOptions;
if (allow_opt_inputs)
{
if (RadioButton("RGB", (opts & ImGuiColorEditFlags_RGB) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_RGB;
if (RadioButton("HSV", (opts & ImGuiColorEditFlags_HSV) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HSV;
if (RadioButton("HEX", (opts & ImGuiColorEditFlags_HEX) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__InputsMask) | ImGuiColorEditFlags_HEX;
}
if (allow_opt_datatype)
{
if (allow_opt_inputs) Separator();
if (RadioButton("0..255", (opts & ImGuiColorEditFlags_Uint8) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Uint8;
if (RadioButton("0.00..1.00", (opts & ImGuiColorEditFlags_Float) ? 1 : 0)) opts = (opts & ~ImGuiColorEditFlags__DataTypeMask) | ImGuiColorEditFlags_Float;
}
if (allow_opt_inputs || allow_opt_datatype)
Separator();
if (Button("Copy as..", ImVec2(-1,0)))
OpenPopup("Copy");
if (BeginPopup("Copy"))
{
int cr = IM_F32_TO_INT8_SAT(col[0]), cg = IM_F32_TO_INT8_SAT(col[1]), cb = IM_F32_TO_INT8_SAT(col[2]), ca = (flags & ImGuiColorEditFlags_NoAlpha) ? 255 : IM_F32_TO_INT8_SAT(col[3]);
char buf[64];
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%.3ff, %.3ff, %.3ff, %.3ff)", col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if (Selectable(buf))
SetClipboardText(buf);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%d,%d,%d,%d)", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
if (flags & ImGuiColorEditFlags_NoAlpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X", cr, cg, cb);
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "0x%02X%02X%02X%02X", cr, cg, cb, ca);
if (Selectable(buf))
SetClipboardText(buf);
EndPopup();
}
g.ColorEditOptions = opts;
EndPopup();
}
static void ColorPickerOptionsPopup(ImGuiColorEditFlags flags, const float* ref_col)
{
bool allow_opt_picker = !(flags & ImGuiColorEditFlags__PickerMask);
bool allow_opt_alpha_bar = !(flags & ImGuiColorEditFlags_NoAlpha) && !(flags & ImGuiColorEditFlags_AlphaBar);
if ((!allow_opt_picker && !allow_opt_alpha_bar) || !ImGui::BeginPopup("context"))
return;
ImGuiContext& g = *GImGui;
if (allow_opt_picker)
{
ImVec2 picker_size(g.FontSize * 8, ImMax(g.FontSize * 8 - (ImGui::GetFrameHeight() + g.Style.ItemInnerSpacing.x), 1.0f)); // FIXME: Picker size copied from main picker function
ImGui::PushItemWidth(picker_size.x);
for (int picker_type = 0; picker_type < 2; picker_type++)
{
// Draw small/thumbnail version of each picker type (over an invisible button for selection)
if (picker_type > 0) ImGui::Separator();
ImGui::PushID(picker_type);
ImGuiColorEditFlags picker_flags = ImGuiColorEditFlags_NoInputs|ImGuiColorEditFlags_NoOptions|ImGuiColorEditFlags_NoLabel|ImGuiColorEditFlags_NoSidePreview|(flags & ImGuiColorEditFlags_NoAlpha);
if (picker_type == 0) picker_flags |= ImGuiColorEditFlags_PickerHueBar;
if (picker_type == 1) picker_flags |= ImGuiColorEditFlags_PickerHueWheel;
ImVec2 backup_pos = ImGui::GetCursorScreenPos();
if (ImGui::Selectable("##selectable", false, 0, picker_size)) // By default, Selectable() is closing popup
g.ColorEditOptions = (g.ColorEditOptions & ~ImGuiColorEditFlags__PickerMask) | (picker_flags & ImGuiColorEditFlags__PickerMask);
ImGui::SetCursorScreenPos(backup_pos);
ImVec4 dummy_ref_col;
memcpy(&dummy_ref_col.x, ref_col, sizeof(float) * (picker_flags & ImGuiColorEditFlags_NoAlpha ? 3 : 4));
ImGui::ColorPicker4("##dummypicker", &dummy_ref_col.x, picker_flags);
ImGui::PopID();
}
ImGui::PopItemWidth();
}
if (allow_opt_alpha_bar)
{
if (allow_opt_picker) ImGui::Separator();
ImGui::CheckboxFlags("Alpha Bar", (unsigned int*)&g.ColorEditOptions, ImGuiColorEditFlags_AlphaBar);
}
ImGui::EndPopup();
}
// Edit colors components (each component in 0.0f..1.0f range).
// See enum ImGuiColorEditFlags_ for available options. e.g. Only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// With typical options: Left-click on colored square to open color picker. Right-click to open option menu. CTRL-Click over input fields to edit them and TAB to go to next item.
bool ImGui::ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return false;
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
const float square_sz = GetFrameHeight();
const float w_extra = (flags & ImGuiColorEditFlags_NoSmallPreview) ? 0.0f : (square_sz + style.ItemInnerSpacing.x);
const float w_items_all = CalcItemWidth() - w_extra;
const char* label_display_end = FindRenderedTextEnd(label);
const bool alpha = (flags & ImGuiColorEditFlags_NoAlpha) == 0;
const bool hdr = (flags & ImGuiColorEditFlags_HDR) != 0;
const int components = alpha ? 4 : 3;
const ImGuiColorEditFlags flags_untouched = flags;
BeginGroup();
PushID(label);
// If we're not showing any slider there's no point in doing any HSV conversions
if (flags & ImGuiColorEditFlags_NoInputs)
flags = (flags & (~ImGuiColorEditFlags__InputsMask)) | ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_NoOptions;
// Context menu: display and modify options (before defaults are applied)
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorEditOptionsPopup(col, flags);
// Read stored options
if (!(flags & ImGuiColorEditFlags__InputsMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__InputsMask);
if (!(flags & ImGuiColorEditFlags__DataTypeMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__DataTypeMask);
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags__PickerMask);
flags |= (g.ColorEditOptions & ~(ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask));
// Convert to the formats we need
float f[4] = { col[0], col[1], col[2], alpha ? col[3] : 1.0f };
if (flags & ImGuiColorEditFlags_HSV)
ColorConvertRGBtoHSV(f[0], f[1], f[2], f[0], f[1], f[2]);
int i[4] = { IM_F32_TO_INT8_UNBOUND(f[0]), IM_F32_TO_INT8_UNBOUND(f[1]), IM_F32_TO_INT8_UNBOUND(f[2]), IM_F32_TO_INT8_UNBOUND(f[3]) };
bool value_changed = false;
bool value_changed_as_float = false;
if ((flags & (ImGuiColorEditFlags_RGB | ImGuiColorEditFlags_HSV)) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB/HSV 0..255 Sliders
const float w_item_one = ImMax(1.0f, (float)(int)((w_items_all - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_items_all - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
const bool hide_prefix = (w_item_one <= CalcTextSize((flags & ImGuiColorEditFlags_Float) ? "M:0.000" : "M:000").x);
const char* ids[4] = { "##X", "##Y", "##Z", "##W" };
const char* fmt_table_int[3][4] =
{
{ "%3.0f", "%3.0f", "%3.0f", "%3.0f" }, // Short display
{ "R:%3.0f", "G:%3.0f", "B:%3.0f", "A:%3.0f" }, // Long display for RGBA
{ "H:%3.0f", "S:%3.0f", "V:%3.0f", "A:%3.0f" } // Long display for HSVA
};
const char* fmt_table_float[3][4] =
{
{ "%0.3f", "%0.3f", "%0.3f", "%0.3f" }, // Short display
{ "R:%0.3f", "G:%0.3f", "B:%0.3f", "A:%0.3f" }, // Long display for RGBA
{ "H:%0.3f", "S:%0.3f", "V:%0.3f", "A:%0.3f" } // Long display for HSVA
};
const int fmt_idx = hide_prefix ? 0 : (flags & ImGuiColorEditFlags_HSV) ? 2 : 1;
PushItemWidth(w_item_one);
for (int n = 0; n < components; n++)
{
if (n > 0)
SameLine(0, style.ItemInnerSpacing.x);
if (n + 1 == components)
PushItemWidth(w_item_last);
if (flags & ImGuiColorEditFlags_Float)
value_changed = value_changed_as_float = value_changed | DragFloat(ids[n], &f[n], 1.0f/255.0f, 0.0f, hdr ? 0.0f : 1.0f, fmt_table_float[fmt_idx][n]);
else
value_changed |= DragInt(ids[n], &i[n], 1.0f, 0, hdr ? 0 : 255, fmt_table_int[fmt_idx][n]);
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
PopItemWidth();
PopItemWidth();
}
else if ((flags & ImGuiColorEditFlags_HEX) != 0 && (flags & ImGuiColorEditFlags_NoInputs) == 0)
{
// RGB Hexadecimal Input
char buf[64];
if (alpha)
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255), ImClamp(i[3],0,255));
else
ImFormatString(buf, IM_ARRAYSIZE(buf), "#%02X%02X%02X", ImClamp(i[0],0,255), ImClamp(i[1],0,255), ImClamp(i[2],0,255));
PushItemWidth(w_items_all);
if (InputText("##Text", buf, IM_ARRAYSIZE(buf), ImGuiInputTextFlags_CharsHexadecimal | ImGuiInputTextFlags_CharsUppercase))
{
value_changed = true;
char* p = buf;
while (*p == '#' || ImCharIsSpace(*p))
p++;
i[0] = i[1] = i[2] = i[3] = 0;
if (alpha)
sscanf(p, "%02X%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2], (unsigned int*)&i[3]); // Treat at unsigned (%X is unsigned)
else
sscanf(p, "%02X%02X%02X", (unsigned int*)&i[0], (unsigned int*)&i[1], (unsigned int*)&i[2]);
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
PopItemWidth();
}
ImGuiWindow* picker_active_window = NULL;
if (!(flags & ImGuiColorEditFlags_NoSmallPreview))
{
if (!(flags & ImGuiColorEditFlags_NoInputs))
SameLine(0, style.ItemInnerSpacing.x);
const ImVec4 col_v4(col[0], col[1], col[2], alpha ? col[3] : 1.0f);
if (ColorButton("##ColorButton", col_v4, flags))
{
if (!(flags & ImGuiColorEditFlags_NoPicker))
{
// Store current color and open a picker
g.ColorPickerRef = col_v4;
OpenPopup("picker");
SetNextWindowPos(window->DC.LastItemRect.GetBL() + ImVec2(-1,style.ItemSpacing.y));
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
if (BeginPopup("picker"))
{
picker_active_window = g.CurrentWindow;
if (label != label_display_end)
{
TextUnformatted(label, label_display_end);
Separator();
}
ImGuiColorEditFlags picker_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags__PickerMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_AlphaBar;
ImGuiColorEditFlags picker_flags = (flags_untouched & picker_flags_to_forward) | ImGuiColorEditFlags__InputsMask | ImGuiColorEditFlags_NoLabel | ImGuiColorEditFlags_AlphaPreviewHalf;
PushItemWidth(square_sz * 12.0f); // Use 256 + bar sizes?
value_changed |= ColorPicker4("##picker", col, picker_flags, &g.ColorPickerRef.x);
PopItemWidth();
EndPopup();
}
}
if (label != label_display_end && !(flags & ImGuiColorEditFlags_NoLabel))
{
SameLine(0, style.ItemInnerSpacing.x);
TextUnformatted(label, label_display_end);
}
// Convert back
if (picker_active_window == NULL)
{
if (!value_changed_as_float)
for (int n = 0; n < 4; n++)
f[n] = i[n] / 255.0f;
if (flags & ImGuiColorEditFlags_HSV)
ColorConvertHSVtoRGB(f[0], f[1], f[2], f[0], f[1], f[2]);
if (value_changed)
{
col[0] = f[0];
col[1] = f[1];
col[2] = f[2];
if (alpha)
col[3] = f[3];
}
}
PopID();
EndGroup();
// Drag and Drop Target
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) && BeginDragDropTarget()) // NB: The flag test is merely an optional micro-optimization, BeginDragDropTarget() does the same test.
{
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_3F))
{
memcpy((float*)col, payload->Data, sizeof(float) * 3);
value_changed = true;
}
if (const ImGuiPayload* payload = AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_COLOR_4F))
{
memcpy((float*)col, payload->Data, sizeof(float) * components);
value_changed = true;
}
EndDragDropTarget();
}
// When picker is being actively used, use its active id so IsItemActive() will function on ColorEdit4().
if (picker_active_window && g.ActiveId != 0 && g.ActiveIdWindow == picker_active_window)
window->DC.LastItemId = g.ActiveId;
return value_changed;
}
bool ImGui::ColorPicker3(const char* label, float col[3], ImGuiColorEditFlags flags)
{
float col4[4] = { col[0], col[1], col[2], 1.0f };
if (!ColorPicker4(label, col4, flags | ImGuiColorEditFlags_NoAlpha))
return false;
col[0] = col4[0]; col[1] = col4[1]; col[2] = col4[2];
return true;
}
// 'pos' is position of the arrow tip. half_sz.x is length from base to tip. half_sz.y is length on each side.
static void RenderArrow(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 void RenderArrowsForVerticalBar(ImDrawList* draw_list, ImVec2 pos, ImVec2 half_sz, float bar_w)
{
RenderArrow(draw_list, ImVec2(pos.x + half_sz.x + 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Right, IM_COL32_BLACK);
RenderArrow(draw_list, ImVec2(pos.x + half_sz.x, pos.y), half_sz, ImGuiDir_Right, IM_COL32_WHITE);
RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x - 1, pos.y), ImVec2(half_sz.x + 2, half_sz.y + 1), ImGuiDir_Left, IM_COL32_BLACK);
RenderArrow(draw_list, ImVec2(pos.x + bar_w - half_sz.x, pos.y), half_sz, ImGuiDir_Left, IM_COL32_WHITE);
}
// ColorPicker
// Note: only access 3 floats if ImGuiColorEditFlags_NoAlpha flag is set.
// FIXME: we adjust the big color square height based on item width, which may cause a flickering feedback loop (if automatic height makes a vertical scrollbar appears, affecting automatic width..)
bool ImGui::ColorPicker4(const char* label, float col[4], ImGuiColorEditFlags flags, const float* ref_col)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImDrawList* draw_list = window->DrawList;
ImGuiStyle& style = g.Style;
ImGuiIO& io = g.IO;
PushID(label);
BeginGroup();
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
flags |= ImGuiColorEditFlags_NoSmallPreview;
// Context menu: display and store options.
if (!(flags & ImGuiColorEditFlags_NoOptions))
ColorPickerOptionsPopup(flags, col);
// Read stored options
if (!(flags & ImGuiColorEditFlags__PickerMask))
flags |= ((g.ColorEditOptions & ImGuiColorEditFlags__PickerMask) ? g.ColorEditOptions : ImGuiColorEditFlags__OptionsDefault) & ImGuiColorEditFlags__PickerMask;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & ImGuiColorEditFlags__PickerMask))); // Check that only 1 is selected
if (!(flags & ImGuiColorEditFlags_NoOptions))
flags |= (g.ColorEditOptions & ImGuiColorEditFlags_AlphaBar);
// Setup
int components = (flags & ImGuiColorEditFlags_NoAlpha) ? 3 : 4;
bool alpha_bar = (flags & ImGuiColorEditFlags_AlphaBar) && !(flags & ImGuiColorEditFlags_NoAlpha);
ImVec2 picker_pos = window->DC.CursorPos;
float square_sz = GetFrameHeight();
float bars_width = square_sz; // Arbitrary smallish width of Hue/Alpha picking bars
float sv_picker_size = ImMax(bars_width * 1, CalcItemWidth() - (alpha_bar ? 2 : 1) * (bars_width + style.ItemInnerSpacing.x)); // Saturation/Value picking box
float bar0_pos_x = picker_pos.x + sv_picker_size + style.ItemInnerSpacing.x;
float bar1_pos_x = bar0_pos_x + bars_width + style.ItemInnerSpacing.x;
float bars_triangles_half_sz = (float)(int)(bars_width * 0.20f);
float backup_initial_col[4];
memcpy(backup_initial_col, col, components * sizeof(float));
float wheel_thickness = sv_picker_size * 0.08f;
float wheel_r_outer = sv_picker_size * 0.50f;
float wheel_r_inner = wheel_r_outer - wheel_thickness;
ImVec2 wheel_center(picker_pos.x + (sv_picker_size + bars_width)*0.5f, picker_pos.y + sv_picker_size*0.5f);
// Note: the triangle is displayed rotated with triangle_pa pointing to Hue, but most coordinates stays unrotated for logic.
float triangle_r = wheel_r_inner - (int)(sv_picker_size * 0.027f);
ImVec2 triangle_pa = ImVec2(triangle_r, 0.0f); // Hue point.
ImVec2 triangle_pb = ImVec2(triangle_r * -0.5f, triangle_r * -0.866025f); // Black point.
ImVec2 triangle_pc = ImVec2(triangle_r * -0.5f, triangle_r * +0.866025f); // White point.
float H,S,V;
ColorConvertRGBtoHSV(col[0], col[1], col[2], H, S, V);
bool value_changed = false, value_changed_h = false, value_changed_sv = false;
PushItemFlag(ImGuiItemFlags_NoNav, true);
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Hue wheel + SV triangle logic
InvisibleButton("hsv", ImVec2(sv_picker_size + style.ItemInnerSpacing.x + bars_width, sv_picker_size));
if (IsItemActive())
{
ImVec2 initial_off = g.IO.MouseClickedPos[0] - wheel_center;
ImVec2 current_off = g.IO.MousePos - wheel_center;
float initial_dist2 = ImLengthSqr(initial_off);
if (initial_dist2 >= (wheel_r_inner-1)*(wheel_r_inner-1) && initial_dist2 <= (wheel_r_outer+1)*(wheel_r_outer+1))
{
// Interactive with Hue wheel
H = atan2f(current_off.y, current_off.x) / IM_PI*0.5f;
if (H < 0.0f)
H += 1.0f;
value_changed = value_changed_h = true;
}
float cos_hue_angle = cosf(-H * 2.0f * IM_PI);
float sin_hue_angle = sinf(-H * 2.0f * IM_PI);
if (ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, ImRotate(initial_off, cos_hue_angle, sin_hue_angle)))
{
// Interacting with SV triangle
ImVec2 current_off_unrotated = ImRotate(current_off, cos_hue_angle, sin_hue_angle);
if (!ImTriangleContainsPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated))
current_off_unrotated = ImTriangleClosestPoint(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated);
float uu, vv, ww;
ImTriangleBarycentricCoords(triangle_pa, triangle_pb, triangle_pc, current_off_unrotated, uu, vv, ww);
V = ImClamp(1.0f - vv, 0.0001f, 1.0f);
S = ImClamp(uu / V, 0.0001f, 1.0f);
value_changed = value_changed_sv = true;
}
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// SV rectangle logic
InvisibleButton("sv", ImVec2(sv_picker_size, sv_picker_size));
if (IsItemActive())
{
S = ImSaturate((io.MousePos.x - picker_pos.x) / (sv_picker_size-1));
V = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_sv = true;
}
if (!(flags & ImGuiColorEditFlags_NoOptions))
OpenPopupOnItemClick("context");
// Hue bar logic
SetCursorScreenPos(ImVec2(bar0_pos_x, picker_pos.y));
InvisibleButton("hue", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
H = ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = value_changed_h = true;
}
}
// Alpha bar logic
if (alpha_bar)
{
SetCursorScreenPos(ImVec2(bar1_pos_x, picker_pos.y));
InvisibleButton("alpha", ImVec2(bars_width, sv_picker_size));
if (IsItemActive())
{
col[3] = 1.0f - ImSaturate((io.MousePos.y - picker_pos.y) / (sv_picker_size-1));
value_changed = true;
}
}
PopItemFlag(); // ImGuiItemFlags_NoNav
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
SameLine(0, style.ItemInnerSpacing.x);
BeginGroup();
}
if (!(flags & ImGuiColorEditFlags_NoLabel))
{
const char* label_display_end = FindRenderedTextEnd(label);
if (label != label_display_end)
{
if ((flags & ImGuiColorEditFlags_NoSidePreview))
SameLine(0, style.ItemInnerSpacing.x);
TextUnformatted(label, label_display_end);
}
}
if (!(flags & ImGuiColorEditFlags_NoSidePreview))
{
PushItemFlag(ImGuiItemFlags_NoNavDefaultFocus, true);
ImVec4 col_v4(col[0], col[1], col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : col[3]);
if ((flags & ImGuiColorEditFlags_NoLabel))
Text("Current");
ColorButton("##current", col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2));
if (ref_col != NULL)
{
Text("Original");
ImVec4 ref_col_v4(ref_col[0], ref_col[1], ref_col[2], (flags & ImGuiColorEditFlags_NoAlpha) ? 1.0f : ref_col[3]);
if (ColorButton("##original", ref_col_v4, (flags & (ImGuiColorEditFlags_HDR|ImGuiColorEditFlags_AlphaPreview|ImGuiColorEditFlags_AlphaPreviewHalf|ImGuiColorEditFlags_NoTooltip)), ImVec2(square_sz * 3, square_sz * 2)))
{
memcpy(col, ref_col, components * sizeof(float));
value_changed = true;
}
}
PopItemFlag();
EndGroup();
}
// Convert back color to RGB
if (value_changed_h || value_changed_sv)
ColorConvertHSVtoRGB(H >= 1.0f ? H - 10 * 1e-6f : H, S > 0.0f ? S : 10*1e-6f, V > 0.0f ? V : 1e-6f, col[0], col[1], col[2]);
// R,G,B and H,S,V slider color editor
if ((flags & ImGuiColorEditFlags_NoInputs) == 0)
{
PushItemWidth((alpha_bar ? bar1_pos_x : bar0_pos_x) + bars_width - picker_pos.x);
ImGuiColorEditFlags sub_flags_to_forward = ImGuiColorEditFlags__DataTypeMask | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha | ImGuiColorEditFlags_NoOptions | ImGuiColorEditFlags_NoSmallPreview | ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_AlphaPreviewHalf;
ImGuiColorEditFlags sub_flags = (flags & sub_flags_to_forward) | ImGuiColorEditFlags_NoPicker;
if (flags & ImGuiColorEditFlags_RGB || (flags & ImGuiColorEditFlags__InputsMask) == 0)
value_changed |= ColorEdit4("##rgb", col, sub_flags | ImGuiColorEditFlags_RGB);
if (flags & ImGuiColorEditFlags_HSV || (flags & ImGuiColorEditFlags__InputsMask) == 0)
value_changed |= ColorEdit4("##hsv", col, sub_flags | ImGuiColorEditFlags_HSV);
if (flags & ImGuiColorEditFlags_HEX || (flags & ImGuiColorEditFlags__InputsMask) == 0)
value_changed |= ColorEdit4("##hex", col, sub_flags | ImGuiColorEditFlags_HEX);
PopItemWidth();
}
// Try to cancel hue wrap (after ColorEdit), if any
if (value_changed)
{
float new_H, new_S, new_V;
ColorConvertRGBtoHSV(col[0], col[1], col[2], new_H, new_S, new_V);
if (new_H <= 0 && H > 0)
{
if (new_V <= 0 && V != new_V)
ColorConvertHSVtoRGB(H, S, new_V <= 0 ? V * 0.5f : new_V, col[0], col[1], col[2]);
else if (new_S <= 0)
ColorConvertHSVtoRGB(H, new_S <= 0 ? S * 0.5f : new_S, new_V, col[0], col[1], col[2]);
}
}
ImVec4 hue_color_f(1, 1, 1, 1); ColorConvertHSVtoRGB(H, 1, 1, hue_color_f.x, hue_color_f.y, hue_color_f.z);
ImU32 hue_color32 = ColorConvertFloat4ToU32(hue_color_f);
ImU32 col32_no_alpha = ColorConvertFloat4ToU32(ImVec4(col[0], col[1], col[2], 1.0f));
const ImU32 hue_colors[6+1] = { IM_COL32(255,0,0,255), IM_COL32(255,255,0,255), IM_COL32(0,255,0,255), IM_COL32(0,255,255,255), IM_COL32(0,0,255,255), IM_COL32(255,0,255,255), IM_COL32(255,0,0,255) };
ImVec2 sv_cursor_pos;
if (flags & ImGuiColorEditFlags_PickerHueWheel)
{
// Render Hue Wheel
const float aeps = 1.5f / wheel_r_outer; // Half a pixel arc length in radians (2pi cancels out).
const int segment_per_arc = ImMax(4, (int)wheel_r_outer / 12);
for (int n = 0; n < 6; n++)
{
const float a0 = (n) /6.0f * 2.0f * IM_PI - aeps;
const float a1 = (n+1.0f)/6.0f * 2.0f * IM_PI + aeps;
const int vert_start_idx = draw_list->VtxBuffer.Size;
draw_list->PathArcTo(wheel_center, (wheel_r_inner + wheel_r_outer)*0.5f, a0, a1, segment_per_arc);
draw_list->PathStroke(IM_COL32_WHITE, false, wheel_thickness);
const int vert_end_idx = draw_list->VtxBuffer.Size;
// Paint colors over existing vertices
ImVec2 gradient_p0(wheel_center.x + cosf(a0) * wheel_r_inner, wheel_center.y + sinf(a0) * wheel_r_inner);
ImVec2 gradient_p1(wheel_center.x + cosf(a1) * wheel_r_inner, wheel_center.y + sinf(a1) * wheel_r_inner);
ShadeVertsLinearColorGradientKeepAlpha(draw_list->VtxBuffer.Data + vert_start_idx, draw_list->VtxBuffer.Data + vert_end_idx, gradient_p0, gradient_p1, hue_colors[n], hue_colors[n+1]);
}
// Render Cursor + preview on Hue Wheel
float cos_hue_angle = cosf(H * 2.0f * IM_PI);
float sin_hue_angle = sinf(H * 2.0f * IM_PI);
ImVec2 hue_cursor_pos(wheel_center.x + cos_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f, wheel_center.y + sin_hue_angle * (wheel_r_inner+wheel_r_outer)*0.5f);
float hue_cursor_rad = value_changed_h ? wheel_thickness * 0.65f : wheel_thickness * 0.55f;
int hue_cursor_segments = ImClamp((int)(hue_cursor_rad / 1.4f), 9, 32);
draw_list->AddCircleFilled(hue_cursor_pos, hue_cursor_rad, hue_color32, hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad+1, IM_COL32(128,128,128,255), hue_cursor_segments);
draw_list->AddCircle(hue_cursor_pos, hue_cursor_rad, IM_COL32_WHITE, hue_cursor_segments);
// Render SV triangle (rotated according to hue)
ImVec2 tra = wheel_center + ImRotate(triangle_pa, cos_hue_angle, sin_hue_angle);
ImVec2 trb = wheel_center + ImRotate(triangle_pb, cos_hue_angle, sin_hue_angle);
ImVec2 trc = wheel_center + ImRotate(triangle_pc, cos_hue_angle, sin_hue_angle);
ImVec2 uv_white = GetFontTexUvWhitePixel();
draw_list->PrimReserve(6, 6);
draw_list->PrimVtx(tra, uv_white, hue_color32);
draw_list->PrimVtx(trb, uv_white, hue_color32);
draw_list->PrimVtx(trc, uv_white, IM_COL32_WHITE);
draw_list->PrimVtx(tra, uv_white, IM_COL32_BLACK_TRANS);
draw_list->PrimVtx(trb, uv_white, IM_COL32_BLACK);
draw_list->PrimVtx(trc, uv_white, IM_COL32_BLACK_TRANS);
draw_list->AddTriangle(tra, trb, trc, IM_COL32(128,128,128,255), 1.5f);
sv_cursor_pos = ImLerp(ImLerp(trc, tra, ImSaturate(S)), trb, ImSaturate(1 - V));
}
else if (flags & ImGuiColorEditFlags_PickerHueBar)
{
// Render SV Square
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_WHITE, hue_color32, hue_color32, IM_COL32_WHITE);
draw_list->AddRectFilledMultiColor(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), IM_COL32_BLACK_TRANS, IM_COL32_BLACK_TRANS, IM_COL32_BLACK, IM_COL32_BLACK);
RenderFrameBorder(picker_pos, picker_pos + ImVec2(sv_picker_size,sv_picker_size), 0.0f);
sv_cursor_pos.x = ImClamp((float)(int)(picker_pos.x + ImSaturate(S) * sv_picker_size + 0.5f), picker_pos.x + 2, picker_pos.x + sv_picker_size - 2); // Sneakily prevent the circle to stick out too much
sv_cursor_pos.y = ImClamp((float)(int)(picker_pos.y + ImSaturate(1 - V) * sv_picker_size + 0.5f), picker_pos.y + 2, picker_pos.y + sv_picker_size - 2);
// Render Hue Bar
for (int i = 0; i < 6; ++i)
draw_list->AddRectFilledMultiColor(ImVec2(bar0_pos_x, picker_pos.y + i * (sv_picker_size / 6)), ImVec2(bar0_pos_x + bars_width, picker_pos.y + (i + 1) * (sv_picker_size / 6)), hue_colors[i], hue_colors[i], hue_colors[i + 1], hue_colors[i + 1]);
float bar0_line_y = (float)(int)(picker_pos.y + H * sv_picker_size + 0.5f);
RenderFrameBorder(ImVec2(bar0_pos_x, picker_pos.y), ImVec2(bar0_pos_x + bars_width, picker_pos.y + sv_picker_size), 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar0_pos_x - 1, bar0_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
// Render cursor/preview circle (clamp S/V within 0..1 range because floating points colors may lead HSV values to be out of range)
float sv_cursor_rad = value_changed_sv ? 10.0f : 6.0f;
draw_list->AddCircleFilled(sv_cursor_pos, sv_cursor_rad, col32_no_alpha, 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad+1, IM_COL32(128,128,128,255), 12);
draw_list->AddCircle(sv_cursor_pos, sv_cursor_rad, IM_COL32_WHITE, 12);
// Render alpha bar
if (alpha_bar)
{
float alpha = ImSaturate(col[3]);
ImRect bar1_bb(bar1_pos_x, picker_pos.y, bar1_pos_x + bars_width, picker_pos.y + sv_picker_size);
RenderColorRectWithAlphaCheckerboard(bar1_bb.Min, bar1_bb.Max, IM_COL32(0,0,0,0), bar1_bb.GetWidth() / 2.0f, ImVec2(0.0f, 0.0f));
draw_list->AddRectFilledMultiColor(bar1_bb.Min, bar1_bb.Max, col32_no_alpha, col32_no_alpha, col32_no_alpha & ~IM_COL32_A_MASK, col32_no_alpha & ~IM_COL32_A_MASK);
float bar1_line_y = (float)(int)(picker_pos.y + (1.0f - alpha) * sv_picker_size + 0.5f);
RenderFrameBorder(bar1_bb.Min, bar1_bb.Max, 0.0f);
RenderArrowsForVerticalBar(draw_list, ImVec2(bar1_pos_x - 1, bar1_line_y), ImVec2(bars_triangles_half_sz + 1, bars_triangles_half_sz), bars_width + 2.0f);
}
EndGroup();
PopID();
return value_changed && memcmp(backup_initial_col, col, components * sizeof(float));
}
// Horizontal separating line.
void ImGui::Separator()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
ImGuiSeparatorFlags flags = 0;
if ((flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)) == 0)
flags |= (window->DC.LayoutType == ImGuiLayoutType_Horizontal) ? ImGuiSeparatorFlags_Vertical : ImGuiSeparatorFlags_Horizontal;
IM_ASSERT(ImIsPowerOfTwo((int)(flags & (ImGuiSeparatorFlags_Horizontal | ImGuiSeparatorFlags_Vertical)))); // Check that only 1 option is selected
if (flags & ImGuiSeparatorFlags_Vertical)
{
VerticalSeparator();
return;
}
// Horizontal Separator
if (window->DC.ColumnsSet)
PopClipRect();
float x1 = window->Pos.x;
float x2 = window->Pos.x + window->Size.x;
if (!window->DC.GroupStack.empty())
x1 += window->DC.IndentX;
const ImRect bb(ImVec2(x1, window->DC.CursorPos.y), ImVec2(x2, window->DC.CursorPos.y+1.0f));
ItemSize(ImVec2(0.0f, 0.0f)); // NB: we don't provide our width so that it doesn't get feed back into AutoFit, we don't provide height to not alter layout.
if (!ItemAdd(bb, 0))
{
if (window->DC.ColumnsSet)
PushColumnClipRect();
return;
}
window->DrawList->AddLine(bb.Min, ImVec2(bb.Max.x,bb.Min.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogRenderedText(NULL, IM_NEWLINE "--------------------------------");
if (window->DC.ColumnsSet)
{
PushColumnClipRect();
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y;
}
}
void ImGui::VerticalSeparator()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
float y1 = window->DC.CursorPos.y;
float y2 = window->DC.CursorPos.y + window->DC.CurrentLineHeight;
const ImRect bb(ImVec2(window->DC.CursorPos.x, y1), ImVec2(window->DC.CursorPos.x + 1.0f, y2));
ItemSize(ImVec2(bb.GetWidth(), 0.0f));
if (!ItemAdd(bb, 0))
return;
window->DrawList->AddLine(ImVec2(bb.Min.x, bb.Min.y), ImVec2(bb.Min.x, bb.Max.y), GetColorU32(ImGuiCol_Separator));
if (g.LogEnabled)
LogText(" |");
}
bool ImGui::SplitterBehavior(ImGuiID id, const ImRect& bb, ImGuiAxis axis, float* size1, float* size2, float min_size1, float min_size2, float hover_extend)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNav | ImGuiItemFlags_NoNavDefaultFocus;
bool item_add = ItemAdd(bb, id);
window->DC.ItemFlags = item_flags_backup;
if (!item_add)
return false;
bool hovered, held;
ImRect bb_interact = bb;
bb_interact.Expand(axis == ImGuiAxis_Y ? ImVec2(0.0f, hover_extend) : ImVec2(hover_extend, 0.0f));
ButtonBehavior(bb_interact, id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap);
if (g.ActiveId != id)
SetItemAllowOverlap();
if (held || (g.HoveredId == id && g.HoveredIdPreviousFrame == id))
SetMouseCursor(axis == ImGuiAxis_Y ? ImGuiMouseCursor_ResizeNS : ImGuiMouseCursor_ResizeEW);
ImRect bb_render = bb;
if (held)
{
ImVec2 mouse_delta_2d = g.IO.MousePos - g.ActiveIdClickOffset - bb_interact.Min;
float mouse_delta = (axis == ImGuiAxis_Y) ? mouse_delta_2d.y : mouse_delta_2d.x;
// Minimum pane size
if (mouse_delta < min_size1 - *size1)
mouse_delta = min_size1 - *size1;
if (mouse_delta > *size2 - min_size2)
mouse_delta = *size2 - min_size2;
// Apply resize
*size1 += mouse_delta;
*size2 -= mouse_delta;
bb_render.Translate((axis == ImGuiAxis_X) ? ImVec2(mouse_delta, 0.0f) : ImVec2(0.0f, mouse_delta));
}
// Render
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
window->DrawList->AddRectFilled(bb_render.Min, bb_render.Max, col, g.Style.FrameRounding);
return held;
}
void ImGui::Spacing()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ItemSize(ImVec2(0,0));
}
void ImGui::Dummy(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
const ImRect bb(window->DC.CursorPos, window->DC.CursorPos + size);
ItemSize(bb);
ItemAdd(bb, 0);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndentX = window->DC.IndentX;
group_data.BackupGroupOffsetX = window->DC.GroupOffsetX;
group_data.BackupCurrentLineHeight = window->DC.CurrentLineHeight;
group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
group_data.BackupLogLinePosY = window->DC.LogLinePosY;
group_data.BackupActiveIdIsAlive = GImGui->ActiveIdIsAlive;
group_data.AdvanceCursor = true;
window->DC.GroupOffsetX = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffsetX;
window->DC.IndentX = window->DC.GroupOffsetX;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrentLineHeight = 0.0f;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.CurrentLineHeight = group_data.BackupCurrentLineHeight;
window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
window->DC.IndentX = group_data.BackupIndentX;
window->DC.GroupOffsetX = group_data.BackupGroupOffsetX;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
if (group_data.AdvanceCursor)
{
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize(), group_data.BackupCurrentLineTextBaseOffset);
ItemAdd(group_bb, 0);
}
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive() will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but if you search for LastItemId you'll notice it is only used in that context.
const bool active_id_within_group = (!group_data.BackupActiveIdIsAlive && g.ActiveIdIsAlive && g.ActiveId && g.ActiveIdWindow->RootWindow == window->RootWindow);
if (active_id_within_group)
window->DC.LastItemId = g.ActiveId;
window->DC.LastItemRect = group_bb;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
// pos_x == 0 : follow right after previous item
// pos_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float pos_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (pos_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffsetX + window->DC.ColumnsOffsetX;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrentLineHeight = window->DC.PrevLineHeight;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::NewLine()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
const ImGuiLayoutType backup_layout_type = window->DC.LayoutType;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
if (window->DC.CurrentLineHeight > 0.0f) // In the event that we are on a line with items that is smaller that FontSize high, we will preserve its height.
ItemSize(ImVec2(0,0));
else
ItemSize(ImVec2(0.0f, g.FontSize));
window->DC.LayoutType = backup_layout_type;
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.ColumnsSet == NULL)
return;
ImGuiContext& g = *GImGui;
PopItemWidth();
PopClipRect();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// Columns 1+ cancel out IndentX
window->DC.ColumnsOffsetX = GetColumnOffset(columns->Current) - window->DC.IndentX + g.Style.ItemSpacing.x;
window->DrawList->ChannelsSetCurrent(columns->Current);
}
else
{
window->DC.ColumnsOffsetX = 0.0f;
window->DrawList->ChannelsSetCurrent(0);
columns->Current = 0;
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrentLineHeight = 0.0f;
window->DC.CurrentLineTextBaseOffset = 0.0f;
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
}
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
}
static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
{
return offset_norm * (columns->MaxX - columns->MinX);
}
static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
{
return offset / (columns->MaxX - columns->MinX);
}
static inline float GetColumnsRectHalfWidth() { return 4.0f; }
static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
{
if (column_index < 0)
column_index = columns->Current;
float offset_norm;
if (before_resize)
offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
else
offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
return OffsetNormToPixels(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
}
void ImGui::PushColumnClipRect(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
if (column_index < 0)
column_index = columns->Current;
PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
}
static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiColumnsSet());
ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count > 1);
IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
PushID(0x11223347 + (str_id ? 0 : columns_count));
ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
// Acquire storage for the columns set
ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.ColumnsSet = columns;
// Set state for first column
const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
columns->MinX = window->DC.IndentX - g.Style.ItemSpacing.x; // Lock our horizontal range
columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
columns->StartPosY = window->DC.CursorPos.y;
columns->StartMaxPosX = window->DC.CursorMaxPos.x;
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize defaults
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
{
columns->Columns.reserve(columns_count + 1);
for (int n = 0; n < columns_count + 1; n++)
{
ImGuiColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWith(window->ClipRect);
}
window->DrawList->ChannelsSplit(columns->Count);
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f);
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
PopItemWidth();
PopClipRect();
window->DrawList->ChannelsMerge();
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = ImMax(columns->StartMaxPosX, columns->MaxX); // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
bool is_being_resized = false;
if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
{
const float y1 = columns->StartPosY;
const float y2 = window->DC.CursorPos.y;
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
{
ButtonBehavior(column_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
dragging_column = n;
}
// Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = (float)(int)x;
window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
}
// Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
if (dragging_column != -1)
{
if (!columns->IsBeingResized)
for (int n = 0; n < columns->Count + 1; n++)
columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
columns->IsBeingResized = is_being_resized = true;
float x = GetDraggedColumnOffset(columns, dragging_column);
SetColumnOffset(dragging_column, x);
}
}
columns->IsBeingResized = is_being_resized;
window->DC.ColumnsSet = NULL;
window->DC.ColumnsOffsetX = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX);
}
// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count != columns_count)
EndColumns();
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.IndentX += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.IndentX -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.IndentX + window->DC.ColumnsOffsetX;
}
void ImGui::TreePush(const char* str_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(str_id ? str_id : "#TreePush");
}
void ImGui::TreePush(const void* ptr_id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
PushID(ptr_id ? ptr_id : (const void*)"#TreePush");
}
void ImGui::TreePushRawID(ImGuiID id)
{
ImGuiWindow* window = GetCurrentWindow();
Indent();
window->DC.TreeDepth++;
window->IDStack.push_back(id);
}
void ImGui::TreePop()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
Unindent();
window->DC.TreeDepth--;
if (g.NavMoveDir == ImGuiDir_Left && g.NavWindow == window && NavMoveRequestButNoResultYet())
if (g.NavIdIsAlive && (window->DC.TreeDepthMayJumpToParentOnPop & (1 << window->DC.TreeDepth)))
{
SetNavID(window->IDStack.back(), g.NavLayer);
NavMoveRequestCancel();
}
window->DC.TreeDepthMayJumpToParentOnPop &= (1 << window->DC.TreeDepth) - 1;
PopID();
}
void ImGui::Value(const char* prefix, bool b)
{
Text("%s: %s", prefix, (b ? "true" : "false"));
}
void ImGui::Value(const char* prefix, int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, unsigned int v)
{
Text("%s: %d", prefix, v);
}
void ImGui::Value(const char* prefix, float v, const char* float_format)
{
if (float_format)
{
char fmt[64];
ImFormatString(fmt, IM_ARRAYSIZE(fmt), "%%s: %s", float_format);
Text(fmt, prefix, v);
}
else
{
Text("%s: %.3f", prefix, v);
}
}
//-----------------------------------------------------------------------------
// DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
int mouse_button = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
if (is_hovered)
SetHoveredID(source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
}
else
{
window = NULL;
source_id = ImHash("#SourceExtern", 0);
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// FIXME-DRAG
//SetNextWindowPos(g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This is better but e.g ColorButton with checkboard has issue with transparent colors :(
SetNextWindowPos(g.IO.MousePos);
PushStyleColor(ImGuiCol_PopupBg, GetStyleColorVec4(ImGuiCol_PopupBg) * ImVec4(1.0f, 1.0f, 1.0f, 0.6f));
BeginTooltip();
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
EndTooltip();
PopStyleColor();
//PopStyleVar();
}
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 12 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy((void*)payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy((void*)payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindow == NULL || window->RootWindow != g.HoveredWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRectFullScreen();
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui; (void)g;
IM_ASSERT(g.DragDropActive);
}
//-----------------------------------------------------------------------------
// PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#ifndef __MINGW32__
#include <Windows.h>
#else
#include <windows.h>
#endif
#endif
// Win32 API clipboard implementation
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
CloseClipboard();
return NULL;
}
if (ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
buf_local.resize(buf_len);
ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
}
GlobalUnlock(wbuf_handle);
CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!OpenClipboard(NULL))
return;
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
{
CloseClipboard();
return;
}
ImWchar* wbuf_global = (ImWchar*)GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
GlobalUnlock(wbuf_handle);
EmptyClipboard();
SetClipboardData(CF_UNICODETEXT, wbuf_handle);
CloseClipboard();
}
#else
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(__GNUC__) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS)
#include <imm.h>
#ifdef _MSC_VER
#pragma comment(lib, "imm32")
#endif
static void ImeSetInputScreenPosFn_DefaultImpl(int x, int y)
{
// Notify OS Input Method Editor of text input position
if (HWND hwnd = (HWND)GImGui->IO.ImeWindowHandle)
if (HIMC himc = ImmGetContext(hwnd))
{
COMPOSITIONFORM cf;
cf.ptCurrentPos.x = x;
cf.ptCurrentPos.y = y;
cf.dwStyle = CFS_FORCE_POSITION;
ImmSetCompositionWindow(himc, &cf);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// HELP
//-----------------------------------------------------------------------------
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (ImGui::Begin("ImGui Metrics", p_open))
{
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", ImGui::GetIO().MetricsRenderVertices, ImGui::GetIO().MetricsRenderIndices, ImGui::GetIO().MetricsRenderIndices / 3);
ImGui::Text("%d allocations", (int)GImAllocatorActiveAllocationsCount);
static bool show_clip_rects = true;
ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_clip_rects);
ImGui::Separator();
struct Funcs
{
static void NodeDrawList(ImGuiWindow* window, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImColor(255,100,100), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* overlay_draw_list = ImGui::GetOverlayDrawList(); // Render additional visuals into the top-most draw list
if (window && ImGui::IsItemHovered())
overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_clip_rects && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect;
for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
}
if (!pcmd_node_open)
continue;
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, vtx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char buf[300];
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, vtx_i++)
{
ImDrawVert& v = draw_list->VtxBuffer[idx_buffer ? idx_buffer[vtx_i] : vtx_i];
triangles_pos[n] = v.pos;
buf_p += ImFormatString(buf_p, (int)(buf_end - buf_p), "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n", (n == 0) ? "vtx" : " ", vtx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = overlay_draw_list->Flags;
overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
overlay_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
Funcs::NodeWindow(windows[i], "Window");
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetScrollMaxX(window), window->Scroll.y, GetScrollMaxY(window));
ImGui::BulletText("Active: %d, WriteAccessed: %d", window->Active, window->WriteAccessed);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
{
const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
{
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
}
ImGui::TreePop();
}
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
};
// Access private state, we are going to display the draw lists from last frame
ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
if (ImGui::TreeNode("DrawList", "Active DrawLists (%d)", g.DrawDataBuilder.Layers[0].Size))
{
for (int i = 0; i < g.DrawDataBuilder.Layers[0].Size; i++)
Funcs::NodeDrawList(NULL, g.DrawDataBuilder.Layers[0][i], "DrawList");
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Open Popups Stack (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec)", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), ActiveIdSource: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::TreePop();
}
}
ImGui::End();
}
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
| [
"WilliamMilesLew@gmail.com"
] | WilliamMilesLew@gmail.com |
f0d80f1fc501a08773b3521943caeeeec869986c | 380f381455503b33fe7d414f8149f23aae46e4f7 | /2DRPG/Library/Il2cppBuildCache/Android/armeabi-v7a/il2cppOutput/Unity.2D.PixelPerfect.cpp | ead9e4a011e1b1ad84f4c32ef0c383f335bc20fe | [] | no_license | jiye-stingray/2DRPG | 5a0355a02885c901997f43cab763f10958a7f820 | 998d7fc4ca5b3020f63a811f6352044615117bfe | refs/heads/main | 2023-08-05T03:57:03.616847 | 2021-09-24T02:07:29 | 2021-09-24T02:07:29 | 406,614,498 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147,419 | cpp | #include "pch-cpp.hpp"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <limits>
#include <stdint.h>
template <typename R>
struct InterfaceFuncInvoker0
{
typedef R (*Func)(void*, const RuntimeMethod*);
static inline R Invoke (Il2CppMethodSlot slot, RuntimeClass* declaringInterface, RuntimeObject* obj)
{
const VirtualInvokeData& invokeData = il2cpp_codegen_get_interface_invoke_data(slot, obj, declaringInterface);
return ((Func)invokeData.methodPtr)(obj, invokeData.method);
}
};
// System.Char[]
struct CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34;
// UnityEngine.Camera
struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C;
// UnityEngine.U2D.CinemachinePixelPerfect
struct CinemachinePixelPerfect_t18A5902325EFE9EAB86D12809C3E672555EAA6F1;
// UnityEngine.Component
struct Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684;
// UnityEngine.U2D.IPixelPerfectCamera
struct IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7;
// UnityEngine.MonoBehaviour
struct MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A;
// UnityEngine.Object
struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A;
// UnityEngine.U2D.PixelPerfectCamera
struct PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8;
// UnityEngine.U2D.PixelPerfectCameraInternal
struct PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB;
// UnityEngine.RenderTexture
struct RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849;
// System.String
struct String_t;
// UnityEngine.Texture
struct Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE;
// UnityEngine.Transform
struct Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1;
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5;
// UnityEngine.Camera/CameraCallback
struct CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D;
IL2CPP_EXTERN_C RuntimeClass* Debug_tEB68BCBEB8EFD60F8043C67146DC05E7F50F374B_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Graphics_t97FAEBE964F3F622D4865E7EC62717FE94D1F56D_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C RuntimeClass* PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8_il2cpp_TypeInfo_var;
IL2CPP_EXTERN_C String_t* _stringLiteral69D2BC13326043EFBE8498680B311F3B34E06698;
IL2CPP_EXTERN_C String_t* _stringLiteral6B44A7675031FCAC57E28AD1002F65360C76AFF2;
IL2CPP_EXTERN_C String_t* _stringLiteral6E3C394542AFDC0953291817DE5BAA9A9329CF27;
IL2CPP_EXTERN_C const RuntimeMethod* Component_GetComponent_TisCamera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_mE17146EF5B0D8E9F9D2D2D94567BF211AD00D320_RuntimeMethod_var;
IL2CPP_EXTERN_C_BEGIN
IL2CPP_EXTERN_C_END
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// <Module>
struct U3CModuleU3E_t5C67F4C00BFAA16443168F922286EEE56F2F70DB
{
public:
public:
};
// System.Object
struct Il2CppArrayBounds;
// System.Array
// System.String
struct String_t : public RuntimeObject
{
public:
// System.Int32 System.String::m_stringLength
int32_t ___m_stringLength_0;
// System.Char System.String::m_firstChar
Il2CppChar ___m_firstChar_1;
public:
inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); }
inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; }
inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; }
inline void set_m_stringLength_0(int32_t value)
{
___m_stringLength_0 = value;
}
inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); }
inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; }
inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; }
inline void set_m_firstChar_1(Il2CppChar value)
{
___m_firstChar_1 = value;
}
};
struct String_t_StaticFields
{
public:
// System.String System.String::Empty
String_t* ___Empty_5;
public:
inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); }
inline String_t* get_Empty_5() const { return ___Empty_5; }
inline String_t** get_address_of_Empty_5() { return &___Empty_5; }
inline void set_Empty_5(String_t* value)
{
___Empty_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___Empty_5), (void*)value);
}
};
// System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52 : public RuntimeObject
{
public:
public:
};
// Native definition for P/Invoke marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.ValueType
struct ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52_marshaled_com
{
};
// System.Boolean
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37
{
public:
// System.Boolean System.Boolean::m_value
bool ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37, ___m_value_0)); }
inline bool get_m_value_0() const { return ___m_value_0; }
inline bool* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(bool value)
{
___m_value_0 = value;
}
};
struct Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields
{
public:
// System.String System.Boolean::TrueString
String_t* ___TrueString_5;
// System.String System.Boolean::FalseString
String_t* ___FalseString_6;
public:
inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___TrueString_5)); }
inline String_t* get_TrueString_5() const { return ___TrueString_5; }
inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; }
inline void set_TrueString_5(String_t* value)
{
___TrueString_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___TrueString_5), (void*)value);
}
inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t07D1E3F34E4813023D64F584DFF7B34C9D922F37_StaticFields, ___FalseString_6)); }
inline String_t* get_FalseString_6() const { return ___FalseString_6; }
inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; }
inline void set_FalseString_6(String_t* value)
{
___FalseString_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___FalseString_6), (void*)value);
}
};
// UnityEngine.Color
struct Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659
{
public:
// System.Single UnityEngine.Color::r
float ___r_0;
// System.Single UnityEngine.Color::g
float ___g_1;
// System.Single UnityEngine.Color::b
float ___b_2;
// System.Single UnityEngine.Color::a
float ___a_3;
public:
inline static int32_t get_offset_of_r_0() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___r_0)); }
inline float get_r_0() const { return ___r_0; }
inline float* get_address_of_r_0() { return &___r_0; }
inline void set_r_0(float value)
{
___r_0 = value;
}
inline static int32_t get_offset_of_g_1() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___g_1)); }
inline float get_g_1() const { return ___g_1; }
inline float* get_address_of_g_1() { return &___g_1; }
inline void set_g_1(float value)
{
___g_1 = value;
}
inline static int32_t get_offset_of_b_2() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___b_2)); }
inline float get_b_2() const { return ___b_2; }
inline float* get_address_of_b_2() { return &___b_2; }
inline void set_b_2(float value)
{
___b_2 = value;
}
inline static int32_t get_offset_of_a_3() { return static_cast<int32_t>(offsetof(Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659, ___a_3)); }
inline float get_a_3() const { return ___a_3; }
inline float* get_address_of_a_3() { return &___a_3; }
inline void set_a_3(float value)
{
___a_3 = value;
}
};
// System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA : public ValueType_tDBF999C1B75C48C68621878250DBF6CDBCF51E52
{
public:
public:
};
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields
{
public:
// System.Char[] System.Enum::enumSeperatorCharArray
CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* ___enumSeperatorCharArray_0;
public:
inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t23B90B40F60E677A8025267341651C94AE079CDA_StaticFields, ___enumSeperatorCharArray_0)); }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; }
inline CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; }
inline void set_enumSeperatorCharArray_0(CharU5BU5D_t7B7FC5BC8091AA3B9CB0B29CDD80B5EE9254AA34* value)
{
___enumSeperatorCharArray_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___enumSeperatorCharArray_0), (void*)value);
}
};
// Native definition for P/Invoke marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_pinvoke
{
};
// Native definition for COM marshalling of System.Enum
struct Enum_t23B90B40F60E677A8025267341651C94AE079CDA_marshaled_com
{
};
// System.Int32
struct Int32_tFDE5F8CD43D10453F6A2E0C77FE48C6CC7009046
{
public:
// System.Int32 System.Int32::m_value
int32_t ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_tFDE5F8CD43D10453F6A2E0C77FE48C6CC7009046, ___m_value_0)); }
inline int32_t get_m_value_0() const { return ___m_value_0; }
inline int32_t* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(int32_t value)
{
___m_value_0 = value;
}
};
// System.IntPtr
struct IntPtr_t
{
public:
// System.Void* System.IntPtr::m_value
void* ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); }
inline void* get_m_value_0() const { return ___m_value_0; }
inline void** get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(void* value)
{
___m_value_0 = value;
}
};
struct IntPtr_t_StaticFields
{
public:
// System.IntPtr System.IntPtr::Zero
intptr_t ___Zero_1;
public:
inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); }
inline intptr_t get_Zero_1() const { return ___Zero_1; }
inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; }
inline void set_Zero_1(intptr_t value)
{
___Zero_1 = value;
}
};
// UnityEngine.Matrix4x4
struct Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461
{
public:
// System.Single UnityEngine.Matrix4x4::m00
float ___m00_0;
// System.Single UnityEngine.Matrix4x4::m10
float ___m10_1;
// System.Single UnityEngine.Matrix4x4::m20
float ___m20_2;
// System.Single UnityEngine.Matrix4x4::m30
float ___m30_3;
// System.Single UnityEngine.Matrix4x4::m01
float ___m01_4;
// System.Single UnityEngine.Matrix4x4::m11
float ___m11_5;
// System.Single UnityEngine.Matrix4x4::m21
float ___m21_6;
// System.Single UnityEngine.Matrix4x4::m31
float ___m31_7;
// System.Single UnityEngine.Matrix4x4::m02
float ___m02_8;
// System.Single UnityEngine.Matrix4x4::m12
float ___m12_9;
// System.Single UnityEngine.Matrix4x4::m22
float ___m22_10;
// System.Single UnityEngine.Matrix4x4::m32
float ___m32_11;
// System.Single UnityEngine.Matrix4x4::m03
float ___m03_12;
// System.Single UnityEngine.Matrix4x4::m13
float ___m13_13;
// System.Single UnityEngine.Matrix4x4::m23
float ___m23_14;
// System.Single UnityEngine.Matrix4x4::m33
float ___m33_15;
public:
inline static int32_t get_offset_of_m00_0() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m00_0)); }
inline float get_m00_0() const { return ___m00_0; }
inline float* get_address_of_m00_0() { return &___m00_0; }
inline void set_m00_0(float value)
{
___m00_0 = value;
}
inline static int32_t get_offset_of_m10_1() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m10_1)); }
inline float get_m10_1() const { return ___m10_1; }
inline float* get_address_of_m10_1() { return &___m10_1; }
inline void set_m10_1(float value)
{
___m10_1 = value;
}
inline static int32_t get_offset_of_m20_2() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m20_2)); }
inline float get_m20_2() const { return ___m20_2; }
inline float* get_address_of_m20_2() { return &___m20_2; }
inline void set_m20_2(float value)
{
___m20_2 = value;
}
inline static int32_t get_offset_of_m30_3() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m30_3)); }
inline float get_m30_3() const { return ___m30_3; }
inline float* get_address_of_m30_3() { return &___m30_3; }
inline void set_m30_3(float value)
{
___m30_3 = value;
}
inline static int32_t get_offset_of_m01_4() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m01_4)); }
inline float get_m01_4() const { return ___m01_4; }
inline float* get_address_of_m01_4() { return &___m01_4; }
inline void set_m01_4(float value)
{
___m01_4 = value;
}
inline static int32_t get_offset_of_m11_5() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m11_5)); }
inline float get_m11_5() const { return ___m11_5; }
inline float* get_address_of_m11_5() { return &___m11_5; }
inline void set_m11_5(float value)
{
___m11_5 = value;
}
inline static int32_t get_offset_of_m21_6() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m21_6)); }
inline float get_m21_6() const { return ___m21_6; }
inline float* get_address_of_m21_6() { return &___m21_6; }
inline void set_m21_6(float value)
{
___m21_6 = value;
}
inline static int32_t get_offset_of_m31_7() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m31_7)); }
inline float get_m31_7() const { return ___m31_7; }
inline float* get_address_of_m31_7() { return &___m31_7; }
inline void set_m31_7(float value)
{
___m31_7 = value;
}
inline static int32_t get_offset_of_m02_8() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m02_8)); }
inline float get_m02_8() const { return ___m02_8; }
inline float* get_address_of_m02_8() { return &___m02_8; }
inline void set_m02_8(float value)
{
___m02_8 = value;
}
inline static int32_t get_offset_of_m12_9() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m12_9)); }
inline float get_m12_9() const { return ___m12_9; }
inline float* get_address_of_m12_9() { return &___m12_9; }
inline void set_m12_9(float value)
{
___m12_9 = value;
}
inline static int32_t get_offset_of_m22_10() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m22_10)); }
inline float get_m22_10() const { return ___m22_10; }
inline float* get_address_of_m22_10() { return &___m22_10; }
inline void set_m22_10(float value)
{
___m22_10 = value;
}
inline static int32_t get_offset_of_m32_11() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m32_11)); }
inline float get_m32_11() const { return ___m32_11; }
inline float* get_address_of_m32_11() { return &___m32_11; }
inline void set_m32_11(float value)
{
___m32_11 = value;
}
inline static int32_t get_offset_of_m03_12() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m03_12)); }
inline float get_m03_12() const { return ___m03_12; }
inline float* get_address_of_m03_12() { return &___m03_12; }
inline void set_m03_12(float value)
{
___m03_12 = value;
}
inline static int32_t get_offset_of_m13_13() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m13_13)); }
inline float get_m13_13() const { return ___m13_13; }
inline float* get_address_of_m13_13() { return &___m13_13; }
inline void set_m13_13(float value)
{
___m13_13 = value;
}
inline static int32_t get_offset_of_m23_14() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m23_14)); }
inline float get_m23_14() const { return ___m23_14; }
inline float* get_address_of_m23_14() { return &___m23_14; }
inline void set_m23_14(float value)
{
___m23_14 = value;
}
inline static int32_t get_offset_of_m33_15() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461, ___m33_15)); }
inline float get_m33_15() const { return ___m33_15; }
inline float* get_address_of_m33_15() { return &___m33_15; }
inline void set_m33_15(float value)
{
___m33_15 = value;
}
};
struct Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461_StaticFields
{
public:
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::zeroMatrix
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 ___zeroMatrix_16;
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::identityMatrix
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 ___identityMatrix_17;
public:
inline static int32_t get_offset_of_zeroMatrix_16() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461_StaticFields, ___zeroMatrix_16)); }
inline Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 get_zeroMatrix_16() const { return ___zeroMatrix_16; }
inline Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 * get_address_of_zeroMatrix_16() { return &___zeroMatrix_16; }
inline void set_zeroMatrix_16(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 value)
{
___zeroMatrix_16 = value;
}
inline static int32_t get_offset_of_identityMatrix_17() { return static_cast<int32_t>(offsetof(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461_StaticFields, ___identityMatrix_17)); }
inline Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 get_identityMatrix_17() const { return ___identityMatrix_17; }
inline Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 * get_address_of_identityMatrix_17() { return &___identityMatrix_17; }
inline void set_identityMatrix_17(Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 value)
{
___identityMatrix_17 = value;
}
};
// UnityEngine.Quaternion
struct Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4
{
public:
// System.Single UnityEngine.Quaternion::x
float ___x_0;
// System.Single UnityEngine.Quaternion::y
float ___y_1;
// System.Single UnityEngine.Quaternion::z
float ___z_2;
// System.Single UnityEngine.Quaternion::w
float ___w_3;
public:
inline static int32_t get_offset_of_x_0() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___x_0)); }
inline float get_x_0() const { return ___x_0; }
inline float* get_address_of_x_0() { return &___x_0; }
inline void set_x_0(float value)
{
___x_0 = value;
}
inline static int32_t get_offset_of_y_1() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___y_1)); }
inline float get_y_1() const { return ___y_1; }
inline float* get_address_of_y_1() { return &___y_1; }
inline void set_y_1(float value)
{
___y_1 = value;
}
inline static int32_t get_offset_of_z_2() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___z_2)); }
inline float get_z_2() const { return ___z_2; }
inline float* get_address_of_z_2() { return &___z_2; }
inline void set_z_2(float value)
{
___z_2 = value;
}
inline static int32_t get_offset_of_w_3() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4, ___w_3)); }
inline float get_w_3() const { return ___w_3; }
inline float* get_address_of_w_3() { return &___w_3; }
inline void set_w_3(float value)
{
___w_3 = value;
}
};
struct Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4_StaticFields
{
public:
// UnityEngine.Quaternion UnityEngine.Quaternion::identityQuaternion
Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___identityQuaternion_4;
public:
inline static int32_t get_offset_of_identityQuaternion_4() { return static_cast<int32_t>(offsetof(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4_StaticFields, ___identityQuaternion_4)); }
inline Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 get_identityQuaternion_4() const { return ___identityQuaternion_4; }
inline Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 * get_address_of_identityQuaternion_4() { return &___identityQuaternion_4; }
inline void set_identityQuaternion_4(Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 value)
{
___identityQuaternion_4 = value;
}
};
// UnityEngine.Rect
struct Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878
{
public:
// System.Single UnityEngine.Rect::m_XMin
float ___m_XMin_0;
// System.Single UnityEngine.Rect::m_YMin
float ___m_YMin_1;
// System.Single UnityEngine.Rect::m_Width
float ___m_Width_2;
// System.Single UnityEngine.Rect::m_Height
float ___m_Height_3;
public:
inline static int32_t get_offset_of_m_XMin_0() { return static_cast<int32_t>(offsetof(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878, ___m_XMin_0)); }
inline float get_m_XMin_0() const { return ___m_XMin_0; }
inline float* get_address_of_m_XMin_0() { return &___m_XMin_0; }
inline void set_m_XMin_0(float value)
{
___m_XMin_0 = value;
}
inline static int32_t get_offset_of_m_YMin_1() { return static_cast<int32_t>(offsetof(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878, ___m_YMin_1)); }
inline float get_m_YMin_1() const { return ___m_YMin_1; }
inline float* get_address_of_m_YMin_1() { return &___m_YMin_1; }
inline void set_m_YMin_1(float value)
{
___m_YMin_1 = value;
}
inline static int32_t get_offset_of_m_Width_2() { return static_cast<int32_t>(offsetof(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878, ___m_Width_2)); }
inline float get_m_Width_2() const { return ___m_Width_2; }
inline float* get_address_of_m_Width_2() { return &___m_Width_2; }
inline void set_m_Width_2(float value)
{
___m_Width_2 = value;
}
inline static int32_t get_offset_of_m_Height_3() { return static_cast<int32_t>(offsetof(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878, ___m_Height_3)); }
inline float get_m_Height_3() const { return ___m_Height_3; }
inline float* get_address_of_m_Height_3() { return &___m_Height_3; }
inline void set_m_Height_3(float value)
{
___m_Height_3 = value;
}
};
// System.Single
struct Single_tE07797BA3C98D4CA9B5A19413C19A76688AB899E
{
public:
// System.Single System.Single::m_value
float ___m_value_0;
public:
inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Single_tE07797BA3C98D4CA9B5A19413C19A76688AB899E, ___m_value_0)); }
inline float get_m_value_0() const { return ___m_value_0; }
inline float* get_address_of_m_value_0() { return &___m_value_0; }
inline void set_m_value_0(float value)
{
___m_value_0 = value;
}
};
// UnityEngine.Vector3
struct Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E
{
public:
// System.Single UnityEngine.Vector3::x
float ___x_2;
// System.Single UnityEngine.Vector3::y
float ___y_3;
// System.Single UnityEngine.Vector3::z
float ___z_4;
public:
inline static int32_t get_offset_of_x_2() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___x_2)); }
inline float get_x_2() const { return ___x_2; }
inline float* get_address_of_x_2() { return &___x_2; }
inline void set_x_2(float value)
{
___x_2 = value;
}
inline static int32_t get_offset_of_y_3() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___y_3)); }
inline float get_y_3() const { return ___y_3; }
inline float* get_address_of_y_3() { return &___y_3; }
inline void set_y_3(float value)
{
___y_3 = value;
}
inline static int32_t get_offset_of_z_4() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E, ___z_4)); }
inline float get_z_4() const { return ___z_4; }
inline float* get_address_of_z_4() { return &___z_4; }
inline void set_z_4(float value)
{
___z_4 = value;
}
};
struct Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields
{
public:
// UnityEngine.Vector3 UnityEngine.Vector3::zeroVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___zeroVector_5;
// UnityEngine.Vector3 UnityEngine.Vector3::oneVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___oneVector_6;
// UnityEngine.Vector3 UnityEngine.Vector3::upVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___upVector_7;
// UnityEngine.Vector3 UnityEngine.Vector3::downVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___downVector_8;
// UnityEngine.Vector3 UnityEngine.Vector3::leftVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___leftVector_9;
// UnityEngine.Vector3 UnityEngine.Vector3::rightVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___rightVector_10;
// UnityEngine.Vector3 UnityEngine.Vector3::forwardVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___forwardVector_11;
// UnityEngine.Vector3 UnityEngine.Vector3::backVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___backVector_12;
// UnityEngine.Vector3 UnityEngine.Vector3::positiveInfinityVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___positiveInfinityVector_13;
// UnityEngine.Vector3 UnityEngine.Vector3::negativeInfinityVector
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___negativeInfinityVector_14;
public:
inline static int32_t get_offset_of_zeroVector_5() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___zeroVector_5)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_zeroVector_5() const { return ___zeroVector_5; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_zeroVector_5() { return &___zeroVector_5; }
inline void set_zeroVector_5(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___zeroVector_5 = value;
}
inline static int32_t get_offset_of_oneVector_6() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___oneVector_6)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_oneVector_6() const { return ___oneVector_6; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_oneVector_6() { return &___oneVector_6; }
inline void set_oneVector_6(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___oneVector_6 = value;
}
inline static int32_t get_offset_of_upVector_7() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___upVector_7)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_upVector_7() const { return ___upVector_7; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_upVector_7() { return &___upVector_7; }
inline void set_upVector_7(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___upVector_7 = value;
}
inline static int32_t get_offset_of_downVector_8() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___downVector_8)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_downVector_8() const { return ___downVector_8; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_downVector_8() { return &___downVector_8; }
inline void set_downVector_8(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___downVector_8 = value;
}
inline static int32_t get_offset_of_leftVector_9() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___leftVector_9)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_leftVector_9() const { return ___leftVector_9; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_leftVector_9() { return &___leftVector_9; }
inline void set_leftVector_9(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___leftVector_9 = value;
}
inline static int32_t get_offset_of_rightVector_10() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___rightVector_10)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_rightVector_10() const { return ___rightVector_10; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_rightVector_10() { return &___rightVector_10; }
inline void set_rightVector_10(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___rightVector_10 = value;
}
inline static int32_t get_offset_of_forwardVector_11() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___forwardVector_11)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_forwardVector_11() const { return ___forwardVector_11; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_forwardVector_11() { return &___forwardVector_11; }
inline void set_forwardVector_11(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___forwardVector_11 = value;
}
inline static int32_t get_offset_of_backVector_12() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___backVector_12)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_backVector_12() const { return ___backVector_12; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_backVector_12() { return &___backVector_12; }
inline void set_backVector_12(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___backVector_12 = value;
}
inline static int32_t get_offset_of_positiveInfinityVector_13() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___positiveInfinityVector_13)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_positiveInfinityVector_13() const { return ___positiveInfinityVector_13; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_positiveInfinityVector_13() { return &___positiveInfinityVector_13; }
inline void set_positiveInfinityVector_13(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___positiveInfinityVector_13 = value;
}
inline static int32_t get_offset_of_negativeInfinityVector_14() { return static_cast<int32_t>(offsetof(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E_StaticFields, ___negativeInfinityVector_14)); }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E get_negativeInfinityVector_14() const { return ___negativeInfinityVector_14; }
inline Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * get_address_of_negativeInfinityVector_14() { return &___negativeInfinityVector_14; }
inline void set_negativeInfinityVector_14(Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E value)
{
___negativeInfinityVector_14 = value;
}
};
// System.Void
struct Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5
{
public:
union
{
struct
{
};
uint8_t Void_t700C6383A2A510C2CF4DD86DABD5CA9FF70ADAC5__padding[1];
};
public:
};
// UnityEngine.FilterMode
struct FilterMode_tE90A08FD96A142C761463D65E524BCDBFEEE3D19
{
public:
// System.Int32 UnityEngine.FilterMode::value__
int32_t ___value___2;
public:
inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(FilterMode_tE90A08FD96A142C761463D65E524BCDBFEEE3D19, ___value___2)); }
inline int32_t get_value___2() const { return ___value___2; }
inline int32_t* get_address_of_value___2() { return &___value___2; }
inline void set_value___2(int32_t value)
{
___value___2 = value;
}
};
// UnityEngine.Object
struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A : public RuntimeObject
{
public:
// System.IntPtr UnityEngine.Object::m_CachedPtr
intptr_t ___m_CachedPtr_0;
public:
inline static int32_t get_offset_of_m_CachedPtr_0() { return static_cast<int32_t>(offsetof(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A, ___m_CachedPtr_0)); }
inline intptr_t get_m_CachedPtr_0() const { return ___m_CachedPtr_0; }
inline intptr_t* get_address_of_m_CachedPtr_0() { return &___m_CachedPtr_0; }
inline void set_m_CachedPtr_0(intptr_t value)
{
___m_CachedPtr_0 = value;
}
};
struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_StaticFields
{
public:
// System.Int32 UnityEngine.Object::OffsetOfInstanceIDInCPlusPlusObject
int32_t ___OffsetOfInstanceIDInCPlusPlusObject_1;
public:
inline static int32_t get_offset_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return static_cast<int32_t>(offsetof(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_StaticFields, ___OffsetOfInstanceIDInCPlusPlusObject_1)); }
inline int32_t get_OffsetOfInstanceIDInCPlusPlusObject_1() const { return ___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline int32_t* get_address_of_OffsetOfInstanceIDInCPlusPlusObject_1() { return &___OffsetOfInstanceIDInCPlusPlusObject_1; }
inline void set_OffsetOfInstanceIDInCPlusPlusObject_1(int32_t value)
{
___OffsetOfInstanceIDInCPlusPlusObject_1 = value;
}
};
// Native definition for P/Invoke marshalling of UnityEngine.Object
struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_marshaled_pinvoke
{
intptr_t ___m_CachedPtr_0;
};
// Native definition for COM marshalling of UnityEngine.Object
struct Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_marshaled_com
{
intptr_t ___m_CachedPtr_0;
};
// UnityEngine.U2D.PixelPerfectCameraInternal
struct PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB : public RuntimeObject
{
public:
// UnityEngine.U2D.IPixelPerfectCamera UnityEngine.U2D.PixelPerfectCameraInternal::m_Component
RuntimeObject* ___m_Component_0;
// UnityEngine.U2D.PixelPerfectCamera UnityEngine.U2D.PixelPerfectCameraInternal::m_SerializableComponent
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * ___m_SerializableComponent_1;
// System.Single UnityEngine.U2D.PixelPerfectCameraInternal::originalOrthoSize
float ___originalOrthoSize_2;
// System.Boolean UnityEngine.U2D.PixelPerfectCameraInternal::hasPostProcessLayer
bool ___hasPostProcessLayer_3;
// System.Boolean UnityEngine.U2D.PixelPerfectCameraInternal::cropFrameXAndY
bool ___cropFrameXAndY_4;
// System.Boolean UnityEngine.U2D.PixelPerfectCameraInternal::cropFrameXOrY
bool ___cropFrameXOrY_5;
// System.Boolean UnityEngine.U2D.PixelPerfectCameraInternal::useStretchFill
bool ___useStretchFill_6;
// System.Int32 UnityEngine.U2D.PixelPerfectCameraInternal::zoom
int32_t ___zoom_7;
// System.Boolean UnityEngine.U2D.PixelPerfectCameraInternal::useOffscreenRT
bool ___useOffscreenRT_8;
// System.Int32 UnityEngine.U2D.PixelPerfectCameraInternal::offscreenRTWidth
int32_t ___offscreenRTWidth_9;
// System.Int32 UnityEngine.U2D.PixelPerfectCameraInternal::offscreenRTHeight
int32_t ___offscreenRTHeight_10;
// UnityEngine.Rect UnityEngine.U2D.PixelPerfectCameraInternal::pixelRect
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___pixelRect_11;
// System.Single UnityEngine.U2D.PixelPerfectCameraInternal::orthoSize
float ___orthoSize_12;
// System.Single UnityEngine.U2D.PixelPerfectCameraInternal::unitsPerPixel
float ___unitsPerPixel_13;
// System.Int32 UnityEngine.U2D.PixelPerfectCameraInternal::cinemachineVCamZoom
int32_t ___cinemachineVCamZoom_14;
public:
inline static int32_t get_offset_of_m_Component_0() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___m_Component_0)); }
inline RuntimeObject* get_m_Component_0() const { return ___m_Component_0; }
inline RuntimeObject** get_address_of_m_Component_0() { return &___m_Component_0; }
inline void set_m_Component_0(RuntimeObject* value)
{
___m_Component_0 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_Component_0), (void*)value);
}
inline static int32_t get_offset_of_m_SerializableComponent_1() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___m_SerializableComponent_1)); }
inline PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * get_m_SerializableComponent_1() const { return ___m_SerializableComponent_1; }
inline PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 ** get_address_of_m_SerializableComponent_1() { return &___m_SerializableComponent_1; }
inline void set_m_SerializableComponent_1(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * value)
{
___m_SerializableComponent_1 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_SerializableComponent_1), (void*)value);
}
inline static int32_t get_offset_of_originalOrthoSize_2() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___originalOrthoSize_2)); }
inline float get_originalOrthoSize_2() const { return ___originalOrthoSize_2; }
inline float* get_address_of_originalOrthoSize_2() { return &___originalOrthoSize_2; }
inline void set_originalOrthoSize_2(float value)
{
___originalOrthoSize_2 = value;
}
inline static int32_t get_offset_of_hasPostProcessLayer_3() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___hasPostProcessLayer_3)); }
inline bool get_hasPostProcessLayer_3() const { return ___hasPostProcessLayer_3; }
inline bool* get_address_of_hasPostProcessLayer_3() { return &___hasPostProcessLayer_3; }
inline void set_hasPostProcessLayer_3(bool value)
{
___hasPostProcessLayer_3 = value;
}
inline static int32_t get_offset_of_cropFrameXAndY_4() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___cropFrameXAndY_4)); }
inline bool get_cropFrameXAndY_4() const { return ___cropFrameXAndY_4; }
inline bool* get_address_of_cropFrameXAndY_4() { return &___cropFrameXAndY_4; }
inline void set_cropFrameXAndY_4(bool value)
{
___cropFrameXAndY_4 = value;
}
inline static int32_t get_offset_of_cropFrameXOrY_5() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___cropFrameXOrY_5)); }
inline bool get_cropFrameXOrY_5() const { return ___cropFrameXOrY_5; }
inline bool* get_address_of_cropFrameXOrY_5() { return &___cropFrameXOrY_5; }
inline void set_cropFrameXOrY_5(bool value)
{
___cropFrameXOrY_5 = value;
}
inline static int32_t get_offset_of_useStretchFill_6() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___useStretchFill_6)); }
inline bool get_useStretchFill_6() const { return ___useStretchFill_6; }
inline bool* get_address_of_useStretchFill_6() { return &___useStretchFill_6; }
inline void set_useStretchFill_6(bool value)
{
___useStretchFill_6 = value;
}
inline static int32_t get_offset_of_zoom_7() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___zoom_7)); }
inline int32_t get_zoom_7() const { return ___zoom_7; }
inline int32_t* get_address_of_zoom_7() { return &___zoom_7; }
inline void set_zoom_7(int32_t value)
{
___zoom_7 = value;
}
inline static int32_t get_offset_of_useOffscreenRT_8() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___useOffscreenRT_8)); }
inline bool get_useOffscreenRT_8() const { return ___useOffscreenRT_8; }
inline bool* get_address_of_useOffscreenRT_8() { return &___useOffscreenRT_8; }
inline void set_useOffscreenRT_8(bool value)
{
___useOffscreenRT_8 = value;
}
inline static int32_t get_offset_of_offscreenRTWidth_9() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___offscreenRTWidth_9)); }
inline int32_t get_offscreenRTWidth_9() const { return ___offscreenRTWidth_9; }
inline int32_t* get_address_of_offscreenRTWidth_9() { return &___offscreenRTWidth_9; }
inline void set_offscreenRTWidth_9(int32_t value)
{
___offscreenRTWidth_9 = value;
}
inline static int32_t get_offset_of_offscreenRTHeight_10() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___offscreenRTHeight_10)); }
inline int32_t get_offscreenRTHeight_10() const { return ___offscreenRTHeight_10; }
inline int32_t* get_address_of_offscreenRTHeight_10() { return &___offscreenRTHeight_10; }
inline void set_offscreenRTHeight_10(int32_t value)
{
___offscreenRTHeight_10 = value;
}
inline static int32_t get_offset_of_pixelRect_11() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___pixelRect_11)); }
inline Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 get_pixelRect_11() const { return ___pixelRect_11; }
inline Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * get_address_of_pixelRect_11() { return &___pixelRect_11; }
inline void set_pixelRect_11(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 value)
{
___pixelRect_11 = value;
}
inline static int32_t get_offset_of_orthoSize_12() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___orthoSize_12)); }
inline float get_orthoSize_12() const { return ___orthoSize_12; }
inline float* get_address_of_orthoSize_12() { return &___orthoSize_12; }
inline void set_orthoSize_12(float value)
{
___orthoSize_12 = value;
}
inline static int32_t get_offset_of_unitsPerPixel_13() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___unitsPerPixel_13)); }
inline float get_unitsPerPixel_13() const { return ___unitsPerPixel_13; }
inline float* get_address_of_unitsPerPixel_13() { return &___unitsPerPixel_13; }
inline void set_unitsPerPixel_13(float value)
{
___unitsPerPixel_13 = value;
}
inline static int32_t get_offset_of_cinemachineVCamZoom_14() { return static_cast<int32_t>(offsetof(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB, ___cinemachineVCamZoom_14)); }
inline int32_t get_cinemachineVCamZoom_14() const { return ___cinemachineVCamZoom_14; }
inline int32_t* get_address_of_cinemachineVCamZoom_14() { return &___cinemachineVCamZoom_14; }
inline void set_cinemachineVCamZoom_14(int32_t value)
{
___cinemachineVCamZoom_14 = value;
}
};
// UnityEngine.Component
struct Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 : public Object_tF2F3778131EFF286AF62B7B013A170F95A91571A
{
public:
public:
};
// UnityEngine.Texture
struct Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE : public Object_tF2F3778131EFF286AF62B7B013A170F95A91571A
{
public:
public:
};
struct Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE_StaticFields
{
public:
// System.Int32 UnityEngine.Texture::GenerateAllMips
int32_t ___GenerateAllMips_4;
public:
inline static int32_t get_offset_of_GenerateAllMips_4() { return static_cast<int32_t>(offsetof(Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE_StaticFields, ___GenerateAllMips_4)); }
inline int32_t get_GenerateAllMips_4() const { return ___GenerateAllMips_4; }
inline int32_t* get_address_of_GenerateAllMips_4() { return &___GenerateAllMips_4; }
inline void set_GenerateAllMips_4(int32_t value)
{
___GenerateAllMips_4 = value;
}
};
// UnityEngine.Behaviour
struct Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9 : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684
{
public:
public:
};
// UnityEngine.RenderTexture
struct RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 : public Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE
{
public:
public:
};
// UnityEngine.Transform
struct Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 : public Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684
{
public:
public:
};
// UnityEngine.Camera
struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C : public Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9
{
public:
public:
};
struct Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields
{
public:
// UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreCull
CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPreCull_4;
// UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPreRender
CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPreRender_5;
// UnityEngine.Camera/CameraCallback UnityEngine.Camera::onPostRender
CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * ___onPostRender_6;
public:
inline static int32_t get_offset_of_onPreCull_4() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPreCull_4)); }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPreCull_4() const { return ___onPreCull_4; }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPreCull_4() { return &___onPreCull_4; }
inline void set_onPreCull_4(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value)
{
___onPreCull_4 = value;
Il2CppCodeGenWriteBarrier((void**)(&___onPreCull_4), (void*)value);
}
inline static int32_t get_offset_of_onPreRender_5() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPreRender_5)); }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPreRender_5() const { return ___onPreRender_5; }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPreRender_5() { return &___onPreRender_5; }
inline void set_onPreRender_5(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value)
{
___onPreRender_5 = value;
Il2CppCodeGenWriteBarrier((void**)(&___onPreRender_5), (void*)value);
}
inline static int32_t get_offset_of_onPostRender_6() { return static_cast<int32_t>(offsetof(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_StaticFields, ___onPostRender_6)); }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * get_onPostRender_6() const { return ___onPostRender_6; }
inline CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D ** get_address_of_onPostRender_6() { return &___onPostRender_6; }
inline void set_onPostRender_6(CameraCallback_tD9E7B69E561CE2EFDEEDB0E7F1406AC52247160D * value)
{
___onPostRender_6 = value;
Il2CppCodeGenWriteBarrier((void**)(&___onPostRender_6), (void*)value);
}
};
// UnityEngine.MonoBehaviour
struct MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A : public Behaviour_t1A3DDDCF73B4627928FBFE02ED52B7251777DBD9
{
public:
public:
};
// UnityEngine.U2D.CinemachinePixelPerfect
struct CinemachinePixelPerfect_t18A5902325EFE9EAB86D12809C3E672555EAA6F1 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A
{
public:
public:
};
// UnityEngine.U2D.PixelPerfectCamera
struct PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 : public MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A
{
public:
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::m_AssetsPPU
int32_t ___m_AssetsPPU_4;
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::m_RefResolutionX
int32_t ___m_RefResolutionX_5;
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::m_RefResolutionY
int32_t ___m_RefResolutionY_6;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_UpscaleRT
bool ___m_UpscaleRT_7;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_PixelSnapping
bool ___m_PixelSnapping_8;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_CropFrameX
bool ___m_CropFrameX_9;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_CropFrameY
bool ___m_CropFrameY_10;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_StretchFill
bool ___m_StretchFill_11;
// UnityEngine.Camera UnityEngine.U2D.PixelPerfectCamera::m_Camera
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * ___m_Camera_12;
// UnityEngine.U2D.PixelPerfectCameraInternal UnityEngine.U2D.PixelPerfectCamera::m_Internal
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * ___m_Internal_13;
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::m_CinemachineCompatibilityMode
bool ___m_CinemachineCompatibilityMode_14;
public:
inline static int32_t get_offset_of_m_AssetsPPU_4() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_AssetsPPU_4)); }
inline int32_t get_m_AssetsPPU_4() const { return ___m_AssetsPPU_4; }
inline int32_t* get_address_of_m_AssetsPPU_4() { return &___m_AssetsPPU_4; }
inline void set_m_AssetsPPU_4(int32_t value)
{
___m_AssetsPPU_4 = value;
}
inline static int32_t get_offset_of_m_RefResolutionX_5() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_RefResolutionX_5)); }
inline int32_t get_m_RefResolutionX_5() const { return ___m_RefResolutionX_5; }
inline int32_t* get_address_of_m_RefResolutionX_5() { return &___m_RefResolutionX_5; }
inline void set_m_RefResolutionX_5(int32_t value)
{
___m_RefResolutionX_5 = value;
}
inline static int32_t get_offset_of_m_RefResolutionY_6() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_RefResolutionY_6)); }
inline int32_t get_m_RefResolutionY_6() const { return ___m_RefResolutionY_6; }
inline int32_t* get_address_of_m_RefResolutionY_6() { return &___m_RefResolutionY_6; }
inline void set_m_RefResolutionY_6(int32_t value)
{
___m_RefResolutionY_6 = value;
}
inline static int32_t get_offset_of_m_UpscaleRT_7() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_UpscaleRT_7)); }
inline bool get_m_UpscaleRT_7() const { return ___m_UpscaleRT_7; }
inline bool* get_address_of_m_UpscaleRT_7() { return &___m_UpscaleRT_7; }
inline void set_m_UpscaleRT_7(bool value)
{
___m_UpscaleRT_7 = value;
}
inline static int32_t get_offset_of_m_PixelSnapping_8() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_PixelSnapping_8)); }
inline bool get_m_PixelSnapping_8() const { return ___m_PixelSnapping_8; }
inline bool* get_address_of_m_PixelSnapping_8() { return &___m_PixelSnapping_8; }
inline void set_m_PixelSnapping_8(bool value)
{
___m_PixelSnapping_8 = value;
}
inline static int32_t get_offset_of_m_CropFrameX_9() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_CropFrameX_9)); }
inline bool get_m_CropFrameX_9() const { return ___m_CropFrameX_9; }
inline bool* get_address_of_m_CropFrameX_9() { return &___m_CropFrameX_9; }
inline void set_m_CropFrameX_9(bool value)
{
___m_CropFrameX_9 = value;
}
inline static int32_t get_offset_of_m_CropFrameY_10() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_CropFrameY_10)); }
inline bool get_m_CropFrameY_10() const { return ___m_CropFrameY_10; }
inline bool* get_address_of_m_CropFrameY_10() { return &___m_CropFrameY_10; }
inline void set_m_CropFrameY_10(bool value)
{
___m_CropFrameY_10 = value;
}
inline static int32_t get_offset_of_m_StretchFill_11() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_StretchFill_11)); }
inline bool get_m_StretchFill_11() const { return ___m_StretchFill_11; }
inline bool* get_address_of_m_StretchFill_11() { return &___m_StretchFill_11; }
inline void set_m_StretchFill_11(bool value)
{
___m_StretchFill_11 = value;
}
inline static int32_t get_offset_of_m_Camera_12() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_Camera_12)); }
inline Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * get_m_Camera_12() const { return ___m_Camera_12; }
inline Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C ** get_address_of_m_Camera_12() { return &___m_Camera_12; }
inline void set_m_Camera_12(Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * value)
{
___m_Camera_12 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_Camera_12), (void*)value);
}
inline static int32_t get_offset_of_m_Internal_13() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_Internal_13)); }
inline PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * get_m_Internal_13() const { return ___m_Internal_13; }
inline PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB ** get_address_of_m_Internal_13() { return &___m_Internal_13; }
inline void set_m_Internal_13(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * value)
{
___m_Internal_13 = value;
Il2CppCodeGenWriteBarrier((void**)(&___m_Internal_13), (void*)value);
}
inline static int32_t get_offset_of_m_CinemachineCompatibilityMode_14() { return static_cast<int32_t>(offsetof(PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8, ___m_CinemachineCompatibilityMode_14)); }
inline bool get_m_CinemachineCompatibilityMode_14() const { return ___m_CinemachineCompatibilityMode_14; }
inline bool* get_address_of_m_CinemachineCompatibilityMode_14() { return &___m_CinemachineCompatibilityMode_14; }
inline void set_m_CinemachineCompatibilityMode_14(bool value)
{
___m_CinemachineCompatibilityMode_14 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
// !!0 UnityEngine.Component::GetComponent<System.Object>()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RuntimeObject * Component_GetComponent_TisRuntimeObject_m69D9C576D6DD024C709E29EEADBC8041299A3AA7_gshared (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Debug::LogError(System.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Debug_LogError_m8850D65592770A364D494025FF3A73E8D4D70485 (RuntimeObject * ___message0, const RuntimeMethod* method);
// System.Void UnityEngine.MonoBehaviour::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED (MonoBehaviour_t37A501200D970A8257124B0EAE00A0FF3DDC354A * __this, const RuntimeMethod* method);
// System.Single UnityEngine.U2D.PixelPerfectCameraInternal::CorrectCinemachineOrthoSize(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PixelPerfectCameraInternal_CorrectCinemachineOrthoSize_mCE913421BC4294451DC3869F2EB052D3B3802ED1 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, float ___targetOrthoSize0, const RuntimeMethod* method);
// UnityEngine.Transform UnityEngine.Component::get_transform()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.Transform::get_position()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341 (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.U2D.PixelPerfectCamera::RoundToPixel(UnityEngine.Vector3)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E PixelPerfectCamera_RoundToPixel_m53B7AE007CD7E21B1B7DFD76A1F330364369C2D8 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position0, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.Vector3::op_Subtraction(UnityEngine.Vector3,UnityEngine.Vector3)
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___b1, const RuntimeMethod* method);
// UnityEngine.Vector3 UnityEngine.Vector3::op_UnaryNegation(UnityEngine.Vector3)
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, const RuntimeMethod* method);
// UnityEngine.Quaternion UnityEngine.Quaternion::get_identity()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 Quaternion_get_identity_mF2E565DBCE793A1AE6208056D42CA7C59D83A702 (const RuntimeMethod* method);
// System.Void UnityEngine.Vector3::.ctor(System.Single,System.Single,System.Single)
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method);
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::TRS(UnityEngine.Vector3,UnityEngine.Quaternion,UnityEngine.Vector3)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 Matrix4x4_TRS_m0CBC696D0BDF58DCEC40B99BC32C716FAD024CE5 (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___pos0, Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 ___q1, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___s2, const RuntimeMethod* method);
// UnityEngine.Matrix4x4 UnityEngine.Transform::get_worldToLocalMatrix()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 Transform_get_worldToLocalMatrix_mE22FDE24767E1DE402D3E7A1C9803379B2E8399D (Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * __this, const RuntimeMethod* method);
// UnityEngine.Matrix4x4 UnityEngine.Matrix4x4::op_Multiply(UnityEngine.Matrix4x4,UnityEngine.Matrix4x4)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 Matrix4x4_op_Multiply_mC2B30D333D4399C1693414F1A73D87FB3450F39F (Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 ___lhs0, Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 ___rhs1, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::set_worldToCameraMatrix(UnityEngine.Matrix4x4)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_set_worldToCameraMatrix_mD9E982CC4F356AC310C5B3145FC59FD73C420BE3 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 ___value0, const RuntimeMethod* method);
// !!0 UnityEngine.Component::GetComponent<UnityEngine.Camera>()
inline Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * Component_GetComponent_TisCamera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_mE17146EF5B0D8E9F9D2D2D94567BF211AD00D320 (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, const RuntimeMethod* method)
{
return (( Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * (*) (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 *, const RuntimeMethod*))Component_GetComponent_TisRuntimeObject_m69D9C576D6DD024C709E29EEADBC8041299A3AA7_gshared)(__this, method);
}
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::.ctor(UnityEngine.U2D.IPixelPerfectCamera)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal__ctor_m8BED9192421CD4B18053B0FEAEF480CE303ABA5C (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, RuntimeObject* ___component0, const RuntimeMethod* method);
// System.Single UnityEngine.Camera::get_orthographicSize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Camera_get_orthographicSize_m970DC87D428A71EDF30F9ED7D0E76E08B1BE4EFE (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// UnityEngine.Component UnityEngine.Component::GetComponent(System.String)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * Component_GetComponent_m23318D7E006D459CA053018DE416E6E1D71B4EB2 (Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * __this, String_t* ___type0, const RuntimeMethod* method);
// System.Boolean UnityEngine.Object::op_Inequality(UnityEngine.Object,UnityEngine.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90 (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A * ___x0, Object_tF2F3778131EFF286AF62B7B013A170F95A91571A * ___y1, const RuntimeMethod* method);
// UnityEngine.RenderTexture UnityEngine.Camera::get_targetTexture()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * Camera_get_targetTexture_m1DF637F05FF945625231DED8F3071795755DD4BF (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Debug::LogWarning(System.Object,UnityEngine.Object)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Debug_LogWarning_mE6AF3EFCF84F2296622CD42FBF9EEAF07244C0A8 (RuntimeObject * ___message0, Object_tF2F3778131EFF286AF62B7B013A170F95A91571A * ___context1, const RuntimeMethod* method);
// System.Int32 UnityEngine.Screen::get_width()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Screen_get_width_m52188F76E8AAF57BE373018CB14083BB74C43C1C (const RuntimeMethod* method);
// System.Int32 UnityEngine.Screen::get_height()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Screen_get_height_m110C90A573EE67895DC4F59E9165235EA22039EE (const RuntimeMethod* method);
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::CalculateCameraProperties(System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal_CalculateCameraProperties_mD30D52BC7D19045E2AD048A85CED88C50F3C97A9 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, int32_t ___screenWidth0, int32_t ___screenHeight1, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::set_forceIntoRenderTexture(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_set_forceIntoRenderTexture_m44C397F4C0E630B9AE3D153768FC771D759AB348 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, bool ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.U2D.PixelPerfectCamera::PixelSnap()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_PixelSnap_m91DD09A7F8EC7047E95D2853591589120C632549 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method);
// UnityEngine.Rect UnityEngine.Rect::get_zero()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589 (const RuntimeMethod* method);
// System.Boolean UnityEngine.Rect::op_Inequality(UnityEngine.Rect,UnityEngine.Rect)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Rect_op_Inequality_m6D87EE93EB6C68B78B8C044217EAFCE33EE12B66 (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___lhs0, Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___rhs1, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::set_pixelRect(UnityEngine.Rect)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_set_pixelRect_mB1BFC3EE5DB87F9A66ED0EBFC10B9F80DF1CC61B (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.Rect::.ctor(System.Single,System.Single,System.Single,System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rect__ctor_m12075526A02B55B680716A34AD5287B223122B70 (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, float ___x0, float ___y1, float ___width2, float ___height3, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::set_rect(UnityEngine.Rect)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_set_rect_m556222CD5D4975EF672DC33D979611405A173F79 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::set_orthographicSize(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_set_orthographicSize_mFC4BBB0BB0097A5FE13E99D8388DF3008971085F (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, float ___value0, const RuntimeMethod* method);
// System.Boolean UnityEngine.Camera::get_forceIntoRenderTexture()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Camera_get_forceIntoRenderTexture_mEB70D7C2721A8AB9FA61439DEC708A7A357EED12 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// System.Boolean UnityEngine.Camera::get_allowMSAA()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Camera_get_allowMSAA_m67C4EA3BF9AC0B742B4C34ED395D946502BCE10C (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// UnityEngine.Color UnityEngine.Color::get_black()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 Color_get_black_m67E91EB7017FC74D9AB5ADEF6B6929B7EFC9A982 (const RuntimeMethod* method);
// System.Void UnityEngine.GL::Clear(System.Boolean,System.Boolean,UnityEngine.Color)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GL_Clear_mF5FCE24D7F60731D6D88AA3DC98B0E88A644CD93 (bool ___clearDepth0, bool ___clearColor1, Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 ___backgroundColor2, const RuntimeMethod* method);
// System.Void UnityEngine.U2D.PixelPerfectRendering::set_pixelSnapSpacing(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectRendering_set_pixelSnapSpacing_m2294835A1D269249C71ACE16384E668369FF4919 (float ___value0, const RuntimeMethod* method);
// UnityEngine.RenderTexture UnityEngine.Camera::get_activeTexture()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * Camera_get_activeTexture_mD7F968C4D92DF00DB6568A3D7B56DF9C5FEFF15A (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Graphics::SetRenderTarget(UnityEngine.RenderTexture)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Graphics_SetRenderTarget_m78AE234327CCDBCEA288FBEFB53D6CEAD3EFC939 (RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * ___rt0, const RuntimeMethod* method);
// System.Void UnityEngine.GL::Viewport(UnityEngine.Rect)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void GL_Viewport_m461F6FF104488EF63474450B79D3A5107BCFC34B (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___pixelRect0, const RuntimeMethod* method);
// System.Void UnityEngine.Texture::set_filterMode(UnityEngine.FilterMode)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Texture_set_filterMode_m045141DB0FEFE496885D45F5F23B15BC0E77C8D0 (Texture_t9FE0218A1EEDF266E8C85879FE123265CACC95AE * __this, int32_t ___value0, const RuntimeMethod* method);
// System.Single UnityEngine.Camera::get_aspect()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Camera_get_aspect_mD0A1FC8F998473DA08866FF9CD61C02E6D5F4987 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// UnityEngine.Rect UnityEngine.U2D.PixelPerfectCameraInternal::CalculatePostRenderPixelRect(System.Single,System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 PixelPerfectCameraInternal_CalculatePostRenderPixelRect_mB3065A3B8D92AA9C1C21D38B0B4301C7E814C45E (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, float ___cameraAspect0, int32_t ___screenWidth1, int32_t ___screenHeight2, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::ResetAspect()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_ResetAspect_mC80AD4BC18EA0E1E05F9295B58B6E7A8DB9072C0 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Camera::ResetWorldToCameraMatrix()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Camera_ResetWorldToCameraMatrix_mE1FBF18A65E9B66FA0609D8D3A8A13052772C9B7 (Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * __this, const RuntimeMethod* method);
// System.Void System.Object::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405 (RuntimeObject * __this, const RuntimeMethod* method);
// System.Int32 System.Math::Min(System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Math_Min_m4C6E1589800A3AA57C1F430C3903847E8D7B4574 (int32_t ___val10, int32_t ___val21, const RuntimeMethod* method);
// System.Int32 System.Math::Max(System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Math_Max_mD8AA27386BF012C65303FCDEA041B0CC65056E7B (int32_t ___val10, int32_t ___val21, const RuntimeMethod* method);
// System.Void UnityEngine.Rect::set_width(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, float ___value0, const RuntimeMethod* method);
// System.Void UnityEngine.Rect::set_height(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23 (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, float ___value0, const RuntimeMethod* method);
// System.Single UnityEngine.Rect::get_width()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Rect_get_width_m4A0500D95CA84917787A8E90D26E66D49DFA90EF (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Rect::set_x(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rect_set_x_m1147A05B5046E1D4427E8EC99B9DFA4A32EEDEE6 (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, float ___value0, const RuntimeMethod* method);
// System.Single UnityEngine.Rect::get_height()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, const RuntimeMethod* method);
// System.Void UnityEngine.Rect::set_y(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void Rect_set_y_m015507262F8AC5AFF1B4E986B66307F31FB3A10E (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * __this, float ___value0, const RuntimeMethod* method);
// System.Boolean UnityEngine.Rect::op_Equality(UnityEngine.Rect,UnityEngine.Rect)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool Rect_op_Equality_m17C955A4F85F01A7CF0B43EDE41463301E93F6C1 (Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___lhs0, Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ___rhs1, const RuntimeMethod* method);
// System.Int32 UnityEngine.Mathf::RoundToInt(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t Mathf_RoundToInt_m56850BDF60FF9E3441CE57E5EFEFEF36EDCDE6DD (float ___f0, const RuntimeMethod* method);
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void UnityEngine.U2D.CinemachinePixelPerfect::OnEnable()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CinemachinePixelPerfect_OnEnable_m0E489FAB7721E805922D3593D76BCCFAFABD98D4 (CinemachinePixelPerfect_t18A5902325EFE9EAB86D12809C3E672555EAA6F1 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_tEB68BCBEB8EFD60F8043C67146DC05E7F50F374B_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral6B44A7675031FCAC57E28AD1002F65360C76AFF2);
s_Il2CppMethodInitialized = true;
}
{
// Debug.LogError("CinemachinePixelPerfect is now deprecated and doesn't function properly. Instead, use the one from Cinemachine v2.4.0 or newer.");
IL2CPP_RUNTIME_CLASS_INIT(Debug_tEB68BCBEB8EFD60F8043C67146DC05E7F50F374B_il2cpp_TypeInfo_var);
Debug_LogError_m8850D65592770A364D494025FF3A73E8D4D70485(_stringLiteral6B44A7675031FCAC57E28AD1002F65360C76AFF2, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.CinemachinePixelPerfect::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void CinemachinePixelPerfect__ctor_mBE4888A0C64FE6B3D47E0688B55695C4F69C0E14 (CinemachinePixelPerfect_t18A5902325EFE9EAB86D12809C3E672555EAA6F1 * __this, const RuntimeMethod* method)
{
{
MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::get_assetsPPU()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t PixelPerfectCamera_get_assetsPPU_mF294CEA88ED86AF12C3B288A32454145E655081D (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public int assetsPPU { get { return m_AssetsPPU; } set { m_AssetsPPU = value > 0 ? value : 1; } }
int32_t L_0 = __this->get_m_AssetsPPU_4();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_assetsPPU(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_assetsPPU_mAF321B9D68BFEEB5F460E85C99EDF3D7165DF270 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, int32_t ___value0, const RuntimeMethod* method)
{
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B2_0 = NULL;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B1_0 = NULL;
int32_t G_B3_0 = 0;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B3_1 = NULL;
{
// public int assetsPPU { get { return m_AssetsPPU; } set { m_AssetsPPU = value > 0 ? value : 1; } }
int32_t L_0 = ___value0;
G_B1_0 = __this;
if ((((int32_t)L_0) > ((int32_t)0)))
{
G_B2_0 = __this;
goto IL_0008;
}
}
{
G_B3_0 = 1;
G_B3_1 = G_B1_0;
goto IL_0009;
}
IL_0008:
{
int32_t L_1 = ___value0;
G_B3_0 = L_1;
G_B3_1 = G_B2_0;
}
IL_0009:
{
NullCheck(G_B3_1);
G_B3_1->set_m_AssetsPPU_4(G_B3_0);
// public int assetsPPU { get { return m_AssetsPPU; } set { m_AssetsPPU = value > 0 ? value : 1; } }
return;
}
}
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::get_refResolutionX()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t PixelPerfectCamera_get_refResolutionX_mD8E1DCEE1434AAC6761DEE8B73D4D163B858FE58 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public int refResolutionX { get { return m_RefResolutionX; } set { m_RefResolutionX = value > 0 ? value : 1; } }
int32_t L_0 = __this->get_m_RefResolutionX_5();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_refResolutionX(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_refResolutionX_mDA8E4201FF94E6B565DA3BFACC5A8B80F26C20C1 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, int32_t ___value0, const RuntimeMethod* method)
{
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B2_0 = NULL;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B1_0 = NULL;
int32_t G_B3_0 = 0;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B3_1 = NULL;
{
// public int refResolutionX { get { return m_RefResolutionX; } set { m_RefResolutionX = value > 0 ? value : 1; } }
int32_t L_0 = ___value0;
G_B1_0 = __this;
if ((((int32_t)L_0) > ((int32_t)0)))
{
G_B2_0 = __this;
goto IL_0008;
}
}
{
G_B3_0 = 1;
G_B3_1 = G_B1_0;
goto IL_0009;
}
IL_0008:
{
int32_t L_1 = ___value0;
G_B3_0 = L_1;
G_B3_1 = G_B2_0;
}
IL_0009:
{
NullCheck(G_B3_1);
G_B3_1->set_m_RefResolutionX_5(G_B3_0);
// public int refResolutionX { get { return m_RefResolutionX; } set { m_RefResolutionX = value > 0 ? value : 1; } }
return;
}
}
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::get_refResolutionY()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t PixelPerfectCamera_get_refResolutionY_m8C37A3DBC9014F034A78F9E921A11BAA113CB24F (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public int refResolutionY { get { return m_RefResolutionY; } set { m_RefResolutionY = value > 0 ? value : 1; } }
int32_t L_0 = __this->get_m_RefResolutionY_6();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_refResolutionY(System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_refResolutionY_mD0998785CF628E2E1841B232EDB53AAFDD60D86D (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, int32_t ___value0, const RuntimeMethod* method)
{
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B2_0 = NULL;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B1_0 = NULL;
int32_t G_B3_0 = 0;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * G_B3_1 = NULL;
{
// public int refResolutionY { get { return m_RefResolutionY; } set { m_RefResolutionY = value > 0 ? value : 1; } }
int32_t L_0 = ___value0;
G_B1_0 = __this;
if ((((int32_t)L_0) > ((int32_t)0)))
{
G_B2_0 = __this;
goto IL_0008;
}
}
{
G_B3_0 = 1;
G_B3_1 = G_B1_0;
goto IL_0009;
}
IL_0008:
{
int32_t L_1 = ___value0;
G_B3_0 = L_1;
G_B3_1 = G_B2_0;
}
IL_0009:
{
NullCheck(G_B3_1);
G_B3_1->set_m_RefResolutionY_6(G_B3_0);
// public int refResolutionY { get { return m_RefResolutionY; } set { m_RefResolutionY = value > 0 ? value : 1; } }
return;
}
}
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::get_upscaleRT()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool PixelPerfectCamera_get_upscaleRT_m36326F6B11D8D2CC33971B805344F2C6458E54C0 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public bool upscaleRT { get { return m_UpscaleRT; } set { m_UpscaleRT = value; } }
bool L_0 = __this->get_m_UpscaleRT_7();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_upscaleRT(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_upscaleRT_m870AC116618CC6358EB9403A59D7E54F0D56F0A9 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, bool ___value0, const RuntimeMethod* method)
{
{
// public bool upscaleRT { get { return m_UpscaleRT; } set { m_UpscaleRT = value; } }
bool L_0 = ___value0;
__this->set_m_UpscaleRT_7(L_0);
// public bool upscaleRT { get { return m_UpscaleRT; } set { m_UpscaleRT = value; } }
return;
}
}
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::get_pixelSnapping()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool PixelPerfectCamera_get_pixelSnapping_mF550795A64EA5FF77DECD748CA5FB21C00D9A121 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public bool pixelSnapping { get { return m_PixelSnapping; } set { m_PixelSnapping = value; } }
bool L_0 = __this->get_m_PixelSnapping_8();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_pixelSnapping(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_pixelSnapping_m9B77AA59CDF18E388D4E033FB5BDC8F950F36226 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, bool ___value0, const RuntimeMethod* method)
{
{
// public bool pixelSnapping { get { return m_PixelSnapping; } set { m_PixelSnapping = value; } }
bool L_0 = ___value0;
__this->set_m_PixelSnapping_8(L_0);
// public bool pixelSnapping { get { return m_PixelSnapping; } set { m_PixelSnapping = value; } }
return;
}
}
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::get_cropFrameX()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool PixelPerfectCamera_get_cropFrameX_mB81332B181CC77B077B48EC5B7B96CBA73912FA6 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public bool cropFrameX { get { return m_CropFrameX; } set { m_CropFrameX = value; } }
bool L_0 = __this->get_m_CropFrameX_9();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_cropFrameX(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_cropFrameX_m2E647446C63C83F20E38413E85698C49988E699C (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, bool ___value0, const RuntimeMethod* method)
{
{
// public bool cropFrameX { get { return m_CropFrameX; } set { m_CropFrameX = value; } }
bool L_0 = ___value0;
__this->set_m_CropFrameX_9(L_0);
// public bool cropFrameX { get { return m_CropFrameX; } set { m_CropFrameX = value; } }
return;
}
}
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::get_cropFrameY()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool PixelPerfectCamera_get_cropFrameY_m4DBB6A286AC29B2213E61B6397754C38E799A5D1 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public bool cropFrameY { get { return m_CropFrameY; } set { m_CropFrameY = value; } }
bool L_0 = __this->get_m_CropFrameY_10();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_cropFrameY(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_cropFrameY_m3EAE38E3B33718D14E290E711F73406B0DC5FC59 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, bool ___value0, const RuntimeMethod* method)
{
{
// public bool cropFrameY { get { return m_CropFrameY; } set { m_CropFrameY = value; } }
bool L_0 = ___value0;
__this->set_m_CropFrameY_10(L_0);
// public bool cropFrameY { get { return m_CropFrameY; } set { m_CropFrameY = value; } }
return;
}
}
// System.Boolean UnityEngine.U2D.PixelPerfectCamera::get_stretchFill()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR bool PixelPerfectCamera_get_stretchFill_m959164B6C59CB30C7EDDFFE93808C2CEEDFC3847 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// public bool stretchFill { get { return m_StretchFill; } set { m_StretchFill = value; } }
bool L_0 = __this->get_m_StretchFill_11();
return L_0;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::set_stretchFill(System.Boolean)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_set_stretchFill_m82F148F1225AB1B5E5C86043632CF6C3B07FA269 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, bool ___value0, const RuntimeMethod* method)
{
{
// public bool stretchFill { get { return m_StretchFill; } set { m_StretchFill = value; } }
bool L_0 = ___value0;
__this->set_m_StretchFill_11(L_0);
// public bool stretchFill { get { return m_StretchFill; } set { m_StretchFill = value; } }
return;
}
}
// System.Int32 UnityEngine.U2D.PixelPerfectCamera::get_pixelRatio()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR int32_t PixelPerfectCamera_get_pixelRatio_m8E1DC329C0C7551837F4AE0E1B70B9730042C96F (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// if (m_CinemachineCompatibilityMode)
bool L_0 = __this->get_m_CinemachineCompatibilityMode_14();
if (!L_0)
{
goto IL_0034;
}
}
{
// if (m_UpscaleRT)
bool L_1 = __this->get_m_UpscaleRT_7();
if (!L_1)
{
goto IL_0028;
}
}
{
// return m_Internal.zoom * m_Internal.cinemachineVCamZoom;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_2 = __this->get_m_Internal_13();
NullCheck(L_2);
int32_t L_3 = L_2->get_zoom_7();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_4 = __this->get_m_Internal_13();
NullCheck(L_4);
int32_t L_5 = L_4->get_cinemachineVCamZoom_14();
return ((int32_t)il2cpp_codegen_multiply((int32_t)L_3, (int32_t)L_5));
}
IL_0028:
{
// return m_Internal.cinemachineVCamZoom;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_6 = __this->get_m_Internal_13();
NullCheck(L_6);
int32_t L_7 = L_6->get_cinemachineVCamZoom_14();
return L_7;
}
IL_0034:
{
// return m_Internal.zoom;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_8 = __this->get_m_Internal_13();
NullCheck(L_8);
int32_t L_9 = L_8->get_zoom_7();
return L_9;
}
}
// UnityEngine.Vector3 UnityEngine.U2D.PixelPerfectCamera::RoundToPixel(UnityEngine.Vector3)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E PixelPerfectCamera_RoundToPixel_m53B7AE007CD7E21B1B7DFD76A1F330364369C2D8 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___position0, const RuntimeMethod* method)
{
float V_0 = 0.0f;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_1;
memset((&V_1), 0, sizeof(V_1));
{
// float unitsPerPixel = m_Internal.unitsPerPixel;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_0 = __this->get_m_Internal_13();
NullCheck(L_0);
float L_1 = L_0->get_unitsPerPixel_13();
V_0 = L_1;
// if (unitsPerPixel == 0.0f)
float L_2 = V_0;
if ((!(((float)L_2) == ((float)(0.0f)))))
{
goto IL_0016;
}
}
{
// return position;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_3 = ___position0;
return L_3;
}
IL_0016:
{
// result.x = Mathf.Round(position.x / unitsPerPixel) * unitsPerPixel;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4 = ___position0;
float L_5 = L_4.get_x_2();
float L_6 = V_0;
float L_7;
L_7 = bankers_roundf(((float)((float)L_5/(float)L_6)));
float L_8 = V_0;
(&V_1)->set_x_2(((float)il2cpp_codegen_multiply((float)L_7, (float)L_8)));
// result.y = Mathf.Round(position.y / unitsPerPixel) * unitsPerPixel;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_9 = ___position0;
float L_10 = L_9.get_y_3();
float L_11 = V_0;
float L_12;
L_12 = bankers_roundf(((float)((float)L_10/(float)L_11)));
float L_13 = V_0;
(&V_1)->set_y_3(((float)il2cpp_codegen_multiply((float)L_12, (float)L_13)));
// result.z = Mathf.Round(position.z / unitsPerPixel) * unitsPerPixel;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_14 = ___position0;
float L_15 = L_14.get_z_4();
float L_16 = V_0;
float L_17;
L_17 = bankers_roundf(((float)((float)L_15/(float)L_16)));
float L_18 = V_0;
(&V_1)->set_z_4(((float)il2cpp_codegen_multiply((float)L_17, (float)L_18)));
// return result;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_19 = V_1;
return L_19;
}
}
// System.Single UnityEngine.U2D.PixelPerfectCamera::CorrectCinemachineOrthoSize(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PixelPerfectCamera_CorrectCinemachineOrthoSize_m7187509929924F1A1DFEEAD8178161D7036A5CA3 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, float ___targetOrthoSize0, const RuntimeMethod* method)
{
{
// m_CinemachineCompatibilityMode = true;
__this->set_m_CinemachineCompatibilityMode_14((bool)1);
// if (m_Internal == null)
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_0 = __this->get_m_Internal_13();
if (L_0)
{
goto IL_0011;
}
}
{
// return targetOrthoSize;
float L_1 = ___targetOrthoSize0;
return L_1;
}
IL_0011:
{
// return m_Internal.CorrectCinemachineOrthoSize(targetOrthoSize);
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_2 = __this->get_m_Internal_13();
float L_3 = ___targetOrthoSize0;
NullCheck(L_2);
float L_4;
L_4 = PixelPerfectCameraInternal_CorrectCinemachineOrthoSize_mCE913421BC4294451DC3869F2EB052D3B3802ED1(L_2, L_3, /*hidden argument*/NULL);
return L_4;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::PixelSnap()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_PixelSnap_m91DD09A7F8EC7047E95D2853591589120C632549 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0;
memset((&V_0), 0, sizeof(V_0));
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_1;
memset((&V_1), 0, sizeof(V_1));
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 V_2;
memset((&V_2), 0, sizeof(V_2));
{
// Vector3 cameraPosition = m_Camera.transform.position;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_0 = __this->get_m_Camera_12();
NullCheck(L_0);
Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_1;
L_1 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_0, /*hidden argument*/NULL);
NullCheck(L_1);
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2;
L_2 = Transform_get_position_m40A8A9895568D56FFC687B57F30E8D53CB5EA341(L_1, /*hidden argument*/NULL);
V_0 = L_2;
// Vector3 roundedCameraPosition = RoundToPixel(cameraPosition);
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_3 = V_0;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4;
L_4 = PixelPerfectCamera_RoundToPixel_m53B7AE007CD7E21B1B7DFD76A1F330364369C2D8(__this, L_3, /*hidden argument*/NULL);
// Vector3 offset = roundedCameraPosition - cameraPosition;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_5 = V_0;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6;
L_6 = Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline(L_4, L_5, /*hidden argument*/NULL);
V_1 = L_6;
// offset.z = -offset.z;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_7 = V_1;
float L_8 = L_7.get_z_4();
(&V_1)->set_z_4(((-L_8)));
// Matrix4x4 offsetMatrix = Matrix4x4.TRS(-offset, Quaternion.identity, new Vector3(1.0f, 1.0f, -1.0f));
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_9 = V_1;
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_10;
L_10 = Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline(L_9, /*hidden argument*/NULL);
Quaternion_t6D28618CF65156D4A0AD747370DDFD0C514A31B4 L_11;
L_11 = Quaternion_get_identity_mF2E565DBCE793A1AE6208056D42CA7C59D83A702(/*hidden argument*/NULL);
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_12;
memset((&L_12), 0, sizeof(L_12));
Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_12), (1.0f), (1.0f), (-1.0f), /*hidden argument*/NULL);
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 L_13;
L_13 = Matrix4x4_TRS_m0CBC696D0BDF58DCEC40B99BC32C716FAD024CE5(L_10, L_11, L_12, /*hidden argument*/NULL);
V_2 = L_13;
// m_Camera.worldToCameraMatrix = offsetMatrix * m_Camera.transform.worldToLocalMatrix;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_14 = __this->get_m_Camera_12();
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 L_15 = V_2;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_16 = __this->get_m_Camera_12();
NullCheck(L_16);
Transform_tA8193BB29D4D2C7EC04918F3ED1816345186C3F1 * L_17;
L_17 = Component_get_transform_mE8496EBC45BEB1BADB5F314960F1DF1C952FA11F(L_16, /*hidden argument*/NULL);
NullCheck(L_17);
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 L_18;
L_18 = Transform_get_worldToLocalMatrix_mE22FDE24767E1DE402D3E7A1C9803379B2E8399D(L_17, /*hidden argument*/NULL);
Matrix4x4_tDE7FF4F2E2EA284F6EFE00D627789D0E5B8B4461 L_19;
L_19 = Matrix4x4_op_Multiply_mC2B30D333D4399C1693414F1A73D87FB3450F39F(L_15, L_18, /*hidden argument*/NULL);
NullCheck(L_14);
Camera_set_worldToCameraMatrix_mD9E982CC4F356AC310C5B3145FC59FD73C420BE3(L_14, L_19, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::Awake()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_Awake_m0EEA0D8C24DDBF0417409FC1ED92D46771038AF6 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Component_GetComponent_TisCamera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_mE17146EF5B0D8E9F9D2D2D94567BF211AD00D320_RuntimeMethod_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Debug_tEB68BCBEB8EFD60F8043C67146DC05E7F50F374B_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral69D2BC13326043EFBE8498680B311F3B34E06698);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&_stringLiteral6E3C394542AFDC0953291817DE5BAA9A9329CF27);
s_Il2CppMethodInitialized = true;
}
{
// m_Camera = GetComponent<Camera>();
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_0;
L_0 = Component_GetComponent_TisCamera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_mE17146EF5B0D8E9F9D2D2D94567BF211AD00D320(__this, /*hidden argument*/Component_GetComponent_TisCamera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C_mE17146EF5B0D8E9F9D2D2D94567BF211AD00D320_RuntimeMethod_var);
__this->set_m_Camera_12(L_0);
// m_Internal = new PixelPerfectCameraInternal(this);
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_1 = (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB *)il2cpp_codegen_object_new(PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB_il2cpp_TypeInfo_var);
PixelPerfectCameraInternal__ctor_m8BED9192421CD4B18053B0FEAEF480CE303ABA5C(L_1, __this, /*hidden argument*/NULL);
__this->set_m_Internal_13(L_1);
// m_Internal.originalOrthoSize = m_Camera.orthographicSize;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_2 = __this->get_m_Internal_13();
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_3 = __this->get_m_Camera_12();
NullCheck(L_3);
float L_4;
L_4 = Camera_get_orthographicSize_m970DC87D428A71EDF30F9ED7D0E76E08B1BE4EFE(L_3, /*hidden argument*/NULL);
NullCheck(L_2);
L_2->set_originalOrthoSize_2(L_4);
// m_Internal.hasPostProcessLayer = GetComponent("PostProcessLayer") != null; // query the component by name to avoid hard dependency
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_5 = __this->get_m_Internal_13();
Component_t62FBC8D2420DA4BE9037AFE430740F6B3EECA684 * L_6;
L_6 = Component_GetComponent_m23318D7E006D459CA053018DE416E6E1D71B4EB2(__this, _stringLiteral69D2BC13326043EFBE8498680B311F3B34E06698, /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
bool L_7;
L_7 = Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90(L_6, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
NullCheck(L_5);
L_5->set_hasPostProcessLayer_3(L_7);
// if (m_Camera.targetTexture != null)
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_8 = __this->get_m_Camera_12();
NullCheck(L_8);
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * L_9;
L_9 = Camera_get_targetTexture_m1DF637F05FF945625231DED8F3071795755DD4BF(L_8, /*hidden argument*/NULL);
bool L_10;
L_10 = Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90(L_9, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
if (!L_10)
{
goto IL_006d;
}
}
{
// Debug.LogWarning("Render to texture is not supported by Pixel Perfect Camera.", m_Camera);
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_11 = __this->get_m_Camera_12();
IL2CPP_RUNTIME_CLASS_INIT(Debug_tEB68BCBEB8EFD60F8043C67146DC05E7F50F374B_il2cpp_TypeInfo_var);
Debug_LogWarning_mE6AF3EFCF84F2296622CD42FBF9EEAF07244C0A8(_stringLiteral6E3C394542AFDC0953291817DE5BAA9A9329CF27, L_11, /*hidden argument*/NULL);
}
IL_006d:
{
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::LateUpdate()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_LateUpdate_m38D630FA419C6D0D2208872ED381B96ECAEC69D8 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * G_B2_0 = NULL;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * G_B1_0 = NULL;
int32_t G_B3_0 = 0;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * G_B3_1 = NULL;
{
// m_Internal.CalculateCameraProperties(Screen.width, Screen.height);
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_0 = __this->get_m_Internal_13();
int32_t L_1;
L_1 = Screen_get_width_m52188F76E8AAF57BE373018CB14083BB74C43C1C(/*hidden argument*/NULL);
int32_t L_2;
L_2 = Screen_get_height_m110C90A573EE67895DC4F59E9165235EA22039EE(/*hidden argument*/NULL);
NullCheck(L_0);
PixelPerfectCameraInternal_CalculateCameraProperties_mD30D52BC7D19045E2AD048A85CED88C50F3C97A9(L_0, L_1, L_2, /*hidden argument*/NULL);
// m_Camera.forceIntoRenderTexture = m_Internal.hasPostProcessLayer || m_Internal.useOffscreenRT;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_3 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_4 = __this->get_m_Internal_13();
NullCheck(L_4);
bool L_5 = L_4->get_hasPostProcessLayer_3();
G_B1_0 = L_3;
if (L_5)
{
G_B2_0 = L_3;
goto IL_0035;
}
}
{
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_6 = __this->get_m_Internal_13();
NullCheck(L_6);
bool L_7 = L_6->get_useOffscreenRT_8();
G_B3_0 = ((int32_t)(L_7));
G_B3_1 = G_B1_0;
goto IL_0036;
}
IL_0035:
{
G_B3_0 = 1;
G_B3_1 = G_B2_0;
}
IL_0036:
{
NullCheck(G_B3_1);
Camera_set_forceIntoRenderTexture_m44C397F4C0E630B9AE3D153768FC771D759AB348(G_B3_1, (bool)G_B3_0, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::OnPreCull()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_OnPreCull_m6E8A8435E206B526BFF26828025289409A981AB6 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// PixelSnap();
PixelPerfectCamera_PixelSnap_m91DD09A7F8EC7047E95D2853591589120C632549(__this, /*hidden argument*/NULL);
// if (m_Internal.pixelRect != Rect.zero)
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_0 = __this->get_m_Internal_13();
NullCheck(L_0);
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_1 = L_0->get_pixelRect_11();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_2;
L_2 = Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589(/*hidden argument*/NULL);
bool L_3;
L_3 = Rect_op_Inequality_m6D87EE93EB6C68B78B8C044217EAFCE33EE12B66(L_1, L_2, /*hidden argument*/NULL);
if (!L_3)
{
goto IL_0035;
}
}
{
// m_Camera.pixelRect = m_Internal.pixelRect;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_4 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_5 = __this->get_m_Internal_13();
NullCheck(L_5);
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_6 = L_5->get_pixelRect_11();
NullCheck(L_4);
Camera_set_pixelRect_mB1BFC3EE5DB87F9A66ED0EBFC10B9F80DF1CC61B(L_4, L_6, /*hidden argument*/NULL);
goto IL_0059;
}
IL_0035:
{
// m_Camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_7 = __this->get_m_Camera_12();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_8;
memset((&L_8), 0, sizeof(L_8));
Rect__ctor_m12075526A02B55B680716A34AD5287B223122B70((&L_8), (0.0f), (0.0f), (1.0f), (1.0f), /*hidden argument*/NULL);
NullCheck(L_7);
Camera_set_rect_m556222CD5D4975EF672DC33D979611405A173F79(L_7, L_8, /*hidden argument*/NULL);
}
IL_0059:
{
// if (!m_CinemachineCompatibilityMode)
bool L_9 = __this->get_m_CinemachineCompatibilityMode_14();
if (L_9)
{
goto IL_0077;
}
}
{
// m_Camera.orthographicSize = m_Internal.orthoSize;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_10 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_11 = __this->get_m_Internal_13();
NullCheck(L_11);
float L_12 = L_11->get_orthoSize_12();
NullCheck(L_10);
Camera_set_orthographicSize_mFC4BBB0BB0097A5FE13E99D8388DF3008971085F(L_10, L_12, /*hidden argument*/NULL);
}
IL_0077:
{
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::OnPreRender()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_OnPreRender_mF532865494E97AE563AEBE9B4496C9C1B55E87F4 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// if (m_Internal.cropFrameXOrY && !m_Camera.forceIntoRenderTexture && !m_Camera.allowMSAA)
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_0 = __this->get_m_Internal_13();
NullCheck(L_0);
bool L_1 = L_0->get_cropFrameXOrY_5();
if (!L_1)
{
goto IL_0033;
}
}
{
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_2 = __this->get_m_Camera_12();
NullCheck(L_2);
bool L_3;
L_3 = Camera_get_forceIntoRenderTexture_mEB70D7C2721A8AB9FA61439DEC708A7A357EED12(L_2, /*hidden argument*/NULL);
if (L_3)
{
goto IL_0033;
}
}
{
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_4 = __this->get_m_Camera_12();
NullCheck(L_4);
bool L_5;
L_5 = Camera_get_allowMSAA_m67C4EA3BF9AC0B742B4C34ED395D946502BCE10C(L_4, /*hidden argument*/NULL);
if (L_5)
{
goto IL_0033;
}
}
{
// GL.Clear(false, true, Color.black);
Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 L_6;
L_6 = Color_get_black_m67E91EB7017FC74D9AB5ADEF6B6929B7EFC9A982(/*hidden argument*/NULL);
GL_Clear_mF5FCE24D7F60731D6D88AA3DC98B0E88A644CD93((bool)0, (bool)1, L_6, /*hidden argument*/NULL);
}
IL_0033:
{
// PixelPerfectRendering.pixelSnapSpacing = m_Internal.unitsPerPixel;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_7 = __this->get_m_Internal_13();
NullCheck(L_7);
float L_8 = L_7->get_unitsPerPixel_13();
PixelPerfectRendering_set_pixelSnapSpacing_m2294835A1D269249C71ACE16384E668369FF4919(L_8, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::OnPostRender()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_OnPostRender_m38D6AE9701187DACFC115503F17C6275AA176D43 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Graphics_t97FAEBE964F3F622D4865E7EC62717FE94D1F56D_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * V_0 = NULL;
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * G_B7_0 = NULL;
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * G_B6_0 = NULL;
int32_t G_B8_0 = 0;
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * G_B8_1 = NULL;
{
// PixelPerfectRendering.pixelSnapSpacing = 0.0f;
PixelPerfectRendering_set_pixelSnapSpacing_m2294835A1D269249C71ACE16384E668369FF4919((0.0f), /*hidden argument*/NULL);
// if (m_Camera.activeTexture != null)
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_0 = __this->get_m_Camera_12();
NullCheck(L_0);
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * L_1;
L_1 = Camera_get_activeTexture_mD7F968C4D92DF00DB6568A3D7B56DF9C5FEFF15A(L_0, /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
bool L_2;
L_2 = Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90(L_1, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
if (!L_2)
{
goto IL_004f;
}
}
{
// Graphics.SetRenderTarget(null as RenderTexture);
IL2CPP_RUNTIME_CLASS_INIT(Graphics_t97FAEBE964F3F622D4865E7EC62717FE94D1F56D_il2cpp_TypeInfo_var);
Graphics_SetRenderTarget_m78AE234327CCDBCEA288FBEFB53D6CEAD3EFC939((RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 *)NULL, /*hidden argument*/NULL);
// GL.Viewport(new Rect(0.0f, 0.0f, Screen.width, Screen.height));
int32_t L_3;
L_3 = Screen_get_width_m52188F76E8AAF57BE373018CB14083BB74C43C1C(/*hidden argument*/NULL);
int32_t L_4;
L_4 = Screen_get_height_m110C90A573EE67895DC4F59E9165235EA22039EE(/*hidden argument*/NULL);
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_5;
memset((&L_5), 0, sizeof(L_5));
Rect__ctor_m12075526A02B55B680716A34AD5287B223122B70((&L_5), (0.0f), (0.0f), ((float)((float)L_3)), ((float)((float)L_4)), /*hidden argument*/NULL);
GL_Viewport_m461F6FF104488EF63474450B79D3A5107BCFC34B(L_5, /*hidden argument*/NULL);
// GL.Clear(false, true, Color.black);
Color_tF40DAF76C04FFECF3FE6024F85A294741C9CC659 L_6;
L_6 = Color_get_black_m67E91EB7017FC74D9AB5ADEF6B6929B7EFC9A982(/*hidden argument*/NULL);
GL_Clear_mF5FCE24D7F60731D6D88AA3DC98B0E88A644CD93((bool)0, (bool)1, L_6, /*hidden argument*/NULL);
}
IL_004f:
{
// if (!m_Internal.useOffscreenRT)
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_7 = __this->get_m_Internal_13();
NullCheck(L_7);
bool L_8 = L_7->get_useOffscreenRT_8();
if (L_8)
{
goto IL_005d;
}
}
{
// return;
return;
}
IL_005d:
{
// RenderTexture activeRT = m_Camera.activeTexture;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_9 = __this->get_m_Camera_12();
NullCheck(L_9);
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * L_10;
L_10 = Camera_get_activeTexture_mD7F968C4D92DF00DB6568A3D7B56DF9C5FEFF15A(L_9, /*hidden argument*/NULL);
V_0 = L_10;
// if (activeRT != null)
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * L_11 = V_0;
IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
bool L_12;
L_12 = Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90(L_11, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
if (!L_12)
{
goto IL_0089;
}
}
{
// activeRT.filterMode = m_Internal.useStretchFill ? FilterMode.Bilinear : FilterMode.Point;
RenderTexture_t5FE7A5B47EF962A0E8D7BEBA05E9FC87D49A1849 * L_13 = V_0;
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_14 = __this->get_m_Internal_13();
NullCheck(L_14);
bool L_15 = L_14->get_useStretchFill_6();
G_B6_0 = L_13;
if (L_15)
{
G_B7_0 = L_13;
goto IL_0083;
}
}
{
G_B8_0 = 0;
G_B8_1 = G_B6_0;
goto IL_0084;
}
IL_0083:
{
G_B8_0 = 1;
G_B8_1 = G_B7_0;
}
IL_0084:
{
NullCheck(G_B8_1);
Texture_set_filterMode_m045141DB0FEFE496885D45F5F23B15BC0E77C8D0(G_B8_1, G_B8_0, /*hidden argument*/NULL);
}
IL_0089:
{
// m_Camera.pixelRect = m_Internal.CalculatePostRenderPixelRect(m_Camera.aspect, Screen.width, Screen.height);
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_16 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_17 = __this->get_m_Internal_13();
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_18 = __this->get_m_Camera_12();
NullCheck(L_18);
float L_19;
L_19 = Camera_get_aspect_mD0A1FC8F998473DA08866FF9CD61C02E6D5F4987(L_18, /*hidden argument*/NULL);
int32_t L_20;
L_20 = Screen_get_width_m52188F76E8AAF57BE373018CB14083BB74C43C1C(/*hidden argument*/NULL);
int32_t L_21;
L_21 = Screen_get_height_m110C90A573EE67895DC4F59E9165235EA22039EE(/*hidden argument*/NULL);
NullCheck(L_17);
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_22;
L_22 = PixelPerfectCameraInternal_CalculatePostRenderPixelRect_mB3065A3B8D92AA9C1C21D38B0B4301C7E814C45E(L_17, L_19, L_20, L_21, /*hidden argument*/NULL);
NullCheck(L_16);
Camera_set_pixelRect_mB1BFC3EE5DB87F9A66ED0EBFC10B9F80DF1CC61B(L_16, L_22, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::OnEnable()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_OnEnable_m901D29B12074BAB16C429BAF4B768DE837B6D5F0 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// m_CinemachineCompatibilityMode = false;
__this->set_m_CinemachineCompatibilityMode_14((bool)0);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::OnDisable()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera_OnDisable_m1ED518FBFC9C85DDC263ADD3BE56571EF7726D96 (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// m_Camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_0 = __this->get_m_Camera_12();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_1;
memset((&L_1), 0, sizeof(L_1));
Rect__ctor_m12075526A02B55B680716A34AD5287B223122B70((&L_1), (0.0f), (0.0f), (1.0f), (1.0f), /*hidden argument*/NULL);
NullCheck(L_0);
Camera_set_rect_m556222CD5D4975EF672DC33D979611405A173F79(L_0, L_1, /*hidden argument*/NULL);
// m_Camera.orthographicSize = m_Internal.originalOrthoSize;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_2 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_3 = __this->get_m_Internal_13();
NullCheck(L_3);
float L_4 = L_3->get_originalOrthoSize_2();
NullCheck(L_2);
Camera_set_orthographicSize_mFC4BBB0BB0097A5FE13E99D8388DF3008971085F(L_2, L_4, /*hidden argument*/NULL);
// m_Camera.forceIntoRenderTexture = m_Internal.hasPostProcessLayer;
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_5 = __this->get_m_Camera_12();
PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * L_6 = __this->get_m_Internal_13();
NullCheck(L_6);
bool L_7 = L_6->get_hasPostProcessLayer_3();
NullCheck(L_5);
Camera_set_forceIntoRenderTexture_m44C397F4C0E630B9AE3D153768FC771D759AB348(L_5, L_7, /*hidden argument*/NULL);
// m_Camera.ResetAspect();
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_8 = __this->get_m_Camera_12();
NullCheck(L_8);
Camera_ResetAspect_mC80AD4BC18EA0E1E05F9295B58B6E7A8DB9072C0(L_8, /*hidden argument*/NULL);
// m_Camera.ResetWorldToCameraMatrix();
Camera_tC44E094BAB53AFC8A014C6F9CFCE11F4FC38006C * L_9 = __this->get_m_Camera_12();
NullCheck(L_9);
Camera_ResetWorldToCameraMatrix_mE1FBF18A65E9B66FA0609D8D3A8A13052772C9B7(L_9, /*hidden argument*/NULL);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCamera::.ctor()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCamera__ctor_mFBF09FC28EF3435A09273EF69AE9D085698F36DF (PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * __this, const RuntimeMethod* method)
{
{
// int m_AssetsPPU = 100;
__this->set_m_AssetsPPU_4(((int32_t)100));
// int m_RefResolutionX = 320;
__this->set_m_RefResolutionX_5(((int32_t)320));
// int m_RefResolutionY = 180;
__this->set_m_RefResolutionY_6(((int32_t)180));
MonoBehaviour__ctor_mC0995D847F6A95B1A553652636C38A2AA8B13BED(__this, /*hidden argument*/NULL);
return;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::.ctor(UnityEngine.U2D.IPixelPerfectCamera)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal__ctor_m8BED9192421CD4B18053B0FEAEF480CE303ABA5C (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, RuntimeObject* ___component0, const RuntimeMethod* method)
{
{
// internal int zoom = 1;
__this->set_zoom_7(1);
// internal Rect pixelRect = Rect.zero;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_0;
L_0 = Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589(/*hidden argument*/NULL);
__this->set_pixelRect_11(L_0);
// internal float orthoSize = 1.0f;
__this->set_orthoSize_12((1.0f));
// internal int cinemachineVCamZoom = 1;
__this->set_cinemachineVCamZoom_14(1);
// internal PixelPerfectCameraInternal(IPixelPerfectCamera component)
Object__ctor_m88880E0413421D13FD95325EDCE231707CE1F405(__this, /*hidden argument*/NULL);
// m_Component = component;
RuntimeObject* L_1 = ___component0;
__this->set_m_Component_0(L_1);
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::OnBeforeSerialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal_OnBeforeSerialize_m103DED2AF898C493C950A670BF7148F465D5AE23 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// m_SerializableComponent = m_Component as PixelPerfectCamera;
RuntimeObject* L_0 = __this->get_m_Component_0();
__this->set_m_SerializableComponent_1(((PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 *)IsInstClass((RuntimeObject*)L_0, PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8_il2cpp_TypeInfo_var)));
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::OnAfterDeserialize()
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal_OnAfterDeserialize_m8FC18117BF7136FDB3D949F29554D45121F90187 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
{
// if (m_SerializableComponent != null)
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * L_0 = __this->get_m_SerializableComponent_1();
IL2CPP_RUNTIME_CLASS_INIT(Object_tF2F3778131EFF286AF62B7B013A170F95A91571A_il2cpp_TypeInfo_var);
bool L_1;
L_1 = Object_op_Inequality_mE1F187520BD83FB7D86A6D850710C4D42B864E90(L_0, (Object_tF2F3778131EFF286AF62B7B013A170F95A91571A *)NULL, /*hidden argument*/NULL);
if (!L_1)
{
goto IL_001a;
}
}
{
// m_Component = m_SerializableComponent;
PixelPerfectCamera_tAEEA2988EBDE91F2C7D260CDA6B65FB24261CFE8 * L_2 = __this->get_m_SerializableComponent_1();
__this->set_m_Component_0(L_2);
}
IL_001a:
{
// }
return;
}
}
// System.Void UnityEngine.U2D.PixelPerfectCameraInternal::CalculateCameraProperties(System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR void PixelPerfectCameraInternal_CalculateCameraProperties_mD30D52BC7D19045E2AD048A85CED88C50F3C97A9 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, int32_t ___screenWidth0, int32_t ___screenHeight1, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
int32_t V_0 = 0;
int32_t V_1 = 0;
int32_t V_2 = 0;
bool V_3 = false;
bool V_4 = false;
bool V_5 = false;
bool V_6 = false;
bool V_7 = false;
int32_t V_8 = 0;
int32_t V_9 = 0;
float V_10 = 0.0f;
float V_11 = 0.0f;
float G_B29_0 = 0.0f;
float G_B36_0 = 0.0f;
{
// int assetsPPU = m_Component.assetsPPU;
RuntimeObject* L_0 = __this->get_m_Component_0();
NullCheck(L_0);
int32_t L_1;
L_1 = InterfaceFuncInvoker0< int32_t >::Invoke(0 /* System.Int32 UnityEngine.U2D.IPixelPerfectCamera::get_assetsPPU() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_0);
V_0 = L_1;
// int refResolutionX = m_Component.refResolutionX;
RuntimeObject* L_2 = __this->get_m_Component_0();
NullCheck(L_2);
int32_t L_3;
L_3 = InterfaceFuncInvoker0< int32_t >::Invoke(2 /* System.Int32 UnityEngine.U2D.IPixelPerfectCamera::get_refResolutionX() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_2);
V_1 = L_3;
// int refResolutionY = m_Component.refResolutionY;
RuntimeObject* L_4 = __this->get_m_Component_0();
NullCheck(L_4);
int32_t L_5;
L_5 = InterfaceFuncInvoker0< int32_t >::Invoke(4 /* System.Int32 UnityEngine.U2D.IPixelPerfectCamera::get_refResolutionY() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_4);
V_2 = L_5;
// bool upscaleRT = m_Component.upscaleRT;
RuntimeObject* L_6 = __this->get_m_Component_0();
NullCheck(L_6);
bool L_7;
L_7 = InterfaceFuncInvoker0< bool >::Invoke(6 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_upscaleRT() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_6);
V_3 = L_7;
// bool pixelSnapping = m_Component.pixelSnapping;
RuntimeObject* L_8 = __this->get_m_Component_0();
NullCheck(L_8);
bool L_9;
L_9 = InterfaceFuncInvoker0< bool >::Invoke(8 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_pixelSnapping() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_8);
V_4 = L_9;
// bool cropFrameX = m_Component.cropFrameX;
RuntimeObject* L_10 = __this->get_m_Component_0();
NullCheck(L_10);
bool L_11;
L_11 = InterfaceFuncInvoker0< bool >::Invoke(10 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_cropFrameX() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_10);
V_5 = L_11;
// bool cropFrameY = m_Component.cropFrameY;
RuntimeObject* L_12 = __this->get_m_Component_0();
NullCheck(L_12);
bool L_13;
L_13 = InterfaceFuncInvoker0< bool >::Invoke(12 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_cropFrameY() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_12);
V_6 = L_13;
// bool stretchFill = m_Component.stretchFill;
RuntimeObject* L_14 = __this->get_m_Component_0();
NullCheck(L_14);
bool L_15;
L_15 = InterfaceFuncInvoker0< bool >::Invoke(14 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_stretchFill() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_14);
V_7 = L_15;
// cropFrameXAndY = cropFrameY && cropFrameX;
bool L_16 = V_6;
bool L_17 = V_5;
__this->set_cropFrameXAndY_4((bool)((int32_t)((int32_t)L_16&(int32_t)L_17)));
// cropFrameXOrY = cropFrameY || cropFrameX;
bool L_18 = V_6;
bool L_19 = V_5;
__this->set_cropFrameXOrY_5((bool)((int32_t)((int32_t)L_18|(int32_t)L_19)));
// useStretchFill = cropFrameXAndY && stretchFill;
bool L_20 = __this->get_cropFrameXAndY_4();
bool L_21 = V_7;
__this->set_useStretchFill_6((bool)((int32_t)((int32_t)L_20&(int32_t)L_21)));
// int verticalZoom = screenHeight / refResolutionY;
int32_t L_22 = ___screenHeight1;
int32_t L_23 = V_2;
V_8 = ((int32_t)((int32_t)L_22/(int32_t)L_23));
// int horizontalZoom = screenWidth / refResolutionX;
int32_t L_24 = ___screenWidth0;
int32_t L_25 = V_1;
V_9 = ((int32_t)((int32_t)L_24/(int32_t)L_25));
// zoom = Math.Max(1, Math.Min(verticalZoom, horizontalZoom));
int32_t L_26 = V_8;
int32_t L_27 = V_9;
IL2CPP_RUNTIME_CLASS_INIT(Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var);
int32_t L_28;
L_28 = Math_Min_m4C6E1589800A3AA57C1F430C3903847E8D7B4574(L_26, L_27, /*hidden argument*/NULL);
int32_t L_29;
L_29 = Math_Max_mD8AA27386BF012C65303FCDEA041B0CC65056E7B(1, L_28, /*hidden argument*/NULL);
__this->set_zoom_7(L_29);
// useOffscreenRT = false;
__this->set_useOffscreenRT_8((bool)0);
// offscreenRTWidth = 0;
__this->set_offscreenRTWidth_9(0);
// offscreenRTHeight = 0;
__this->set_offscreenRTHeight_10(0);
// if (cropFrameXOrY)
bool L_30 = __this->get_cropFrameXOrY_5();
if (!L_30)
{
goto IL_0157;
}
}
{
// if (!upscaleRT)
bool L_31 = V_3;
if (L_31)
{
goto IL_00fe;
}
}
{
// if (useStretchFill)
bool L_32 = __this->get_useStretchFill_6();
if (!L_32)
{
goto IL_018e;
}
}
{
// useOffscreenRT = true;
__this->set_useOffscreenRT_8((bool)1);
// offscreenRTWidth = zoom * refResolutionX;
int32_t L_33 = __this->get_zoom_7();
int32_t L_34 = V_1;
__this->set_offscreenRTWidth_9(((int32_t)il2cpp_codegen_multiply((int32_t)L_33, (int32_t)L_34)));
// offscreenRTHeight = zoom * refResolutionY;
int32_t L_35 = __this->get_zoom_7();
int32_t L_36 = V_2;
__this->set_offscreenRTHeight_10(((int32_t)il2cpp_codegen_multiply((int32_t)L_35, (int32_t)L_36)));
// }
goto IL_018e;
}
IL_00fe:
{
// useOffscreenRT = true;
__this->set_useOffscreenRT_8((bool)1);
// if (cropFrameXAndY)
bool L_37 = __this->get_cropFrameXAndY_4();
if (!L_37)
{
goto IL_011d;
}
}
{
// offscreenRTWidth = refResolutionX;
int32_t L_38 = V_1;
__this->set_offscreenRTWidth_9(L_38);
// offscreenRTHeight = refResolutionY;
int32_t L_39 = V_2;
__this->set_offscreenRTHeight_10(L_39);
// }
goto IL_018e;
}
IL_011d:
{
// else if (cropFrameY)
bool L_40 = V_6;
if (!L_40)
{
goto IL_013c;
}
}
{
// offscreenRTWidth = screenWidth / zoom / 2 * 2; // Make sure it's an even number by / 2 * 2.
int32_t L_41 = ___screenWidth0;
int32_t L_42 = __this->get_zoom_7();
__this->set_offscreenRTWidth_9(((int32_t)il2cpp_codegen_multiply((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_41/(int32_t)L_42))/(int32_t)2)), (int32_t)2)));
// offscreenRTHeight = refResolutionY;
int32_t L_43 = V_2;
__this->set_offscreenRTHeight_10(L_43);
// }
goto IL_018e;
}
IL_013c:
{
// offscreenRTWidth = refResolutionX;
int32_t L_44 = V_1;
__this->set_offscreenRTWidth_9(L_44);
// offscreenRTHeight = screenHeight / zoom / 2 * 2; // Make sure it's an even number by / 2 * 2.
int32_t L_45 = ___screenHeight1;
int32_t L_46 = __this->get_zoom_7();
__this->set_offscreenRTHeight_10(((int32_t)il2cpp_codegen_multiply((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_45/(int32_t)L_46))/(int32_t)2)), (int32_t)2)));
// }
goto IL_018e;
}
IL_0157:
{
// else if (upscaleRT && zoom > 1)
bool L_47 = V_3;
if (!L_47)
{
goto IL_018e;
}
}
{
int32_t L_48 = __this->get_zoom_7();
if ((((int32_t)L_48) <= ((int32_t)1)))
{
goto IL_018e;
}
}
{
// useOffscreenRT = true;
__this->set_useOffscreenRT_8((bool)1);
// offscreenRTWidth = screenWidth / zoom / 2 * 2; // Make sure it's an even number by / 2 * 2.
int32_t L_49 = ___screenWidth0;
int32_t L_50 = __this->get_zoom_7();
__this->set_offscreenRTWidth_9(((int32_t)il2cpp_codegen_multiply((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_49/(int32_t)L_50))/(int32_t)2)), (int32_t)2)));
// offscreenRTHeight = screenHeight / zoom / 2 * 2;
int32_t L_51 = ___screenHeight1;
int32_t L_52 = __this->get_zoom_7();
__this->set_offscreenRTHeight_10(((int32_t)il2cpp_codegen_multiply((int32_t)((int32_t)((int32_t)((int32_t)((int32_t)L_51/(int32_t)L_52))/(int32_t)2)), (int32_t)2)));
}
IL_018e:
{
// pixelRect = Rect.zero;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_53;
L_53 = Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589(/*hidden argument*/NULL);
__this->set_pixelRect_11(L_53);
// if (cropFrameXOrY && !upscaleRT && !useStretchFill)
bool L_54 = __this->get_cropFrameXOrY_5();
if (!L_54)
{
goto IL_0269;
}
}
{
bool L_55 = V_3;
if (L_55)
{
goto IL_0269;
}
}
{
bool L_56 = __this->get_useStretchFill_6();
if (L_56)
{
goto IL_0269;
}
}
{
// if (cropFrameXAndY)
bool L_57 = __this->get_cropFrameXAndY_4();
if (!L_57)
{
goto IL_01e7;
}
}
{
// pixelRect.width = zoom * refResolutionX;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_58 = __this->get_address_of_pixelRect_11();
int32_t L_59 = __this->get_zoom_7();
int32_t L_60 = V_1;
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_58, ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_59, (int32_t)L_60)))), /*hidden argument*/NULL);
// pixelRect.height = zoom * refResolutionY;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_61 = __this->get_address_of_pixelRect_11();
int32_t L_62 = __this->get_zoom_7();
int32_t L_63 = V_2;
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_61, ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_62, (int32_t)L_63)))), /*hidden argument*/NULL);
// }
goto IL_022f;
}
IL_01e7:
{
// else if (cropFrameY)
bool L_64 = V_6;
if (!L_64)
{
goto IL_020e;
}
}
{
// pixelRect.width = screenWidth;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_65 = __this->get_address_of_pixelRect_11();
int32_t L_66 = ___screenWidth0;
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_65, ((float)((float)L_66)), /*hidden argument*/NULL);
// pixelRect.height = zoom * refResolutionY;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_67 = __this->get_address_of_pixelRect_11();
int32_t L_68 = __this->get_zoom_7();
int32_t L_69 = V_2;
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_67, ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_68, (int32_t)L_69)))), /*hidden argument*/NULL);
// }
goto IL_022f;
}
IL_020e:
{
// pixelRect.width = zoom * refResolutionX;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_70 = __this->get_address_of_pixelRect_11();
int32_t L_71 = __this->get_zoom_7();
int32_t L_72 = V_1;
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_70, ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_71, (int32_t)L_72)))), /*hidden argument*/NULL);
// pixelRect.height = screenHeight;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_73 = __this->get_address_of_pixelRect_11();
int32_t L_74 = ___screenHeight1;
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_73, ((float)((float)L_74)), /*hidden argument*/NULL);
}
IL_022f:
{
// pixelRect.x = (screenWidth - (int)pixelRect.width) / 2;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_75 = __this->get_address_of_pixelRect_11();
int32_t L_76 = ___screenWidth0;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_77 = __this->get_address_of_pixelRect_11();
float L_78;
L_78 = Rect_get_width_m4A0500D95CA84917787A8E90D26E66D49DFA90EF((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_77, /*hidden argument*/NULL);
Rect_set_x_m1147A05B5046E1D4427E8EC99B9DFA4A32EEDEE6((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_75, ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_76, (int32_t)((int32_t)((int32_t)L_78))))/(int32_t)2)))), /*hidden argument*/NULL);
// pixelRect.y = (screenHeight - (int)pixelRect.height) / 2;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_79 = __this->get_address_of_pixelRect_11();
int32_t L_80 = ___screenHeight1;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_81 = __this->get_address_of_pixelRect_11();
float L_82;
L_82 = Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_81, /*hidden argument*/NULL);
Rect_set_y_m015507262F8AC5AFF1B4E986B66307F31FB3A10E((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_79, ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_80, (int32_t)((int32_t)((int32_t)L_82))))/(int32_t)2)))), /*hidden argument*/NULL);
// }
goto IL_0294;
}
IL_0269:
{
// else if (useOffscreenRT)
bool L_83 = __this->get_useOffscreenRT_8();
if (!L_83)
{
goto IL_0294;
}
}
{
// pixelRect = new Rect(0.0f, 0.0f, offscreenRTWidth, offscreenRTHeight);
int32_t L_84 = __this->get_offscreenRTWidth_9();
int32_t L_85 = __this->get_offscreenRTHeight_10();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_86;
memset((&L_86), 0, sizeof(L_86));
Rect__ctor_m12075526A02B55B680716A34AD5287B223122B70((&L_86), (0.0f), (0.0f), ((float)((float)L_84)), ((float)((float)L_85)), /*hidden argument*/NULL);
__this->set_pixelRect_11(L_86);
}
IL_0294:
{
// if (cropFrameY)
bool L_87 = V_6;
if (!L_87)
{
goto IL_02ae;
}
}
{
// orthoSize = (refResolutionY * 0.5f) / assetsPPU;
int32_t L_88 = V_2;
int32_t L_89 = V_0;
__this->set_orthoSize_12(((float)((float)((float)il2cpp_codegen_multiply((float)((float)((float)L_88)), (float)(0.5f)))/(float)((float)((float)L_89)))));
goto IL_0359;
}
IL_02ae:
{
// else if (cropFrameX)
bool L_90 = V_5;
if (!L_90)
{
goto IL_02fa;
}
}
{
// float aspect = (pixelRect == Rect.zero) ? (float)screenWidth / screenHeight : pixelRect.width / pixelRect.height;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_91 = __this->get_pixelRect_11();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_92;
L_92 = Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589(/*hidden argument*/NULL);
bool L_93;
L_93 = Rect_op_Equality_m17C955A4F85F01A7CF0B43EDE41463301E93F6C1(L_91, L_92, /*hidden argument*/NULL);
if (L_93)
{
goto IL_02dd;
}
}
{
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_94 = __this->get_address_of_pixelRect_11();
float L_95;
L_95 = Rect_get_width_m4A0500D95CA84917787A8E90D26E66D49DFA90EF((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_94, /*hidden argument*/NULL);
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_96 = __this->get_address_of_pixelRect_11();
float L_97;
L_97 = Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_96, /*hidden argument*/NULL);
G_B29_0 = ((float)((float)L_95/(float)L_97));
goto IL_02e2;
}
IL_02dd:
{
int32_t L_98 = ___screenWidth0;
int32_t L_99 = ___screenHeight1;
G_B29_0 = ((float)((float)((float)((float)L_98))/(float)((float)((float)L_99))));
}
IL_02e2:
{
V_10 = G_B29_0;
// orthoSize = ((refResolutionX / aspect) * 0.5f) / assetsPPU;
int32_t L_100 = V_1;
float L_101 = V_10;
int32_t L_102 = V_0;
__this->set_orthoSize_12(((float)((float)((float)il2cpp_codegen_multiply((float)((float)((float)((float)((float)L_100))/(float)L_101)), (float)(0.5f)))/(float)((float)((float)L_102)))));
// }
goto IL_0359;
}
IL_02fa:
{
// else if (upscaleRT && zoom > 1)
bool L_103 = V_3;
if (!L_103)
{
goto IL_031e;
}
}
{
int32_t L_104 = __this->get_zoom_7();
if ((((int32_t)L_104) <= ((int32_t)1)))
{
goto IL_031e;
}
}
{
// orthoSize = (offscreenRTHeight * 0.5f) / assetsPPU;
int32_t L_105 = __this->get_offscreenRTHeight_10();
int32_t L_106 = V_0;
__this->set_orthoSize_12(((float)((float)((float)il2cpp_codegen_multiply((float)((float)((float)L_105)), (float)(0.5f)))/(float)((float)((float)L_106)))));
goto IL_0359;
}
IL_031e:
{
// float pixelHeight = (pixelRect == Rect.zero) ? screenHeight : pixelRect.height;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_107 = __this->get_pixelRect_11();
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_108;
L_108 = Rect_get_zero_m4F738804E40698120CC691AB45A6416C4FF52589(/*hidden argument*/NULL);
bool L_109;
L_109 = Rect_op_Equality_m17C955A4F85F01A7CF0B43EDE41463301E93F6C1(L_107, L_108, /*hidden argument*/NULL);
if (L_109)
{
goto IL_033d;
}
}
{
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 * L_110 = __this->get_address_of_pixelRect_11();
float L_111;
L_111 = Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)L_110, /*hidden argument*/NULL);
G_B36_0 = L_111;
goto IL_033f;
}
IL_033d:
{
int32_t L_112 = ___screenHeight1;
G_B36_0 = ((float)((float)L_112));
}
IL_033f:
{
V_11 = G_B36_0;
// orthoSize = (pixelHeight * 0.5f) / (zoom * assetsPPU);
float L_113 = V_11;
int32_t L_114 = __this->get_zoom_7();
int32_t L_115 = V_0;
__this->set_orthoSize_12(((float)((float)((float)il2cpp_codegen_multiply((float)L_113, (float)(0.5f)))/(float)((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_114, (int32_t)L_115)))))));
}
IL_0359:
{
// if (upscaleRT || (!upscaleRT && pixelSnapping))
bool L_116 = V_3;
if (L_116)
{
goto IL_0365;
}
}
{
bool L_117 = V_3;
bool L_118 = V_4;
if (!((int32_t)((int32_t)((((int32_t)L_117) == ((int32_t)0))? 1 : 0)&(int32_t)L_118)))
{
goto IL_0374;
}
}
IL_0365:
{
// unitsPerPixel = 1.0f / assetsPPU;
int32_t L_119 = V_0;
__this->set_unitsPerPixel_13(((float)((float)(1.0f)/(float)((float)((float)L_119)))));
return;
}
IL_0374:
{
// unitsPerPixel = 1.0f / (zoom * assetsPPU);
int32_t L_120 = __this->get_zoom_7();
int32_t L_121 = V_0;
__this->set_unitsPerPixel_13(((float)((float)(1.0f)/(float)((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_120, (int32_t)L_121)))))));
// }
return;
}
}
// UnityEngine.Rect UnityEngine.U2D.PixelPerfectCameraInternal::CalculatePostRenderPixelRect(System.Single,System.Int32,System.Int32)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 PixelPerfectCameraInternal_CalculatePostRenderPixelRect_mB3065A3B8D92AA9C1C21D38B0B4301C7E814C45E (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, float ___cameraAspect0, int32_t ___screenWidth1, int32_t ___screenHeight2, const RuntimeMethod* method)
{
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 V_0;
memset((&V_0), 0, sizeof(V_0));
{
// Rect pixelRect = new Rect();
il2cpp_codegen_initobj((&V_0), sizeof(Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 ));
// if (useStretchFill)
bool L_0 = __this->get_useStretchFill_6();
if (!L_0)
{
goto IL_0087;
}
}
{
// float screenAspect = (float)screenWidth / screenHeight;
int32_t L_1 = ___screenWidth1;
int32_t L_2 = ___screenHeight2;
// if (screenAspect > cameraAspect)
float L_3 = ___cameraAspect0;
if ((!(((float)((float)((float)((float)((float)L_1))/(float)((float)((float)L_2))))) > ((float)L_3))))
{
goto IL_0051;
}
}
{
// pixelRect.height = screenHeight;
int32_t L_4 = ___screenHeight2;
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)L_4)), /*hidden argument*/NULL);
// pixelRect.width = screenHeight * cameraAspect;
int32_t L_5 = ___screenHeight2;
float L_6 = ___cameraAspect0;
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)il2cpp_codegen_multiply((float)((float)((float)L_5)), (float)L_6)), /*hidden argument*/NULL);
// pixelRect.x = (screenWidth - (int)pixelRect.width) / 2;
int32_t L_7 = ___screenWidth1;
float L_8;
L_8 = Rect_get_width_m4A0500D95CA84917787A8E90D26E66D49DFA90EF((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), /*hidden argument*/NULL);
Rect_set_x_m1147A05B5046E1D4427E8EC99B9DFA4A32EEDEE6((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_7, (int32_t)((int32_t)((int32_t)L_8))))/(int32_t)2)))), /*hidden argument*/NULL);
// pixelRect.y = 0;
Rect_set_y_m015507262F8AC5AFF1B4E986B66307F31FB3A10E((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), (0.0f), /*hidden argument*/NULL);
// }
goto IL_00d9;
}
IL_0051:
{
// pixelRect.width = screenWidth;
int32_t L_9 = ___screenWidth1;
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)L_9)), /*hidden argument*/NULL);
// pixelRect.height = screenWidth / cameraAspect;
int32_t L_10 = ___screenWidth1;
float L_11 = ___cameraAspect0;
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((float)((float)L_10))/(float)L_11)), /*hidden argument*/NULL);
// pixelRect.y = (screenHeight - (int)pixelRect.height) / 2;
int32_t L_12 = ___screenHeight2;
float L_13;
L_13 = Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), /*hidden argument*/NULL);
Rect_set_y_m015507262F8AC5AFF1B4E986B66307F31FB3A10E((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_12, (int32_t)((int32_t)((int32_t)L_13))))/(int32_t)2)))), /*hidden argument*/NULL);
// pixelRect.x = 0;
Rect_set_x_m1147A05B5046E1D4427E8EC99B9DFA4A32EEDEE6((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), (0.0f), /*hidden argument*/NULL);
// }
goto IL_00d9;
}
IL_0087:
{
// pixelRect.height = zoom * offscreenRTHeight;
int32_t L_14 = __this->get_zoom_7();
int32_t L_15 = __this->get_offscreenRTHeight_10();
Rect_set_height_m4A00B16C122F44FEF4BA074386F3DC11FF4B4D23((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_14, (int32_t)L_15)))), /*hidden argument*/NULL);
// pixelRect.width = zoom * offscreenRTWidth;
int32_t L_16 = __this->get_zoom_7();
int32_t L_17 = __this->get_offscreenRTWidth_9();
Rect_set_width_m07D84AD7C7093EDCCD94A7B93A9447CA9917DD9D((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_16, (int32_t)L_17)))), /*hidden argument*/NULL);
// pixelRect.x = (screenWidth - (int)pixelRect.width) / 2;
int32_t L_18 = ___screenWidth1;
float L_19;
L_19 = Rect_get_width_m4A0500D95CA84917787A8E90D26E66D49DFA90EF((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), /*hidden argument*/NULL);
Rect_set_x_m1147A05B5046E1D4427E8EC99B9DFA4A32EEDEE6((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_18, (int32_t)((int32_t)((int32_t)L_19))))/(int32_t)2)))), /*hidden argument*/NULL);
// pixelRect.y = (screenHeight - (int)pixelRect.height) / 2;
int32_t L_20 = ___screenHeight2;
float L_21;
L_21 = Rect_get_height_m42FEF31015A269E6E2B7E6F62E72E5BF6602302A((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), /*hidden argument*/NULL);
Rect_set_y_m015507262F8AC5AFF1B4E986B66307F31FB3A10E((Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 *)(&V_0), ((float)((float)((int32_t)((int32_t)((int32_t)il2cpp_codegen_subtract((int32_t)L_20, (int32_t)((int32_t)((int32_t)L_21))))/(int32_t)2)))), /*hidden argument*/NULL);
}
IL_00d9:
{
// return pixelRect;
Rect_t7D9187DB6339DBA5741C09B6CCEF2F54F1966878 L_22 = V_0;
return L_22;
}
}
// System.Single UnityEngine.U2D.PixelPerfectCameraInternal::CorrectCinemachineOrthoSize(System.Single)
IL2CPP_EXTERN_C IL2CPP_METHOD_ATTR float PixelPerfectCameraInternal_CorrectCinemachineOrthoSize_mCE913421BC4294451DC3869F2EB052D3B3802ED1 (PixelPerfectCameraInternal_t95E6E3E3BDA1D90E9F4489ED6B43D1673E0818AB * __this, float ___targetOrthoSize0, const RuntimeMethod* method)
{
static bool s_Il2CppMethodInitialized;
if (!s_Il2CppMethodInitialized)
{
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var);
il2cpp_codegen_initialize_runtime_metadata((uintptr_t*)&Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var);
s_Il2CppMethodInitialized = true;
}
float V_0 = 0.0f;
{
// if (m_Component.upscaleRT)
RuntimeObject* L_0 = __this->get_m_Component_0();
NullCheck(L_0);
bool L_1;
L_1 = InterfaceFuncInvoker0< bool >::Invoke(6 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_upscaleRT() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_0);
if (!L_1)
{
goto IL_0037;
}
}
{
// cinemachineVCamZoom = Math.Max(1, Mathf.RoundToInt(orthoSize / targetOrthoSize));
float L_2 = __this->get_orthoSize_12();
float L_3 = ___targetOrthoSize0;
int32_t L_4;
L_4 = Mathf_RoundToInt_m56850BDF60FF9E3441CE57E5EFEFEF36EDCDE6DD(((float)((float)L_2/(float)L_3)), /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var);
int32_t L_5;
L_5 = Math_Max_mD8AA27386BF012C65303FCDEA041B0CC65056E7B(1, L_4, /*hidden argument*/NULL);
__this->set_cinemachineVCamZoom_14(L_5);
// correctedOrthoSize = orthoSize / cinemachineVCamZoom;
float L_6 = __this->get_orthoSize_12();
int32_t L_7 = __this->get_cinemachineVCamZoom_14();
V_0 = ((float)((float)L_6/(float)((float)((float)L_7))));
// }
goto IL_006f;
}
IL_0037:
{
// cinemachineVCamZoom = Math.Max(1, Mathf.RoundToInt(zoom * orthoSize / targetOrthoSize));
int32_t L_8 = __this->get_zoom_7();
float L_9 = __this->get_orthoSize_12();
float L_10 = ___targetOrthoSize0;
int32_t L_11;
L_11 = Mathf_RoundToInt_m56850BDF60FF9E3441CE57E5EFEFEF36EDCDE6DD(((float)((float)((float)il2cpp_codegen_multiply((float)((float)((float)L_8)), (float)L_9))/(float)L_10)), /*hidden argument*/NULL);
IL2CPP_RUNTIME_CLASS_INIT(Math_tA269614262430118C9FC5C4D9EF4F61C812568F0_il2cpp_TypeInfo_var);
int32_t L_12;
L_12 = Math_Max_mD8AA27386BF012C65303FCDEA041B0CC65056E7B(1, L_11, /*hidden argument*/NULL);
__this->set_cinemachineVCamZoom_14(L_12);
// correctedOrthoSize = zoom * orthoSize / cinemachineVCamZoom;
int32_t L_13 = __this->get_zoom_7();
float L_14 = __this->get_orthoSize_12();
int32_t L_15 = __this->get_cinemachineVCamZoom_14();
V_0 = ((float)((float)((float)il2cpp_codegen_multiply((float)((float)((float)L_13)), (float)L_14))/(float)((float)((float)L_15))));
}
IL_006f:
{
// if (!m_Component.upscaleRT && !m_Component.pixelSnapping)
RuntimeObject* L_16 = __this->get_m_Component_0();
NullCheck(L_16);
bool L_17;
L_17 = InterfaceFuncInvoker0< bool >::Invoke(6 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_upscaleRT() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_16);
if (L_17)
{
goto IL_00a8;
}
}
{
RuntimeObject* L_18 = __this->get_m_Component_0();
NullCheck(L_18);
bool L_19;
L_19 = InterfaceFuncInvoker0< bool >::Invoke(8 /* System.Boolean UnityEngine.U2D.IPixelPerfectCamera::get_pixelSnapping() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_18);
if (L_19)
{
goto IL_00a8;
}
}
{
// unitsPerPixel = 1.0f / (cinemachineVCamZoom * m_Component.assetsPPU);
int32_t L_20 = __this->get_cinemachineVCamZoom_14();
RuntimeObject* L_21 = __this->get_m_Component_0();
NullCheck(L_21);
int32_t L_22;
L_22 = InterfaceFuncInvoker0< int32_t >::Invoke(0 /* System.Int32 UnityEngine.U2D.IPixelPerfectCamera::get_assetsPPU() */, IPixelPerfectCamera_t9F0A1326B7A342C5BDF45EB98760E0E380CEEAB7_il2cpp_TypeInfo_var, L_21);
__this->set_unitsPerPixel_13(((float)((float)(1.0f)/(float)((float)((float)((int32_t)il2cpp_codegen_multiply((int32_t)L_20, (int32_t)L_22)))))));
}
IL_00a8:
{
// return correctedOrthoSize;
float L_23 = V_0;
return L_23;
}
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_Subtraction_m2725C96965D5C0B1F9715797E51762B13A5FED58_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___b1, const RuntimeMethod* method)
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0;
memset((&V_0), 0, sizeof(V_0));
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0 = ___a0;
float L_1 = L_0.get_x_2();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2 = ___b1;
float L_3 = L_2.get_x_2();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4 = ___a0;
float L_5 = L_4.get_y_3();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6 = ___b1;
float L_7 = L_6.get_y_3();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_8 = ___a0;
float L_9 = L_8.get_z_4();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_10 = ___b1;
float L_11 = L_10.get_z_4();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_12;
memset((&L_12), 0, sizeof(L_12));
Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_12), ((float)il2cpp_codegen_subtract((float)L_1, (float)L_3)), ((float)il2cpp_codegen_subtract((float)L_5, (float)L_7)), ((float)il2cpp_codegen_subtract((float)L_9, (float)L_11)), /*hidden argument*/NULL);
V_0 = L_12;
goto IL_0030;
}
IL_0030:
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_13 = V_0;
return L_13;
}
}
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E Vector3_op_UnaryNegation_m362EA356F4CADEDB39F965A0DBDED6EA890925F7_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E ___a0, const RuntimeMethod* method)
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E V_0;
memset((&V_0), 0, sizeof(V_0));
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_0 = ___a0;
float L_1 = L_0.get_x_2();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_2 = ___a0;
float L_3 = L_2.get_y_3();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_4 = ___a0;
float L_5 = L_4.get_z_4();
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_6;
memset((&L_6), 0, sizeof(L_6));
Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline((&L_6), ((-L_1)), ((-L_3)), ((-L_5)), /*hidden argument*/NULL);
V_0 = L_6;
goto IL_001e;
}
IL_001e:
{
Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E L_7 = V_0;
return L_7;
}
}
IL2CPP_MANAGED_FORCE_INLINE IL2CPP_METHOD_ATTR void Vector3__ctor_m57495F692C6CE1CEF278CAD9A98221165D37E636_inline (Vector3_t65B972D6A585A0A5B63153CF1177A90D3C90D65E * __this, float ___x0, float ___y1, float ___z2, const RuntimeMethod* method)
{
{
float L_0 = ___x0;
__this->set_x_2(L_0);
float L_1 = ___y1;
__this->set_y_3(L_1);
float L_2 = ___z2;
__this->set_z_4(L_2);
return;
}
}
| [
"81548078+jiye-stingray@users.noreply.github.com"
] | 81548078+jiye-stingray@users.noreply.github.com |
93f5dfe4f7edebdc4dd2da94cd91d55b1217f937 | 6d0fd084f9b9162769cdd4fd9239e9299cdc2e68 | /examples/sevSegFloatSerial/sevSegFloatSerial.ino | 0d9e9aaa5d72aeaf5cf587698c05d1b0a80283b7 | [] | no_license | poisa/SevSegFloat | bf749545a6bf8230886a869c9cc71dd5f1976fa7 | 4156ea5f6c1712f55c4357b9d407113b535e4a67 | refs/heads/master | 2020-12-25T02:29:49.222772 | 2014-03-27T08:00:39 | 2014-03-27T08:00:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | ino | // For the Arduino Uno and other Atmega328 based boards
#include <SevSegFloat.h> // Include the library
SevSegFloat SevSeg(Serial); // Make an instance of SevSegFloat on the Serial Stream called SevSeg
float printVal = 0.12345; // The value to print
void setup() {
Serial.begin(9600); // Initiate Serial connection
}
void loop() {
SevSeg.send(printVal); // Send data
delay(100); // Don't overload the display, not really necessary
}
| [
"ahalekelly@gmail.com"
] | ahalekelly@gmail.com |
54572f2aea5a1290a03280c47dd6efc37c051fc7 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_5212_git-2.8.3.cpp | 25c0086818c8078a924b93904ad7e187176f86a6 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | cpp | static int add(int ac, const char **av, const char *prefix)
{
struct add_opts opts;
const char *new_branch_force = NULL;
const char *path, *branch;
struct option options[] = {
OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
N_("create a new branch")),
OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
N_("create or reset a branch")),
OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
OPT_END()
};
memset(&opts, 0, sizeof(opts));
ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
die(_("-b, -B, and --detach are mutually exclusive"));
if (ac < 1 || ac > 2)
usage_with_options(worktree_usage, options);
path = prefix ? prefix_filename(prefix, strlen(prefix), av[0]) : av[0];
branch = ac < 2 ? "HEAD" : av[1];
opts.force_new_branch = !!new_branch_force;
if (opts.force_new_branch) {
struct strbuf symref = STRBUF_INIT;
opts.new_branch = new_branch_force;
if (!opts.force &&
!strbuf_check_branch_ref(&symref, opts.new_branch) &&
ref_exists(symref.buf))
die_if_checked_out(symref.buf);
strbuf_release(&symref);
}
if (ac < 2 && !opts.new_branch && !opts.detach) {
int n;
const char *s = worktree_basename(path, &n);
opts.new_branch = xstrndup(s, n);
}
if (opts.new_branch) {
struct child_process cp;
memset(&cp, 0, sizeof(cp));
cp.git_cmd = 1;
argv_array_push(&cp.args, "branch");
if (opts.force_new_branch)
argv_array_push(&cp.args, "--force");
argv_array_push(&cp.args, opts.new_branch);
argv_array_push(&cp.args, branch);
if (run_command(&cp))
return -1;
branch = opts.new_branch;
}
return add_worktree(path, branch, &opts);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
66630041831d7f608d05e6a7383f4b9e9b753170 | 0c6de538f9b54ee01fe46b833d1262364317e165 | /source-code/musicmanager.cpp | 9f2b94bdc9fe87e1cbd42c8a6038ad47e6a3dcde | [] | no_license | fabsgc/Terminale-S-Zombie | e79b1cd932e7739ec8ec0d5b74d21df78888ef1e | c48cdbdcaa90186a9d75fecbbff28a25d0286028 | refs/heads/master | 2021-01-18T18:16:07.144478 | 2017-03-31T19:43:57 | 2017-03-31T19:43:57 | 86,853,187 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 891 | cpp | #include "musicmanager.hpp"
sf::Music MusicManager::m_playedMusic;
/**
* Joue une musique. note : la même instance de la classe ne peut jouer plusieurs musiques simultanément
* @param std::string name : chemin vers la musique
* @param float volume : volume entre 0 et 100
* @param bool loop : le son sera répété ou non (true ou false)
* @access public
* @return void
*/
void MusicManager::playMusic(std::string name, float volume, bool loop)
{
m_playedMusic.OpenFromFile(name);
m_playedMusic.SetLoop(loop);
m_playedMusic.SetVolume(volume);
if(m_playedMusic.GetStatus() != sf::Sound::Playing)
{
m_playedMusic.Play();
std::cout << "[INFORMATION] : [MusicManager::playMusic] lancement de : \"" << name << "\", repetition : " << loop << ", volume : " << volume << std::endl;
}
}
| [
"fabienbeaudimi@hotmail.fr"
] | fabienbeaudimi@hotmail.fr |
649ab7cb7759697b4a462553879a34bf836e8bd2 | 26ee35e6d6dbe6dc3da44f5301673afa47ad7494 | /yzzusb/trunk/UsbFoundation/RegistryKey.h | c9d97414ffec799d16c502e1ab47144e1e994389 | [] | no_license | uvbs/terry_old_project | d2d4a4a24fafec4277c026380c404101ea619526 | 673ec2908512d816d24c4932dfdd8f3a6012cb6b | refs/heads/master | 2021-01-20T22:44:42.319453 | 2013-08-14T05:54:48 | 2013-08-14T05:54:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,008 | h | #pragma once
#include <list>
class CRegistryKey
{
public:
/**
* Constructor.
* \param key the path to the key, including the key. example: "Software\\Company\\SubKey"
* \param base a predefined base key like HKEY_LOCAL_MACHINE
*/
CRegistryKey(const CString& key,HKEY base = HKEY_CURRENT_USER,BOOL bReadOnly = FALSE);
virtual ~CRegistryKey();
/**
* \return ERROR_SUCCESS or an nonzero error code. Use FormatMessage() to get an error description.
*/
DWORD Open(const CString& key,HKEY base = HKEY_CURRENT_USER,BOOL bReadOnly = FALSE);
/**
* \return ERROR_SUCCESS or an nonzero error code. Use FormatMessage() to get an error description.
*/
DWORD createKey();
/**
* \return ERROR_SUCCESS or an nonzero error code. Use FormatMessage() to get an error description.
*/
DWORD removeKey();
bool getSubKeys(std::list<CString>& subkeys); ///< returns the list of sub keys
bool getSubKeys(std::list<CRegistryKey*>& lst); ///< returns the list of sub keys
public:
HKEY getRoot() const {return m_base;}
CString getPath() const {return m_path;}
bool keyExist() const {return m_hKey != NULL;}
DWORD NotifyChange(BOOL bWatchSubtree, HANDLE hEvent);
DWORD GetValue(const CString& name, CString& value, bool autoexpand = true);
DWORD GetValue(const CString& name, DWORD& value);
DWORD GetValue(const CString& name, std::list<CString> value);
DWORD SetValue(const CString& name, const CString& value, bool expand = false);
DWORD SetValue(const CString& name, DWORD value);
DWORD SetValue(const CString& name, const std::list<CString>& value);
public:
virtual CString getErrorString();
LONG GetLastError() const {return m_lastError;}
protected:
DWORD Close();
protected:
HKEY m_base; ///< handle to the registry base
HKEY m_hKey; ///< handle to the open registry key
CString m_path; ///< the path to the key
LONG m_lastError;
}; | [
"zzhhuujjiiee@qq.com"
] | zzhhuujjiiee@qq.com |
bd97d13c9ef4bbdcacb12e0b799b1727c3a6e427 | aaba921e3cb58429f59714175fe79ca5877b9884 | /code/callexpr.h | 18b5ca010b6b71257009789ba07ff67dd110dc8c | [
"BSD-2-Clause-Views"
] | permissive | Duttenheim/asl | aaa78c17be3f8baefe8ee51aebcaf4c7d490e2cc | 00ab8886e30ba0d206a247ddba201aea9def734d | refs/heads/master | 2021-01-10T17:10:12.339021 | 2015-10-09T13:07:49 | 2015-10-09T13:07:49 | 43,918,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | h | #pragma once
//-----------------------------------------------------------------------------------------------------
/*
NAMESPACE::CLASS
DESC
Copyright 2015 - See license file LICENSE.txt
*/
//-----------------------------------------------------------------------------------------------------
#include "expr.h"
namespace ASL
{
struct CallExpr : public Expr
{
public:
/// constructor
CallExpr();
/// destructor
virtual ~CallExpr();
private:
};
} // namespace ASL
| [
"gusste@ltu.se"
] | gusste@ltu.se |
605b4708160ac44d6352be9ee4b30eef305dbe3d | e359db0e752a11c5d677e3a82574065831bab447 | /app/demo/touchgfx_demo2014_240x320/gui/src/live_data_display_screen/WeekInfo.cpp | cdb452efee60a33056563a19d65f1c159106759e | [] | no_license | chichtlm/TouchGFX | 694936495ba49b4baba4fb56fd1165f424518c94 | 09cfdf466ae98fa61f54d55548248134a007871f | refs/heads/master | 2020-05-10T00:07:11.813953 | 2016-12-14T06:55:22 | 2016-12-14T06:55:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,624 | cpp | /******************************************************************************
*
* @brief This file is part of the TouchGFX 4.5.0 evaluation distribution.
*
* @author Draupner Graphics A/S <http://www.touchgfx.com>
*
******************************************************************************
*
* @section Copyright
*
* This file is free software and is provided for example purposes. You may
* use, copy, and modify within the terms and conditions of the license
* agreement.
*
* This is licensed software for evaluation use, any use must strictly comply
* with the evaluation license agreement provided with delivery of the
* TouchGFX software.
*
* The evaluation license agreement can be seen on www.touchgfx.com
*
* @section Disclaimer
*
* DISCLAIMER OF WARRANTY/LIMITATION OF REMEDIES: Draupner Graphics A/S has
* no obligation to support this software. Draupner Graphics A/S is providing
* the software "AS IS", with no express or implied warranties of any kind,
* including, but not limited to, any implied warranties of merchantability
* or fitness for any particular purpose or warranties against infringement
* of any proprietary rights of a third party.
*
* Draupner Graphics A/S can not be held liable for any consequential,
* incidental, or special damages, or any other relief, or for any claim by
* any third party, arising from your use of this software.
*
*****************************************************************************/
#include <gui/live_data_display_screen/WeekInfo.hpp>
#include "BitmapDatabase.hpp"
#include <texts/TextKeysAndLanguages.hpp>
#include <touchgfx/Color.hpp>
WeekInfo::WeekInfo()
{
int smallIconDiff = 74;
smallIcons[0].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_CLOUD_ID));
smallIcons[0].setXY(12, 10);
smallIcons[1].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_CLOUD_ID));
smallIcons[1].setXY(smallIcons[0].getX() + 1 * smallIconDiff, 10);
smallIcons[2].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_CLOUD_ID));
smallIcons[2].setXY(smallIcons[0].getX() + 2 * smallIconDiff, 10);
days[0].setTypedText(TypedText(T_WEATHER_DAY_0));
days[0].setPosition(48, 11, 30, 16);
days[1].setTypedText(TypedText(T_WEATHER_DAY_1));
days[1].setPosition(days[0].getX() + 1 * smallIconDiff, 10, 30, 16);
days[2].setTypedText(TypedText(T_WEATHER_DAY_2));
days[2].setPosition(days[0].getX() + 2 * smallIconDiff, 10, 30, 16);
smallTemperature->setX(48);
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
smallTemperature[i].setColor(Color::getColorFrom24BitRGB(0xFF, 0xFF, 0xFF));
smallTemperature[i].setTypedText(TypedText(T_WEATHER_SMALL_TEMPERATURE));
smallTemperature[i].setPosition(smallTemperature[0].getX() + i * smallIconDiff, 25, 30, 16);
smallTemperature[i].setWildcard(smallTemperatureBuffer[i]);
smallTemperatureDropShadow[i].setColor(Color::getColorFrom24BitRGB(0x0, 0x0, 0x0));
smallTemperatureDropShadow[i].setTypedText(TypedText(T_WEATHER_SMALL_TEMPERATURE));
smallTemperatureDropShadow[i].setPosition(smallTemperature[i].getX() + 1, smallTemperature[i].getY() + 1, 30, 16);
smallTemperatureDropShadow[i].setWildcard(smallTemperatureBuffer[i]);
smallTemperatureDropShadow[i].setAlpha(128);
}
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
add(smallIcons[i]);
add(days[i]);
add(smallTemperatureDropShadow[i]);
add(smallTemperature[i]);
}
}
/* Setup the WeekInfo with some static city information
* In a real world example this data would be live updated
* and come from the model, but in this demo it is just hard coded.
*/
void WeekInfo::setInfo(CityInfo::Cities city)
{
switch (city)
{
case CityInfo::COPENHAGEN:
smallIcons[0].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_ID));
smallIcons[1].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_BIGCLOUD_ID));
smallIcons[2].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_ID));
Unicode::snprintf(smallTemperatureBuffer[0], 4, "%d", 23);
Unicode::snprintf(smallTemperatureBuffer[1], 4, "%d", 16);
Unicode::snprintf(smallTemperatureBuffer[2], 4, "%d", 24);
break;
case CityInfo::HONG_KONG:
smallIcons[0].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_ID));
smallIcons[1].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_BIGCLOUD_ID));
smallIcons[2].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SHOWER_ID));
Unicode::snprintf(smallTemperatureBuffer[0], 4, "%d", 23);
Unicode::snprintf(smallTemperatureBuffer[1], 4, "%d", 19);
Unicode::snprintf(smallTemperatureBuffer[2], 4, "%d", 21);
break;
case CityInfo::MUMBAI:
smallIcons[0].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_ID));
smallIcons[1].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_BIGCLOUD_ID));
smallIcons[2].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_ID));
Unicode::snprintf(smallTemperatureBuffer[0], 4, "%d", 32);
Unicode::snprintf(smallTemperatureBuffer[1], 4, "%d", 28);
Unicode::snprintf(smallTemperatureBuffer[2], 4, "%d", 27);
break;
case CityInfo::NEW_YORK:
smallIcons[0].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SUN_BIGCLOUD_ID));
smallIcons[1].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SHOWER_ID));
smallIcons[2].setBitmap(Bitmap(BITMAP_WEATHER_SMALL_ICON_SHOWER_ID));
Unicode::snprintf(smallTemperatureBuffer[0], 4, "%d", 20);
Unicode::snprintf(smallTemperatureBuffer[1], 4, "%d", 19);
Unicode::snprintf(smallTemperatureBuffer[2], 4, "%d", 19);
break;
default:
break;
}
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
smallIcons[i].invalidate();
smallTemperature[i].invalidate();
smallTemperatureDropShadow[i].invalidate();
}
}
void WeekInfo::setAlpha(int alpha)
{
if (alpha < 0)
{
alpha = 0;
}
if (alpha > 255)
{
alpha = 255;
}
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
smallIcons[i].setAlpha(alpha);
smallIcons[i].invalidate();
smallTemperature[i].setAlpha(alpha);
smallTemperature[i].invalidate();
smallTemperatureDropShadow[i].setAlpha(alpha);
smallTemperatureDropShadow[i].invalidate();
days[i].setAlpha(alpha);
days[i].invalidate();
}
}
void WeekInfo::setTextColor(colortype color)
{
for (int i = 0; i < NUMBER_OF_DAYS; i++)
{
days[i].setColor(color);
days[i].invalidate();
}
}
| [
"2869905223@qq.com"
] | 2869905223@qq.com |
4167c58e5f7c6eaa579d070506cfd5682a028ee9 | 974a44e586afd3f53a8c202dd0a5a71e0476ee50 | /Physics Particle System/main.cpp | 53f975fe98796c3458d164dc96ce9c48f465cbc3 | [] | no_license | waqas66426/Artificial-Life | b9bd6d54532ef47e7fdcfe60657e5a53c48d11d1 | 2cbfc0536b92986084054b72cf8644f84cde4d80 | refs/heads/master | 2020-05-01T17:38:10.812237 | 2013-06-23T14:53:45 | 2013-06-23T14:53:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | cpp | #include <GL\glfw.h>
#include <stdlib.h>
#include <iostream>
#include "World.h"
#include "Timer.h"
#pragma comment(lib, "GLFW.lib")
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
static const int WIDTH = 1600;
static const int HEIGHT = 950;
int main( void )
{
int running = GL_TRUE;
// Initialize GLFW
if( !glfwInit() )
{
exit( EXIT_FAILURE );
}
// Open an OpenGL window
glfwOpenWindowHint( GLFW_WINDOW_NO_RESIZE, GL_TRUE );
if( !glfwOpenWindow( WIDTH,HEIGHT,0,0,0,0,0,0, GLFW_WINDOW ) )
{
glfwTerminate();
exit( EXIT_FAILURE );
}
glfwSetWindowTitle("Physics: Fireworks System" );
glViewport(0, 0, WIDTH, HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, WIDTH,0, HEIGHT, -1, 1);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glfwSwapInterval(1);
World &World = World::getInstance();
World.Initialize(WIDTH,HEIGHT);
//_gf.init();
glfwSetMousePosCallback(&World::updateMousePos);
Timer t;
t.start();
float currentTime = t.getElapsedTimeInMilliSec();
// Main loop
while( running )
{
static float lastTime = t.getElapsedTimeInMilliSec();
currentTime = t.getElapsedTimeInMilliSec();
float deltaTime = (currentTime - lastTime) / 1000.0f;
lastTime = currentTime;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
World.updateAndRender(deltaTime);
//World.render(deltaTime);
// Swap front and back rendering buffers
glfwSwapBuffers();
// Check if ESC key was pressed or window was closed
running = !glfwGetKey( GLFW_KEY_ESC ) && glfwGetWindowParam( GLFW_OPENED );
}
// Close window and terminate GLFW
glfwTerminate();
// Exit program
exit( EXIT_SUCCESS );
} | [
"david.pertiller@gmail.com"
] | david.pertiller@gmail.com |
5e8b64cde9a40ab75bd00e30d99a241e940fd6fa | 50f63963e73a8436bef3c0e6e3be7056291e1e3b | /panda/include/cLwoSurfaceBlock.h | d62f73684dcfdcdf1c2c495f6b9df23d26d44e4a | [
"BSD-3-Clause",
"BSD-2-Clause"
] | permissive | MTTPAM/installer | 7f4ad0c29631548345fac29ca7fbfcb38e37a111 | aee7a9b75f1da88fdf6d5eae5cdf24739c540438 | refs/heads/master | 2020-03-09T15:32:48.765847 | 2018-11-13T03:35:50 | 2018-11-13T03:35:50 | 128,861,764 | 1 | 4 | null | 2018-11-13T03:35:50 | 2018-04-10T02:28:29 | Python | UTF-8 | C++ | false | false | 1,552 | h | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file cLwoSurfaceBlock.h
* @author drose
* @date 2001-04-26
*/
#ifndef CLWOSURFACEBLOCK_H
#define CLWOSURFACEBLOCK_H
#include "pandatoolbase.h"
#include "lwoSurfaceBlock.h"
#include "lwoSurfaceBlockOpacity.h"
#include "lwoSurfaceBlockProjection.h"
#include "lwoSurfaceBlockAxis.h"
#include "lwoSurfaceBlockWrap.h"
#include "luse.h"
class LwoToEggConverter;
class CLwoSurfaceBlockTMap;
/**
* This class is a wrapper around LwoSurfaceBlock and stores additional
* information useful during the conversion-to-egg process.
*/
class CLwoSurfaceBlock {
public:
CLwoSurfaceBlock(LwoToEggConverter *converter, const LwoSurfaceBlock *block);
~CLwoSurfaceBlock();
IffId _block_type;
IffId _channel_id;
string _ordinal;
bool _enabled;
LwoSurfaceBlockOpacity::Type _opacity_type;
PN_stdfloat _opacity;
LMatrix4d _transform;
LMatrix4d _inv_transform;
LwoSurfaceBlockProjection::Mode _projection_mode;
LwoSurfaceBlockAxis::Axis _axis;
int _clip_index;
LwoSurfaceBlockWrap::Mode _w_wrap;
LwoSurfaceBlockWrap::Mode _h_wrap;
PN_stdfloat _w_repeat;
PN_stdfloat _h_repeat;
string _uv_name;
LwoToEggConverter *_converter;
CPT(LwoSurfaceBlock) _block;
CLwoSurfaceBlockTMap *_tmap;
};
#include "cLwoSurfaceBlock.I"
#endif
| [
"linktlh@gmail.com"
] | linktlh@gmail.com |
eef62587608a3896050fa9b36bb1acbc369345b3 | 1866f2304237087b561cdc34b402e5ec6077d2ac | /arm/src/joystick.cpp | 75d3845a7fc80810a6f1af01afb6637717d26f84 | [
"MIT"
] | permissive | AvatarQuest/AVA-ros | e99d39b3cc5c7d0b7df0d68c08280bdaf79b442a | 3e945d859155f559761f47040b1431e0e9ee8da1 | refs/heads/master | 2023-08-03T23:53:41.204941 | 2021-09-17T14:19:06 | 2021-09-17T14:19:06 | 362,283,882 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,688 | cpp | #include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/Vector3.h>
#include <moveit/move_group_interface/move_group_interface.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
geometry_msgs::Pose target_pose;
static const std::string PLANNING_GROUP = "right_arm";
moveit::planning_interface::MoveGroupInterface* move_group;
void joystickCallback(const geometry_msgs::Vector3::ConstPtr& msg) {
double x = msg->x;
double y = msg->y;
double z = msg->z;
if (x == 0 && y == 0 && z == 0) {
return;
}
target_pose.position.x = target_pose.position.x + x * 0.09;
target_pose.position.y = target_pose.position.y + y * 0.09;
target_pose.position.z = target_pose.position.z + z * 0.09;
move_group->setStartStateToCurrentState();
move_group->setApproximateJointValueTarget(target_pose);
move_group->asyncMove();
ROS_WARN("ARM POSITION: (%.3f, %.3f, %.3f)", target_pose.position.x, target_pose.position.y, target_pose.position.z);
}
int main(int argc, char** argv) {
ros::init(argc, argv, "move_group_interface_tutorial");
ros::NodeHandle node_handle;
ros::AsyncSpinner spinner(2);
spinner.start();
move_group = (new moveit::planning_interface::MoveGroupInterface(PLANNING_GROUP));
target_pose = move_group->getPoseTarget().pose;
target_pose.orientation.w = 0;
move_group->setApproximateJointValueTarget(target_pose);
move_group->asyncMove();
move_group->setGoalOrientationTolerance(3.14);
ros::Subscriber joystick_topic = node_handle.subscribe("arm_position", 1, joystickCallback);
ros::waitForShutdown();
}
| [
"aditya.pawar@warriorlife.net"
] | aditya.pawar@warriorlife.net |
4eb13bf012ed83a56b7d3e339c688663eb08e500 | db557a30a28f77774cf4662c119a9197fb3ae0a0 | /HelperFunctions/populateVkTimeDomainEXTCollection.cpp | 38a35a4f24616312657b3d4c28308dc658c3ba4d | [
"Apache-2.0"
] | permissive | dkaip/jvulkan-natives-Linux-x86_64 | b076587525a5ee297849e08368f32d72098ae87e | ea7932f74e828953c712feea11e0b01751f9dc9b | refs/heads/master | 2021-07-14T16:57:14.386271 | 2020-09-13T23:04:39 | 2020-09-13T23:04:39 | 183,515,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,253 | cpp | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* populateVkTimeDomainEXTCollection.cpp
*
* Created on: Nov 4, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void populateVkTimeDomainEXTCollection(
JNIEnv *env,
jobject jVkTimeDomainEXTCollectionObject,
VkTimeDomainEXT const *vkTimeDomainEXTs,
int numberOfVkTimeDomainEXTs)
{
jclass theClass = env->GetObjectClass(jVkTimeDomainEXTCollectionObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find class for a Collecion of com/CIMthetics/jvulkan/VulkanExtensions/Enums/VkTimeDomainEXT");
return;
}
jmethodID addMethodId = env->GetMethodID(theClass, "add", "(Ljava/lang/Object;)Z");
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Could not find method id for add");
return;
}
for(int i = 0; i < numberOfVkTimeDomainEXTs; i++)
{
jobject jVkTimeDomainEXT = createEnumFromValue(
env,
"com/CIMthetics/jvulkan/VulkanExtensions/Enums/VkTimeDomainEXT",
vkTimeDomainEXTs[i]);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling createEnumFromValue.");
return;
}
jboolean addResult = env->CallBooleanMethod(jVkTimeDomainEXTCollectionObject, addMethodId, jVkTimeDomainEXT);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Error calling CallBooleanMethod");
return;
}
if (addResult == 0)
{
LOGERROR(env, "%s", "Failed trying to add jVkTimeDomainEXT Object");
}
}
}
}
| [
"dkaip@earthlink.net"
] | dkaip@earthlink.net |
a78eccc506dfcf3091d7b0e846d6c616977616d8 | f7fadc413cad92f03721742b9c5d94281c12ba02 | /C++/Test/cpp/UPDATE_F.CPP | d29102e3a8b0eeb6de5a91d558829801bb675201 | [] | no_license | amitmca/EducationalMaterial | f7acc7f701b42fb5f2821e56bab4ce253532c3f7 | 088a1fe34a0bdd4b46ea5cc7f930d8d1a3f510d0 | refs/heads/master | 2021-06-06T18:20:39.774159 | 2019-11-30T15:52:07 | 2019-11-30T15:52:07 | 134,157,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,263 | cpp | #include<conio.h>
#include<iostream.h>
#include<fstream.h>
#include<string.h>
#define MAX 20
class file
{
protected:
int rno;
char name[MAX];
public:
void getdata(void)
{
cout<<"\n\nEnter the name:";
cin>>name;
cout<<"\n\nEnter the Roll No:";
cin>>rno;
}
void putdata(void)
{
cout<<"\n\n\t"<<name<<"\t"<<rno;
}
};
int main()
{
file F;
fstream file;
file.open("temp.dat",ios::in|ios::binary|ios::app|ios::out);
if(file.fail())
cout<<"\n\n\tThe File Not found";
cout<<"\n\n\tEnter the data:";
F.getdata();
char ch;
file.write((char *) & F,sizeof(F));
file.seekg(0);
while(file.read((char *) & F,sizeof(F)))
{
F.putdata();
}
int n;
cout<<"\n\nEnter the object no to modify:";
cin>>n;
n=(n-1) *sizeof(F);
file.seekp(n);
file.read((char *) & F,sizeof(F));
while(!file.eof())
{
file.read((char *) & F,sizeof(F));
F.putdata();
}
//F.putdata();
/* cout<<"\n\nEnter the new data:";
F.getdata();
file.write((char *) & F,sizeof(F));
cout<<"\n\nThe updateed data is:";
file.seekg(0,ios::beg);
while(file.read((char *) & F,sizeof(F)))
{
F.putdata();
}*/
file.close();
getch();
return 0;
} | [
"amitbaramatimca@gmail.com"
] | amitbaramatimca@gmail.com |
7c1c6c327d50f0717b941de289870516ebd78c05 | e97aa666dac039faeb1185013781bb6dd3333c8f | /Task1.cpp | d651a02fbef46f1a90f64eac4e222fe888f9a4c7 | [] | no_license | VitaliyV/Task1 | 1ca9a01dd2a61fc2cd8483830302ca1cf64690a1 | 9b4a9236554beed9c62b2909ae50e7f7ab74ea56 | refs/heads/master | 2016-09-03T07:15:06.197834 | 2013-11-24T19:27:05 | 2013-11-24T19:27:05 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,117 | cpp | //
//
#include "stdafx.h"
#include "iostream"
#include "fstream"
using namespace std;
int main()
{
unsigned char data;
setlocale(LC_ALL, "Ukrainian");
cout<<" ***********************************\n"
<<" *** ***\n"
<<" **** Ця програма зчитує файл *****\n"
<<" ****** data.txt i виводить його данi *******\n"
<<" ******* в ASCII кодi. ********\n"
<<" ****** *******\n"
<<" **** *****\n"
<<" *** 2013. Vitaliy ***\n"
<<" ***********************************\n\n\n";
ifstream infile("data.txt");
if (!infile)
cerr<<"Файл не вiдкрився! Перевiрте назву файлу (повинна бути data.txt)"<<endl;
else
cout<<"Данi з файлу в ASCII кодi: ";
while (infile>>data)
cout<<hex<<(int)data<<" ";
cout<<endl;
system("pause");
return 0;
} | [
"vitaliy3v@rambler.ru"
] | vitaliy3v@rambler.ru |
8147db94c45d3531a58d133ac1e0e9a75cf593f5 | 3490954f207f1fc26a6ae4195476ce170a59e845 | /src/Utils/SzArray.h | d0ab2db0d50a9e6815956b752a6de77f0f258df5 | [] | no_license | rssh/UAKGQuery | cf69566fbd091f9117f76bb7cd51a050cbe59576 | 63de600999ef3c0b9b51f860c5d0522ad39575dc | refs/heads/master | 2016-09-06T03:19:44.588353 | 2013-11-17T15:43:05 | 2013-11-17T15:43:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,827 | h | #ifndef __Utils_SzArray_h
#define __Utils_SzArray_h
/*
* SzArray.h
* part of implementation of CORBA Query service for Oracle.
* (c) Grad-Soft Ltd <http://www.gradsoft.kiev.ua>, 2000-2003
* $Id: SzArray.h,v 1.15 2003-03-11 19:25:22 rssh Exp $
*/
#ifndef __importCORBA_h
#include <importCORBA.h>
#endif
#ifndef __GradSoft_vector_INCLUDED
#include <vector>
#ifndef __GradSoft_vector_INCLUDED
#define __GradSoft_vector_INCLUDED
#endif
#endif
class SzArray
{
protected:
std::vector<char *> strzs_;
public:
SzArray() {}
SzArray( const char*, const char );
~SzArray()
{
//
// Memory must be allocateed by operator new
//
for(unsigned int i=0; i<strzs_.size(); i++)
delete[] strzs_[i];
}
public:
//
// get vector element
//
const char* get_sz_at( int i ) const
{ return strzs_[i]; }
char* get_sz_at(int i)
{ return strzs_[i]; }
char* operator []( int i )
{ return strzs_[i]; }
const char* operator []( int i ) const
{ return strzs_[i]; }
/**
* get size
*/
size_t size() const
{ return strzs_.size(); }
/**
* in: (prefix, suffix, delimiter)
* example: (["a","b","c"], "a", "z", ',') -> "aaz,abz,acz"
*/
char* generate_list(const char* prefix, const char* suffix,
const char* delimiter);
//
// in: (sz_array, suffix)
// incoming array must be the same size with stored
// example: (["a", "z", 'p'], "=") -> ["a=a", "b=z", "c=p"]
// where ["a","b","c"] is stored in *this
//
void reduct_assigment(const SzArray&, const char*);
//
// append element to sz_array
//
void append_sz_nodup(char*);
void append_sz_dup(const char*);
//
// append vector to sz_array
//
void append_szarray(const SzArray&);
private:
SzArray& operator = (const SzArray& );
SzArray(const SzArray&);
};
#endif
| [
"ruslan@shevchenko.kiev.ua"
] | ruslan@shevchenko.kiev.ua |
a3dd6f12ffa7f6b15f423f0a92a5db11181b1e3f | 1ab0196b4f7039bd3ccd25c8a2d4a7694e2ee93f | /cascade.h | 9f9d7dd2ffe9e3247fcc7bfbe5568a43ca6bffae | [] | no_license | zhangyonglei/TCPGO-Another-TCPCOPY- | 97ca5f8390ebca4bbc9b462fd33c5da459c42d10 | d2b18050281f669c972d6a2b0077eedcefb4c943 | refs/heads/master | 2020-03-24T00:26:35.650123 | 2018-07-20T03:41:00 | 2018-07-20T03:41:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | h | /*********************************************
* cascade.h
* Author: kamuszhou@tencent.com kamuszhou@qq.com
* website: v.qq.com www.dogeye.net
* Created on: 19 Mar, 2014
* Praise Be to the Lord. BUG-FREE CODE !
********************************************/
#ifndef _CASCADE_H_
#define _CASCADE_H_
#include "misc.h"
#include "utils.h"
#include <boost/thread/thread.hpp>
#include <boost/lockfree/spsc_queue.hpp>
#include <boost/atomic.hpp>
#include <boost/asio/signal_set.hpp>
class cascade;
extern cascade g_cascade;
/**
* To chain together many horos instances running on different machines.
*/
class cascade
{
public:
typedef boost::lockfree::spsc_queue<boost::shared_ptr<MemBlock>, boost::lockfree::capacity<10000> > LockFreeQueue;
public:
cascade();
virtual ~cascade();
void ready_go();
// if the queue is full, this packet will be dropped.
void push_back(boost::shared_ptr<MemBlock> block);
void run();
void stop();
private:
void enable_sigpipe();
private:
LockFreeQueue _mem_blocks;
boost::thread _forwarder;
boost::atomic_int _count;
boost::atomic<bool> _done;
boost::mutex _mutex;
boost::condition_variable _con_var;
int _fifo_fd;
};
#endif /* _CASCADE_H_ */
| [
"zausiu@gmail.com"
] | zausiu@gmail.com |
f576a34363a4b7acccaff30192ff90d6e4061ebc | 9cefee022eec34a27e4ad16e47bb615993ac99e6 | /Labview Software/Hardware Mfg/AlazarTech SDK/7.2.3/Samples_C/ATS9350/DualPort/NPT_onFPGA_FFT/ATS9350_NPT_onFPGA_FFT.cpp | 1fa14418fb303e171d9303e5b7809b5f652b7319 | [] | no_license | BUNPC/SerialSectOCT | 8fb497012bbd98751fbf752fb8fa08d6ddc86ec5 | b3ddbe87595fc246dc3959cc0c81b453c27b0781 | refs/heads/master | 2023-08-17T23:51:09.781058 | 2023-08-05T15:28:08 | 2023-08-05T15:28:32 | 133,862,311 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 20,790 | cpp | //-------------------------------------------------------------------------------------------------
//
// Copyright (c) 2008-2016 AlazarTech, Inc.
//
// AlazarTech, Inc. licenses this software under specific terms and conditions. Use of any of the
// software or derivatives thereof in any product without an AlazarTech digitizer board is strictly
// prohibited.
//
// AlazarTech, Inc. provides this software AS IS, WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED,
// INCLUDING, WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR
// PURPOSE. AlazarTech makes no guarantee or representations regarding the use of, or the results of
// the use of, the software and documentation in terms of correctness, accuracy, reliability,
// currentness, or otherwise; and you rely on the software, documentation and results solely at your
// own risk.
//
// IN NO EVENT SHALL ALAZARTECH BE LIABLE FOR ANY LOSS OF USE, LOSS OF BUSINESS, LOSS OF PROFITS,
// INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OF ANY KIND. IN NO EVENT SHALL
// ALAZARTECH'S TOTAL LIABILITY EXCEED THE SUM PAID TO ALAZARTECH FOR THE PRODUCT LICENSED
// HEREUNDER.
//
//-------------------------------------------------------------------------------------------------
// AcqToDisk.cpp :
//
// This program demonstrates how to configure a ATS9350 to make a onFPGA FFT
// NPT_onFPGA_FFT acquisition.
//
#include <vector>
#include <stdio.h>
#include <string.h>
#include "AlazarError.h"
#include "AlazarApi.h"
#include "AlazarCmd.h"
#include "AlazarDSP.h"
#ifdef _WIN32
#include <conio.h>
#else // ifndef _WIN32
#include <errno.h>
#include <math.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#define TRUE 1
#define FALSE 0
#define _snprintf snprintf
inline U32 GetTickCount(void);
inline void Sleep(U32 dwTime_ms);
inline int _kbhit (void);
inline int GetLastError();
#endif // ifndef _WIN32
#define ERR_CHECK(x) \
do \
{ \
RETURN_CODE retCode = (x); \
if (retCode != ApiSuccess) \
{ \
printf("Error : %s -- %s\n", #x, AlazarErrorToText(retCode)); \
return FALSE; \
} \
} while (0)
// TODO: Select the number of DMA buffers to allocate.
#define BUFFER_COUNT 4
// Globals variables
U16 *BufferArray[BUFFER_COUNT] = { NULL };
double samplesPerSec = 0.0;
// Forward declarations
BOOL ConfigureBoard(HANDLE boardHandle, dsp_module_handle fftHandle, U32 recordLength_samples);
BOOL AcquireData(HANDLE boardHandle, dsp_module_handle fftHandle, U32 recordLength_samples);
//-------------------------------------------------------------------------------------------------
//
// Function : main
//
// Description : Program entry point
//
//-------------------------------------------------------------------------------------------------
int main(int argc, char *argv[])
{
// TODO: Select a board
U32 systemId = 1;
U32 boardId = 1;
// Get a handle to the board
HANDLE boardHandle = AlazarGetBoardBySystemID(systemId, boardId);
if (boardHandle == NULL)
{
printf("Error: Unable to open board system Id %u board Id %u\n", systemId, boardId);
return 1;
}
// Get a handle to the FFT module
U32 numModules;
ERR_CHECK(AlazarDSPGetModules(boardHandle, 0, NULL, &numModules));
if (numModules < 1) {
printf("This board does any DSP modules.\n");
return FALSE;
}
std::vector<dsp_module_handle> dspHandles(numModules);
ERR_CHECK(AlazarDSPGetModules(boardHandle, numModules, &dspHandles[0], NULL));
dsp_module_handle fftHandle = dspHandles[0];
// TODO: Select the record length
U32 recordLength_samples = 2048;
// Configure the board's sample rate, input, and trigger settings
if (!ConfigureBoard(boardHandle, fftHandle, recordLength_samples))
{
printf("Error: Configure board failed\n");
return 1;
}
// Make an acquisition, optionally saving sample data to a file
if (!AcquireData(boardHandle, fftHandle, recordLength_samples))
{
printf("Error: Acquisition failed\n");
return 1;
}
return 0;
}
//-------------------------------------------------------------------------------------------------
//
// Function : ConfigureBoard
//
// Description : Configure sample rate, input, and trigger settings
//
//-------------------------------------------------------------------------------------------------
BOOL ConfigureBoard(HANDLE boardHandle, dsp_module_handle fftHandle, U32 recordLength_samples)
{
// TODO: Specify the sample rate (see sample rate id below)
samplesPerSec = 500000000.0;
// TODO: Select the window function type
U32 windowType = DSP_WINDOW_HANNING;
// TODO: Select the background subtraction record
std::vector<S16> backgroundSubtractionRecord(recordLength_samples, 0);
// TODO: Select clock parameters as required to generate this sample rate.
//
// For example: if samplesPerSec is 100.e6 (100 MS/s), then:
// - select clock source INTERNAL_CLOCK and sample rate SAMPLE_RATE_100MSPS
// - select clock source FAST_EXTERNAL_CLOCK, sample rate SAMPLE_RATE_USER_DEF, and connect a
// 100 MHz signal to the EXT CLK BNC connector.
ERR_CHECK(AlazarSetCaptureClock(boardHandle,
INTERNAL_CLOCK,
SAMPLE_RATE_500MSPS,
CLOCK_EDGE_RISING,
0));
// TODO: Select channel A input parameters as required
ERR_CHECK(AlazarInputControlEx(boardHandle,
CHANNEL_A,
DC_COUPLING,
INPUT_RANGE_PM_400_MV,
IMPEDANCE_50_OHM));
// TODO: Select channel A bandwidth limit as required
ERR_CHECK(AlazarSetBWLimit(boardHandle,
CHANNEL_A,
0));
// TODO: Select channel B input parameters as required
ERR_CHECK(AlazarInputControlEx(boardHandle,
CHANNEL_B,
DC_COUPLING,
INPUT_RANGE_PM_400_MV,
IMPEDANCE_50_OHM));
// TODO: Select channel B bandwidth limit as required
ERR_CHECK(AlazarSetBWLimit(boardHandle,
CHANNEL_B,
0));
// TODO: Select trigger inputs and levels as required
ERR_CHECK(AlazarSetTriggerOperation(boardHandle,
TRIG_ENGINE_OP_J,
TRIG_ENGINE_J,
TRIG_CHAN_A,
TRIGGER_SLOPE_POSITIVE,
150,
TRIG_ENGINE_K,
TRIG_DISABLE,
TRIGGER_SLOPE_POSITIVE,
128));
// TODO: Select external trigger parameters as required
ERR_CHECK(AlazarSetExternalTrigger(boardHandle,
DC_COUPLING,
ETR_5V));
// TODO: Set trigger delay as required.
double triggerDelay_sec = 0;
U32 triggerDelay_samples = (U32)(triggerDelay_sec * samplesPerSec + 0.5);
ERR_CHECK(AlazarSetTriggerDelay(boardHandle, triggerDelay_samples));
// TODO: Set trigger timeout as required.
// NOTE:
// The board will wait for a for this amount of time for a trigger event. If a trigger event
// does not arrive, then
// the board will automatically trigger. Set the trigger timeout value to 0 to force the board
// to wait forever for a
// trigger event.
//
// IMPORTANT:
// The trigger timeout value should be set to zero after appropriate trigger parameters have
// been determined,
// otherwise the board may trigger if the timeout interval expires before a hardware trigger
// event arrives.
double triggerTimeout_sec = 0;
U32 triggerTimeout_clocks = (U32)(triggerTimeout_sec / 10.e-6 + 0.5);
ERR_CHECK(AlazarSetTriggerTimeOut(boardHandle, triggerTimeout_clocks));
// TODO: Configure AUX I/O connector as required
ERR_CHECK(AlazarConfigureAuxIO(boardHandle, AUX_OUT_TRIGGER, 0));
// FFT Configuration
U32 dspModuleId;
ERR_CHECK(AlazarDSPGetInfo(fftHandle, &dspModuleId, NULL, NULL, NULL, NULL, NULL));
if (dspModuleId != DSP_MODULE_FFT) {
printf("Error: DSP module is not FFT\n");
return FALSE;
}
U32 fftLength_samples = 1;
while (fftLength_samples < recordLength_samples)
fftLength_samples *= 2;
// Create and fill the window function
std::vector<float> window(fftLength_samples);
ERR_CHECK(AlazarDSPGenerateWindowFunction(windowType,
&window[0],
recordLength_samples,
fftLength_samples - recordLength_samples));
// Set the window function
ERR_CHECK(AlazarFFTSetWindowFunction(fftHandle,
fftLength_samples,
&window[0],
NULL));
// Background subtraction
ERR_CHECK(AlazarFFTBackgroundSubtractionSetRecordS16(fftHandle, &backgroundSubtractionRecord[0],
recordLength_samples));
ERR_CHECK(AlazarFFTBackgroundSubtractionSetEnabled(fftHandle, TRUE));
return TRUE;
}
//-------------------------------------------------------------------------------------------------
//
// Function : AcquireData
//
// Description : Perform an acquisition, optionally saving data to file.
//
//-------------------------------------------------------------------------------------------------
BOOL AcquireData(HANDLE boardHandle, dsp_module_handle fftHandle, U32 recordLength_samples)
{
RETURN_CODE retCode = ApiSuccess;
// TODO: Specify the number of records per DMA buffer
U32 recordsPerBuffer = 10;
// TODO: Specify the total number of buffers to capture
U32 buffersPerAcquisition = 10;
// TODO: Select which channels to capture (A, B, or both)
U16 channelMask = CHANNEL_A;
// TODO: Select if you wish to save the sample data to a file
BOOL saveData = false;
// TODO: Select the FFT output format
U32 outputFormat = FFT_OUTPUT_FORMAT_U16_LOG;
// TODO: Select the presence of NPT footers
U32 footer = FFT_FOOTER_NONE;
// Calculate the number of enabled channels from the channel mask
int channelCount = 0;
int channelsPerBoard = 2;
for (int channel = 0; channel < channelsPerBoard; channel++)
{
U32 channelId = 1U << channel;
if (channelMask & channelId)
channelCount++;
}
// Get the sample size in bits, and the on-board memory size in samples per channel
U8 bitsPerSample;
U32 maxSamplesPerChannel;
ERR_CHECK(AlazarGetChannelInfo(boardHandle, &maxSamplesPerChannel, &bitsPerSample));
// Create a data file if required
FILE *fpData = NULL;
if (saveData)
{
fpData = fopen("data.bin", "wb");
if (fpData == NULL)
{
printf("Error: Unable to create data file -- %u\n", GetLastError());
return FALSE;
}
}
// Configure the FFT
U32 fftLength_samples = 1;
while (fftLength_samples < recordLength_samples)
fftLength_samples *= 2;
U32 bytesPerOutputRecord;
BOOL success = TRUE;
if (success)
{
retCode = AlazarFFTSetup(fftHandle,
channelMask,
recordLength_samples,
fftLength_samples,
outputFormat,
footer,
0,
&bytesPerOutputRecord);
if (retCode != ApiSuccess)
{
printf("Error: AlazarSetRecordSize failed -- %s\n", AlazarErrorToText(retCode));
success = FALSE;
}
}
U32 bytesPerBuffer = bytesPerOutputRecord * recordsPerBuffer;
// Allocate memory for DMA buffers
U32 bufferIndex;
for (bufferIndex = 0; (bufferIndex < BUFFER_COUNT) && success; bufferIndex++)
{
// Allocate page aligned memory
BufferArray[bufferIndex] = (U16 *)AlazarAllocBufferU16(boardHandle, bytesPerBuffer);
if (BufferArray[bufferIndex] == NULL)
{
printf("Error: Alloc %u bytes failed\n", bytesPerBuffer);
success = FALSE;
}
}
// Configure the board to make an NPT AutoDMA acquisition
if (success)
{
U32 recordsPerAcquisition = recordsPerBuffer * buffersPerAcquisition;
U32 admaFlags = ADMA_EXTERNAL_STARTCAPTURE | ADMA_NPT | ADMA_DSP;
retCode = AlazarBeforeAsyncRead(boardHandle, channelMask, 0,
bytesPerOutputRecord, recordsPerBuffer, 0x7FFFFFFF,
admaFlags);
if (retCode != ApiSuccess)
{
printf("Error: AlazarBeforeAsyncRead failed -- %s\n", AlazarErrorToText(retCode));
success = FALSE;
}
}
// Add the buffers to a list of buffers available to be filled by the board
for (bufferIndex = 0; (bufferIndex < BUFFER_COUNT) && success; bufferIndex++)
{
U16 *pBuffer = BufferArray[bufferIndex];
retCode = AlazarPostAsyncBuffer(boardHandle, pBuffer, bytesPerBuffer);
if (retCode != ApiSuccess)
{
printf("Error: AlazarPostAsyncBuffer %u failed -- %s\n", bufferIndex,
AlazarErrorToText(retCode));
success = FALSE;
}
}
// Arm the board system to wait for a trigger event to begin the acquisition
if (success)
{
retCode = AlazarStartCapture(boardHandle);
if (retCode != ApiSuccess)
{
printf("Error: AlazarStartCapture failed -- %s\n", AlazarErrorToText(retCode));
success = FALSE;
}
}
// Wait for each buffer to be filled, process the buffer, and re-post it to
// the board.
if (success)
{
printf("Capturing %d buffers ... press any key to abort\n", buffersPerAcquisition);
U32 startTickCount = GetTickCount();
U32 buffersCompleted = 0;
INT64 bytesTransferred = 0;
while (buffersCompleted < buffersPerAcquisition)
{
// TODO: Set a buffer timeout that is longer than the time
// required to capture all the records in one buffer.
U32 timeout_ms = 5000;
// Wait for the buffer at the head of the list of available buffers
// to be filled by the board.
bufferIndex = buffersCompleted % BUFFER_COUNT;
U16 *pBuffer = BufferArray[bufferIndex];
retCode = AlazarDSPGetBuffer(boardHandle, pBuffer, timeout_ms);
if (retCode != ApiSuccess)
{
printf("Error: AlazarDSPGetBuffer failed -- %s\n",
AlazarErrorToText(retCode));
success = FALSE;
}
if (success)
{
// The buffer is full and has been removed from the list
// of buffers available for the board
buffersCompleted++;
bytesTransferred += bytesPerBuffer;
// TODO: Process sample data in this buffer.
// NOTE:
//
// While you are processing this buffer, the board is already filling the next
// available buffer(s).
//
// You MUST finish processing this buffer and post it back to the board before
// the board fills all of its available DMA buffers and on-board memory.
//
if (saveData)
{
// Write record to file
size_t bytesWritten = fwrite(pBuffer, sizeof(BYTE), bytesPerBuffer, fpData);
if (bytesWritten != bytesPerBuffer)
{
printf("Error: Write buffer %u failed -- %u\n", buffersCompleted,
GetLastError());
success = FALSE;
}
}
}
// Add the buffer to the end of the list of available buffers.
if (success)
{
retCode = AlazarPostAsyncBuffer(boardHandle, pBuffer, bytesPerBuffer);
if (retCode != ApiSuccess)
{
printf("Error: AlazarPostAsyncBuffer failed -- %s\n",
AlazarErrorToText(retCode));
success = FALSE;
}
}
// If the acquisition failed, exit the acquisition loop
if (!success)
break;
// If a key was pressed, exit the acquisition loop
if (_kbhit())
{
printf("Aborted...\n");
break;
}
// Display progress
printf("Completed %u buffers\r", buffersCompleted);
}
// Display results
double transferTime_sec = (GetTickCount() - startTickCount) / 1000.;
printf("Capture completed in %.2lf sec\n", transferTime_sec);
double buffersPerSec;
double bytesPerSec;
double recordsPerSec;
U32 recordsTransferred = recordsPerBuffer * buffersCompleted;
if (transferTime_sec > 0.)
{
buffersPerSec = buffersCompleted / transferTime_sec;
bytesPerSec = bytesTransferred / transferTime_sec;
recordsPerSec = recordsTransferred / transferTime_sec;
}
else
{
buffersPerSec = 0.;
bytesPerSec = 0.;
recordsPerSec = 0.;
}
printf("Captured %u buffers (%.4g buffers per sec)\n", buffersCompleted, buffersPerSec);
printf("Captured %u records (%.4g records per sec)\n", recordsTransferred, recordsPerSec);
printf("Transferred %I64d bytes (%.4g bytes per sec)\n", bytesTransferred, bytesPerSec);
}
// Abort the acquisition
retCode = AlazarDSPAbortCapture(boardHandle);
if (retCode != ApiSuccess)
{
printf("Error: AlazarAbortAsyncRead failed -- %s\n", AlazarErrorToText(retCode));
success = FALSE;
}
// Free all memory allocated
for (bufferIndex = 0; bufferIndex < BUFFER_COUNT; bufferIndex++)
{
if (BufferArray[bufferIndex] != NULL)
{
AlazarFreeBufferU16(boardHandle, BufferArray[bufferIndex]);
}
}
// Close the data file
if (fpData != NULL)
fclose(fpData);
return success;
}
#ifndef WIN32
inline U32 GetTickCount(void)
{
struct timeval tv;
if (gettimeofday(&tv, NULL) != 0)
return 0;
return (tv.tv_sec * 1000) + (tv.tv_usec / 1000);
}
inline void Sleep(U32 dwTime_ms)
{
usleep(dwTime_ms * 1000);
}
inline int _kbhit (void)
{
struct timeval tv;
fd_set rdfs;
tv.tv_sec = 0;
tv.tv_usec = 0;
FD_ZERO(&rdfs);
FD_SET (STDIN_FILENO, &rdfs);
select(STDIN_FILENO+1, &rdfs, NULL, NULL, &tv);
return FD_ISSET(STDIN_FILENO, &rdfs);
}
inline int GetLastError()
{
return errno;
}
#endif | [
"Shuaibin@bu.edu"
] | Shuaibin@bu.edu |
e64f894583d8a8c6aefe5013a06aee5944cb643c | 5d8194e3b9a04d1bbdc0c8826318f721f93fc811 | /basic_compute/main.cpp | 15e910d224abdc163304f7b946c817953ac18c9f | [] | no_license | jeremycheong/CudaSampleUtils | ede517fdc64ba07685aeb6aeedb99dca0544637b | e0bdec36ce2a4a50b9a8ed71cab495a7095959e9 | refs/heads/master | 2023-05-09T08:53:39.030307 | 2021-05-26T07:25:57 | 2021-05-26T07:25:57 | 277,861,319 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,419 | cpp | #include "common.h"
#include "operate.cuh"
#include <iostream>
#include <cstring>
#include <memory>
void TestMatrixAdd()
{
uint32_t width = 1 << 6;
uint32_t height = 1 << 5;
float* matrix_a = new float[width * height];
float* matrix_b = new float[width * height];
Common::GenerateRangeData(matrix_a, width * height);
Common::GenerateRangeData(matrix_b, width * height, 2);
INFO_LOG("Generate data success");
float* matrix_out = new float[width * height];
Operate op;
op.MatrixAdd(matrix_a, matrix_b, matrix_out, width, height);
for (uint32_t i = 0; i < height; ++ i)
{
float* data_ptr = matrix_out + i * width;
std::cout << "[ ";
for (uint32_t j = 0; j < width; ++ j)
{
std::cout << data_ptr[j] << ", ";
}
std::cout << "]" << std::endl;
std::cout << "========================================================" << std::endl;
}
delete[](matrix_a);
delete[](matrix_b);
delete[](matrix_out);
INFO_LOG("Done");
}
int TestReduceSum(int argc, char* argv[])
{
uint32_t data_size = 1 << 10;
INFO_LOG("data_size: %u", data_size);
float* data = new float[data_size];
Common::GenerateRangeData(data, data_size);
INFO_LOG("Generate data success");
float sum = 0.f;
for (int i = 0; i < data_size; i ++)
{
sum += data[i];
}
INFO_LOG("cpu sum: %f", sum);
sum = 0.f;
Operate op;
op.ReduceSum(data, sum, data_size);
INFO_LOG("reduce sum: %f", sum);
delete[](data);
INFO_LOG("Done");
return 0;
}
void TestSparseMatrixTranspose()
{
uint32_t data_size = 845;
INFO_LOG("data_size: %u", data_size);
uint32_t width = 65;
uint32_t height = data_size / width;
float* data = new float[data_size];
Common::GenerateRangeData(data, data_size);
INFO_LOG("Generate data success");
float* out_data = new float[data_size];
std::memset(out_data, 0, data_size * sizeof(float));
Operate op;
op.SparseMatrixTranspose(data, out_data, width, height);
uint32_t out_width = height;
uint32_t out_height = width;
for (uint32_t i = 0; i < out_height; i ++)
{
std::cout << "========================================== " << i << std::endl;
float* row_data = out_data + i * out_width;
std::cout << "[ ";
for (int j = 0; j < out_width; j ++)
{
std::cout << row_data[j] << ", ";
}
std::cout << "]" << std::endl;
}
delete[](data);
delete[](out_data);
INFO_LOG("Done");
}
void TestCvResize()
{
cv::Mat input_image = cv::imread("../data/lena.jpg");
cv::Mat resized;
cv::Mat cv_resized;
// cv::resize(input_image, cv_resized, cv::Size(input_image.cols * 2, input_image.rows * 2), 0.f, 0.f, cv::INTER_NEAREST);
cv::resize(input_image, cv_resized, cv::Size(640, 640), 0.f, 0.f, cv::INTER_LINEAR);
cv::imshow("cv resize", cv_resized);
Operate op;
// op.CvResize(input_image, input_image.cols * 2, input_image.rows * 2, resized);
// op.CvBiLinearResize(input_image, input_image.cols * 2, input_image.rows * 2, resized);
float scale;
cv::Rect paste_roi;
op.CvPadResize(cv_resized, 640, 384, scale, paste_roi, resized);
cv::imwrite("./pad_resized.jpg", resized);
// cv::imshow("lena", input_image);
// cv::imshow("resized", resized);
cv::waitKey(0);
cv::destroyAllWindows();
}
void TestCvPadResizeNormal()
{
cv::Mat input_image = cv::imread("../data/lena.jpg");
int width = input_image.cols;
int height = input_image.rows;
int c = input_image.channels();
int resized_out_w = 640;
int resized_out_h = 384;
cv::Mat resized;
Operate op;
// opencv 方式进行预处理
float scale;
cv::Rect paste_roi;
op.CvPadResize(input_image, resized_out_w, resized_out_h, scale, paste_roi, resized);
// cv::imshow("Resized", resized);
cv::Mat input_float;
resized.convertTo(input_float, CV_32FC3, 1.0f / 255);
float *input_data = new float[resized.cols * resized.rows * resized.channels()];
cv::Mat channel_r(cv::Size(resized_out_w, resized_out_h), CV_32FC1, input_data);
cv::Mat channel_g(cv::Size(resized_out_w, resized_out_h), CV_32FC1, input_data + resized_out_w * resized_out_h);
cv::Mat channel_b(cv::Size(resized_out_w, resized_out_h), CV_32FC1, input_data + resized_out_w * resized_out_h * 2);
std::vector<cv::Mat> channels = {channel_b, channel_g, channel_r};
cv::split(input_float, channels); // bgr
// cuda 方式进行预处理
std::cout << "=================================" << std::endl;
uchar3* input_dev = nullptr;
float* output_dev = nullptr;
int input_bytes_size = height * width * sizeof(uchar3);
int output_bytes_size = resized_out_w * resized_out_h * c * sizeof(float);
cudaMalloc((void**)&input_dev, input_bytes_size);
cudaMalloc((void**)&output_dev, output_bytes_size);
// cv::imshow("cuda_input_image", input_image);
cudaMemcpy(input_dev, input_image.data, input_bytes_size, cudaMemcpyHostToDevice);
std::vector<int> means = {0, 0, 0};
std::vector<float> vars = {1.0f / 255, 1.0f / 255, 1.0f / 255};
float scale_g;
op.CvPadResizeGpu(input_dev, width, height, resized_out_w, resized_out_h, means, vars, scale_g, output_dev);
float* input_data_g = new float[resized_out_w * resized_out_h * c];
cudaMemcpy(input_data_g, output_dev, output_bytes_size, cudaMemcpyDeviceToHost);
cudaFree(input_dev);
cudaFree(output_dev);
// 判断是否一致
int data_size = resized_out_w * resized_out_h * c;
INFO_LOG("=====================");
for (size_t i = 0; i < data_size; i ++)
{
// std::cout << input_data[i] << std::endl;
// if (input_data_g[i])
// {
// std::cout << input_data_g[i] << std::endl;
// }
if (input_data[i] != input_data_g[i])
{
INFO_LOG("opencv process [%zu] result is not equal with gpu process result [%0.4f != %0.4f]", i, input_data[i], input_data_g[i]);
}
}
delete[](input_data);
delete[](input_data_g);
// cv::waitKey(0);
}
int main(int argc, char* argv[])
{
// TestReduceSum(argc, argv);
// TestMatrixAdd();
// TestSparseMatrixTranspose();
// TestCvResize();
TestCvPadResizeNormal();
return 0;
} | [
"jeremy_2015@163.com"
] | jeremy_2015@163.com |
0f6aa6e61d2a2323d5292b460c0c200d51c2c9c5 | 6f7e2c1a2bd098cf11c823a0e1d4a1132b50a84d | /code_c++/mesh.hpp | cfbad78224bbdf7a4057c28d2ccb61fffe28830d | [] | no_license | MBruliard/macs2_advection_diffusion | 5054b5f932db25ae10c153f10bb79ea26988877d | e198488de3f372c316375629810f58d81c41eb20 | refs/heads/master | 2020-03-17T20:31:57.475628 | 2018-06-01T13:29:09 | 2018-06-01T13:29:09 | 133,914,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,274 | hpp | /*
* BRULIARD - RIGAL
* Projet Numérique - MACS 2
*/
#ifndef __MESH_HPP__
#define __MESH_HPP__
/*
Classe permrettant de définir un mesh regulier.
soit les parametres suivants:
@_nx est le nombre de discretisations en x
@_ny le nombre de discretisations en y
la distance @a est la longueur du cote selon x
la distance @b est la longueur du cote selon y
@
*/
#include <vector>
#include <string>
#include <fstream>
#include <iostream>
/*
@_xmax et @_ymax
@_nx et @_ny sont le nombre de discrétisations entre 0 et _xmax et 0 et _ymax
@_discretX sont les différents x discrétisées
@_discretY sont les différents y discrétisées
*/
class MeshRegulier
{
public:
/*attributs*/
double _xmax, _ymax;
int _nx, _ny;
std::vector<double> _discretX;
std::vector<double> _discretY;
/*constructeurs*/
MeshRegulier () = default;
MeshRegulier (double a, double b, int nx, int ny);
MeshRegulier (std::string chemin);
MeshRegulier (int nx, int ny);
MeshRegulier (const MeshRegulier &u);
/*lecture et ecriture dans les fichiers .dat*/
void save(std::string chemin);
void genererGrapheGnuplot (std::string chemindonnees, std::string chemingnuplot);
void lancerGraphe (std::string chemingraphe);
};
#endif //__MESH_HPP__
| [
"margauxbruliard@live.com"
] | margauxbruliard@live.com |
31b35663e599893fd95f9a334b515b3889c09a48 | 84b36166204ec2e6c7e76cc7a56e9ae4cd7ca208 | /CategoryLB.h | 403f344f0f99fa3bef181057336e55cd3926fd69 | [] | no_license | shigeru-yokochi/AutoPC | 24836bb91197e82d5e682a7b8a33098d7aedeb6e | a6015f415e216c40f649596d10559ea3ea299197 | refs/heads/master | 2020-03-25T06:09:44.266547 | 2018-08-04T01:19:43 | 2018-08-04T01:19:43 | 143,486,365 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,935 | h | #if !defined(AFX_CATEGORYLB_H__82D4C948_4FA5_4124_9308_A3E26887AB81__INCLUDED_)
#define AFX_CATEGORYLB_H__82D4C948_4FA5_4124_9308_A3E26887AB81__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
// CategoryLB.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CCategoryLB window
#include "define.h"
class CCategoryLB : public CListBox
{
// Construction
public:
CCategoryLB();
// Attributes
public:
// Operations
public:
void DispCategoryData(CString strDataPath,CListBox *pLB1,CString strFname,int nType,
int *npInfoCode=NULL);
//カテゴリ検索ファイル 内容LB表示
CString GetCategorySelectAreaCode(CString strDataPath,CListBox *pLB1,CString strFname);
//選択したカテゴリ地域コード獲得
CString GetCategoryNextFile(CString strDataPath,CListBox *pLB1,CString strFname);
//次カテゴリファイル名獲得
BOOL GetEWNS(CString strDataPath,CListBox *pLB1,CString strFname,
int *npEW,int *npNS); //現在選択しているアイテムの緯度経度を獲得
// int GetStructCategoryFileSize(); //カテゴリ file 構造体サイズ獲得
void SetCircumferenceItem(int *npBuf,CString *strpName,CString strDataPath,CString strCircumferenceFile); //周辺検索ITEM全ての緯度経度と名称をバッファに格納
int GetCircumferenceItemCntMax(CString strDataPath,CString strCircumferenceFile); //周辺検索ITEM総数獲得
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CCategoryLB)
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CCategoryLB();
// Generated message map functions
protected:
//{{AFX_MSG(CCategoryLB)
// NOTE - the ClassWizard will add and remove member functions here.
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
//-----------地域file 構造体--------------------------------------
struct struct_area_file{
char zName[22];
char zCode[4];
};
//-----------大分類、小分類file 構造体--------------------------------------
struct struct_G1G2_file{
char zName[22];
char zCode[2];
};
//-----------カテゴリ file 構造体--------------------------------------
struct struct_category_file{
char zName[28];
int nEW;
int nNS;
int nInfoCode;
};
int HlpGetCircumferenceItemCntMax(CString strDataPath,CString strCircumferenceFile); //周辺検索ITEM総数獲得sub
void HlpSetCircumferenceItem(int *npCnt,int *npBuf,CString *strpName,CString strDataPath,CString strCircumferenceFile); //周辺検索ITEM全ての緯度経度と名称をバッファに格納sub
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CATEGORYLB_H__82D4C948_4FA5_4124_9308_A3E26887AB81__INCLUDED_)
| [
"shigeru@yokochi.jp"
] | shigeru@yokochi.jp |
f1297155f9e56a00e6e75c2f8a5333a7671f2e57 | bd04d063fc3220b4b648a83b34a0e86df1daff7e | /Source/Common/Menus/HighScoresMenu.cpp | 3dccbb332f914ea00a0a242db46012af1f2100a5 | [] | no_license | beno0103/FinalProject | f04fc52aaa61e327f6b1bae02f302f6a46c049f4 | c03da119550bea8ea02926d365309be4ba8f889e | refs/heads/master | 2016-09-06T00:54:14.018695 | 2013-12-13T22:12:00 | 2013-12-13T22:12:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | cpp | //
// HighScoresMenu.cpp
// GAM-1514 OSX Game
//
// Created by Amedee Benoitrevert on 2013-12-13.
// Copyright (c) 2013 Algonquin College. All rights reserved.
//
#include "HighScoresMenu.h"
#include "../UI/UIButton.h"
#include "../Game/Game.h"
#include "../Game/Level.h"
#include "../Screen Manager/ScreenManager.h"
#include "../SaveAndLoadMenu/SaveAndLoadMenu.h"
HighScoresMenu::HighScoresMenu() : Menu(NULL, NULL)
{
addButton(new UIButton("ExitButton"));
}
HighScoresMenu::~HighScoresMenu()
{
}
const char* HighScoresMenu::getName()
{
return HIGHSCORES_MENU_SCREEN_NAME;
}
void HighScoresMenu::buttonAction(UIButton* button)
{
int index = getIndexForButton(button);
if(index == 0)
{
ScreenManager::getInstance()->switchScreen(MAIN_MENU_SCREEN_NAME);
}
else if(index == 1)
{
}
else if(index == 2)
{
}
else if(index == 3)
{
}
else if (index == 4)
{
}
}
| [
"beno0103@wj310-06.ottawa.ad.algonquincollege.com"
] | beno0103@wj310-06.ottawa.ad.algonquincollege.com |
061f7e54ef7200c942326f29dd6ed13d9ef29172 | 1acf5742a620da04cc786e88a31f96a0cc14f7ee | /winMain/winMain.cpp | 3c5f657ca6c3945934343575cdd6192955280c88 | [] | no_license | jdk211/Age_Of_One_Piece | 37abe058ebef974cc5c00657cad3308fa8a342ea | d2b515b759cdaab72b820b440d4ad4c275a29caa | refs/heads/master | 2021-07-16T06:29:04.753162 | 2017-10-21T12:32:18 | 2017-10-21T12:32:18 | 107,778,365 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 4,540 | cpp | // winMain.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//
#include "stdafx.h"
#include "gameStudy.h"
/* #### 전역변수 #### */
HINSTANCE _hInstance;
HWND _hWnd;
POINT _ptMouse = {0, 0};
bool _leftButtonDown = false;
bool _rightButtonDown = false;
int _mapSizeX = 1600, _mapSizeY = 768;
int _unitID = 0;
int _lineNum = 1;
gameStudy _gs;
/* #### 함수 #### */
LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM );
void setWindowSize( int x, int y, int width, int height );
/* #### 메인 #### */
int APIENTRY WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpszCmdParam, int nCmdShow )
{
_hInstance = hInstance;
//MSG : 운영체제에서 발행하는 메시지 정보를 저장하기 위한 구조체
MSG message;
//WNDCLASS : 윈도우의 정보를 저장하기 위한 구조체
WNDCLASS wndClass;
wndClass.cbClsExtra = 0; //클래스 여분 메모리
wndClass.cbWndExtra = 0; //윈도우 여분 메모리
wndClass.hbrBackground = (HBRUSH) GetStockObject( WHITE_BRUSH ); //백그라운드
wndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); //커서
wndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION );//아이콘
wndClass.hInstance = hInstance; //인스턴스
wndClass.lpfnWndProc = (WNDPROC) WndProc; //윈도우 프로시져
wndClass.lpszClassName = WINNAME; //클래스이름
wndClass.lpszMenuName = NULL; //메뉴이름
wndClass.style = CS_HREDRAW | CS_VREDRAW; //윈도우 스타일
//윈도우 클래스 등록
RegisterClass( &wndClass );
//윈도우 생성
_hWnd = CreateWindow(
WINNAME, //윈도우 클래스의 이름
WINNAME, //윈도우 타이틀바 이름
WINSTYLE, //윈도우 스타일
WINSTARTX, //윈도우 화면좌표 x
WINSTARTY, //윈도우 화면좌표 y
WINSIZEX, //윈도우 화면좌표 width
WINSIZEY, //윈도우 화면좌표 height
NULL, //부모 윈도우
(HMENU) NULL,//메뉴핸들
hInstance, //인스턴스 지정
NULL ); //윈도우 및 자식 윈도우를 생성하면
//지정해주되 그렇지 않으면 NULL
//화면 작업 사이즈 영역 계산
setWindowSize(WINSTARTX, WINSTARTY, WINSIZEX, WINSIZEY);
//화면에 윈도우 보여준다
ShowWindow( _hWnd, nCmdShow );
//게임 스터디의 초기화가 정상적으로 이뤄지지 않았다면 그냥 나가라
if ( FAILED( _gs.init() ) )
{
return 0;
}
//메시지 루프~~
//GetMessage : GetMessage는 메시지를 꺼내올 수 있을때까지 멈춰있는 함수이고,
//PeekMessage : PeekMessage는 메시지가 없더라도 리턴되는 함수로서,
//계속 루프되는 함수이다.
while ( true ) //게임용
{
if ( PeekMessage( &message, NULL, 0, 0, PM_REMOVE ) )
{
if ( message.message == WM_QUIT ) break;
TranslateMessage( &message );
DispatchMessage( &message );
}
else
{
TIMEMANAGER->update( 70.f );
_gs.update();
_gs.render();
}
}
//TranslateMessage : 키보드 입력메시지 처리를 담당한다.
//입력된 키가 문자키인지 확인후 대문자 혹은 소문자, 한글, 영문,
//인지에 대한 WM_CHAR메시지를 발생시킨다.
//DispatchMessage : 윈도우 프로시져에서 전달된 메시지를 실제
//윈도우로 전달해준다
//메시지 큐에 메시지가 있으면 메시지 처리...
//while ( GetMessage( &message, 0, 0, 0 ) ) //일반 프로그램용
//{
// TranslateMessage( &message );
// DispatchMessage( &message );
//}
//스터디 해제
_gs.release();
//윈도우 클래스 등록 해제
UnregisterClass( WINNAME, hInstance );
return message.wParam;
}
//윈도우 프로시져 : 메시지를 운영체제에 전달
//강제로 운영체제가 호출해준다
//hWnd : 어느 윈도우에서 발생한 메시지인지 구분
//iMessage : 메시지 구분 번호
//wParam : unsigned int 마우스 버튼의 상태, 키보드 조합키의 상태를 전달
//lParam : unsigned long 마우스 클릭 좌표 전달
LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam )
{
return _gs.MainProc( hWnd, iMessage, wParam, lParam );
}
//윈도우 사이즈 WINSIZEX, WINSIZEY 딱 맞게
void setWindowSize( int x, int y, int width, int height )
{
RECT rc;
rc.left = 0;
rc.top = 0;
rc.right = width;
rc.bottom = height;
AdjustWindowRect( &rc, WINSTYLE, false );
SetWindowPos( _hWnd, NULL, x, y, ( rc.right - rc.left ),
( rc.bottom - rc.top ), SWP_NOZORDER | SWP_NOMOVE );
}
| [
"jdk211@naver.com"
] | jdk211@naver.com |
fa8a68dfe2e3c4d8849255960eac75cc398e581f | b6d90054fd559b5b115fb830d169525ad8b73321 | /Code/lab2/mymatrix.h | 99ba2d3555b4c76bc1b8be368a6db3b9603d1a2e | [] | no_license | Painted-Black/BMSTU-AlgorithmAnalysis | deddbd63534b95b65adc405198fb4c8d23dd33ec | cc366d9e290cd160fb02019485a99dbba0cc1bc3 | refs/heads/master | 2020-09-10T18:58:56.435641 | 2019-12-03T22:36:35 | 2019-12-03T22:36:35 | 221,806,118 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 885 | h | #ifndef MYMATRIX_H
#define MYMATRIX_H
#include <iostream>
#include <stdexcept>
#include <stdlib.h>
#include <ctime>
#include <vector>
class MyMatrix
{
public:
MyMatrix(int rows, int cols, bool randomize=false, int defaultValue=0);
MyMatrix(const MyMatrix& m);
MyMatrix(std::vector<std::vector<int>> &vec);
MyMatrix(std::initializer_list<std::initializer_list<int>> list);
~MyMatrix();
void print();
int at(int row, int col) const;
void set(int row, int col, int val);
MyMatrix multiply(const MyMatrix& m);
MyMatrix multiplyVinograd(const MyMatrix& m);
MyMatrix multiplyVinogradOptimized(const MyMatrix& m);
bool isEqual(const MyMatrix& m);
bool isEqual(const MyMatrix& m1, const MyMatrix& m2);
private:
int mColumns;
int mRows;
int *mValues;
int mMinRand = -50;
int mRandRange = 100;
};
#endif // MYMATRIX_H
| [
"syzygy.sys@gmail.com"
] | syzygy.sys@gmail.com |
1e4ce542f134526905e685ed836ca48485bba6d9 | c2a50f048fd9cded050fdbdb1e1b1d0cdbd0fee5 | /src/boxes/FileTypeBox.h | c9ee8a31a57f51edf3e8fe500c11a9a7e231aa3d | [
"MIT"
] | permissive | alexmdodge/cmafp | 722ee87ab13bf67cddc3081725cec82e77db8282 | 47fc81918b594b36787e299be7175ed5aabedd38 | refs/heads/main | 2023-06-22T04:00:26.677461 | 2021-07-24T21:43:14 | 2021-07-24T21:43:14 | 378,416,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | h |
#include <vector>
#include "Box.h"
// File Type Box
// Format Req: 1
//
// General compatability metadata
class FileTypeBox : public Box {
public:
FileTypeBox(std::shared_ptr<MediaFile>& file, uint32_t start_offset);
json to_json();
std::string major_brand;
uint32_t minor_version;
std::vector<std::string> compatible_brands;
};
| [
"alex.mdodge@gmail.com"
] | alex.mdodge@gmail.com |
dce7f1b171becf871ef356021121511ba498ea57 | b05b89e1f6378905bbb62e2a2bf2d4f8e3187932 | /diameterOfBinaryTree.cpp | 68fe61191c91890358c6cbd268e38370ca00ed94 | [
"MIT"
] | permissive | anishmo99/Daily-Interview-Pro | c959cd336209132aebad67a409df685e654cfdfc | d8724e8feec558ab1882d22c9ca63b850b767753 | refs/heads/master | 2023-04-10T08:09:46.089227 | 2021-04-27T07:27:38 | 2021-04-27T07:27:38 | 269,157,996 | 1 | 1 | MIT | 2020-06-08T07:09:19 | 2020-06-03T17:57:21 | C++ | UTF-8 | C++ | false | false | 758 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int depth;
int diameterOfBinaryTree(TreeNode* root) {
depth = 0;
rec(root);
return depth;
}
int rec(TreeNode* root){
if(root == nullptr)
return 0;
int l = rec(root->left);
int r = rec(root->right);
depth = max(depth, l + r);
return max(l,r) + 1;
}
}; | [
"ani10sh@gmail.com"
] | ani10sh@gmail.com |
58c647a6d5a8163433a8ca4a8ac51e2fe12ad668 | 553e2c3e6aec473171e81bdf235f960ed51a4425 | /gestionTurnosASP/ess/shared/inc/colors_ess.inc | 03db82392d892a6e848a4589b6a0244afc2f50a7 | [] | no_license | niugeramirez/trivoli-sw-factory | 9dbf3d32a2a23509c0f0b1d932f1850c3c84a2e4 | f84739734b5e98e8bf856fe8fccde5bd3fa7ed4e | refs/heads/master | 2022-12-20T14:31:56.151354 | 2022-02-11T16:27:04 | 2022-02-11T16:27:04 | 39,565,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,088 | inc | <%
' Case 1
const css_default = "/serviciolocal/ess/shared/css/ess1.css"
const css_tablas = "/serviciolocal/ess/shared/css/tables3.css"
const css_tablas_int = "/serviciolocal/ess/shared/css/tables_gray.css"
const color_menu_off = "#F7C521"
const color_menu_on = "#B99106"
const color_sub_menu_off = "#003366"
const color_sub_menu_on = "#336699"
' Case 2
' const css_default = "/serviciolocal/ess/shared/css/default_2.css"
' const css_tablas = "/serviciolocal/ess/shared/css/tables3_2.css"
' const css_tablas_int = "css/tables_gray_2.css"
' const color_menu_off = "#004000"
' const color_menu_on = "#669966"
' const color_sub_menu_off = "#669966"
' const color_sub_menu_on = "Green"
' Case 3
' const css_default = "/serviciolocal/ess/shared/css/default_3.css"
' const css_tablas = "/serviciolocal/ess/shared/css/tables3_3.css"
' const css_tablas_int = "/serviciolocal/ess/shared/css/tables_gray_3.css"
' const color_menu_off = "#660000"
' const color_menu_on = "#CC3300"
' const color_sub_menu_off = "#CC3300"
' const color_sub_menu_on = "Maroon"
%>
| [
"niugeramirez@bcf0a061-0236-3b59-aeac-4c6e9de247fc"
] | niugeramirez@bcf0a061-0236-3b59-aeac-4c6e9de247fc |
121cc70e242b00b8412ad34036d1da3c87d50ac7 | 0ca8832a2818af66f1a584d7cf6c56abf0af8591 | /src/thirdparty/boost/boost/mpl/sort.hpp | ec736bbf9d5731969c174428763e0e6c434d78f5 | [] | no_license | knobik/source-python | 241e27d325d40fc8374fc9fb8f8311a146dc7e77 | e57308a662c25110f1a1730199985a5f2cf11713 | refs/heads/master | 2021-01-10T08:28:55.402519 | 2013-09-12T04:00:12 | 2013-09-12T04:00:12 | 54,717,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 744 | hpp |
#ifndef BOOST_MPL_SORT_HPP_INCLUDED
#define BOOST_MPL_SORT_HPP_INCLUDED
// Copyright Eric Friedman 2002-2003
// Copyright Aleksey Gurtovoy 2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: sort.hpp 49239 2008-10-10 09:10:26Z agurtovoy $
// $Date: 2008-10-10 05:10:26 -0400 (Fri, 10 Oct 2008) $
// $Revision: 49239 $
#include <boost/mpl/aux_/sort_impl.hpp>
#include <boost/mpl/aux_/inserter_algorithm.hpp>
namespace boost { namespace mpl {
BOOST_MPL_AUX_INSERTER_ALGORITHM_DEF(3, sort)
}}
#endif // BOOST_MPL_SORT_HPP_INCLUDED
| [
"satoon101@gmail.com"
] | satoon101@gmail.com |
423f6f6a1447ba138699d301594e0d11e3356cb1 | b5bbe0b4d438e8852df1f581234d2101b25f1672 | /source/src/binds/components/LuaCSelectable.cpp | 44b06d9845b20a2fe362ea8891270c9a2e572702 | [] | no_license | Galaco/sokoban3d | 8315cbc8d23fa0d86e1f0b638590a00b99b878b9 | d630fb74238a5e5bae10f2e4c5cd2375cc93945c | refs/heads/master | 2021-01-20T17:23:41.713001 | 2018-11-15T11:14:23 | 2018-11-15T11:14:23 | 25,152,727 | 2 | 0 | null | 2018-11-15T11:14:24 | 2014-10-13T09:46:50 | C++ | UTF-8 | C++ | false | false | 843 | cpp | #include "LuaCSelectable.h"
LuaCSelectable::LuaCSelectable(){}
LuaCSelectable::~LuaCSelectable(){}
const luaL_Reg LuaCSelectable::luaBinds[] = {
{"Create", lua_Create},
{"IsSelected", lua_GetSelected},
{"HoveredOver", lua_GetHovered},
{NULL, NULL}
};
int LuaCSelectable::lua_Create(lua_State* L)
{
LuaBinder binder(L);
CSelectable* v = new CSelectable();
binder.pushusertype(v, "CSelectable");
return 1;
}
int LuaCSelectable::lua_GetHovered(lua_State* L)
{
LuaBinder binder(L);
CSelectable* c = static_cast<CSelectable*>(binder.checkusertype(1, "CSelectable"));
binder.pushnumber(c->getHovered());
return 1;
}
int LuaCSelectable::lua_GetSelected(lua_State* L)
{
LuaBinder binder(L);
CSelectable* c = static_cast<CSelectable*>(binder.checkusertype(1, "CSelectable"));
binder.pushnumber(c->getSelected());
return 1;
} | [
"contact@joshmartin.eu"
] | contact@joshmartin.eu |
af2ff0161f8391bedd5a86f1bbfba715ba8281f2 | 90047daeb462598a924d76ddf4288e832e86417c | /content/browser/service_worker/service_worker_context_core.h | 65050374a9d6f5547c399f2bb51c280343a32b22 | [
"BSD-3-Clause"
] | permissive | massbrowser/android | 99b8c21fa4552a13c06bbedd0f9c88dd4a4ad080 | a9c4371682c9443d6e1d66005d4db61a24a9617c | refs/heads/master | 2022-11-04T21:15:50.656802 | 2017-06-08T12:31:39 | 2017-06-08T12:31:39 | 93,747,579 | 2 | 2 | BSD-3-Clause | 2022-10-31T10:34:25 | 2017-06-08T12:36:07 | null | UTF-8 | C++ | false | false | 17,665 | h | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CORE_H_
#define CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CORE_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/files/file_path.h"
#include "base/id_map.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list_threadsafe.h"
#include "content/browser/service_worker/service_worker_info.h"
#include "content/browser/service_worker/service_worker_process_manager.h"
#include "content/browser/service_worker/service_worker_provider_host.h"
#include "content/browser/service_worker/service_worker_registration_status.h"
#include "content/browser/service_worker/service_worker_storage.h"
#include "content/common/content_export.h"
#include "content/common/worker_url_loader_factory_provider.mojom.h"
#include "content/public/browser/service_worker_context.h"
class GURL;
namespace base {
class FilePath;
class SingleThreadTaskRunner;
}
namespace storage {
class QuotaManagerProxy;
class SpecialStoragePolicy;
}
namespace content {
class EmbeddedWorkerRegistry;
class ServiceWorkerContextObserver;
class ServiceWorkerContextWrapper;
class ServiceWorkerDatabaseTaskManager;
class ServiceWorkerDispatcherHost;
class ServiceWorkerJobCoordinator;
class ServiceWorkerNavigationHandleCore;
class ServiceWorkerProviderHost;
class ServiceWorkerRegistration;
class ServiceWorkerStorage;
// This class manages data associated with service workers.
// The class is single threaded and should only be used on the IO thread.
// In chromium, there is one instance per storagepartition. This class
// is the root of the containment hierarchy for service worker data
// associated with a particular partition.
class CONTENT_EXPORT ServiceWorkerContextCore
: NON_EXPORTED_BASE(public ServiceWorkerVersion::Listener) {
public:
using BoolCallback = base::Callback<void(bool)>;
using StatusCallback = base::Callback<void(ServiceWorkerStatusCode status)>;
using RegistrationCallback =
base::Callback<void(ServiceWorkerStatusCode status,
const std::string& status_message,
int64_t registration_id)>;
using UpdateCallback = base::Callback<void(ServiceWorkerStatusCode status,
const std::string& status_message,
int64_t registration_id)>;
using UnregistrationCallback =
base::Callback<void(ServiceWorkerStatusCode status)>;
using ProviderMap = IDMap<std::unique_ptr<ServiceWorkerProviderHost>>;
using ProcessToProviderMap = IDMap<std::unique_ptr<ProviderMap>>;
using ProviderByClientUUIDMap =
std::map<std::string, ServiceWorkerProviderHost*>;
// Directory for ServiceWorkerStorage and ServiceWorkerCacheManager.
static const base::FilePath::CharType kServiceWorkerDirectory[];
// Iterates over ServiceWorkerProviderHost objects in a ProcessToProviderMap.
class CONTENT_EXPORT ProviderHostIterator {
public:
~ProviderHostIterator();
ServiceWorkerProviderHost* GetProviderHost();
void Advance();
bool IsAtEnd();
private:
friend class ServiceWorkerContextCore;
using ProviderHostPredicate =
base::Callback<bool(ServiceWorkerProviderHost*)>;
ProviderHostIterator(ProcessToProviderMap* map,
const ProviderHostPredicate& predicate);
void Initialize();
bool ForwardUntilMatchingProviderHost();
ProcessToProviderMap* map_;
ProviderHostPredicate predicate_;
std::unique_ptr<ProcessToProviderMap::iterator> process_iterator_;
std::unique_ptr<ProviderMap::iterator> provider_host_iterator_;
DISALLOW_COPY_AND_ASSIGN(ProviderHostIterator);
};
// This is owned by the StoragePartition, which will supply it with
// the local path on disk. Given an empty |user_data_directory|,
// nothing will be stored on disk. |observer_list| is created in
// ServiceWorkerContextWrapper. When Notify() of |observer_list| is called in
// ServiceWorkerContextCore, the methods of ServiceWorkerContextObserver will
// be called on the thread which called AddObserver() of |observer_list|.
ServiceWorkerContextCore(
const base::FilePath& user_data_directory,
std::unique_ptr<ServiceWorkerDatabaseTaskManager>
database_task_runner_manager,
const scoped_refptr<base::SingleThreadTaskRunner>& disk_cache_thread,
storage::QuotaManagerProxy* quota_manager_proxy,
storage::SpecialStoragePolicy* special_storage_policy,
base::ObserverListThreadSafe<ServiceWorkerContextObserver>* observer_list,
ServiceWorkerContextWrapper* wrapper);
ServiceWorkerContextCore(
ServiceWorkerContextCore* old_context,
ServiceWorkerContextWrapper* wrapper);
~ServiceWorkerContextCore() override;
// ServiceWorkerVersion::Listener overrides.
void OnRunningStateChanged(ServiceWorkerVersion* version) override;
void OnVersionStateChanged(ServiceWorkerVersion* version) override;
void OnDevToolsRoutingIdChanged(ServiceWorkerVersion* version) override;
void OnMainScriptHttpResponseInfoSet(ServiceWorkerVersion* version) override;
void OnErrorReported(ServiceWorkerVersion* version,
const base::string16& error_message,
int line_number,
int column_number,
const GURL& source_url) override;
void OnReportConsoleMessage(ServiceWorkerVersion* version,
int source_identifier,
int message_level,
const base::string16& message,
int line_number,
const GURL& source_url) override;
void OnControlleeAdded(ServiceWorkerVersion* version,
ServiceWorkerProviderHost* provider_host) override;
void OnControlleeRemoved(ServiceWorkerVersion* version,
ServiceWorkerProviderHost* provider_host) override;
ServiceWorkerContextWrapper* wrapper() const { return wrapper_; }
ServiceWorkerStorage* storage() { return storage_.get(); }
ServiceWorkerProcessManager* process_manager();
EmbeddedWorkerRegistry* embedded_worker_registry() {
return embedded_worker_registry_.get();
}
ServiceWorkerJobCoordinator* job_coordinator() {
return job_coordinator_.get();
}
// Maintains DispatcherHosts to exchange service worker related messages
// through them. The DispatcherHosts are not owned by this class.
void AddDispatcherHost(int process_id,
ServiceWorkerDispatcherHost* dispatcher_host);
ServiceWorkerDispatcherHost* GetDispatcherHost(int process_id);
void RemoveDispatcherHost(int process_id);
// The context class owns the set of ProviderHosts.
void AddProviderHost(
std::unique_ptr<ServiceWorkerProviderHost> provider_host);
ServiceWorkerProviderHost* GetProviderHost(int process_id, int provider_id);
void RemoveProviderHost(int process_id, int provider_id);
void RemoveAllProviderHostsForProcess(int process_id);
std::unique_ptr<ProviderHostIterator> GetProviderHostIterator();
// Returns a ProviderHost iterator for all ServiceWorker clients for
// the |origin|. This only returns ProviderHosts that are of CONTROLLEE
// and belong to the |origin|.
std::unique_ptr<ProviderHostIterator> GetClientProviderHostIterator(
const GURL& origin);
// Runs the callback with true if there is a ProviderHost for |origin| of type
// SERVICE_WORKER_PROVIDER_FOR_WINDOW which is a main (top-level) frame.
void HasMainFrameProviderHost(const GURL& origin,
const BoolCallback& callback) const;
// Maintains a map from Client UUID to ProviderHost.
// (Note: instead of maintaining 2 maps we might be able to uniformly use
// UUID instead of process_id+provider_id elsewhere. For now I'm leaving
// these as provider_id is deeply wired everywhere)
void RegisterProviderHostByClientID(const std::string& client_uuid,
ServiceWorkerProviderHost* provider_host);
void UnregisterProviderHostByClientID(const std::string& client_uuid);
ServiceWorkerProviderHost* GetProviderHostByClientID(
const std::string& client_uuid);
// A child process of |source_process_id| may be used to run the created
// worker for initial installation.
// Non-null |provider_host| must be given if this is called from a document.
void RegisterServiceWorker(const GURL& pattern,
const GURL& script_url,
ServiceWorkerProviderHost* provider_host,
const RegistrationCallback& callback);
void UnregisterServiceWorker(const GURL& pattern,
const UnregistrationCallback& callback);
// Callback is called issued after all unregistrations occur. The Status
// is populated as SERVICE_WORKER_OK if all succeed, or SERVICE_WORKER_FAILED
// if any did not succeed.
void UnregisterServiceWorkers(const GURL& origin,
const UnregistrationCallback& callback);
// Updates the service worker. If |force_bypass_cache| is true or 24 hours
// have passed since the last update, bypasses the browser cache.
void UpdateServiceWorker(ServiceWorkerRegistration* registration,
bool force_bypass_cache);
void UpdateServiceWorker(ServiceWorkerRegistration* registration,
bool force_bypass_cache,
bool skip_script_comparison,
ServiceWorkerProviderHost* provider_host,
const UpdateCallback& callback);
// Used in DevTools to update the service worker registrations without
// consulting the browser cache while loading the controlled page. The
// loading is delayed until the update completes and the new worker is
// activated. The new worker skips the waiting state and immediately
// becomes active after installed.
bool force_update_on_page_load() { return force_update_on_page_load_; }
void set_force_update_on_page_load(bool force_update_on_page_load) {
force_update_on_page_load_ = force_update_on_page_load;
}
// This class maintains collections of live instances, this class
// does not own these object or influence their lifetime.
ServiceWorkerRegistration* GetLiveRegistration(int64_t registration_id);
void AddLiveRegistration(ServiceWorkerRegistration* registration);
void RemoveLiveRegistration(int64_t registration_id);
const std::map<int64_t, ServiceWorkerRegistration*>& GetLiveRegistrations()
const {
return live_registrations_;
}
ServiceWorkerVersion* GetLiveVersion(int64_t version_id);
void AddLiveVersion(ServiceWorkerVersion* version);
void RemoveLiveVersion(int64_t registration_id);
const std::map<int64_t, ServiceWorkerVersion*>& GetLiveVersions() const {
return live_versions_;
}
// PlzNavigate
// Methods to manage the map keeping track of all
// ServiceWorkerNavigationHandleCores registered for ongoing navigations.
void AddNavigationHandleCore(int service_worker_provider_id,
ServiceWorkerNavigationHandleCore* handle);
void RemoveNavigationHandleCore(int service_worker_provider_id);
ServiceWorkerNavigationHandleCore* GetNavigationHandleCore(
int service_worker_provider_id);
std::vector<ServiceWorkerRegistrationInfo> GetAllLiveRegistrationInfo();
std::vector<ServiceWorkerVersionInfo> GetAllLiveVersionInfo();
// ProtectVersion holds a reference to |version| until UnprotectVersion is
// called.
void ProtectVersion(const scoped_refptr<ServiceWorkerVersion>& version);
void UnprotectVersion(int64_t version_id);
// Returns new context-local unique ID.
int GetNewServiceWorkerHandleId();
int GetNewRegistrationHandleId();
void ScheduleDeleteAndStartOver() const;
// Deletes all files on disk and restarts the system. This leaves the system
// in a disabled state until it's done.
void DeleteAndStartOver(const StatusCallback& callback);
// Methods to support cross site navigations.
std::unique_ptr<ServiceWorkerProviderHost> TransferProviderHostOut(
int process_id,
int provider_id);
void TransferProviderHostIn(
int new_process_id,
int new_host_id,
std::unique_ptr<ServiceWorkerProviderHost> provider_host);
void ClearAllServiceWorkersForTest(const base::Closure& callback);
// Determines if there is a ServiceWorker registration that matches |url|, and
// if |other_url| falls inside the scope of the same registration. See
// ServiceWorkerContext::CheckHasServiceWorker for more details.
void CheckHasServiceWorker(
const GURL& url,
const GURL& other_url,
const ServiceWorkerContext::CheckHasServiceWorkerCallback callback);
void UpdateVersionFailureCount(int64_t version_id,
ServiceWorkerStatusCode status);
// Returns the count of consecutive start worker failures for the given
// version. The count resets to zero when the worker successfully starts.
int GetVersionFailureCount(int64_t version_id);
// Binds the ServiceWorkerWorkerClient of a dedicated (or shared) worker to
// the parent frame's ServiceWorkerProviderHost. (This is used only when
// off-main-thread-fetch is enabled.)
void BindWorkerFetchContext(
int render_process_id,
int service_worker_provider_id,
mojom::ServiceWorkerWorkerClientAssociatedPtrInfo client_ptr_info);
base::WeakPtr<ServiceWorkerContextCore> AsWeakPtr() {
return weak_factory_.GetWeakPtr();
}
private:
friend class ServiceWorkerContextCoreTest;
FRIEND_TEST_ALL_PREFIXES(ServiceWorkerContextCoreTest, FailureInfo);
typedef std::map<int64_t, ServiceWorkerRegistration*> RegistrationsMap;
typedef std::map<int64_t, ServiceWorkerVersion*> VersionMap;
struct FailureInfo {
int count;
ServiceWorkerStatusCode last_failure;
};
ProviderMap* GetProviderMapForProcess(int process_id) {
return providers_->Lookup(process_id);
}
void RegistrationComplete(const GURL& pattern,
const RegistrationCallback& callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration);
void UpdateComplete(const UpdateCallback& callback,
ServiceWorkerStatusCode status,
const std::string& status_message,
ServiceWorkerRegistration* registration);
void UnregistrationComplete(const GURL& pattern,
const UnregistrationCallback& callback,
int64_t registration_id,
ServiceWorkerStatusCode status);
void DidGetAllRegistrationsForUnregisterForOrigin(
const UnregistrationCallback& result,
const GURL& origin,
ServiceWorkerStatusCode status,
const std::vector<ServiceWorkerRegistrationInfo>& registrations);
void DidFindRegistrationForCheckHasServiceWorker(
const GURL& other_url,
const ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration);
void OnRegistrationFinishedForCheckHasServiceWorker(
const ServiceWorkerContext::CheckHasServiceWorkerCallback callback,
scoped_refptr<ServiceWorkerRegistration> registration);
// It's safe to store a raw pointer instead of a scoped_refptr to |wrapper_|
// because the Wrapper::Shutdown call that hops threads to destroy |this| uses
// Bind() to hold a reference to |wrapper_| until |this| is fully destroyed.
ServiceWorkerContextWrapper* wrapper_;
std::map<int /* process_id */, ServiceWorkerDispatcherHost*>
dispatcher_hosts_;
std::unique_ptr<ProcessToProviderMap> providers_;
std::unique_ptr<ProviderByClientUUIDMap> provider_by_uuid_;
std::unique_ptr<ServiceWorkerStorage> storage_;
scoped_refptr<EmbeddedWorkerRegistry> embedded_worker_registry_;
std::unique_ptr<ServiceWorkerJobCoordinator> job_coordinator_;
std::map<int64_t, ServiceWorkerRegistration*> live_registrations_;
std::map<int64_t, ServiceWorkerVersion*> live_versions_;
std::map<int64_t, scoped_refptr<ServiceWorkerVersion>> protected_versions_;
std::map<int64_t /* version_id */, FailureInfo> failure_counts_;
// PlzNavigate
// Map of ServiceWorkerNavigationHandleCores used for navigation requests.
std::map<int, ServiceWorkerNavigationHandleCore*>
navigation_handle_cores_map_;
bool force_update_on_page_load_;
int next_handle_id_;
int next_registration_handle_id_;
// Set in RegisterServiceWorker(), cleared in ClearAllServiceWorkersForTest().
// This is used to avoid unnecessary disk read operation in tests. This value
// is false if Chrome was relaunched after service workers were registered.
bool was_service_worker_registered_;
scoped_refptr<base::ObserverListThreadSafe<ServiceWorkerContextObserver>>
observer_list_;
base::WeakPtrFactory<ServiceWorkerContextCore> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(ServiceWorkerContextCore);
};
} // namespace content
#endif // CONTENT_BROWSER_SERVICE_WORKER_SERVICE_WORKER_CONTEXT_CORE_H_
| [
"xElvis89x@gmail.com"
] | xElvis89x@gmail.com |
0c691b2fdc1c328e24cf751224f83097c6e1459a | 477b998baf135a7d3563c46329ef191893a1ea40 | /s02e01_cinema/cinema_ptr.cpp | 053b5dcce88c47096a3aa0917f3f874b9ebfef8b | [] | no_license | senapk/poo_2018_2 | eaadc5a639b6b4c591a6391a928299c9c616015e | ab17a1ee8b05ecb678df9a5d8b9319c3aed77b3c | refs/heads/master | 2021-07-18T03:58:27.494325 | 2018-12-13T13:33:11 | 2018-12-13T13:33:11 | 143,944,359 | 5 | 8 | null | 2018-11-15T19:09:06 | 2018-08-08T01:19:43 | C++ | UTF-8 | C++ | false | false | 2,381 | cpp | #include <iostream>
#include <vector>
#include <sstream>
using namespace std;
struct Cliente{
string id;
string fone;
Cliente(string id = "fulano", string fone = "0000"){
this->id = id;
this->fone = fone;
}
string toString(){
stringstream ss;
ss << this->id << ":" << this->fone;
return ss.str();
}
};
struct Sala{
vector<Cliente*> cadeiras;
/*
Sala(int qtd = 0){
for(int i = 0; i < qtd; i++)
cadeiras.push_back(nullptr);
}*/
Sala(int qtd = 0):
cadeiras(qtd, nullptr)
{
}
~Sala(){
for(Cliente * cli : cadeiras)
delete(cli);
}
bool reservar(Cliente * cliente, int ind){
int qtd = cadeiras.size();
if((ind < 0) || (ind >= qtd)){
cout << "fail: essa cadeira nao existe" << endl;
return false;
}
if(cadeiras[ind] != nullptr){
cout << "fail: essa cadeira ja esta ocupada" << endl;
return false;
}
for(int i = 0; i < (int) cadeiras.size(); i++){
if((cadeiras[i] != nullptr) && (cadeiras[i]->id == cliente->id)){
cout << "fail: voce ja esta no cinema" << endl;
return false;
}
}
cadeiras[ind] = cliente;
return true;
}
string toString(){
stringstream ss;
ss << "[ ";
for(Cliente * cliente : cadeiras)
if(cliente == nullptr)
ss << "- ";
else
ss << cliente->toString() << " ";
ss << "]";
return ss.str();
}
};
int main(){
Sala sala;
string op;
while(true){
cin >> op;
if(op == "end")
break;
if(op == "help"){
cout << "show; init _qtd; reservar _id _fone _ind; cancelar _id" << endl;
}else if(op == "show"){
cout << sala.toString() << endl;
}else if(op == "init"){
int qtd;
cin >> qtd;
sala = Sala(qtd);
cout << "sala criada com " << qtd << " cadeiras" << endl;
}else if(op == "reservar"){
string nome, fone;
int ind;
cin >> nome >> fone >> ind;
if(sala.reservar(new Cliente(nome, fone), ind))
cout << "done" << endl;
}
}
} | [
"sena.ufc@gmail.com"
] | sena.ufc@gmail.com |
6afbf6c7fa138a4040798a73bbdfe6af099b369c | fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd | /third_party/WebKit/public/web/WebWindowFeatures.h | cf213a90434a507a32eb12c0e6b19ff3f8629eaa | [
"BSD-3-Clause",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | wzyy2/chromium-browser | 2644b0daf58f8b3caee8a6c09a2b448b2dfe059c | eb905f00a0f7e141e8d6c89be8fb26192a88c4b7 | refs/heads/master | 2022-11-23T20:25:08.120045 | 2018-01-16T06:41:26 | 2018-01-16T06:41:26 | 117,618,467 | 3 | 2 | BSD-3-Clause | 2022-11-20T22:03:57 | 2018-01-16T02:09:10 | null | UTF-8 | C++ | false | false | 2,234 | h | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WebWindowFeatures_h
#define WebWindowFeatures_h
namespace blink {
struct WebWindowFeatures {
float x = 0;
bool x_set = false;
float y = 0;
bool y_set = false;
float width = 0;
bool width_set = false;
float height = 0;
bool height_set = false;
bool menu_bar_visible = true;
bool status_bar_visible = true;
// This can be set based on "locationbar" or "toolbar" in a window features
// string, we don't distinguish between the two.
bool tool_bar_visible = true;
bool scrollbars_visible = true;
bool resizable = true;
bool noopener = false;
bool background = false;
bool persistent = false;
};
} // namespace blink
#endif
| [
"jacob-chen@iotwrt.com"
] | jacob-chen@iotwrt.com |
d7d7831b6fdf6e2007ea5d9e19f46ef7c8eb942e | 9a178d7e313148b5c110a036628c81f416c6c3b1 | /ttud/CBUS..cpp | 982867c23ad4ea5b114730e57ba441f1b3501ce7 | [] | no_license | hieunv183534/ttud | 09d1300e9de54cf48824c64d42c1e4b86da9d128 | 6ca378968795928db2351e998f3abd66281e53c5 | refs/heads/main | 2023-08-02T01:42:23.698392 | 2021-09-08T03:47:00 | 2021-09-08T03:47:00 | 404,202,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | #include<bits/stdc++.h>
using namespace std;
const int N=10001;
int n,k;
int c[N][N];
int main(){
return 0;
}
| [
"Email"
] | Email |
b1e565afe0a0766eff261136550c0273398ab2f2 | 1dbf007249acad6038d2aaa1751cbde7e7842c53 | /gaussdb/include/huaweicloud/gaussdb/v3/model/UpgradeGaussMySqlInstanceDatabaseResponse.h | e5c022c8ee24e7c39646150f881326d1f9141578 | [] | permissive | huaweicloud/huaweicloud-sdk-cpp-v3 | 24fc8d93c922598376bdb7d009e12378dff5dd20 | 71674f4afbb0cd5950f880ec516cfabcde71afe4 | refs/heads/master | 2023-08-04T19:37:47.187698 | 2023-08-03T08:25:43 | 2023-08-03T08:25:43 | 324,328,641 | 11 | 10 | Apache-2.0 | 2021-06-24T07:25:26 | 2020-12-25T09:11:43 | C++ | UTF-8 | C++ | false | false | 1,535 | h |
#ifndef HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_UpgradeGaussMySqlInstanceDatabaseResponse_H_
#define HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_UpgradeGaussMySqlInstanceDatabaseResponse_H_
#include <huaweicloud/gaussdb/v3/GaussDBExport.h>
#include <huaweicloud/core/utils/ModelBase.h>
#include <huaweicloud/core/http/HttpResponse.h>
#include <string>
namespace HuaweiCloud {
namespace Sdk {
namespace Gaussdb {
namespace V3 {
namespace Model {
using namespace HuaweiCloud::Sdk::Core::Utils;
using namespace HuaweiCloud::Sdk::Core::Http;
/// <summary>
/// Response Object
/// </summary>
class HUAWEICLOUD_GAUSSDB_V3_EXPORT UpgradeGaussMySqlInstanceDatabaseResponse
: public ModelBase, public HttpResponse
{
public:
UpgradeGaussMySqlInstanceDatabaseResponse();
virtual ~UpgradeGaussMySqlInstanceDatabaseResponse();
/////////////////////////////////////////////
/// ModelBase overrides
void validate() override;
web::json::value toJson() const override;
bool fromJson(const web::json::value& json) override;
/////////////////////////////////////////////
/// UpgradeGaussMySqlInstanceDatabaseResponse members
/// <summary>
/// 任务ID。
/// </summary>
std::string getJobId() const;
bool jobIdIsSet() const;
void unsetjobId();
void setJobId(const std::string& value);
protected:
std::string jobId_;
bool jobIdIsSet_;
#ifdef RTTR_FLAG
RTTR_ENABLE()
#endif
};
}
}
}
}
}
#endif // HUAWEICLOUD_SDK_GAUSSDB_V3_MODEL_UpgradeGaussMySqlInstanceDatabaseResponse_H_
| [
"hwcloudsdk@huawei.com"
] | hwcloudsdk@huawei.com |
987cd8b2402db8d3b993447e79a15fca5b81d076 | 5470644b5f0834b9646649da365c96101a2f9b2a | /Sources/Elastos/Frameworks/Droid/Base/Core/inc/webkit/SslCertLookupTable.h | a0b82e89ecbe7524c857c5975dc1ba6dd6665f7b | [] | no_license | dothithuy/ElastosRDK5_0 | 42372da3c749170581b5ee9b3884f4a27ae81608 | 2cf231e9f09f8b3b8bcacb11080b4a87d047833f | refs/heads/master | 2021-05-13T15:02:22.363934 | 2015-05-25T01:54:38 | 2015-05-25T01:54:38 | 116,755,452 | 1 | 0 | null | 2018-01-09T02:33:06 | 2018-01-09T02:33:06 | null | UTF-8 | C++ | false | false | 1,193 | h |
#ifndef __SSLCERTLOOKUPTABLE_H__
#define __SSLCERTLOOKUPTABLE_H__
#include "ext/frameworkext.h"
using Elastos::Droid::Os::IBundle;
using Elastos::Droid::Net::Http::ISslError;
namespace Elastos {
namespace Droid {
namespace Webkit {
/**
* Stores the user's decision of whether to allow or deny an invalid certificate.
*
* This class is not threadsafe. It is used only on the WebCore thread. Also, it
* is used only by the Chromium HTTP stack.
*/
class SslCertLookupTable : public ElRefBase
{
public:
static CARAPI_(AutoPtr<SslCertLookupTable>) GetInstance();
CARAPI_(void) SetIsAllowed(
/* [in] */ ISslError* sslError);
// We allow the decision to be re-used if it's for the same host and is for
// an error of equal or greater severity than this error.
CARAPI_(Boolean) IsAllowed(
/* [in] */ ISslError* sslError);
CARAPI_(void) Clear();
private:
SslCertLookupTable();
private:
static AutoPtr<SslCertLookupTable> sTable;
// We store the most severe error we're willing to allow for each host.
AutoPtr<IBundle> mTable;
};
} // namespace Webkit
} // namespace Droid
} // namespace Elastos
#endif //__SSLCERTLOOKUPTABLE_H__
| [
"chen.yunzhi@kortide.com"
] | chen.yunzhi@kortide.com |
38512d4bcbe39932d55ffd8a1c1448e035aa34a6 | cbbd25eec79fb0e945c634f6ed701925df4b5bbd | /test/mat.cpp | 8a10ba36c7d1b4f290614e204d17787f477182dd | [] | no_license | rzs840707/walabot | e9ce3ba0d8820c37bf604e1216597f1aa77db10b | 6af17764f03ef4d8a96f5ef2cba54d3b668e9d6f | refs/heads/master | 2020-04-14T07:59:46.278133 | 2016-08-17T16:25:26 | 2016-08-17T16:25:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,981 | cpp | #include <iostream>
#include <fstream>
#include <stdio.h>
#include <assert.h>
#include <unistd.h>
#include <typeinfo>
#include <math.h>
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/videoio.hpp"
using namespace cv;
using namespace std;
#define PI 3.14159265
#define PAUSE printf("Press Enter key to continue..."); fgetc(stdin);
void easyAdd()
{
Mat a1 = Mat::zeros(5,5, CV_8UC1);
Mat a2 = Mat::eye(5,5, CV_8UC1);
Mat a3 = Mat::zeros(5,5, CV_8UC1);
Mat mask;
a3 = a1+a2*10;
mask = a3 == 0;
cout << a3 <<endl;
cout << mask <<endl;
cout << sum(a3)[0] << endl;
Mat kern = (Mat_<char>(3,3) << 0, -1, 0,
-1, 5, -1,
0, -1, 0);
Mat kern_mask = kern > 0;
Mat output;
kern.copyTo(output,kern_mask);
cout << kern << endl;
cout << kern_mask << endl;
cout << output << endl;
//cout << "type of sum(a3) " << typeid(sum(a3)[0]).name() <<endl;
//cout << mean(a3.col(1)) <<endl;
}
void minMaxid()
{
Mat m = Mat::zeros(5,5,CV_8UC1);
double minVal;
double maxVal;
Point minLoc;
Point maxLoc;
int ctr = 0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
m.at<uchar>(i,j) += ctr;
ctr++;
}
}
minMaxLoc( m, &minVal, &maxVal, &minLoc, &maxLoc );
cout << "m: " << endl << m <<endl;
cout << "min val : " << minVal << endl;
cout << "max val: " << maxVal << endl;
cout << "minLoc: " << minLoc.x << minLoc.y << endl;
cout << "maxLoc: " << maxLoc.x << maxLoc.y << endl;
cout << (int)m.at<uchar>(maxLoc.x,maxLoc.y) << endl;
//double threshold(InputArray src, OutputArray dst, double thresh, double maxval, int type)
}
void simulation()
{
Mat matx = (Mat_<char>(5,5) << 0, 1, 2, 1, 0,
1, 2, 3, 2, 1,
2, 3, 4, 4, 3,
1, 2, 3, 2, 1,
0, 1, 2, 1, 0);
Mat mask = matx >= 2;
Mat output;
matx.copyTo(output,mask);
cout << output << endl;
int sumR=0,sumC=0,ctr=0,centerR=0,centerC=0;
//cout << output.rows<<endl;
//cout << output.cols<<endl;
for (int i=0;i<output.rows;i++)
{
for (int j=0;j<output.cols;j++)
{
if ((int)output.at<char>(i,j) != 0){
cout << (int)output.at<char>(i,j) << " ";
sumR += i;
sumC += j;
ctr += 1;
}
}
cout << endl;
}
centerR = sumR / ctr;
centerC = sumC / ctr;
//cout << centerR <<endl;
//cout << centerC <<endl;
output.at<char>(centerR,centerC) = 100;
cout << output << endl;
}
void log()
{
fstream fp;
fp.open ("walabot.log",ios::out|ios::app);
fp << "Writing this to a file.\n";
fp.close();
}
double fp()
{
int a=1,b=21;
double c = (double)a/21;
return c;
}
int main()
{
//easyAdd();
//minMaxid();
//simulation();
//log();
cout << fp()<<endl;
return 0;
}
| [
"dunkyfool0113@gmail.com"
] | dunkyfool0113@gmail.com |
062a6e08340b2d8dc31075acedc83f2a322a116f | 0b45aa221f069d9cd781dafa14bc2099b20fb03e | /branches/1.10.1/sdk/angelscript/source/as_callfunc_x86.cpp | 7bc25e5b84d7ece445b0e1fe128b105c02b54d26 | [] | no_license | svn2github/angelscript | f2d16c2f32d89a364823904d6ca3048222951f8d | 6af5956795e67f8b41c6a23d20e369fe2c5ee554 | refs/heads/master | 2023-09-03T07:42:01.087488 | 2015-01-12T00:00:30 | 2015-01-12T00:00:30 | 19,475,268 | 0 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 24,937 | cpp | /*
AngelCode Scripting Library
Copyright (c) 2003-2004 Andreas Jönsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jönsson
andreas@angelcode.com
*/
//
// as_callfunc.cpp
//
// These functions handle the actual calling of system functions
//
#include "as_config.h"
#include "as_callfunc.h"
#include "as_scriptengine.h"
#include "as_texts.h"
#include "as_tokendef.h"
int DetectCallingConvention(const char *obj, asUPtr &ptr, int callConv, asSSystemFunctionInterface *internal)
{
memset(internal, 0, sizeof(asSSystemFunctionInterface));
internal->func = (asDWORD)ptr.func;
int base = callConv;
if( obj == 0 )
{
if( base == asCALL_CDECL )
internal->callConv = ICC_CDECL;
else if( base == asCALL_STDCALL )
internal->callConv = ICC_STDCALL;
else
return asNOT_SUPPORTED;
}
else
{
if( base == asCALL_THISCALL )
{
internal->callConv = ICC_THISCALL;
#ifdef GNU_STYLE_VIRTUAL_METHOD
if( (asDWORD(ptr.func) & 1) )
internal->callConv = ICC_VIRTUAL_THISCALL;
#endif
internal->baseOffset = MULTI_BASE_OFFSET(ptr);
#ifdef HAVE_VIRTUAL_BASE_OFFSET
// We don't support virtual inheritance
if( VIRTUAL_BASE_OFFSET(ptr) != 0 )
return asNOT_SUPPORTED;
#endif
}
else if( base == asCALL_CDECL_OBJLAST )
internal->callConv = ICC_CDECL_OBJLAST;
else if( base == asCALL_CDECL_OBJFIRST )
internal->callConv = ICC_CDECL_OBJFIRST;
else
return asNOT_SUPPORTED;
}
return 0;
}
// This function should prepare system functions so that it will be faster to call them
int PrepareSystemFunction(asCScriptFunction *func, asSSystemFunctionInterface *internal, asCScriptEngine *engine)
{
// References and pointers are always returned the same way
if( func->returnType.isReference || func->returnType.pointerLevel > 0 )
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = 1;
internal->hostReturnFloat = false;
}
// Registered types have special flags that determine how they are returned
else if( func->returnType.objectType != 0 )
{
asDWORD objType = func->returnType.objectType->flags;
if( objType == 0 )
{
objType = asOBJ_CLASS;
// We should determine type from registered behaviours
asSTypeBehaviour *beh = engine->GetBehaviour(&func->returnType);
if( beh )
{
if( beh->construct ) objType |= asOBJ_CLASS_CONSTRUCTOR;
if( beh->destruct ) objType |= asOBJ_CLASS_DESTRUCTOR;
if( beh->copy ) objType |= asOBJ_CLASS_ASSIGNMENT;
}
}
if( objType & asOBJ_CLASS )
{
if( objType & COMPLEX_MASK )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
internal->hostReturnFloat = false;
}
else
{
internal->hostReturnFloat = false;
if( func->returnType.GetSizeOnStackDWords() > 2 )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
}
else
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = func->returnType.GetSizeOnStackDWords();
}
#ifdef THISCALL_RETURN_SIMPLE_IN_MEMORY
if( internal->callConv == ICC_THISCALL ||
internal->callConv == ICC_VIRTUAL_THISCALL )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
}
#endif
#ifdef CDECL_RETURN_SIMPLE_IN_MEMORY
if( internal->callConv == ICC_CDECL ||
internal->callConv == ICC_CDECL_OBJLAST ||
internal->callConv == ICC_CDECL_OBJFIRST )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
}
#endif
#ifdef STDCALL_RETURN_SIMPLE_IN_MEMORY
if( internal->callConv == ICC_STDCALL )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
}
#endif
}
}
else if( objType == asOBJ_PRIMITIVE )
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = func->returnType.GetSizeOnStackDWords();
internal->hostReturnFloat = false;
}
else if( objType == asOBJ_FLOAT )
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = func->returnType.GetSizeOnStackDWords();
internal->hostReturnFloat = true;
}
}
// Primitive types can easily be determined
else if( func->returnType.GetSizeOnStackDWords() > 2 )
{
internal->hostReturnInMemory = true;
internal->hostReturnSize = 1;
internal->hostReturnFloat = false;
}
else if( func->returnType.GetSizeOnStackDWords() == 2 )
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = 2;
internal->hostReturnFloat = func->returnType.IsEqualExceptConst(asCDataType(ttDouble, true, false));
}
else if( func->returnType.GetSizeOnStackDWords() == 1 )
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = 1;
internal->hostReturnFloat = func->returnType.IsEqualExceptConst(asCDataType(ttFloat, true, false));
}
else
{
internal->hostReturnInMemory = false;
internal->hostReturnSize = 0;
internal->hostReturnFloat = false;
}
// Calculate the size needed for the parameters
internal->paramSize = func->GetSpaceNeededForArguments();
return 0;
}
typedef asQWORD (*t_CallCDeclQW)(const asDWORD *, int, asDWORD);
typedef asDWORD (*t_CallCDeclRetByRef)(const asDWORD *, int, asDWORD, void *);
typedef asQWORD (*t_CallSTDCallQW)(const asDWORD *, int, asDWORD);
typedef asQWORD (*t_CallThisCallQW)(const void *, const asDWORD *, int, asDWORD);
typedef asDWORD (*t_CallThisCallRetByRef)(const void *, const asDWORD *, int, asDWORD, void *);
// Prototypes
void CallCDeclFunction(const asDWORD *args, int paramSize, asDWORD func);
void CallCDeclFunctionObjFirst(const asDWORD *args, int paramSize, asDWORD func);
void CallCDeclFunctionRetByRef_impl(const asDWORD *args, int paramSize, asDWORD func, void *retPtr);
void CallCDeclFunctionRetByRefObjFirst_impl(const asDWORD *args, int paramSize, asDWORD func, void *retPtr);
void CallSTDCallFunction(const asDWORD *args, int paramSize, asDWORD func);
void CallThisCallFunction(const void *obj, const asDWORD *args, int paramSize, asDWORD func);
void CallThisCallFunctionRetByRef_impl(const void *, const asDWORD *, int, asDWORD, void *retPtr);
// Initialize function pointers
const t_CallCDeclQW CallCDeclFunctionQWord = (t_CallCDeclQW)CallCDeclFunction;
const t_CallCDeclQW CallCDeclFunctionQWordObjFirst = (t_CallCDeclQW)CallCDeclFunctionObjFirst;
const t_CallCDeclRetByRef CallCDeclFunctionRetByRef = (t_CallCDeclRetByRef)CallCDeclFunctionRetByRef_impl;
const t_CallCDeclRetByRef CallCDeclFunctionRetByRefObjFirst = (t_CallCDeclRetByRef)CallCDeclFunctionRetByRefObjFirst_impl;
const t_CallSTDCallQW CallSTDCallFunctionQWord = (t_CallSTDCallQW)CallSTDCallFunction;
const t_CallThisCallQW CallThisCallFunctionQWord = (t_CallThisCallQW)CallThisCallFunction;
const t_CallThisCallRetByRef CallThisCallFunctionRetByRef = (t_CallThisCallRetByRef)CallThisCallFunctionRetByRef_impl;
asDWORD GetReturnedFloat();
asQWORD GetReturnedDouble();
int CallSystemFunction(int id, asCContext *context)
{
id = -id - 1;
asQWORD retTemp = 0;
asDWORD retDW = 0;
asQWORD retQW = 0;
asCScriptEngine *engine = context->engine;
asSSystemFunctionInterface *sysFunc = (engine->systemFunctionInterfaces)[id];
int callConv = sysFunc->callConv;
void *func = (void*)sysFunc->func;
int paramSize = sysFunc->paramSize;
asDWORD *args = context->stackPointer;
void *retPointer = 0;
void *obj = 0;
asDWORD *vftable;
int popSize = paramSize;
if( sysFunc->scriptReturnInMemory )
{
popSize++;
if( !sysFunc->hostReturnInMemory )
{
// Skip the address sent by the script engine
args++;
}
else
{
// The return is made in memory
callConv++;
// Get the return pointer
retPointer = (void*)*args;
// Skip the pointer
args++;
}
}
else
{
if( sysFunc->hostReturnInMemory )
{
// The return is made in memory
callConv++;
retPointer = (void*)&retTemp;
}
}
if( callConv >= ICC_THISCALL )
{
popSize++;
// Check for null pointer
obj = (void*)*(args + paramSize);
if( obj == 0 )
{
context->SetInternalException(TXT_NULL_POINTER_ACCESS);
return 0;
}
// Add the base offset for multiple inheritance
obj = (void*)(int(obj) + sysFunc->baseOffset);
}
context->isCallingSystemFunction = true;
switch( callConv )
{
case ICC_CDECL:
retQW = CallCDeclFunctionQWord(args, paramSize<<2, (asDWORD)func);
break;
case ICC_CDECL_RETURNINMEM:
retQW = CallCDeclFunctionRetByRef(args, paramSize<<2, (asDWORD)func, retPointer);
break;
case ICC_STDCALL:
retQW = CallSTDCallFunctionQWord(args, paramSize<<2, (asDWORD)func);
break;
case ICC_STDCALL_RETURNINMEM:
// Push the return pointer on the stack
paramSize++;
args--;
*args = (asDWORD)retPointer;
retQW = CallSTDCallFunctionQWord(args, paramSize<<2, (asDWORD)func);
break;
case ICC_THISCALL:
retQW = CallThisCallFunctionQWord(obj, args, paramSize<<2, (asDWORD)func);
break;
case ICC_THISCALL_RETURNINMEM:
retQW = CallThisCallFunctionRetByRef(obj, args, paramSize<<2, (asDWORD)func, retPointer);
break;
case ICC_VIRTUAL_THISCALL:
// Get virtual function table from the object pointer
vftable = *(asDWORD**)obj;
retQW = CallThisCallFunctionQWord(obj, args, paramSize<<2, vftable[asDWORD(func)>>2]);
break;
case ICC_VIRTUAL_THISCALL_RETURNINMEM:
// Get virtual function table from the object pointer
vftable = *(asDWORD**)obj;
retQW = CallThisCallFunctionRetByRef(obj, args, paramSize<<2, vftable[asDWORD(func)>>2], retPointer);
break;
case ICC_CDECL_OBJLAST:
// Call the system object method as a cdecl with the obj ref as the last parameter
paramSize++;
retQW = CallCDeclFunctionQWord(args, paramSize<<2, (asDWORD)func);
break;
case ICC_CDECL_OBJLAST_RETURNINMEM:
// Call the system object method as a cdecl with the obj ref as the last parameter
paramSize++;
retQW = CallCDeclFunctionRetByRef(args, paramSize<<2, (asDWORD)func, retPointer);
break;
case ICC_CDECL_OBJFIRST:
// Call the system object method as a cdecl with the obj ref as the first parameter
retQW = CallCDeclFunctionQWordObjFirst(args, paramSize<<2, (asDWORD)func);
break;
case ICC_CDECL_OBJFIRST_RETURNINMEM:
// Call the system object method as a cdecl with the obj ref as the first parameter
retQW = CallCDeclFunctionRetByRefObjFirst(args, paramSize<<2, (asDWORD)func, retPointer);
break;
default:
context->SetInternalException(TXT_INVALID_CALLING_CONVENTION);
}
context->isCallingSystemFunction = false;
if( context->status == tsUnhandledException )
return 0;
// Restore the original location of the arguments
args = context->stackPointer;
// Store the returned value in our stack
if( sysFunc->scriptReturnInMemory )
{
if( !sysFunc->hostReturnInMemory )
{
// Copy the returned value to the pointer sent by the script engine
if( sysFunc->hostReturnSize == 1 )
*(asDWORD*)*args = (asDWORD)retQW;
else
*(asQWORD*)*args = retQW;
}
// Return the address to the location
*(asDWORD*)&context->returnVal = *args;
}
else
{
if( sysFunc->hostReturnInMemory )
{
// Copy the return value
retDW = (asDWORD)retTemp;
}
else
{
if( sysFunc->hostReturnFloat )
{
if( sysFunc->hostReturnSize == 1 )
retDW = GetReturnedFloat();
else
retQW = GetReturnedDouble();
}
else if( sysFunc->hostReturnSize == 1 )
retDW = (asDWORD)retQW;
}
// Store value in returnVal register
if( sysFunc->hostReturnSize == 1 )
*(asDWORD*)&context->returnVal = retDW;
else if( sysFunc->hostReturnSize == 2 )
context->returnVal = retQW;
}
return popSize;
}
void CallCDeclFunction(const asDWORD *args, int paramSize, asDWORD func)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
// Call function
call [func]
// Pop arguments from stack
add esp, paramSize
// Restore registers
pop ecx
// return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push arguments on the stack
"cmp $0, %ecx \n"
"je endcopy \n"
"copyloop: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop \n"
"endcopy: \n"
"call *16(%ebp) \n"
"addl 12(%ebp), %esp \n" // pop arguments
"popl %ecx \n");
#endif
}
void CallCDeclFunctionObjFirst(const asDWORD *args, int paramSize, asDWORD func)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
// push object as first parameter
mov eax, args
add eax, paramSize
push dword ptr [eax]
// Call function
call [func]
// Pop arguments from stack
add esp, paramSize
add esp, 4
// Restore registers
pop ecx
// return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push arguments on the stack
"cmp $0, %ecx \n"
"je endcopy6 \n"
"copyloop6: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop6 \n"
"endcopy6: \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n"
"pushl (%eax) \n" // push object first
"call *16(%ebp) \n"
"addl 12(%ebp), %esp \n" // pop arguments
"addl $4, %esp \n"
"popl %ecx \n");
#endif
}
void CallCDeclFunctionRetByRefObjFirst_impl(const asDWORD *args, int paramSize, asDWORD func, void *retPtr)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
// Push the object pointer
mov eax, args
add eax, paramSize
push dword ptr [eax]
// Push the return pointer
push retPtr;
// Call function
call [func]
// Pop arguments from stack
add esp, paramSize
#ifndef CALLEE_POPS_HIDDEN_RETURN_POINTER
// Pop the return pointer
add esp, 8
#else
add esp, 4
#endif
// Restore registers
pop ecx
// return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push arguments on the stack
"cmp $0, %ecx \n"
"je endcopy5 \n"
"copyloop5: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop5 \n"
"endcopy5: \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n"
"pushl (%eax) \n" // push object first
"pushl 20(%ebp) \n" // retPtr
"call *16(%ebp) \n" // func
"addl 12(%ebp), %esp \n" // pop arguments
#ifndef CALLEE_POPS_HIDDEN_RETURN_POINTER
"addl $8, %esp \n" // Pop the return pointer
#else
"addl $4, %esp \n" // Pop the return pointer
#endif
"popl %ecx \n");
#endif
}
void CallCDeclFunctionRetByRef_impl(const asDWORD *args, int paramSize, asDWORD func, void *retPtr)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
// Push the return pointer
push retPtr;
// Call function
call [func]
// Pop arguments from stack
add esp, paramSize
#ifndef CALLEE_POPS_HIDDEN_RETURN_POINTER
// Pop the return pointer
add esp, 4
#endif
// Restore registers
pop ecx
// return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push arguments on the stack
"cmp $0, %ecx \n"
"je endcopy4 \n"
"copyloop4: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop4 \n"
"endcopy4: \n"
"pushl 20(%ebp) \n" // retPtr
"call *16(%ebp) \n" // func
"addl 12(%ebp), %esp \n" // pop arguments
#ifndef CALLEE_POPS_HIDDEN_RETURN_POINTER
"addl $4, %esp \n" // Pop the return pointer
#endif
"popl %ecx \n");
#endif
}
void CallSTDCallFunction(const asDWORD *args, int paramSize, asDWORD func)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
// Call function
call [func]
// The callee already removed parameters from the stack
// Restore registers
pop ecx
// return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 12(%ebp), %ecx \n" // paramSize
"movl 8(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push arguments on the stack
"cmp $0, %ecx \n"
"je endcopy2 \n"
"copyloop2: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop2 \n"
"endcopy2: \n"
"call *16(%ebp) \n" // callee pops the arguments
"popl %ecx \n");
#endif
}
void CallThisCallFunction(const void *obj, const asDWORD *args, int paramSize, asDWORD func)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
#ifdef THISCALL_PASS_OBJECT_POINTER_ON_THE_STACK
// Push the object pointer on the stack
push obj
#else
// Move object pointer to ECX
mov ecx, obj
#endif
// Call function
call [func]
#ifndef THISCALL_CALLEE_POPS_ARGUMENTS
// Pop arguments
add esp, paramSize
#ifdef THISCALL_PASS_OBJECT_POINTER_ON_THE_STACK
// Pop object pointer
add esp, 4
#endif
#endif
// Restore registers
pop ecx
// Return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 16(%ebp), %ecx \n" // paramSize
"movl 12(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push all arguments on the stack
"cmp $0, %ecx \n"
"je endcopy1 \n"
"copyloop1: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop1 \n"
"endcopy1: \n"
"movl 8(%ebp), %ecx \n" // move obj into ECX
"pushl 8(%ebp) \n" // push obj on the stack
"call *20(%ebp) \n"
"addl 16(%ebp), %esp \n" // pop arguments
"addl $4, %esp \n" // pop obj
"popl %ecx \n");
#endif
}
void CallThisCallFunctionRetByRef_impl(const void *obj, const asDWORD *args, int paramSize, asDWORD func, void *retPtr)
{
#if defined ASM_INTEL
// Copy the data to the real stack. If we fail to do
// this we may run into trouble in case of exceptions.
__asm
{
// We must save registers that are used
push ecx
// Copy arguments from script
// stack to application stack
mov ecx, paramSize
mov eax, args
add eax, ecx
cmp ecx, 0
je endcopy
copyloop:
sub eax, 4
push dword ptr [eax]
sub ecx, 4
jne copyloop
endcopy:
#ifdef THISCALL_PASS_OBJECT_POINTER_ON_THE_STACK
// Push the object pointer on the stack
push obj
#else
// Move object pointer to ECX
mov ecx, obj
#endif
// Push the return pointer
push retPtr
// Call function
call [func]
#ifndef THISCALL_CALLEE_POPS_ARGUMENTS
// Pop arguments
add esp, paramSize
#ifdef THISCALL_PASS_OBJECT_POINTER_ON_THE_STACK
// Pop object pointer
add esp, 4
#endif
#endif
// Restore registers
pop ecx
// Return value in EAX or EAX:EDX
}
#elif defined ASM_AT_N_T
asm("pushl %ecx \n"
"movl 16(%ebp), %ecx \n" // paramSize
"movl 12(%ebp), %eax \n" // args
"addl %ecx, %eax \n" // push all arguments to the stack
"cmp $0, %ecx \n"
"je endcopy3 \n"
"copyloop3: \n"
"subl $4, %eax \n"
"pushl (%eax) \n"
"subl $4, %ecx \n"
"jne copyloop3 \n"
"endcopy3: \n"
"movl 8(%ebp), %ecx \n" // move obj into ECX
"pushl 8(%ebp) \n" // push obj on the stack
"pushl 24(%ebp) \n" // push retPtr on the stack
"call *20(%ebp) \n"
"addl 16(%ebp), %esp \n" // pop arguments
"addl $4, %esp \n" // pop the object pointer
// the return pointer was popped by the callee
"popl %ecx \n");
#endif
}
asDWORD GetReturnedFloat()
{
asDWORD f;
#if defined ASM_INTEL
// Get the float value from ST0
__asm fstp dword ptr [f]
#elif defined ASM_AT_N_T
asm("fstps %0 \n" : "=m" (f));
#endif
return f;
}
asQWORD GetReturnedDouble()
{
asQWORD d;
#if defined ASM_INTEL
// Get the double value from ST0
__asm fstp qword ptr [d]
#elif defined ASM_AT_N_T
asm("fstpl %0 \n" : "=m" (d));
#endif
return d;
}
| [
"angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf"
] | angelcode@404ce1b2-830e-0410-a2e2-b09542c77caf |
405ba3adaba2322b9b19a50fe4cf8904fb37c6c6 | 71163a950257b5d7cb757d5640d0580c356b76cd | /algoTest/combinations.cpp | 843a52194d166a8b625ac696d72c8c1e84b2749f | [] | no_license | WeichenXu/LeetCode | ffc5c975d24231c61064a8b95f88a61f1f44f78e | 4491e225a0c38ff03b053eabff934583f3e1f1e9 | refs/heads/master | 2021-01-18T21:17:36.705741 | 2016-05-30T21:49:51 | 2016-05-30T21:49:51 | 46,749,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 766 | cpp | class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
vector<int> tmp;
findCombine(1, n, k, tmp, res);
return res;
}
void findCombine(int cur, int n, int k, vector<int> &curCombine, vector<vector<int>>& allCombines){
if(k<=0 || k>(n-cur+1)) return;
if(k == 1){
for(int i=cur; i<=n; i++){
curCombine.push_back(i);
allCombines.push_back(curCombine);
curCombine.pop_back();
}
return;
}
for(int i=cur; i< n; i++){
curCombine.push_back(i);
findCombine(i+1, n, k-1, curCombine, allCombines);
curCombine.pop_back();
}
}
}; | [
"weichenxu1993@icloud.com"
] | weichenxu1993@icloud.com |
972ed40b685d2ab5f388582e5560c901cc489545 | 79c09af7c34d24f055ebcb8dbae7e1bcf5de4a6a | /deposit/deposit.cpp | a599a0222b6a5760020ec84be05207bdc6ee4a38 | [] | no_license | tradzero/eos_contract_test | b009b143a060eec183d73b0f096851fc514b9fac | 9a39a956647d709fdadac9bfd1b4198ddad92414 | refs/heads/master | 2020-03-30T00:24:03.704547 | 2019-01-15T06:33:05 | 2019-01-15T06:33:05 | 150,521,302 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,517 | cpp | #include <eosiolib/eosio.hpp>
#include <eosio.token/eosio.token.hpp>
using namespace eosio;
namespace wallet{
class deposit : contract {
// @abi table
struct [[eosio::table]] deposit_record {
uint64_t id;
account_name payer;
int64_t amount;
string memo;
auto primary_key()const { return id; }
EOSLIB_SERIALIZE(deposit_record, (id)(payer)(amount)(memo))
};
public:
deposit(account_name self) : contract(self){}
typedef eosio::multi_index<N(deposit), deposit_record> record_index;
template<typename T>
void saverecord(const T& t, uint64_t receiver) {
if (t.to == _self) {
record_index _records(_self, _self);
_records.emplace(_self, [&](auto& _t) {
_t.id = _records.available_primary_key();
_t.payer = t.from;
_t.amount = t.quantity.amount;
_t.memo = t.memo;
});
}
}
};
}
using namespace wallet;
extern "C" {
/// The apply method implements the dispatch of events to this contract
void apply( uint64_t receiver, uint64_t code, uint64_t action ) {
if( code == N(eosio.token) && action == N(transfer) ) {
wallet::deposit de(receiver);
de.saverecord(unpack_action_data<eosio::token::transfer_args>(), receiver);
}
}
}
| [
"fate_zero@Fate-ZerodeMac-mini.local"
] | fate_zero@Fate-ZerodeMac-mini.local |
cb6cd67b056c60f6b2ff817b9e7f1ac45f4e799c | b04cde06b03c5a81d1320beeaa73815d148cd840 | /2947.cpp | f1c75bf086687c864872f9bbb3e32bc8b6ca9265 | [
"Beerware"
] | permissive | JrSousaJ/Uri-Solved-Problems | 61748bf90d3227b0361721802571b2358e535f55 | ae777b9aa1f3d64b2f75eb91d57aff8c62b3296b | refs/heads/master | 2020-03-09T21:13:38.026506 | 2019-09-16T13:02:18 | 2019-09-16T13:02:18 | 129,003,832 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 662 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;scanf("%d",&n);
char s[n+1];
scanf(" %s",s);
int k;scanf("%d",&k);
vector<string>v;
for (int i = 0; i < k; i++)
{
char s1[n+1];
scanf(" %s",s1);
v.push_back(s1);
}
int vv[27];
memset(vv,0,sizeof vv);
int ans=0;
for(int i=0;i<n;i++)
{
int ma=0;
memset(vv,0,sizeof vv);
for(int j=0;j<k;j++)
{
int a = s[i]-'A';
int b = v[j][i] -'A';
//printf("%d %d\n",a,b);
if(a!=b){
vv[b]++;
//printf("%c %c %d\n",s[i], v[j][i],vv[b]);
ma = max(vv[b],ma);
}
// printf("deu ruim\n");
}
//printf("fon\n");
ans+=ma;
}
printf("%d\n",ans);
return 0;
} | [
"jairosousajunior@gmail.com"
] | jairosousajunior@gmail.com |
8906e508017ec9e6b1a9bee89c7b840f373d55bf | 9ca5f29f559ae5b718f8b271c727c6b492983b0c | /src/test/test_bitcoin.cpp | 35259fcff70b0a3af83e6269bbf4cf52b61e70b6 | [
"MIT"
] | permissive | ibnux/NuxCoin | 52dd9382063ae5007fbea0e99dc94fb5a2136f46 | 786454d12baf324916ded07eb7d107faeed4920b | refs/heads/master | 2022-12-18T16:34:52.704463 | 2020-09-17T12:33:35 | 2020-09-17T12:33:35 | 291,203,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,215 | cpp | // Copyright (c) 2011-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/test_bitcoin.h>
#include <banman.h>
#include <chainparams.h>
#include <consensus/consensus.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <crypto/sha256.h>
#include <miner.h>
#include <net_processing.h>
#include <noui.h>
#include <pow.h>
#include <rpc/register.h>
#include <rpc/server.h>
#include <script/sigcache.h>
#include <streams.h>
#include <ui_interface.h>
#include <validation.h>
const std::function<std::string(const char*)> G_TRANSLATION_FUN = nullptr;
FastRandomContext g_insecure_rand_ctx;
std::ostream& operator<<(std::ostream& os, const uint256& num)
{
os << num.ToString();
return os;
}
BasicTestingSetup::BasicTestingSetup(const std::string& chainName)
: m_path_root(fs::temp_directory_path() / "test_nuxcoin" / strprintf("%lu_%i", (unsigned long)GetTime(), (int)(InsecureRandRange(1 << 30))))
{
SHA256AutoDetect();
ECC_Start();
SetupEnvironment();
SetupNetworking();
InitSignatureCache();
InitScriptExecutionCache();
fCheckBlockIndex = true;
// CreateAndProcessBlock() does not support building SegWit blocks, so don't activate in these tests.
// TODO: fix the code to support SegWit blocks.
gArgs.ForceSetArg("-vbparams", strprintf("segwit:0:%d", (int64_t)Consensus::BIP9Deployment::NO_TIMEOUT));
SelectParams(chainName);
noui_connect();
}
BasicTestingSetup::~BasicTestingSetup()
{
fs::remove_all(m_path_root);
ECC_Stop();
}
fs::path BasicTestingSetup::SetDataDir(const std::string& name)
{
fs::path ret = m_path_root / name;
fs::create_directories(ret);
gArgs.ForceSetArg("-datadir", ret.string());
return ret;
}
TestingSetup::TestingSetup(const std::string& chainName) : BasicTestingSetup(chainName)
{
SetDataDir("tempdir");
const CChainParams& chainparams = Params();
// Ideally we'd move all the RPC tests to the functional testing framework
// instead of unit tests, but for now we need these here.
RegisterAllCoreRPCCommands(tableRPC);
ClearDatadirCache();
// We have to run a scheduler thread to prevent ActivateBestChain
// from blocking due to queue overrun.
threadGroup.create_thread(std::bind(&CScheduler::serviceQueue, &scheduler));
GetMainSignals().RegisterBackgroundSignalScheduler(scheduler);
mempool.setSanityCheck(1.0);
pblocktree.reset(new CBlockTreeDB(1 << 20, true));
pcoinsdbview.reset(new CCoinsViewDB(1 << 23, true));
pcoinsTip.reset(new CCoinsViewCache(pcoinsdbview.get()));
if (!LoadGenesisBlock(chainparams)) {
throw std::runtime_error("LoadGenesisBlock failed.");
}
{
CValidationState state;
if (!ActivateBestChain(state, chainparams)) {
throw std::runtime_error(strprintf("ActivateBestChain failed. (%s)", FormatStateMessage(state)));
}
}
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
g_banman = MakeUnique<BanMan>(GetDataDir() / "banlist.dat", nullptr, DEFAULT_MISBEHAVING_BANTIME);
g_connman = MakeUnique<CConnman>(0x1337, 0x1337); // Deterministic randomness for tests.
}
TestingSetup::~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
GetMainSignals().FlushBackgroundCallbacks();
GetMainSignals().UnregisterBackgroundSignalScheduler();
g_connman.reset();
g_banman.reset();
UnloadBlockIndex();
pcoinsTip.reset();
pcoinsdbview.reset();
pblocktree.reset();
}
TestChain100Setup::TestChain100Setup() : TestingSetup(CBaseChainParams::REGTEST)
{
// Generate a 100-block chain:
coinbaseKey.MakeNewKey(true);
CScript scriptPubKey = CScript() << ToByteVector(coinbaseKey.GetPubKey()) << OP_CHECKSIG;
for (int i = 0; i < COINBASE_MATURITY; i++)
{
std::vector<CMutableTransaction> noTxns;
CBlock b = CreateAndProcessBlock(noTxns, scriptPubKey);
m_coinbase_txns.push_back(b.vtx[0]);
}
}
//
// Create a new block with just given transactions, coinbase paying to
// scriptPubKey, and try to add it to the current chain.
//
CBlock
TestChain100Setup::CreateAndProcessBlock(const std::vector<CMutableTransaction>& txns, const CScript& scriptPubKey)
{
const CChainParams& chainparams = Params();
std::unique_ptr<CBlockTemplate> pblocktemplate = BlockAssembler(chainparams).CreateNewBlock(scriptPubKey);
CBlock& block = pblocktemplate->block;
// Replace mempool-selected txns with just coinbase plus passed-in txns:
block.vtx.resize(1);
for (const CMutableTransaction& tx : txns)
block.vtx.push_back(MakeTransactionRef(tx));
// IncrementExtraNonce creates a valid coinbase and merkleRoot
{
LOCK(cs_main);
unsigned int extraNonce = 0;
IncrementExtraNonce(&block, chainActive.Tip(), extraNonce);
}
while (!CheckProofOfWork(block.GetPoWHash(), block.nBits, chainparams.GetConsensus())) ++block.nNonce;
std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(block);
ProcessNewBlock(chainparams, shared_pblock, true, nullptr);
CBlock result = block;
return result;
}
TestChain100Setup::~TestChain100Setup()
{
}
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CMutableTransaction &tx) {
return FromTx(MakeTransactionRef(tx));
}
CTxMemPoolEntry TestMemPoolEntryHelper::FromTx(const CTransactionRef& tx)
{
return CTxMemPoolEntry(tx, nFee, nTime, nHeight,
spendsCoinbase, sigOpCost, lp);
}
/**
* @returns a real block (0000000000013b8ab2cd513b0261a14096412195a72a0c4827d229dcc7e0f7af)
* with 9 txs.
*/
CBlock getBlock13b8a()
{
CBlock block;
CDataStream stream(ParseHex("0100000090f0a9f110702f808219ebea1173056042a714bad51b916cb6800000000000005275289558f51c9966699404ae2294730c3c9f9bda53523ce50e9b95e558da2fdb261b4d4c86041b1ab1bf930901000000010000000000000000000000000000000000000000000000000000000000000000ffffffff07044c86041b0146ffffffff0100f2052a01000000434104e18f7afbe4721580e81e8414fc8c24d7cfacf254bb5c7b949450c3e997c2dc1242487a8169507b631eb3771f2b425483fb13102c4eb5d858eef260fe70fbfae0ac00000000010000000196608ccbafa16abada902780da4dc35dafd7af05fa0da08cf833575f8cf9e836000000004a493046022100dab24889213caf43ae6adc41cf1c9396c08240c199f5225acf45416330fd7dbd022100fe37900e0644bf574493a07fc5edba06dbc07c311b947520c2d514bc5725dcb401ffffffff0100f2052a010000001976a914f15d1921f52e4007b146dfa60f369ed2fc393ce288ac000000000100000001fb766c1288458c2bafcfec81e48b24d98ec706de6b8af7c4e3c29419bfacb56d000000008c493046022100f268ba165ce0ad2e6d93f089cfcd3785de5c963bb5ea6b8c1b23f1ce3e517b9f022100da7c0f21adc6c401887f2bfd1922f11d76159cbc597fbd756a23dcbb00f4d7290141042b4e8625a96127826915a5b109852636ad0da753c9e1d5606a50480cd0c40f1f8b8d898235e571fe9357d9ec842bc4bba1827daaf4de06d71844d0057707966affffffff0280969800000000001976a9146963907531db72d0ed1a0cfb471ccb63923446f388ac80d6e34c000000001976a914f0688ba1c0d1ce182c7af6741e02658c7d4dfcd388ac000000000100000002c40297f730dd7b5a99567eb8d27b78758f607507c52292d02d4031895b52f2ff010000008b483045022100f7edfd4b0aac404e5bab4fd3889e0c6c41aa8d0e6fa122316f68eddd0a65013902205b09cc8b2d56e1cd1f7f2fafd60a129ed94504c4ac7bdc67b56fe67512658b3e014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffffca5065ff9617cbcba45eb23726df6498a9b9cafed4f54cbab9d227b0035ddefb000000008a473044022068010362a13c7f9919fa832b2dee4e788f61f6f5d344a7c2a0da6ae740605658022006d1af525b9a14a35c003b78b72bd59738cd676f845d1ff3fc25049e01003614014104732012cb962afa90d31b25d8fb0e32c94e513ab7a17805c14ca4c3423e18b4fb5d0e676841733cb83abaf975845c9f6f2a8097b7d04f4908b18368d6fc2d68ecffffffff01001ec4110200000043410469ab4181eceb28985b9b4e895c13fa5e68d85761b7eee311db5addef76fa8621865134a221bd01f28ec9999ee3e021e60766e9d1f3458c115fb28650605f11c9ac000000000100000001cdaf2f758e91c514655e2dc50633d1e4c84989f8aa90a0dbc883f0d23ed5c2fa010000008b48304502207ab51be6f12a1962ba0aaaf24a20e0b69b27a94fac5adf45aa7d2d18ffd9236102210086ae728b370e5329eead9accd880d0cb070aea0c96255fae6c4f1ddcce1fd56e014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff02404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac002d3101000000001976a9141befba0cdc1ad56529371864d9f6cb042faa06b588ac000000000100000001b4a47603e71b61bc3326efd90111bf02d2f549b067f4c4a8fa183b57a0f800cb010000008a4730440220177c37f9a505c3f1a1f0ce2da777c339bd8339ffa02c7cb41f0a5804f473c9230220585b25a2ee80eb59292e52b987dad92acb0c64eced92ed9ee105ad153cdb12d001410443bd44f683467e549dae7d20d1d79cbdb6df985c6e9c029c8d0c6cb46cc1a4d3cf7923c5021b27f7a0b562ada113bc85d5fda5a1b41e87fe6e8802817cf69996ffffffff0280651406000000001976a9145505614859643ab7b547cd7f1f5e7e2a12322d3788ac00aa0271000000001976a914ea4720a7a52fc166c55ff2298e07baf70ae67e1b88ac00000000010000000586c62cd602d219bb60edb14a3e204de0705176f9022fe49a538054fb14abb49e010000008c493046022100f2bc2aba2534becbdf062eb993853a42bbbc282083d0daf9b4b585bd401aa8c9022100b1d7fd7ee0b95600db8535bbf331b19eed8d961f7a8e54159c53675d5f69df8c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff03ad0e58ccdac3df9dc28a218bcf6f1997b0a93306faaa4b3a28ae83447b2179010000008b483045022100be12b2937179da88599e27bb31c3525097a07cdb52422d165b3ca2f2020ffcf702200971b51f853a53d644ebae9ec8f3512e442b1bcb6c315a5b491d119d10624c83014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff2acfcab629bbc8685792603762c921580030ba144af553d271716a95089e107b010000008b483045022100fa579a840ac258871365dd48cd7552f96c8eea69bd00d84f05b283a0dab311e102207e3c0ee9234814cfbb1b659b83671618f45abc1326b9edcc77d552a4f2a805c0014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffdcdc6023bbc9944a658ddc588e61eacb737ddf0a3cd24f113b5a8634c517fcd2000000008b4830450221008d6df731df5d32267954bd7d2dda2302b74c6c2a6aa5c0ca64ecbabc1af03c75022010e55c571d65da7701ae2da1956c442df81bbf076cdbac25133f99d98a9ed34c014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffffe15557cd5ce258f479dfd6dc6514edf6d7ed5b21fcfa4a038fd69f06b83ac76e010000008b483045022023b3e0ab071eb11de2eb1cc3a67261b866f86bf6867d4558165f7c8c8aca2d86022100dc6e1f53a91de3efe8f63512850811f26284b62f850c70ca73ed5de8771fb451014104462e76fd4067b3a0aa42070082dcb0bf2f388b6495cf33d789904f07d0f55c40fbd4b82963c69b3dc31895d0c772c812b1d5fbcade15312ef1c0e8ebbb12dcd4ffffffff01404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000010000000166d7577163c932b4f9690ca6a80b6e4eb001f0a2fa9023df5595602aae96ed8d000000008a4730440220262b42546302dfb654a229cefc86432b89628ff259dc87edd1154535b16a67e102207b4634c020a97c3e7bbd0d4d19da6aa2269ad9dded4026e896b213d73ca4b63f014104979b82d02226b3a4597523845754d44f13639e3bf2df5e82c6aab2bdc79687368b01b1ab8b19875ae3c90d661a3d0a33161dab29934edeb36aa01976be3baf8affffffff02404b4c00000000001976a9144854e695a02af0aeacb823ccbc272134561e0a1688ac40420f00000000001976a914abee93376d6b37b5c2940655a6fcaf1c8e74237988ac0000000001000000014e3f8ef2e91349a9059cb4f01e54ab2597c1387161d3da89919f7ea6acdbb371010000008c49304602210081f3183471a5ca22307c0800226f3ef9c353069e0773ac76bb580654d56aa523022100d4c56465bdc069060846f4fbf2f6b20520b2a80b08b168b31e66ddb9c694e240014104976c79848e18251612f8940875b2b08d06e6dc73b9840e8860c066b7e87432c477e9a59a453e71e6d76d5fe34058b800a098fc1740ce3012e8fc8a00c96af966ffffffff02c0e1e400000000001976a9144134e75a6fcb6042034aab5e18570cf1f844f54788ac404b4c00000000001976a9142b6ba7c9d796b75eef7942fc9288edd37c32f5c388ac00000000"), SER_NETWORK, PROTOCOL_VERSION);
stream >> block;
return block;
}
| [
"ibnumaksum@gmail.com"
] | ibnumaksum@gmail.com |
09dd6f46ee608ce20c0abf5c02a3c1d1597a4f12 | 337c41b9bcb0e80426a54810086043c615fe61bb | /source/RenderObjects.cpp | ac0a9b15784a20066399d1df0f4e205f260b352d | [] | no_license | shubbart/Graphics | 83b4cd6e6172cdf9d73f256f17682d4fc0e9f8fc | 347c5f3482bead335e305a34e7b466e53019c450 | refs/heads/master | 2021-01-18T20:11:52.491678 | 2017-09-22T16:46:32 | 2017-09-22T16:46:32 | 100,545,885 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,645 | cpp | #define GLM_FORCE_SWIZZLE
#include "glinc.h"
#include "graphics\RenderObjects.h"
#include "graphics\Vertex.h"
#ifdef _DEBUG
#include <iostream>
#endif
glm::vec4 calcTangent(const Vertex &v0, const Vertex &v1, const Vertex &v2)
{
// Calculate the left and right edge of the triangle
glm::vec4 p1 = v1.position - v0.position;
glm::vec4 p2 = v2.position - v0.position;
// Calculate the left and right edge of the triangle's UVs
glm::vec2 t1 = v1.texCoord - v0.texCoord;
glm::vec2 t2 = v2.texCoord - v0.texCoord;
// Rotate the position edge to line up with the texture edge and normalize
return glm::normalize((p1*t2.y - p2*t1.y) / (t1.x*t2.y - t1.y*t2.x));
}
Geometry makeGeometry(const Vertex *verts, size_t vsize,
const unsigned *idxs, size_t isize)
{
Geometry retval = { 0,0,0,isize };
// Declare openGL objects and acquire handles
glGenBuffers(1, &retval.vbo);
glGenBuffers(1, &retval.ibo);
glGenVertexArrays(1, &retval.handle);
// Scope the variables
glBindVertexArray(retval.handle);
glBindBuffer(GL_ARRAY_BUFFER, retval.vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, retval.ibo);
// Initialize the buffers
glBufferData(GL_ARRAY_BUFFER, vsize * sizeof(Vertex), verts, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, isize * sizeof(unsigned), idxs, GL_STATIC_DRAW);
// Describe memory layout
glEnableVertexAttribArray(0); // Position attribute
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glEnableVertexAttribArray(1); // Color attribute
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)16);
glEnableVertexAttribArray(2); // texCoord
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)32);
glEnableVertexAttribArray(3); // Normals
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)40);
glEnableVertexAttribArray(4); // Tangent
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)56);
glEnableVertexAttribArray(5); // Bitangent
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)72);
// Unbind data
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return retval;
}
void freeGeometry(Geometry &g)
{
glDeleteBuffers(1, &g.vbo);
glDeleteBuffers(1, &g.ibo);
glDeleteBuffers(1, &g.handle);
g = { 0, 0, 0, 0 };
}
Shader makeShader(const char *vert_source, const char *frag_source)
{
Shader retval = { 0 };
retval.handle = glCreateProgram();
unsigned vs = glCreateShader(GL_VERTEX_SHADER);
unsigned fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(vs, 1, &vert_source, 0);
glShaderSource(fs, 1, &frag_source, 0);
glCompileShader(vs);
#ifdef _DEBUG
GLint success = GL_FALSE;
glGetShaderiv(vs, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
int length = 0;
glGetShaderiv(vs, GL_INFO_LOG_LENGTH, &length);
char *log = new char[length];
glGetShaderInfoLog(vs, length, 0, log);
std::cerr << log << std::endl;
delete[] log;
}
#endif _DEBUG
glCompileShader(fs);
#ifdef _DEBUG
success = GL_FALSE;
glGetShaderiv(fs, GL_COMPILE_STATUS, &success);
if (success == GL_FALSE)
{
int length = 0;
glGetShaderiv(fs, GL_INFO_LOG_LENGTH, &length);
char *log = new char[length];
glGetShaderInfoLog(fs, length, 0, log);
std::cerr << log << std::endl;
delete[] log;
}
#endif _DEBUG
glAttachShader(retval.handle, vs);
glAttachShader(retval.handle, fs);
glLinkProgram(retval.handle);
#ifdef _DEBUG
success = GL_FALSE;
glGetProgramiv(retval.handle, GL_LINK_STATUS, &success);
if (success == GL_FALSE)
{
int length = 0;
glGetProgramiv(retval.handle, GL_INFO_LOG_LENGTH, &length);
char *log = new char[length];
glGetProgramInfoLog(retval.handle, length, 0, log);
std::cerr << log << std::endl;
delete[] log;
}
#endif _DEBUG
glDeleteShader(vs);
glDeleteShader(fs);
return retval;
}
Shader loadUpdateShader(const char *vert_path);
Shader makeUpdateShader(const char *vert_src);
void freeShader(Shader &s)
{
glDeleteProgram(s.handle);
s = { 0 };
}
Texture makeTexture(unsigned w, unsigned h, unsigned c, const void *pixels, bool isFloat)
{
Texture retval = { 0 };
GLenum f = 0, i = 0; // External and internal format for color storage
switch (c)
{
case 0: f = GL_DEPTH_COMPONENT; i = GL_DEPTH24_STENCIL8; break;
case 1: f = GL_RED; i = GL_R32F; break;
case 2: f = GL_RG; i = GL_RG32F; break;
case 3: f = GL_RGB; i = GL_RGB32F; break;
case 4: f = GL_RGBA; i = GL_RGBA32F; break;
}
glGenTextures(1, &retval.handle);
glBindTexture(GL_TEXTURE_2D, retval.handle);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f, (isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels);
glBindTexture(GL_TEXTURE_2D, 0);
return retval;
}
void freeTexture(Texture &t)
{
glDeleteTextures(1, &t.handle);
t = { 0 };
}
// Requires #define GLM_FORCE_SWIZZLE
void solveTangents(Vertex *v, size_t vsize, const unsigned *idxs, size_t isize)
{
for (int i = 0; i < isize; i += 3)
{
glm::vec4 T = calcTangent(v[idxs[i]], v[idxs[i + 1]], v[idxs[i] + 2]);
for (int j = 0; j < 3; ++j)
{
v[idxs[i + j]].tangent = glm::normalize(T + v[idxs[i + j]].tangent);
}
}
for (int i = 0; i < vsize; ++i)
v[i].bitangent = glm::vec4(glm::cross(v[i].normal.xyz(), v[i].tangent.xyz()), 0);
}
CubeTexture makeCubeMap(unsigned w, unsigned h, unsigned c,
const void **pixels, bool isFloat)
{
CubeTexture retval = { 0 };
GLenum f = 0, i = 0; // External and internal format for color storage
switch (c)
{
case 0: f = GL_DEPTH_COMPONENT; i = GL_DEPTH24_STENCIL8; break;
case 1: f = GL_RED; i = GL_R32F; break;
case 2: f = GL_RG; i = GL_RG32F; break;
case 3: f = GL_RGB; i = GL_RGB32F; break;
case 4: f = GL_RGBA; i = GL_RGBA32F; break;
}
glGenTextures(1, &retval.handle);
glBindTexture(GL_TEXTURE_CUBE_MAP, retval.handle);
// Back, Front
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[0]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[1]);
// Top, Bottom
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[2]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[3]);
// Right, Left
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[4]);
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, ((isFloat || c == 0) ? i : f), w, h, 0, f,
(isFloat ? GL_FLOAT : GL_UNSIGNED_BYTE), pixels[5]);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
return retval;
}
void freeCubeTexture(CubeTexture &t)
{
glDeleteTextures(1, &t.handle);
t = { 0 };
}
Framebuffer makeFramebuffer(unsigned w, unsigned h, unsigned c, bool hasDepth,
unsigned nTargets, unsigned nFloatTargets)
{
Framebuffer retval = { 0,w,h, nTargets + nFloatTargets ,0,{ 0 } };
// Code goes here!
glGenFramebuffers(1, &retval.handle);
glBindFramebuffer(GL_FRAMEBUFFER, retval.handle);
if (hasDepth) {
retval.depthTarget = makeTexture(w, h, 0, 0, 0);
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
retval.depthTarget.handle, 0);
}
const GLenum attachments[8] = {
GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2,
GL_COLOR_ATTACHMENT3, GL_COLOR_ATTACHMENT4, GL_COLOR_ATTACHMENT5,
GL_COLOR_ATTACHMENT6, GL_COLOR_ATTACHMENT7 };
for (int i = 0; i < retval.nTargets && i < 8; ++i)
{
retval.targets[i] = makeTexture(w, h, c, 0, i >= nTargets);
glFramebufferTexture(GL_FRAMEBUFFER, attachments[i],
retval.targets[i].handle, 0);
}
glDrawBuffers(retval.nTargets, attachments);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return retval;
}
void freeFramebuffer(Framebuffer &fb);
ParticleBuffer makeParticleBuffer(const ParticleBuffer *parts, size_t psize); | [
"shawn.hubbart@gmail.com"
] | shawn.hubbart@gmail.com |
ccbcfe6010cb4f3bf2e1f63294c01ee9cc050a62 | aa10e3edb2d9db88b0fa48beee2c8a4c93d6958f | /5e/C++11/384.cpp | 63df3bee0041106192688bdde14910f810854603 | [
"MIT"
] | permissive | mallius/CppPrimer | e1a04d6e1a00d180ecca60a0207466a46a5651b7 | 0285fabe5934492dfed0a9cf67ba5650982a5f76 | refs/heads/master | 2021-06-05T10:32:55.651469 | 2021-05-20T03:36:22 | 2021-05-20T03:36:22 | 88,345,336 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | #include <iostream>
#include <map>
#include <string>
using namespace std;
int main(void)
{
auto f = [] { return 42; };
cout << f() << endl;
[](const string& a, const string& b)
{ return a.size() < b.size(); };
return 0;
}
| [
"mallius@qq.com"
] | mallius@qq.com |
972139826e7f90eacb49c6eb4ddff16a1b1ad184 | 78e66bac02019d418a37d5a58cfe9b754e2994f9 | /Dev/ida5sdk/module/z80/ins.hpp | f8f58fc1a12ded787fff8d29da43b6f2a48244df | [] | no_license | raimundojimenez/usefulres | 1db49c36bc08d409eec7253367d054e3b85489be | 1121a7b280cc95002b5d901b7e151741fffcafd3 | refs/heads/master | 2021-05-29T12:44:47.694847 | 2015-05-27T04:14:15 | 2015-05-27T04:14:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,813 | hpp | /*
* Interactive disassembler (IDA).
* Version 2.09
* Copyright (c) 1990-93 by Ilfak Guilfanov. (2:5020/209@fidonet)
* ALL RIGHTS RESERVED.
*
*/
#ifndef __INSTRS_HPP
#define __INSTRS_HPP
extern instruc_t Instructions[];
enum nameNum {
I5_null = 0, // Unknown Operation
//
// Intel 8080-8085 instructions
//
I5_aci,
I5_adc, Z80_adc = I5_adc,
I5_add, Z80_add = I5_add,
I5_adi,
I5_ana,
I5_ani,
I5_call,
I5_cnz,
I5_cz,
I5_cnc,
I5_cc,
I5_cpo,
I5_cpe,
I5_cp,
I5_cm,
I5_cmc,
I5_cmp,
I5_cpi,
I5_cma,
I5_daa,
I5_dad,
I5_dcr,
I5_dcx,
I5_di, Z80_di = I5_di,
I5_ei, Z80_ei = I5_ei,
I5_halt,
I5_in, Z80_in = I5_in,
I5_inr,
I5_inx,
I5_jmp,
I5_jnz,
I5_jz,
I5_jnc,
I5_jc,
I5_jpo,
I5_jpe,
I5_jp,
I5_jm,
I5_lda,
I5_ldax,
I5_lhld,
I5_lxi,
I5_mov,
I5_mvi,
I5_nop,
I5_ora,
I5_ori,
I5_out, Z80_out = I5_out,
I5_pchl,
I5_pop, Z80_pop = I5_pop,
I5_push, Z80_push = I5_push,
I5_ret,
I5_rnz,
I5_rz,
I5_rnc,
I5_rc,
I5_rpo,
I5_rpe,
I5_rp,
I5_rm,
I5_ral,
I5_rlc,
I5_rar,
I5_rrc,
I5_rst,
I5_sbb,
I5_sbi,
I5_stc,
I5_sphl,
I5_sta,
I5_stax,
I5_shld,
I5_sui,
I5_sub, Z80_sub = I5_sub,
I5_xra,
I5_xri,
I5_xchg,
I5_xthl,
I5_rim,
I5_sim,
//
// Z80 extensions
//
Z80_and,
Z80_bit,
Z80_call,
Z80_ccf,
Z80_cp,
Z80_cpd,
Z80_cpdr,
Z80_cpi,
Z80_cpir,
Z80_cpl,
Z80_dec,
Z80_djnz,
Z80_ex,
Z80_exx,
Z80_halt,
Z80_im,
Z80_inc,
Z80_ind,
Z80_indr,
Z80_ini,
Z80_inir,
Z80_jp,
Z80_jr,
Z80_ld,
Z80_ldd,
Z80_lddr,
Z80_ldi,
Z80_ldir,
Z80_neg,
Z80_or,
Z80_otdr,
Z80_otir,
Z80_outd,
Z80_outi,
Z80_res,
Z80_ret,
Z80_reti,
Z80_retn,
Z80_rl,
Z80_rla,
Z80_rlc,
Z80_rlca,
Z80_rld,
Z80_rr,
Z80_rra,
Z80_rrc,
Z80_rrca,
Z80_rrd,
Z80_scf,
Z80_sbc,
Z80_set,
Z80_sla,
Z80_sra,
Z80_srl,
Z80_xor,
Z80_inp, // undocumented
Z80_outp, // undocumented
Z80_srr, // undocumented
//
// HD64180 extensions
//
HD_in0, Z80_in0 = HD_in0,
HD_mlt, Z80_mlt = HD_mlt,
HD_otim, Z80_otim = HD_otim,
HD_otimr, Z80_otimr = HD_otimr,
HD_otdm, Z80_otdm = HD_otdm,
HD_otdmr, Z80_otdmr = HD_otdmr,
HD_out0, Z80_out0 = HD_out0,
HD_slp, Z80_slp = HD_slp,
HD_tst, Z80_tst = HD_tst,
HD_tstio, Z80_tstio = HD_tstio,
//
// A80 special instructions
//
A80_lbcd,
A80_lded,
A80_lspd,
A80_lixd,
A80_liyd,
A80_sbcd,
A80_sded,
A80_sspd,
A80_sixd,
A80_siyd,
A80_xtix,
A80_xtiy,
A80_spix,
A80_spiy,
A80_pcix,
A80_pciy,
A80_mvra,
A80_mvia,
A80_mvar,
A80_mvai,
A80_addix,
A80_addiy,
A80_addc,
A80_addcix,
A80_addciy,
A80_subc,
A80_subcix,
A80_subciy,
A80_jrc,
A80_jrnc,
A80_jrz,
A80_jrnz,
A80_cmpi,
A80_cmpd,
A80_im0,
A80_im1,
A80_im2,
A80_otd,
A80_oti,
// Intel 8085 undocumented instructions
// (info from http://oak.oakland.edu/pub/cpm/maclib/i8085.lib)
I5_dsub, // (HL) <- (HL)-(BC), affects all flags
I5_arhl, // SHIFT HL RIGHT ONE BIT, (H7 IS DUPLICATED, L0 IS SHIFTED INTO CY)
I5_rdel, // ROTATE DE LEFT ONE BIT THRU CY, (E0 RECEIVES CY, CY RECEIVES D7)
I5_ldhi, // (DE) <- (HL)+arg
I5_ldsi, // (DE) <- (SP)+arg
I5_shlx, // ((DE)) <- (HL)
I5_lhlx, // (HL) <- ((DE))
I5_rstv, // RESTART 40H ON V (OVERFLOW)
I5_jx5, // JUMP IF X5 SET
I5_jnx5, // JUMP IF NOT X5 SET
// Z380 instructions
Z80_cplw, // Complement HL register
Z80_swap, // Swap upper register word with lower register word
Z80_inw, // Input word
Z80_outw, // Output word
Z80_ldw, // Load word
Z80_addw, // Add word
Z80_subw, // Subtract word
Z80_adcw, // Add with carry word
Z80_sbcw, // Subtract with borrow word
Z80_andw, // AND logical word
Z80_xorw, // XOR logical word
Z80_orw, // OR logical word
Z80_cpw, // Compare word
Z80_ddir, // Decoder directive
Z80_calr, // Call relative
Z80_ldctl, // Load control register
Z80_mtest, // Mode test
Z80_exxx, // Exchange Index Register with Alternate Bank
Z80_exxy, // Exchange Index Register with Alternate Bank
Z80_exall, // Exchange all registers with Alternate Bank
Z80_setc, // Set control bit
Z80_resc, // Reset control bit
Z80_rlcw, // Rotate Left Circular Word
Z80_rrcw, // Rotate Right Circular Word
Z80_rlw, // Rotate Left Word
Z80_rrw, // Rotate Right Word
Z80_slaw, // Shift Left Arithmetic Word
Z80_sraw, // Shift Right Arithmetic Word
Z80_srlw, // Shift Right Logical Word
Z80_multw, // Multiply Word
Z80_multuw, // Multiply Word Unsigned
Z80_divuw, // Divide unsigned
Z80_outaw, // Output word direct to port address
Z80_inaw, // Input word direct from port address
Z80_outa, // Output byte direct to port address
Z80_ina, // Input byte direct from port address
Z80_negw, // Negate word
Z80_exts, // Extend byte sign
Z80_extsw, // Extend word sign
Z80_btest, // Bank test
Z80_ldiw, // Load and increment (word)
Z80_ldirw, // Load and increment, repeat (word)
Z80_lddw, // Load and decrement (word)
Z80_lddrw, // Load and decrement, repeat (word)
Z80_iniw, // Input and increment (word)
Z80_inirw, // Input and increment, repeat (word)
Z80_indw, // Input and decrement (word)
Z80_indrw, // Input and decrement, repeat (word)
Z80_outiw, // Output and increment (word)
Z80_otirw, // Output and increment, repeat (word)
Z80_outdw, // Output and decrement (word)
Z80_otdrw, // Output and decrement, repeat (word)
// Gameboy instructions
GB_ldh,
GB_stop,
I5_last,
};
#endif
| [
"WellKnownSoft@3eee2735-b65a-edde-9f56-9c96bd66f7d7"
] | WellKnownSoft@3eee2735-b65a-edde-9f56-9c96bd66f7d7 |
1e6ef9574c1a3bd2a7fb204f26dcf9d5a8d0c22b | aaa634d2b8ea71b160a98f4279f787ed201b369d | /0.1now/parking lot host/Src/usr/extendllrp/ExtendLLRP.cpp | f222825d7ad8726cec200c6dd8dca08ef308a444 | [] | no_license | MCreatorD/parking-lot | 41f11a175bfbdd671f86b3eb03eec712897ab2dc | 8dac908132cd1c1d83b8bee3896adc52f5334f6e | refs/heads/master | 2021-07-12T08:57:28.351875 | 2020-07-08T05:48:07 | 2020-07-08T05:48:07 | 161,132,824 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,567 | cpp | #include "ExtendLLRP.h"
/*
* Generated file - DO NOT EDIT
*
* This is the header file for the LLRP Tool Kit (LTK)
* C++ (aka cpp) implementation. It is generated into a .inc file
* that is included by a platform specific .cpp source file.
* That .cpp file takes care of prerequisites needed by this file.
*/
/*
* Vendor descriptors
*/
/*
* Namespace descriptors
*/
/*
* Enumeration string tables
*/
/*
*****************************************************************
**
** Message ManufacturerCommand
**
*****************************************************************
*/
const CTypeDescriptor
CManufacturerCommand::s_typeDescriptor =
{
TRUE, // m_bIsMessage
"ManufacturerCommand", // m_pName
NULL, // m_pVendorDescriptor
&g_nsdescllrp, // m_pNamespaceDescriptor
1000, // m_TypeNum
NULL, // m_pResponseType
s_apFieldDescriptorTable, // m_ppFieldDescriptorTable
s_construct, // m_pfConstruct
s_decodeFields, // m_pfDecodeFields
};
const CFieldDescriptor * const
CManufacturerCommand::s_apFieldDescriptorTable[] =
{
&s_fdByteStream,
NULL
};
const CFieldDescriptor
CManufacturerCommand::s_fdByteStream =
{
CFieldDescriptor::FT_U8V, // m_eFieldType
CFieldDescriptor::FMT_NORMAL, // m_eFieldFormat
"ByteStream", // m_pName
NULL // m_pEnumTable
};
CManufacturerCommand::CManufacturerCommand (void)
{
m_pType = &s_typeDescriptor;
}
CManufacturerCommand::~CManufacturerCommand (void)
{
}
CElement *
CManufacturerCommand::s_construct (void)
{
return (CElement *) new CManufacturerCommand();
}
void
CManufacturerCommand::s_decodeFields (
CDecoderStream * pDecoderStream,
CElement * pTargetElement)
{
CManufacturerCommand * pTarget = (CManufacturerCommand *) pTargetElement;
if(NULL != pTarget)
{
pTarget->m_ByteStream = pDecoderStream->get_u8v(&s_fdByteStream);
}
else
{
pDecoderStream->get_u8v(&s_fdByteStream);
}
}
void
CManufacturerCommand::decodeFields (
CDecoderStream * pDecoderStream)
{
s_decodeFields(pDecoderStream, (CElement *)this);
}
void
CManufacturerCommand::assimilateSubParameters (
CErrorDetails * pError)
{
tListOfParameters::iterator Cur = m_listAllSubParameters.begin();
tListOfParameters::iterator End = m_listAllSubParameters.end();
const CTypeDescriptor * pType;
if(Cur != End)
{
pError->unexpectedParameter(*Cur);
}
return;
missing:
pError->missingParameter(pType);
}
void
CManufacturerCommand::encode (
CEncoderStream * pEncoderStream) const
{
const CTypeDescriptor * pType;
pEncoderStream->put_u8v(m_ByteStream, &s_fdByteStream);
}
/*
*****************************************************************
**
** Message ManufacturerCommandAck
**
*****************************************************************
*/
const CTypeDescriptor
CManufacturerCommandAck::s_typeDescriptor =
{
TRUE, // m_bIsMessage
"ManufacturerCommandAck", // m_pName
NULL, // m_pVendorDescriptor
&g_nsdescllrp, // m_pNamespaceDescriptor
1001, // m_TypeNum
NULL, // m_pResponseType
s_apFieldDescriptorTable, // m_ppFieldDescriptorTable
s_construct, // m_pfConstruct
s_decodeFields, // m_pfDecodeFields
};
const CFieldDescriptor * const
CManufacturerCommandAck::s_apFieldDescriptorTable[] =
{
NULL
};
CManufacturerCommandAck::CManufacturerCommandAck (void)
{
m_pType = &s_typeDescriptor;
m_pStatus = NULL;
}
CManufacturerCommandAck::~CManufacturerCommandAck (void)
{
}
CElement *
CManufacturerCommandAck::s_construct (void)
{
return (CElement *) new CManufacturerCommandAck();
}
void
CManufacturerCommandAck::s_decodeFields (
CDecoderStream * pDecoderStream,
CElement * pTargetElement)
{
CManufacturerCommandAck * pTarget = (CManufacturerCommandAck *) pTargetElement;
}
void
CManufacturerCommandAck::decodeFields (
CDecoderStream * pDecoderStream)
{
s_decodeFields(pDecoderStream, (CElement *)this);
}
void
CManufacturerCommandAck::assimilateSubParameters (
CErrorDetails * pError)
{
tListOfParameters::iterator Cur = m_listAllSubParameters.begin();
tListOfParameters::iterator End = m_listAllSubParameters.end();
const CTypeDescriptor * pType;
// 1 of Status
pType = &CStatus::s_typeDescriptor;
if(Cur == End || (*Cur)->m_pType != pType)
{
goto missing;
}
m_pStatus = (CStatus *)*Cur++;
if(Cur != End)
{
pError->unexpectedParameter(*Cur);
}
return;
missing:
pError->missingParameter(pType);
}
EResultCode
CManufacturerCommandAck::setStatus (
CStatus * pValue)
{
removeSubParameterFromAllList(m_pStatus);
delete m_pStatus;
m_pStatus = pValue;
addSubParameterToAllList(pValue);
return RC_OK;
}
void
CManufacturerCommandAck::encode (
CEncoderStream * pEncoderStream) const
{
const CTypeDescriptor * pType;
pType = &CStatus::s_typeDescriptor;
pEncoderStream->putRequiredSubParameter(m_pStatus, pType);
}
/*
*****************************************************************
**
** Message ManufacturerReport
**
*****************************************************************
*/
const CTypeDescriptor
CManufacturerReport::s_typeDescriptor =
{
TRUE, // m_bIsMessage
"ManufacturerReport", // m_pName
NULL, // m_pVendorDescriptor
&g_nsdescllrp, // m_pNamespaceDescriptor
1002, // m_TypeNum
NULL, // m_pResponseType
s_apFieldDescriptorTable, // m_ppFieldDescriptorTable
s_construct, // m_pfConstruct
s_decodeFields, // m_pfDecodeFields
};
const CFieldDescriptor * const
CManufacturerReport::s_apFieldDescriptorTable[] =
{
&s_fdByteStream,
NULL
};
const CFieldDescriptor
CManufacturerReport::s_fdByteStream =
{
CFieldDescriptor::FT_U8V, // m_eFieldType
CFieldDescriptor::FMT_NORMAL, // m_eFieldFormat
"ByteStream", // m_pName
NULL // m_pEnumTable
};
CManufacturerReport::CManufacturerReport (void)
{
m_pType = &s_typeDescriptor;
}
CManufacturerReport::~CManufacturerReport (void)
{
}
CElement *
CManufacturerReport::s_construct (void)
{
return (CElement *) new CManufacturerReport();
}
void
CManufacturerReport::s_decodeFields (
CDecoderStream * pDecoderStream,
CElement * pTargetElement)
{
CManufacturerReport * pTarget = (CManufacturerReport *) pTargetElement;
if(NULL != pTarget)
{
pTarget->m_ByteStream = pDecoderStream->get_u8v(&s_fdByteStream);
}
else
{
pDecoderStream->get_u8v(&s_fdByteStream);
}
}
void
CManufacturerReport::decodeFields (
CDecoderStream * pDecoderStream)
{
s_decodeFields(pDecoderStream, (CElement *)this);
}
void
CManufacturerReport::assimilateSubParameters (
CErrorDetails * pError)
{
tListOfParameters::iterator Cur = m_listAllSubParameters.begin();
tListOfParameters::iterator End = m_listAllSubParameters.end();
const CTypeDescriptor * pType;
if(Cur != End)
{
pError->unexpectedParameter(*Cur);
}
return;
missing:
pError->missingParameter(pType);
}
void
CManufacturerReport::encode (
CEncoderStream * pEncoderStream) const
{
const CTypeDescriptor * pType;
pEncoderStream->put_u8v(m_ByteStream, &s_fdByteStream);
}
/*
*****************************************************************
**
** Message ManufacturerReportAck
**
*****************************************************************
*/
const CTypeDescriptor
CManufacturerReportAck::s_typeDescriptor =
{
TRUE, // m_bIsMessage
"ManufacturerReportAck", // m_pName
NULL, // m_pVendorDescriptor
&g_nsdescllrp, // m_pNamespaceDescriptor
1003, // m_TypeNum
NULL, // m_pResponseType
s_apFieldDescriptorTable, // m_ppFieldDescriptorTable
s_construct, // m_pfConstruct
s_decodeFields, // m_pfDecodeFields
};
const CFieldDescriptor * const
CManufacturerReportAck::s_apFieldDescriptorTable[] =
{
NULL
};
CManufacturerReportAck::CManufacturerReportAck (void)
{
m_pType = &s_typeDescriptor;
m_pStatus = NULL;
}
CManufacturerReportAck::~CManufacturerReportAck (void)
{
}
CElement *
CManufacturerReportAck::s_construct (void)
{
return (CElement *) new CManufacturerReportAck();
}
void
CManufacturerReportAck::s_decodeFields (
CDecoderStream * pDecoderStream,
CElement * pTargetElement)
{
CManufacturerReportAck * pTarget = (CManufacturerReportAck *) pTargetElement;
}
void
CManufacturerReportAck::decodeFields (
CDecoderStream * pDecoderStream)
{
s_decodeFields(pDecoderStream, (CElement *)this);
}
void
CManufacturerReportAck::assimilateSubParameters (
CErrorDetails * pError)
{
tListOfParameters::iterator Cur = m_listAllSubParameters.begin();
tListOfParameters::iterator End = m_listAllSubParameters.end();
const CTypeDescriptor * pType;
// 1 of Status
pType = &CStatus::s_typeDescriptor;
if(Cur == End || (*Cur)->m_pType != pType)
{
goto missing;
}
m_pStatus = (CStatus *)*Cur++;
if(Cur != End)
{
pError->unexpectedParameter(*Cur);
}
return;
missing:
pError->missingParameter(pType);
}
EResultCode
CManufacturerReportAck::setStatus (
CStatus * pValue)
{
removeSubParameterFromAllList(m_pStatus);
delete m_pStatus;
m_pStatus = pValue;
addSubParameterToAllList(pValue);
return RC_OK;
}
void
CManufacturerReportAck::encode (
CEncoderStream * pEncoderStream) const
{
const CTypeDescriptor * pType;
pType = &CStatus::s_typeDescriptor;
pEncoderStream->putRequiredSubParameter(m_pStatus, pType);
}
void
tmp_enrollCoreTypesIntoRegistry (
CTypeRegistry * pTypeRegistry)
{
pTypeRegistry->enroll(&CManufacturerCommand::s_typeDescriptor);
pTypeRegistry->enroll(&CManufacturerCommandAck::s_typeDescriptor);
pTypeRegistry->enroll(&CManufacturerReport::s_typeDescriptor);
pTypeRegistry->enroll(&CManufacturerReportAck::s_typeDescriptor);
}
| [
"2854836020@qq.comm"
] | 2854836020@qq.comm |
ee896d5d808bc7f30d2583137b7a36c42db6d423 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2645486_0/C++/hesibo/b.cpp | e6d8cf48a28e53e73b546b9e8ebf04c0f9700b1f | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,032 | cpp | #include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
int main() {
freopen("B-small-attempt1.in", "r", stdin);
freopen("out.txt", "w", stdout);
int tot;
cin >> tot;
for (int task = 1; task <= tot; task++) {
int e, r, n;
cin >> e >> r >> n;
int v[10];
for (int i = 0; i < n; i++) {
cin >> v[i];
}
int f[11][6];
memset(f, 0, sizeof(f));
for (int i = 0; i < e; i++) {
f[0][i] = -1;
}
for (int i = 0; i < n; i++)
for (int j = 0; j <= e; j++) {
if (f[i][j] >= 0) {
for (int k = 0; k <= j; k++) {
f[i + 1][min(e, j - k + r)] >?= f[i][j] + k * v[i];
}
}
}
int ans = 0;
for (int i = 0; i <= e; i++) {
ans = max(ans, f[n][i]);
}
cout << "Case #" << task << ": " << ans << endl;
}
}
| [
"eewestman@gmail.com"
] | eewestman@gmail.com |
24f187ee8c06f4f57e6cfd4a87b62776349d20a1 | 86a9081a05b837ad0f0feaf6e003a1cbb276993f | /cg_exercise_05/cglib/lib/glm/glm/gtx/common.hpp | e13be84fff44144829a9ca637b58d0bf43dac958 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-happy-bunny"
] | permissive | flex3r/cg_exercises | e2defd27427c251d5f0f567a8d192af8d87bca3c | 7c4b699a8211ba66710ac2137f0d460933069331 | refs/heads/master | 2020-12-11T14:06:15.052585 | 2018-02-11T13:58:23 | 2018-02-11T13:58:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,994 | hpp | /// @ref gtx_common
/// @file glm/gtx/common.hpp
///
/// @see core (dependence)
/// @see gtc_half_float (dependence)
///
/// @defgroup gtx_common GLM_GTX_common
/// @ingroup gtx
///
/// @brief Provide functions to increase the compatibility with Cg and HLSL languages
///
/// <glm/gtx/common.hpp> need to be included to use these functionalities.
#pragma once
// Dependencies:
#include "../vec2.hpp"
#include "../vec3.hpp"
#include "../vec4.hpp"
#include "../gtc/vec1.hpp"
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_common extension included")
#endif
namespace glm
{
/// @addtogroup gtx_common
/// @{
/// Returns true if x is a denormalized number
/// Numbers whose absolute value is too small to be represented in the normal format are represented in an alternate, denormalized format.
/// This format is less precise but can represent values closer to zero.
///
/// @tparam genType Floating-point scalar or vector types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/isnan.xml">GLSL isnan man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.3 Common Functions</a>
template <typename genType>
GLM_FUNC_DECL typename genType::bool_type isdenormal(genType const & x);
/// Similar to 'mod' but with a different rounding and integer support.
/// Returns 'x - y * trunc(x/y)' instead of 'x - y * floor(x/y)'
///
/// @see <a href="http://stackoverflow.com/questions/7610631/glsl-mod-vs-hlsl-fmod">GLSL mod vs HLSL fmod</a>
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/mod.xml">GLSL mod man page</a>
template <typename T, precision P, template <typename, precision> class vecType>
GLM_FUNC_DECL vecType<T, P> fmod(vecType<T, P> const & v);
/// @}
}//namespace glm
#include "common.inl"
// CG_REVISION ab290eedfc16bcf76a3816f6664e85db04a6520c
| [
"n1085633848@outlook.com"
] | n1085633848@outlook.com |
94f94801e1ccce045e6eb495d3b0be188ed665f2 | ae32263088df7a258b3802f548eb05516b693087 | /tests/tst-concurrent-read.cc | eb2f1d570337173062c5254ae0235f933e2f583d | [
"BSD-3-Clause"
] | permissive | mkenigs/osv | 6809452169e4172d2a010bbd53dbf6b1a7de229f | 9c8ee44bd67b3031d857f31319783a53e3889258 | refs/heads/master | 2023-03-17T05:56:26.863141 | 2021-01-30T02:59:25 | 2021-02-01T19:06:48 | 318,828,802 | 1 | 0 | NOASSERTION | 2020-12-05T15:59:51 | 2020-12-05T15:59:51 | null | UTF-8 | C++ | false | false | 2,793 | cc | #include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <thread>
#include <vector>
#include <atomic>
#if defined(READ_ONLY_FS)
#define SUBDIR "rofs"
#else
#define SUBDIR "tmp"
#endif
int tests = 0, fails = 0;
using namespace std;
#define expect(actual, expected) do_expect(actual, expected, #actual, #expected, __FILE__, __LINE__)
template<typename T>
bool do_expect(T actual, T expected, const char *actuals, const char *expecteds, const char *file, int line)
{
++tests;
if (actual != expected) {
fails++;
cout << "FAIL: " << file << ":" << line << ": For " << actuals <<
", expected " << expecteds << ", saw " << actual << ".\n";
return false;
}
return true;
}
int main()
{
srand (time(NULL));
//
// First read first file using mmap
string file_1("/" SUBDIR "/mmap-file-test1");
int fd1 = open(file_1.c_str(), O_RDONLY, 0666);
expect(fd1 >= 0, true );
struct stat sb;
if (fstat (fd1, &sb) == -1) {
perror ("fstat");
return 1;
}
if (!S_ISREG (sb.st_mode)) {
cerr << file_1 << " is not a file\n";
return 1;
}
off_t length = sb.st_size;
void *address = mmap(0, length, PROT_READ, MAP_PRIVATE, fd1, 0);
if (address == MAP_FAILED) {
return 1;
}
string file_2("/" SUBDIR "/mmap-file-test2");
int fd2 = open(file_2.c_str(), O_RDONLY, 0666);
expect(fd2 >= 0, true );
vector<thread> readers;
int thread_count = 10, reads_count = 100;
atomic<long> identical_count(0);
for(int i = 0; i < thread_count; i++) {
readers.emplace_back(thread([i,reads_count,fd2,length,address,&identical_count]{
unsigned char buffer[4096];
for(int step = 0; step < reads_count; step++) {
off_t offset = rand() % length;
size_t amount = min(length - offset, 4096l);
int ret = pread(fd2, buffer, amount, offset);
expect(ret > 0, true);
if( ret > 0 ) {
auto is_identical = memcmp(buffer, static_cast<unsigned char*>(address) + offset, amount) == 0 ? 1 : 0;
identical_count += is_identical;
}
else {
cout << "[" << i << "] FAILED to read " << amount << " bytes at " << offset << "\n";
}
}
}));
}
for(auto &t : readers) {
t.join();
}
cout << "Identical count " << identical_count.load() << endl;
munmap(address,length);
close(fd1);
close(fd2);
expect(identical_count.load(),(long)(thread_count * reads_count));
}
| [
"nyh@scylladb.com"
] | nyh@scylladb.com |
71cf9107b33e918750ba35b58d8759b751483e96 | c8d4c272bdc6e331e7102f4b6bf236d07ce9d8d8 | /HZOJ/486.cpp | 78b18c1412b56507454ae4b230b8814b1bcc0601 | [] | no_license | index1101/CPractice | 59773be3346ba0abf26a002cdb7236d46061b7da | b92cb870ce12bd536fb6402c6c255f6b09082781 | refs/heads/master | 2020-05-09T13:48:20.556117 | 2019-11-06T12:47:40 | 2019-11-06T12:47:40 | 181,168,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 630 | cpp | /*************************************************************************
> File Name: 486.cpp
> Author: liutaiwei
> Mail: 243187728@qq.com
> Created Time: 2019年10月22日 星期二 18时41分39秒
************************************************************************/
#include <iostream>
using namespace std;
#define MAX_N 1000
long long f[MAX_N + 5] = {0};
long long func(int n) {
if (f[n] >= 12345) f[n] %= 12345;
if (f[n]) return f[n];
return f[n] = func(n - 1) + func(n - 2) * 2;
}
int main() {
int n;
f[1] = 1, f[2] = 3;
cin >> n;
cout << func(n) % 12345 << endl;
return 0;
}
| [
"243187728@qq.com"
] | 243187728@qq.com |
c95ceed837521a69fea5f1f61a0dd99608fb583e | f7d12dd299c09f06a2de705f045ee19ed8515a69 | /numeric.h | c15ff3f9f8d3125e9741ed97ee4ace7e4e0f1f58 | [] | no_license | Immac/TeoriaDB | 7c24f74d5db213bf8647bdfbda2c7f61ff772848 | a20d7047f51b34d75c30c21134b05d1be16f798a | refs/heads/master | 2020-05-19T14:55:05.940455 | 2014-09-20T02:32:03 | 2014-09-20T02:32:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 347 | h | #ifndef NUMERIC_H
#define NUMERIC_H
#include <QString>
class Numeric
{
public:
Numeric(bool isPositive,double integer,double decimal):
isPositive(isPositive),
integer(integer),
decimal(decimal)
{}
QString toString();
private:
bool isPositive;
double integer;
double decimal;
};
#endif // NUMERIC_H
| [
"immac.gm@gmail.com"
] | immac.gm@gmail.com |
f6cac4383372ab55d562eb28ac1d55d8f20fa1e6 | 66880b4c06bf662d058b1184642e9f052779ea9e | /art/compiler/dex/compiler_ir.h | 70159cae9f1aae8f8a04ef84ccaf638ee43abd57 | [] | no_license | ParkHanbum/dex2ir | afa195163a048efa01c1cbd44c90ffd84565d053 | a4cc0fe939146ca258c50a6b52b8fa09313f5eb4 | refs/heads/master | 2022-07-02T20:28:19.323269 | 2022-05-30T09:22:33 | 2022-05-30T09:22:33 | 247,693,944 | 51 | 16 | null | null | null | null | UTF-8 | C++ | false | false | 3,448 | h | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ART_COMPILER_DEX_COMPILER_IR_H_
#define ART_COMPILER_DEX_COMPILER_IR_H_
#include <vector>
#include "compiler_enums.h"
#include "dex/quick/mir_to_lir.h"
#include "dex_instruction.h"
#include "driver/compiler_driver.h"
#include "driver/dex_compilation_unit.h"
#include "safe_map.h"
#include "utils/scoped_arena_allocator.h"
#include "base/timing_logger.h"
#include "utils/arena_allocator.h"
namespace art {
struct ArenaMemBlock;
class Backend;
struct Memstats;
class MIRGraph;
class Mir2Lir;
struct CompilationUnit {
explicit CompilationUnit(ArenaPool* pool);
~CompilationUnit();
void StartTimingSplit(const char* label);
void NewTimingSplit(const char* label);
void EndTiming();
/*
* Fields needed/generated by common frontend and generally used throughout
* the compiler.
*/
CompilerDriver* compiler_driver;
ClassLinker* class_linker; // Linker to resolve fields and methods.
const DexFile* dex_file; // DexFile containing the method being compiled.
jobject class_loader; // compiling method's class loader.
uint16_t class_def_idx; // compiling method's defining class definition index.
uint32_t method_idx; // compiling method's index into method_ids of DexFile.
const DexFile::CodeItem* code_item; // compiling method's DexFile code_item.
uint32_t access_flags; // compiling method's access flags.
InvokeType invoke_type; // compiling method's invocation type.
const char* shorty; // compiling method's shorty.
uint32_t disable_opt; // opt_control_vector flags.
uint32_t enable_debug; // debugControlVector flags.
bool verbose;
const Compiler* compiler;
InstructionSet instruction_set;
bool target64;
InstructionSetFeatures GetInstructionSetFeatures() {
return compiler_driver->GetInstructionSetFeatures();
}
// TODO: much of this info available elsewhere. Go to the original source?
uint16_t num_dalvik_registers; // method->registers_size.
const uint16_t* insns;
uint16_t num_ins;
uint16_t num_outs;
uint16_t num_regs; // Unlike num_dalvik_registers, does not include ins.
// If non-empty, apply optimizer/debug flags only to matching methods.
std::string compiler_method_match;
// Flips sense of compiler_method_match - apply flags if doesn't match.
bool compiler_flip_match;
// TODO: move memory management to mir_graph, or just switch to using standard containers.
ArenaAllocator arena;
ArenaStack arena_stack; // Arenas for ScopedArenaAllocator.
UniquePtr<MIRGraph> mir_graph; // MIR container.
UniquePtr<Backend> cg; // Target-specific codegen.
TimingLogger timings;
};
} // namespace art
#endif // ART_COMPILER_DEX_COMPILER_IR_H_
| [
"kese111@gmail.com"
] | kese111@gmail.com |
00d7b12ad95b35b53daccc63347d15cb43631fc6 | 7cce0635a50e8d2db92b7b1bf4ad49fc218fb0b8 | /测线源程序/测线源程序0914/测线界面程序/SeismonitorGraphView.cpp | 2063e210f1ba93eb715f0fa949ff7b1af6b84d1f | [] | no_license | liquanhai/cxm-hitech-matrix428 | dcebcacea58123aabcd9541704b42b3491444220 | d06042a3de79379a77b0e4e276de42de3c1c6d23 | refs/heads/master | 2021-01-20T12:06:23.622153 | 2013-01-24T01:05:10 | 2013-01-24T01:05:10 | 54,619,320 | 2 | 2 | null | null | null | null | GB18030 | C++ | false | false | 30,680 | cpp | // SensorGraphView.cpp : 实现文件
//
#include "stdafx.h"
#include "BCGPVisualStudioGUIDemo.h"
#include "SeismonitorGraphView.h"
#include "SeismonitorGraphChildFrame.h"
// CSeismonitorGraphView
IMPLEMENT_DYNCREATE(CSeismonitorGraphView, CScrollView)
CSeismonitorGraphView::CSeismonitorGraphView()
{
m_pSiteData = NULL;; // 现场数据对象
m_iGridX = 0; // 单元格X方向尺寸
m_iGridY = 0; // 单元格Y方向尺寸
m_iGridXPre = 0; // 单元格X方向尺寸,上一次
m_iGridYPre = 0; // 单元格Y方向尺寸,上一次
m_iPaperX = 0; // 图形区X方向尺寸
m_iPaperY = 0; // 图形区Y方向尺寸
m_fZoomRate = 1.0; // 放大倍数
m_bMouseDownLeft = false; // 鼠标左键是否按下
m_bMouseDownMiddle = false; // 鼠标中间键是否按下
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
m_strAbsoluteSpread = "all"; // 选中区域对应的绝对排列
m_iSelectUnitColumnIndex = -1; // 选中单元列索引
m_iSelectUnitRowIndex = -1; // 选中单元行索引
}
CSeismonitorGraphView::~CSeismonitorGraphView()
{
}
BEGIN_MESSAGE_MAP(CSeismonitorGraphView, CScrollView)
// 标准打印命令
ON_COMMAND(ID_FILE_PRINT, OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, OnFilePrintPreview)
ON_WM_CREATE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONUP()
ON_WM_LBUTTONDBLCLK()
ON_WM_MOUSEMOVE()
ON_WM_MBUTTONDOWN()
ON_WM_MBUTTONUP()
ON_WM_CONTEXTMENU()
ON_COMMAND(IDR_POPUP_GRAPHVIEW_SENSOR_PROPERTIES, OnGraphViewSensorProperties)
ON_COMMAND(IDR_POPUP_GRAPHVIEW_SENSOR_SETAUXILIARY, OnGraphViewSensorSetAuxiliary)
ON_COMMAND(IDR_POPUP_GRAPHVIEW_SENSOR_MUTE, OnGraphViewSensorSetMute)
END_MESSAGE_MAP()
// CSeismonitorGraphView 绘图
void CSeismonitorGraphView::OnInitialUpdate()
{
CScrollView::OnInitialUpdate();
CDocument* pDoc = GetDocument ();
ASSERT_VALID (pDoc);
pDoc->SetTitle (_T("Seismonitor Graph View"));
// 绘图前设置绘图参数
SetupPageSize();
}
void CSeismonitorGraphView::OnDraw(CDC* pDC)
{
// 画网格图
// m_pSiteData->m_oGraphSensorList.DrawGrid(pDC, m_iPaperX, m_iPaperY, m_iGridX, m_iGridY);
// 画鼠标中间键选中区域
DrawSelectArea(pDC);
// 画测线标尺和测点标尺
m_pSiteData->m_oGraphSensorList.DrawMarkLineNbAndPointNb(pDC, m_iGridX, m_iGridY);
// 画图形单元
CSeismonitorGraphChildFrame* pParentFrame = (CSeismonitorGraphChildFrame*)GetParentFrame();
m_pSiteData->m_oGraphSensorList.DrawUnitAll(pDC, m_iGridX, m_iGridY, pParentFrame->m_uiTestType, pParentFrame->m_uiSensorNb, pParentFrame->m_oSensorNbMap, pParentFrame->m_fSeismonitorLimit);
}
// CSeismonitorGraphView 诊断
#ifdef _DEBUG
void CSeismonitorGraphView::AssertValid() const
{
CScrollView::AssertValid();
}
#ifndef _WIN32_WCE
void CSeismonitorGraphView::Dump(CDumpContext& dc) const
{
CScrollView::Dump(dc);
}
#endif
#endif //_DEBUG
// CSeismonitorGraphView 打印
void CSeismonitorGraphView::OnFilePrintPreview()
{
BCGPPrintPreview(this);
}
void CSeismonitorGraphView::OnFilePrint()
{
CScrollView::OnFilePrint();
}
BOOL CSeismonitorGraphView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 默认准备
return DoPreparePrinting(pInfo);
}
void CSeismonitorGraphView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加额外的打印前进行的初始化过程
}
void CSeismonitorGraphView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 添加打印后进行的清理过程
}
// CSeismonitorGraphView 消息处理程序
int CSeismonitorGraphView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CScrollView::OnCreate(lpCreateStruct) == -1)
return -1;
// 加载现场数据
OnLoadSiteData();
// 生成测试值漂浮窗口
m_wndStaticFloat.Create("", WS_CHILD, CRect(0, 0, 100, 20), this);
return 0;
}
void CSeismonitorGraphView::OnPrepareDC(CDC* pDC, CPrintInfo* pInfo)
{
CScrollView::OnPrepareDC(pDC, pInfo);
pDC->SetWindowOrg(-m_pSiteData->m_oGraphSensorList.m_iPaperHeadLeft, -m_pSiteData->m_oGraphSensorList.m_iPaperHeadTop);
}
void CSeismonitorGraphView::OnContextMenu(CWnd* pWnd, CPoint point)
{
CRect oRect;
GetWindowRect(oRect);
CPoint ptClient;
ptClient = point;
ptClient.x = ptClient.x - oRect.left;
ptClient.y = ptClient.y - oRect.top;
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
oDC.DPtoLP(&ptClient);
// 判断点是否在绘图区域内
if(true == JudgeIfPointInPaper(&ptClient))
{
// 得到点坐标对应的单元
GetUnitUnderPoint(&ptClient);
if((-1 != m_iSelectUnitRowIndex) && (-1 != m_iSelectUnitColumnIndex))
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
CMenu menu;
menu.LoadMenu (IDR_POPUP_GRAPHVIEW_SENSOR);
CMenu* pSumMenu = menu.GetSubMenu(0);
// 判断:
if(0 == pChannelSetupData->m_uiSN)
{
pSumMenu->DeleteMenu(IDR_POPUP_GRAPHVIEW_SENSOR_SETAUXILIARY, MF_BYCOMMAND);
}
if (AfxGetMainWnd()->IsKindOf(RUNTIME_CLASS(CBCGPMDIFrameWnd)))
{
CBCGPPopupMenu* pPopupMenu = new CBCGPPopupMenu;
if (!pPopupMenu->Create(this, point.x, point.y, (HMENU)pSumMenu->m_hMenu, FALSE, TRUE))
return;
((CBCGPMDIFrameWnd*)AfxGetMainWnd())->OnShowPopupMenu (pPopupMenu);
UpdateDialogControls(this, FALSE);
}
}
}
}
}
void CSeismonitorGraphView::OnLButtonDblClk(UINT nFlags, CPoint point)
{
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
oDC.DPtoLP(&point);
// 判断点是否在绘图区域内
if(true == JudgeIfPointInPaper(&point))
{
// 得到点坐标对应的单元
GetUnitUnderPoint(&point);
if((-1 != m_iSelectUnitRowIndex) && (-1 != m_iSelectUnitColumnIndex))
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
// 响应显示属性值
OnShowProperty(pChannelSetupData->m_uiIndex);
}
}
}
CScrollView::OnLButtonDblClk(nFlags, point);
}
void CSeismonitorGraphView::OnLButtonDown(UINT nFlags, CPoint point)
{
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
if(true == m_bDrawSelectArea)
{
m_oSelectAreaPoint.left = m_oSelectAreaPoint.left - 2;
m_oSelectAreaPoint.top = m_oSelectAreaPoint.top - 2;
m_oSelectAreaPoint.right = m_oSelectAreaPoint.right + 2;
m_oSelectAreaPoint.bottom = m_oSelectAreaPoint.bottom + 2;
oDC.LPtoDP(&m_oSelectAreaPoint);
InvalidateRect(&m_oSelectAreaPoint, TRUE);
}
oDC.DPtoLP(&point);
m_oPointBase = point; // 鼠标键按下时鼠标点
m_oPointLast = m_oPointBase; // 鼠标键释放时鼠标点
m_bMouseDownLeft = true; // 鼠标左键是否按下
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
m_strAbsoluteSpread = "all"; // 选中区域对应的绝对排列
CScrollView::OnLButtonDown(nFlags, point);
}
void CSeismonitorGraphView::OnLButtonUp(UINT nFlags, CPoint point)
{
if(true == m_bMouseDownLeft) // 鼠标左键是否按下
{
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
oDC.DPtoLP(&point);
CRect oRect;
oRect.left = m_oPointBase.x;
oRect.top = m_oPointBase.y;
oRect.right = m_oPointLast.x;
oRect.bottom = m_oPointLast.y;
oRect.NormalizeRect();
oDC.DrawFocusRect(&oRect);
m_oPointLast = point; // 鼠标键释放时鼠标点
m_bMouseDownLeft = false; // 鼠标左键是否按下
// 得到选中的区域
if(true == GetSelectAreaPoint())
{
// 局部放大
OnZoomInDrag();
Invalidate(TRUE);
}
else
{
oRect.left = oRect.left - 2;
oRect.top = oRect.top - 2;
oRect.right = oRect.right + 2;
oRect.bottom = oRect.bottom + 2;
oDC.LPtoDP(&oRect);
InvalidateRect(&oRect, TRUE);
}
}
CScrollView::OnLButtonUp(nFlags, point);
}
void CSeismonitorGraphView::OnMButtonDown(UINT nFlags, CPoint point)
{
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
if(true == m_bDrawSelectArea) // 是否画鼠标中间键选中区域位置
{
m_oSelectAreaPoint.left = m_oSelectAreaPoint.left - 2;
m_oSelectAreaPoint.top = m_oSelectAreaPoint.top - 2;
m_oSelectAreaPoint.right = m_oSelectAreaPoint.right + 2;
m_oSelectAreaPoint.bottom = m_oSelectAreaPoint.bottom + 2;
oDC.LPtoDP(&m_oSelectAreaPoint);
InvalidateRect(&m_oSelectAreaPoint, TRUE);
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
}
oDC.DPtoLP(&point);
m_oPointBase = point; // 鼠标键按下时鼠标点
m_oPointLast = m_oPointBase; // 鼠标键释放时鼠标点
m_bMouseDownMiddle = true; // 鼠标中间键是否按下
CScrollView::OnMButtonDown(nFlags, point);
}
void CSeismonitorGraphView::OnMButtonUp(UINT nFlags, CPoint point)
{
if(true == m_bMouseDownMiddle) // 鼠标中间键是否按下
{
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
oDC.DPtoLP(&point);
CRect oRect;
oRect.left = m_oPointBase.x;
oRect.top = m_oPointBase.y;
oRect.right = m_oPointLast.x;
oRect.bottom = m_oPointLast.y;
oRect.NormalizeRect();
oDC.DrawFocusRect(&oRect);
m_oPointLast = point; // 鼠标键释放时鼠标点
m_bMouseDownMiddle = false; // 鼠标中间键是否按下
// 得到选中的区域
if(true == GetSelectAreaPoint())
{
// 得到选中区域的行坐标和列坐标区域
GetSelectAreaIndex();
// 把选中区域转换为绝对排列字符串
ConvertSelectAreaToAbsoluteSpreadString();
m_bDrawSelectArea = true; // 是否画鼠标中间键选中区域位置
Invalidate(TRUE);
}
else
{
m_strAbsoluteSpread = "all";
oRect.left = oRect.left - 2;
oRect.top = oRect.top - 2;
oRect.right = oRect.right + 2;
oRect.bottom = oRect.bottom + 2;
oDC.LPtoDP(&oRect);
InvalidateRect(&oRect, TRUE);
}
}
CScrollView::OnMButtonUp(nFlags, point);
}
void CSeismonitorGraphView::OnMouseMove(UINT nFlags, CPoint point)
{
CPoint pointClient = point;
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
oDC.DPtoLP(&point);
if((true == m_bMouseDownLeft) || (true == m_bMouseDownMiddle)) // 鼠标左键是否按下或鼠标中间键是否按下
{
CRect oRect;
oRect.left = m_oPointBase.x;
oRect.top = m_oPointBase.y;
oRect.right = m_oPointLast.x;
oRect.bottom = m_oPointLast.y;
oRect.NormalizeRect();
oDC.DrawFocusRect(&oRect);
oRect.left = m_oPointBase.x;
oRect.top = m_oPointBase.y;
oRect.right = point.x;
oRect.bottom = point.y;
oRect.NormalizeRect();
oDC.DrawFocusRect(&oRect);
m_oPointLast = point; // 鼠标键释放时鼠标点
}
else
{
// 判断点是否在绘图区域内
if(true == JudgeIfPointInPaper(&point))
{
// 得到点坐标对应的单元
GetUnitUnderPoint(&point);
if((-1 != m_iSelectUnitRowIndex) && (-1 != m_iSelectUnitColumnIndex))
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
// 显示单元的测线号和测点号
OnShowUnitPosition(pChannelSetupData->m_uiNbLine, pChannelSetupData->m_uiNbPoint);
// 在浮动窗口中显示测试值
OnShowTestValueInFloatWindow(pChannelSetupData, pointClient);
}
}
else
{
m_wndStaticFloat.ShowWindow(SW_HIDE);
}
}
else
{
m_wndStaticFloat.ShowWindow(SW_HIDE);
}
}
CScrollView::OnMouseMove(nFlags, point);
}
/**
* 函数说明
* @param void
* @return void
*/
void CSeismonitorGraphView::OnGraphViewSensorProperties()
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
// 响应显示属性值
OnShowProperty(pChannelSetupData->m_uiIndex);
}
}
/**
* 函数说明
* @param void
* @return void
*/
void CSeismonitorGraphView::OnGraphViewSensorSetAuxiliary()
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
CMainFrame* pMainFrame = NULL;
pMainFrame = (CMainFrame*)AfxGetMainWnd();
// 响应仪器图形视图弹出菜单设置辅助道
pMainFrame->OnGraphViewInstrumentSetAuxiliary(3, pChannelSetupData->m_uiSN);
}
}
/**
* 函数说明
* @param void
* @return void
*/
void CSeismonitorGraphView::OnGraphViewSensorSetMute()
{
CChannelSetupData* pChannelSetupData = NULL;
pChannelSetupData = m_pSiteData->m_oGraphSensorList.GetChannelSetupData(m_iSelectUnitRowIndex, m_iSelectUnitColumnIndex);
if(NULL != pChannelSetupData)
{
CMainFrame* pMainFrame = NULL;
pMainFrame = (CMainFrame*)AfxGetMainWnd();
// 响应检波器图形视图弹出菜单Mute设置
pMainFrame->OnGraphViewSensorSetMute(pChannelSetupData->m_uiNbLine, pChannelSetupData->m_uiNbPoint);
}
}
// 现场数据对象初始化
void CSeismonitorGraphView::OnSiteDataInit()
{
CMainFrame* pMainFrame = NULL;
pMainFrame = (CMainFrame*)AfxGetMainWnd();
m_pSiteData = &pMainFrame->m_oSiteData;
m_iPaperX = m_pSiteData->m_oGraphSensorList.m_iPaperX; // 图形区X方向尺寸
m_iPaperY = m_pSiteData->m_oGraphSensorList.m_iPaperY; // 图形区Y方向尺寸
m_iGridX = m_pSiteData->m_oGraphSensorList.m_iGridX; // 单元格X方向尺寸
m_iGridY = m_pSiteData->m_oGraphSensorList.m_iGridY; // 单元格Y方向尺寸
m_iGridXPre = m_iGridX; // 单元格X方向尺寸,上一次
m_iGridYPre = m_iGridY; // 单元格Y方向尺寸,上一次
m_fZoomRate = 1.0; // 放大倍数
m_oPointScrollPos.SetPoint(0, 0); // 滚动条位置
m_oPointBase.SetPoint(0, 0); // 鼠标键按下时鼠标点
m_oPointLast.SetPoint(0, 0); // 鼠标键释放时鼠标点
m_bMouseDownLeft = false; // 鼠标左键是否按下
m_bMouseDownMiddle = false; // 鼠标中间键是否按下
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
m_strAbsoluteSpread = "all"; // 选中区域对应的绝对排列
m_oSelectAreaPoint.SetRectEmpty(); // 鼠标选中区域位置,单位像素
m_oSelectAreaIndex.SetRectEmpty(); // 鼠标中间键选中区域位置,单位单元格
m_iSelectUnitColumnIndex = -1; // 选中单元列索引
m_iSelectUnitRowIndex = -1; // 选中单元行索引
}
/**
* 响应设置测线数量
* @param void
* @return void
*/
void CSeismonitorGraphView::OnSetLineCount()
{
CSeismonitorGraphChildFrame* pParentFrame = (CSeismonitorGraphChildFrame*)GetParentFrame();
pParentFrame->OnSetLineCount(m_pSiteData->m_oGraphSensorList.m_uiRowCount);
}
// 加载现场数据
void CSeismonitorGraphView::OnLoadSiteData()
{
// 现场数据对象初始化
OnSiteDataInit();
// 响应设置测线数量
OnSetLineCount();
}
// 重新加载现场数据
void CSeismonitorGraphView::OnReloadSiteDataCMD()
{
// 现场数据对象初始化
OnSiteDataInit();
// 响应设置测线数量
OnSetLineCount();
// 绘图前设置绘图参数
SetupPageSize();
// 设置滚动条新位置
ScrollToPosition(m_oPointScrollPos);
Invalidate(TRUE);
}
// 绘图前设置绘图参数
void CSeismonitorGraphView::SetupPageSize()
{
CSize sizeTotal;
// TODO: 计算此视图的合计大小
sizeTotal.cx = m_iPaperX + m_pSiteData->m_oGraphSensorList.m_iPaperHeadLeft * 2;
sizeTotal.cy = m_iPaperY + m_pSiteData->m_oGraphSensorList.m_iPaperHeadTop * 2;
SetScrollSizes(MM_TEXT, sizeTotal);
}
// 放大
void CSeismonitorGraphView::OnZoomIn()
{
float fGridXPre = (float)m_iGridXPre;
float fGridYPre = (float)m_iGridYPre;
m_fZoomRate = 2.0; // 放大倍数
// 缩放图形
OnZoomGraph();
// 得到滚动条位置
m_oPointScrollPos = GetScrollPosition();
float fZoomRateX = m_iGridX / fGridXPre;
float fZoomRateY = m_iGridY / fGridYPre;
m_oPointScrollPos.x = (int)((float)(m_oPointScrollPos.x - m_pSiteData->m_oGraphSensorList.m_iPaperHeadLeft) * fZoomRateX) + m_pSiteData->m_oGraphSensorList.m_iPaperHeadLeft;
m_oPointScrollPos.y = (int)((float)(m_oPointScrollPos.y - m_pSiteData->m_oGraphSensorList.m_iPaperHeadTop) * fZoomRateY) + m_pSiteData->m_oGraphSensorList.m_iPaperHeadTop;
// 绘图前设置绘图参数
SetupPageSize();
// 设置滚动条新位置
ScrollToPosition(m_oPointScrollPos);
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
m_strAbsoluteSpread = "all"; // 选中区域对应的绝对排列
Invalidate(TRUE);
}
/**
* 左键拖放出选择框,框内区域局部放大
* @param void
* @return void
*/
void CSeismonitorGraphView::OnZoomInDrag()
{
float fWidthDrag= (float)m_oSelectAreaPoint.Width();
float fGridXPre = (float)m_iGridXPre;
float fGridYPre = (float)m_iGridYPre;
CRect oRect;
GetClientRect(&oRect);
float fWidthClient = (float)oRect.Width();
m_fZoomRate = fWidthClient / fWidthDrag;
// 缩放图形
OnZoomGraph();
// 得到滚动条位置
m_oPointScrollPos.x = m_oSelectAreaPoint.left;
m_oPointScrollPos.y = m_oSelectAreaPoint.top;
float fZoomRateX = m_iGridX / fGridXPre;
float fZoomRateY = m_iGridY / fGridYPre;
m_oPointScrollPos.x = (int)((float)m_oPointScrollPos.x * fZoomRateX) + m_pSiteData->m_oGraphSensorList.m_iPaperHeadLeft;
m_oPointScrollPos.y = (int)((float)m_oPointScrollPos.y * fZoomRateY) + m_pSiteData->m_oGraphSensorList.m_iPaperHeadTop;
if((m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) <= oRect.Height())
{
m_oPointScrollPos.y = 0;
}
else
{
if(m_oPointScrollPos.y > ((m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) - oRect.Height()))
{
m_oPointScrollPos.y = (m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) - oRect.Height();
}
}
// 绘图前设置绘图参数
SetupPageSize();
// 设置滚动条新位置
ScrollToPosition(m_oPointScrollPos);
Invalidate(TRUE);
}
/**
* 导航局部放大
* @param float fZoomRate 放大倍数
* @param float fRateX 基准点X
* @param float fRateY 基准点Y
* @return void
*/
void CSeismonitorGraphView::OnZoomInNavigater(float fZoomRate, float fRateX, float fRateY)
{
// 现场数据对象初始化
OnSiteDataInit();
// 绘图前设置绘图参数
SetupPageSize();
// 设置滚动条新位置
ScrollToPosition(m_oPointScrollPos);
// 判断:放大系数大于1.0
if((fZoomRate > 1.01) || (fRateY > 0.01))
{
CRect oRect;
GetClientRect(&oRect);
m_fZoomRate = fZoomRate;
// 缩放图形
OnZoomGraph();
m_oPointScrollPos.x = (int)((float)m_iPaperX * fRateX) + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadLeft;
m_oPointScrollPos.y = (int)((float)m_iPaperX * fRateY) + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop;
if((m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) <= oRect.Height())
{
m_oPointScrollPos.y = 0;
}
else
{
if(m_oPointScrollPos.y > ((m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) - oRect.Height()))
{
m_oPointScrollPos.y = (m_iPaperY + m_pSiteData->m_oGraphInstrumentList.m_iPaperHeadTop * 2) - oRect.Height();
}
}
// 绘图前设置绘图参数
SetupPageSize();
// 设置滚动条新位置
ScrollToPosition(m_oPointScrollPos);
}
Invalidate(TRUE);
}
// 缩小
void CSeismonitorGraphView::OnZoomOut()
{
m_fZoomRate = 0.5; // 放大倍数
// 缩放图形
OnZoomGraph();
// 绘图前设置绘图参数
SetupPageSize();
m_bDrawSelectArea = false; // 是否画鼠标中间键选中区域位置
m_strAbsoluteSpread = "all"; // 选中区域对应的绝对排列
Invalidate(TRUE);
}
/**
* 缩放图形
* @param void
* @return void
*/
void CSeismonitorGraphView::OnZoomGraph()
{
m_iGridX = (int)((float)m_iGridX * m_fZoomRate); // 单元格X方向尺寸
m_iGridY = (int)((float)m_iGridY * m_fZoomRate); // 单元格Y方向尺寸
if(m_iGridX > m_pSiteData->m_oGraphSensorList.m_iGridXMax)
{
m_iGridX = m_pSiteData->m_oGraphSensorList.m_iGridXMax;
}
if(m_iGridY > m_pSiteData->m_oGraphSensorList.m_iGridYMax)
{
m_iGridY = m_pSiteData->m_oGraphSensorList.m_iGridYMax;
}
if(m_iGridX < m_pSiteData->m_oGraphSensorList.m_iGridXMin)
{
m_iGridX = m_pSiteData->m_oGraphSensorList.m_iGridXMin;
}
if(m_iGridY < m_pSiteData->m_oGraphSensorList.m_iGridYMin)
{
m_iGridY = m_pSiteData->m_oGraphSensorList.m_iGridYMin;
}
m_iPaperX = (m_pSiteData->m_oGraphSensorList.m_uiColumnCount - 1) * m_iGridX; // X方向尺寸
m_iPaperY = (m_pSiteData->m_oGraphSensorList.m_uiRowCount - 1) * m_iGridY; // Y方向尺寸
m_iGridXPre = m_iGridX; // 单元格X方向尺寸,上一次
m_iGridYPre = m_iGridY; // 单元格Y方向尺寸,上一次
}
/**
* 得到点坐标对应的单元
* @param CPoint* pPoint 当前鼠标点
* @return void
*/
void CSeismonitorGraphView::GetUnitUnderPoint(CPoint* pPoint)
{
m_iSelectUnitColumnIndex = -1; // 选中单元列索引
m_iSelectUnitRowIndex = -1; // 选中单元行索引
int iColumnIndex; // 鼠标点靠近的列索引
int iRowIndex; // 鼠标点靠近的行索引
int iAreaColumnndex; // 鼠标点所在区域的列索引
int iAreaRowIndex; // 鼠标点所在区域的行索引
int iUnitWidth; // 图形单元宽度
int iUnitHight; // 图形单元高度
int iUnitSizeMode; // 图形单元尺寸模式;1-最小;2-正常;3-最大
// 得到图形单元尺寸
m_pSiteData->m_oGraphSensorList.GetUnitSize(m_iGridX, iUnitWidth, iUnitHight, iUnitSizeMode);
iColumnIndex = (int)((float)pPoint->x / (float)m_iGridX + 0.5); // 鼠标点靠近的列索引
iRowIndex = (int)((float)pPoint->y / (float)m_iGridY + 0.5); // 鼠标点靠近的列索引
iAreaColumnndex = (int)((float)pPoint->x / (float)m_iGridX); // 鼠标点所在区域的列索引
iAreaRowIndex = (int)((float)pPoint->y / (float)m_iGridY); // 鼠标点所在区域的行索引
if(iColumnIndex == iAreaColumnndex) // 区域左
{
if(iRowIndex == iAreaRowIndex) // 区域左上
{
// 在单元右下角范围内
if((pPoint->x <= iColumnIndex * m_iGridX + iUnitWidth / 2) && (pPoint->y <= iRowIndex * m_iGridY + iUnitHight / 2))
{
m_iSelectUnitColumnIndex = iColumnIndex; // 选中单元列索引
m_iSelectUnitRowIndex = iRowIndex; // 选中单元行索引
}
}
else if(iRowIndex == iAreaRowIndex + 1) // 区域左下
{
// 在单元右上角范围内
if((pPoint->x <= iColumnIndex * m_iGridX + iUnitWidth / 2) && (pPoint->y >= iRowIndex * m_iGridY - iUnitHight / 2))
{
m_iSelectUnitColumnIndex = iColumnIndex; // 选中单元列索引
m_iSelectUnitRowIndex = iRowIndex; // 选中单元行索引
}
}
}
else if(iColumnIndex == iAreaColumnndex + 1) // 区域右
{
if(iRowIndex == iAreaRowIndex) // 区域右上
{
// 在单元左下角范围内
if((pPoint->x >= iColumnIndex * m_iGridX - iUnitWidth / 2) && (pPoint->y <= iRowIndex * m_iGridY + iUnitHight / 2))
{
m_iSelectUnitColumnIndex = iColumnIndex; // 选中单元列索引
m_iSelectUnitRowIndex = iRowIndex; // 选中单元行索引
}
}
else if(iRowIndex == iAreaRowIndex + 1) // 区域右下
{
// 在单元左上角范围内
if((pPoint->x >= iColumnIndex * m_iGridX - iUnitWidth / 2) && (pPoint->y >= iRowIndex * m_iGridY - iUnitHight / 2))
{
m_iSelectUnitColumnIndex = iColumnIndex; // 选中单元列索引
m_iSelectUnitRowIndex = iRowIndex; // 选中单元行索引
}
}
}
}
/**
* 得到选中的区域
* @param void
* @return void
*/
bool CSeismonitorGraphView::GetSelectAreaPoint()
{
m_oSelectAreaPoint.left = m_oPointBase.x;
m_oSelectAreaPoint.top = m_oPointBase.y;
m_oSelectAreaPoint.right = m_oPointLast.x;
m_oSelectAreaPoint.bottom = m_oPointLast.y;
m_oSelectAreaPoint.NormalizeRect();
float fWidthDrag= (float)m_oSelectAreaPoint.Width();
if(fWidthDrag < 50.0)
{
return false;
}
if(m_oSelectAreaPoint.left < 0)
{
m_oSelectAreaPoint.left = 0;
}
if(m_oSelectAreaPoint.top < 0)
{
m_oSelectAreaPoint.top = 0;
}
if(m_oSelectAreaPoint.right > m_iPaperX)
{
m_oSelectAreaPoint.right = m_iPaperX;
}
if(m_oSelectAreaPoint.bottom > m_iPaperY)
{
m_oSelectAreaPoint.bottom = m_iPaperY;
}
return true;
}
/**
* 得到选中区域的行坐标和列坐标区域
* @param void
* @return void
*/
void CSeismonitorGraphView::GetSelectAreaIndex()
{
int iAreaColumnIndex; // 鼠标点所在区域的列索引
int iAreaRowIndex; // 鼠标点所在区域的行索引
iAreaColumnIndex = (int)((float)m_oSelectAreaPoint.left / (float)m_iGridX); // 鼠标点所在区域的列索引
iAreaRowIndex = (int)((float)m_oSelectAreaPoint.top / (float)m_iGridY); // 鼠标点所在区域的行索引
m_oSelectAreaIndex.left = iAreaColumnIndex; // 鼠标中间键选中区域位置
m_oSelectAreaIndex.top = iAreaRowIndex; // 鼠标中间键选中区域位置
if(m_oSelectAreaPoint.left > 0)
{
m_oSelectAreaIndex.left = iAreaColumnIndex + 1; // 鼠标中间键选中区域位置
}
if(m_oSelectAreaPoint.top > 0)
{
m_oSelectAreaIndex.top = iAreaRowIndex + 1; // 鼠标中间键选中区域位置
}
iAreaColumnIndex = (int)((float)m_oSelectAreaPoint.right / (float)m_iGridX); // 鼠标点所在区域的列索引
iAreaRowIndex = (int)((float)m_oSelectAreaPoint.bottom / (float)m_iGridY); // 鼠标点所在区域的行索引
m_oSelectAreaIndex.right = iAreaColumnIndex; // 鼠标中间键选中区域位置
m_oSelectAreaIndex.bottom = iAreaRowIndex; // 鼠标中间键选中区域位置
}
/**
* 把选中区域转换为绝对排列字符串
* @param void
* @return void
*/
void CSeismonitorGraphView::ConvertSelectAreaToAbsoluteSpreadString()
{
// 把选中区域转换为绝对排列字符串
m_strAbsoluteSpread = m_pSiteData->m_oGraphSensorList.ConvertSelectAreaToAbsoluteSpreadString(&m_oSelectAreaIndex);
}
/**
* 判断点是否在绘图区域内
* @param CPoint* pPoint 鼠标点
* @return void
*/
bool CSeismonitorGraphView::JudgeIfPointInPaper(CPoint* pPoint)
{
int iUnitWidth; // 图形单元宽度
int iUnitHight; // 图形单元高度
int iUnitSizeMode; // 图形单元尺寸模式;1-最小;2-正常;3-最大
// 得到图形单元尺寸
m_pSiteData->m_oGraphSensorList.GetUnitSize(m_iGridX, iUnitWidth, iUnitHight, iUnitSizeMode);
if((pPoint->x >= (-iUnitWidth / 2)) && (pPoint->x <= (m_iPaperX + (iUnitWidth / 2))) && (pPoint->y >= (-iUnitHight / 2)) && (pPoint->y <= (m_iPaperY + (iUnitHight / 2))))
{
return true;
}
return false;
}
/**
* 显示单元的测线号和测点号
* @param unsigned int uiNbLine 测线号
* @param unsigned int uiNbPoint 测点号
* @return void
*/
void CSeismonitorGraphView::OnShowUnitPosition(unsigned int uiNbLine, unsigned int uiNbPoint)
{
CSeismonitorGraphChildFrame* pParentFrame = (CSeismonitorGraphChildFrame*)GetParentFrame();
pParentFrame->OnShowUnitPosition(uiNbLine, uiNbPoint);
}
/**
* 在浮动窗口中显示测试值
* @param CChannelSetupData* pChannelSetupData 检波器
* @param CPoint pointClient 鼠标点
* @return void
*/
void CSeismonitorGraphView::OnShowTestValueInFloatWindow(CChannelSetupData* pChannelSetupData, CPoint pointClient)
{
CSeismonitorGraphChildFrame* pParentFrame = (CSeismonitorGraphChildFrame*)GetParentFrame();
CString strTestUnit = "";
CString strTestValue = "";
CString strValue = "";
strTestUnit = m_pSiteData->GetSensorTestTypeUnitStringByID(pParentFrame->m_uiTestType);
strTestValue = pChannelSetupData->GetTestResultStringByTestType(pParentFrame->m_uiTestType, strTestUnit);
strValue.Format("%d %s", pChannelSetupData->m_uiSN, strTestValue);
if("" != strValue)
{
m_wndStaticFloat.SetWindowText(strValue);
m_wndStaticFloat.MoveWindow(pointClient.x + 20, pointClient.y, 200, 20);
m_wndStaticFloat.ShowWindow(SW_SHOW);
}
}
/**
* 响应显示属性值
* @param unsigned int uiIndex 检波器索引号
* @return void
*/
void CSeismonitorGraphView::OnShowProperty(unsigned int uiIndex)
{
CSeismonitorGraphChildFrame* pParentFrame = (CSeismonitorGraphChildFrame*)GetParentFrame();
pParentFrame->OnShowProperty(uiIndex);
}
// 画鼠标中间键选中区域
void CSeismonitorGraphView::DrawSelectArea(CDC* pDC)
{
if(true == m_bDrawSelectArea) // 是否画鼠标中间键选中区域位置
{
CPen oPen;
CPen* pOldPen;
CBrush oBrush;
CBrush* pOldPenBrush;
oPen.CreatePen(PS_SOLID, 0, RGB(255, 0, 0));
oBrush.CreateSolidBrush(RGB(255, 0, 0));
pOldPen = pDC->SelectObject(&oPen);
pOldPenBrush = pDC->SelectObject(&oBrush);
pDC->FillRect(&m_oSelectAreaPoint, &oBrush);
pDC->Rectangle(&m_oSelectAreaPoint);
pDC->SelectObject(pOldPen);
pDC->SelectObject(pOldPenBrush);
}
}
// 为新的测试数据刷新显示
void CSeismonitorGraphView::OnRefreshForNewTestValue()
{
int iUnitWidth; // 图形单元宽度
int iUnitHight; // 图形单元高度
int iUnitSizeMode; // 图形单元尺寸模式;1-最小;2-正常;3-最大
// 得到图形单元尺寸
m_pSiteData->m_oGraphSensorList.GetUnitSize(m_iGridX, iUnitWidth, iUnitHight, iUnitSizeMode);
unsigned int uiIP = 0;
CChannelSetupData* pChannelSetupData = NULL;
CGraphSensorData* m_pGraphSensor = NULL;
CRect oRect;
int iCenterX;
int iCenterY;
CClientDC oDC(this);
OnPrepareDC(&oDC, NULL);
while(m_pSiteData->m_olsIPSeismonitor.GetCount() > 0)
{
uiIP = m_pSiteData->m_olsIPSeismonitor.RemoveHead();
if(TRUE == m_pSiteData->m_oChannelList.GetChannelFromMap(uiIP, pChannelSetupData))
{
m_pGraphSensor = &m_pSiteData->m_oGraphSensorList.m_pArrayGraphSensor[pChannelSetupData->m_uiIndex];
iCenterX = m_pGraphSensor->m_iPosX * m_iGridX;
iCenterY = m_pGraphSensor->m_iPosY * m_iGridY;
oRect.left = iCenterX - iUnitWidth / 2;
oRect.top = iCenterY - iUnitHight / 2;
oRect.right = oRect.left + iUnitWidth;
oRect.bottom = oRect.top + iUnitHight;
oDC.LPtoDP(&oRect);
InvalidateRect(&oRect, TRUE);
}
}
} | [
"chengxianming1981@gmail.com"
] | chengxianming1981@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.