text
stringlengths 5
1.04M
|
|---|
//
// FILE: dht.cpp
// AUTHOR: Rob Tillaart
// VERSION: 0.1.20
// PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
// URL: http://arduino.cc/playground/Main/DHTLib
//
// HISTORY:
// 0.1.20 Reduce footprint (34 bytes) by using int8_t as error codes.
// (thanks to chaveiro)
// 0.1.19 masking error for DHT11 - FIXED (thanks Richard for noticing)
// 0.1.18 version 1.16/17 broke the DHT11 - FIXED
// 0.1.17 replaced micros() with adaptive loopcount
// removed DHTLIB_INVALID_VALUE
// added DHTLIB_ERROR_CONNECT
// added DHTLIB_ERROR_ACK_L DHTLIB_ERROR_ACK_H
// 0.1.16 masking unused bits (less errors); refactored bits[]
// 0.1.15 reduced # micros calls 2->1 in inner loop.
// 0.1.14 replace digital read with faster (~3x) code
// => more robust low MHz machines.
//
// 0.1.13 fix negative temperature
// 0.1.12 support DHT33 and DHT44 initial version
// 0.1.11 renamed DHTLIB_TIMEOUT
// 0.1.10 optimized faster WAKEUP + TIMEOUT
// 0.1.09 optimize size: timeout check + use of mask
// 0.1.08 added formula for timeout based upon clockspeed
// 0.1.07 added support for DHT21
// 0.1.06 minimize footprint (2012-12-27)
// 0.1.05 fixed negative temperature bug (thanks to Roseman)
// 0.1.04 improved readability of code using DHTLIB_OK in code
// 0.1.03 added error values for temp and humidity when read failed
// 0.1.02 added error codes
// 0.1.01 added support for Arduino 1.0, fixed typos (31/12/2011)
// 0.1.00 by Rob Tillaart (01/04/2011)
//
// inspired by DHT11 library
//
// Released to the public domain
//
#include "dht.h"
/////////////////////////////////////////////////////
//
// PUBLIC
//
int8_t dht::read11(uint8_t pin)
{
// READ VALUES
int8_t result = _readSensor(pin, DHTLIB_DHT11_WAKEUP, DHTLIB_DHT11_LEADING_ZEROS);
// these bits are always zero, masking them reduces errors.
bits[0] &= 0x7F;
bits[2] &= 0x7F;
// CONVERT AND STORE
humidity = bits[0]; // bits[1] == 0;
temperature = bits[2]; // bits[3] == 0;
// TEST CHECKSUM
// bits[1] && bits[3] both 0
uint8_t sum = bits[0] + bits[2];
if (bits[4] != sum)
{
return DHTLIB_ERROR_CHECKSUM;
}
return result;
}
int8_t dht::read(uint8_t pin)
{
// READ VALUES
int8_t result = _readSensor(pin, DHTLIB_DHT_WAKEUP, DHTLIB_DHT_LEADING_ZEROS);
// these bits are always zero, masking them reduces errors.
bits[0] &= 0x03;
bits[2] &= 0x83;
// CONVERT AND STORE
humidity = word(bits[0], bits[1]) * 0.1;
temperature = word(bits[2] & 0x7F, bits[3]) * 0.1;
if (bits[2] & 0x80) // negative temperature
{
temperature = -temperature;
}
// TEST CHECKSUM
uint8_t sum = bits[0] + bits[1] + bits[2] + bits[3];
if (bits[4] != sum)
{
return DHTLIB_ERROR_CHECKSUM;
}
return result;
}
/////////////////////////////////////////////////////
//
// PRIVATE
//
int8_t dht::_readSensor(uint8_t pin, uint8_t wakeupDelay, uint8_t leadingZeroBits)
{
// INIT BUFFERVAR TO RECEIVE DATA
uint8_t mask = 128;
uint8_t idx = 0;
uint8_t data = 0;
uint8_t state = LOW;
uint8_t pstate = LOW;
uint16_t zeroLoop = DHTLIB_TIMEOUT;
uint16_t delta = 0;
leadingZeroBits = 40 - leadingZeroBits; // reverse counting...
// replace digitalRead() with Direct Port Reads.
// reduces footprint ~100 bytes => portability issue?
// direct port read is about 3x faster
uint8_t bit = digitalPinToBitMask(pin);
uint8_t port = digitalPinToPort(pin);
volatile uint8_t *PIR = portInputRegister(port);
// REQUEST SAMPLE
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW); // T-be
delay(wakeupDelay);
digitalWrite(pin, HIGH); // T-go
pinMode(pin, INPUT);
uint16_t loopCount = DHTLIB_TIMEOUT * 2; // 200uSec max
// while(digitalRead(pin) == HIGH)
while ((*PIR & bit) != LOW )
{
if (--loopCount == 0) return DHTLIB_ERROR_CONNECT;
}
// GET ACKNOWLEDGE or TIMEOUT
loopCount = DHTLIB_TIMEOUT;
// while(digitalRead(pin) == LOW)
while ((*PIR & bit) == LOW ) // T-rel
{
if (--loopCount == 0) return DHTLIB_ERROR_ACK_L;
}
loopCount = DHTLIB_TIMEOUT;
// while(digitalRead(pin) == HIGH)
while ((*PIR & bit) != LOW ) // T-reh
{
if (--loopCount == 0) return DHTLIB_ERROR_ACK_H;
}
loopCount = DHTLIB_TIMEOUT;
// READ THE OUTPUT - 40 BITS => 5 BYTES
for (uint8_t i = 40; i != 0; )
{
// WAIT FOR FALLING EDGE
state = (*PIR & bit);
if (state == LOW && pstate != LOW)
{
if (i > leadingZeroBits) // DHT22 first 6 bits are all zero !! DHT11 only 1
{
zeroLoop = min(zeroLoop, loopCount);
delta = (DHTLIB_TIMEOUT - zeroLoop)/4;
}
else if ( loopCount <= (zeroLoop - delta) ) // long -> one
{
data |= mask;
}
mask >>= 1;
if (mask == 0) // next byte
{
mask = 128;
bits[idx] = data;
idx++;
data = 0;
}
// next bit
--i;
// reset timeout flag
loopCount = DHTLIB_TIMEOUT;
}
pstate = state;
// Check timeout
if (--loopCount == 0)
{
return DHTLIB_ERROR_TIMEOUT;
}
}
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
return DHTLIB_OK;
}
//
// END OF FILE
//
|
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int m,n,s;
cin>>m>>n;
if(m>=1&&n>=1&&m<=16&&n<=16)
{
s=abs((m*n)/2);
}
cout<<s;
}
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "platform/v8_inspector/V8StringUtil.h"
#include "platform/inspector_protocol/String16.h"
#include "platform/v8_inspector/V8DebuggerImpl.h"
#include "platform/v8_inspector/V8InspectorSessionImpl.h"
#include "platform/v8_inspector/V8Regex.h"
#include "platform/v8_inspector/public/V8ContentSearchUtil.h"
#include "platform/v8_inspector/public/V8ToProtocolValue.h"
namespace blink {
namespace {
String16 findMagicComment(const String16& content, const String16& name, bool multiline, bool* deprecated)
{
DCHECK(name.find("=") == kNotFound);
if (deprecated)
*deprecated = false;
unsigned length = content.length();
unsigned nameLength = name.length();
size_t pos = length;
size_t equalSignPos = 0;
size_t closingCommentPos = 0;
while (true) {
pos = content.reverseFind(name, pos);
if (pos == kNotFound)
return String16();
// Check for a /\/[\/*][@#][ \t]/ regexp (length of 4) before found name.
if (pos < 4)
return String16();
pos -= 4;
if (content[pos] != '/')
continue;
if ((content[pos + 1] != '/' || multiline)
&& (content[pos + 1] != '*' || !multiline))
continue;
if (content[pos + 2] != '#' && content[pos + 2] != '@')
continue;
if (content[pos + 3] != ' ' && content[pos + 3] != '\t')
continue;
equalSignPos = pos + 4 + nameLength;
if (equalSignPos < length && content[equalSignPos] != '=')
continue;
if (multiline) {
closingCommentPos = content.find("*/", equalSignPos + 1);
if (closingCommentPos == kNotFound)
return String16();
}
break;
}
if (deprecated && content[pos + 2] == '@')
*deprecated = true;
DCHECK(equalSignPos);
DCHECK(!multiline || closingCommentPos);
size_t urlPos = equalSignPos + 1;
String16 match = multiline
? content.substring(urlPos, closingCommentPos - urlPos)
: content.substring(urlPos);
size_t newLine = match.find("\n");
if (newLine != kNotFound)
match = match.substring(0, newLine);
match = match.stripWhiteSpace();
String16 disallowedChars("\"' \t");
for (unsigned i = 0; i < match.length(); ++i) {
if (disallowedChars.find(match[i]) != kNotFound)
return "";
}
return match;
}
String16 createSearchRegexSource(const String16& text)
{
String16Builder result;
String16 specials("[](){}+-*.,?\\^$|");
for (unsigned i = 0; i < text.length(); i++) {
if (specials.find(text[i]) != kNotFound)
result.append('\\');
result.append(text[i]);
}
return result.toString();
}
std::unique_ptr<std::vector<unsigned>> lineEndings(const String16& text)
{
std::unique_ptr<std::vector<unsigned>> result(new std::vector<unsigned>());
unsigned start = 0;
while (start < text.length()) {
size_t lineEnd = text.find('\n', start);
if (lineEnd == kNotFound)
break;
result->push_back(static_cast<unsigned>(lineEnd));
start = lineEnd + 1;
}
result->push_back(text.length());
return result;
}
std::vector<std::pair<int, String16>> scriptRegexpMatchesByLines(const V8Regex& regex, const String16& text)
{
std::vector<std::pair<int, String16>> result;
if (text.isEmpty())
return result;
std::unique_ptr<std::vector<unsigned>> endings(lineEndings(text));
unsigned size = endings->size();
unsigned start = 0;
for (unsigned lineNumber = 0; lineNumber < size; ++lineNumber) {
unsigned lineEnd = endings->at(lineNumber);
String16 line = text.substring(start, lineEnd - start);
if (line.endsWith('\r'))
line = line.substring(0, line.length() - 1);
int matchLength;
if (regex.match(line, 0, &matchLength) != -1)
result.push_back(std::pair<int, String16>(lineNumber, line));
start = lineEnd + 1;
}
return result;
}
std::unique_ptr<protocol::Debugger::SearchMatch> buildObjectForSearchMatch(int lineNumber, const String16& lineContent)
{
return protocol::Debugger::SearchMatch::create()
.setLineNumber(lineNumber)
.setLineContent(lineContent)
.build();
}
std::unique_ptr<V8Regex> createSearchRegex(V8DebuggerImpl* debugger, const String16& query, bool caseSensitive, bool isRegex)
{
String16 regexSource = isRegex ? query : createSearchRegexSource(query);
return wrapUnique(new V8Regex(debugger, regexSource, caseSensitive));
}
} // namespace
v8::Local<v8::String> toV8String(v8::Isolate* isolate, const String16& string)
{
if (string.isEmpty())
return v8::String::Empty(isolate);
return v8::String::NewFromTwoByte(isolate, reinterpret_cast<const uint16_t*>(string.characters16()), v8::NewStringType::kNormal, string.length()).ToLocalChecked();
}
v8::Local<v8::String> toV8StringInternalized(v8::Isolate* isolate, const String16& string)
{
if (string.isEmpty())
return v8::String::Empty(isolate);
return v8::String::NewFromTwoByte(isolate, reinterpret_cast<const uint16_t*>(string.characters16()), v8::NewStringType::kInternalized, string.length()).ToLocalChecked();
}
String16 toProtocolString(v8::Local<v8::String> value)
{
if (value.IsEmpty() || value->IsNull() || value->IsUndefined())
return String16();
std::unique_ptr<UChar[]> buffer(new UChar[value->Length()]);
value->Write(reinterpret_cast<uint16_t*>(buffer.get()), 0, value->Length());
return String16(buffer.get(), value->Length());
}
String16 toProtocolStringWithTypeCheck(v8::Local<v8::Value> value)
{
if (value.IsEmpty() || !value->IsString())
return String16();
return toProtocolString(value.As<v8::String>());
}
namespace V8ContentSearchUtil {
String16 findSourceURL(const String16& content, bool multiline, bool* deprecated)
{
return findMagicComment(content, "sourceURL", multiline, deprecated);
}
String16 findSourceMapURL(const String16& content, bool multiline, bool* deprecated)
{
return findMagicComment(content, "sourceMappingURL", multiline, deprecated);
}
std::unique_ptr<protocol::Array<protocol::Debugger::SearchMatch>> searchInTextByLines(V8InspectorSession* session, const String16& text, const String16& query, const bool caseSensitive, const bool isRegex)
{
std::unique_ptr<protocol::Array<protocol::Debugger::SearchMatch>> result = protocol::Array<protocol::Debugger::SearchMatch>::create();
std::unique_ptr<V8Regex> regex = createSearchRegex(static_cast<V8InspectorSessionImpl*>(session)->debugger(), query, caseSensitive, isRegex);
std::vector<std::pair<int, String16>> matches = scriptRegexpMatchesByLines(*regex.get(), text);
for (const auto& match : matches)
result->addItem(buildObjectForSearchMatch(match.first, match.second));
return result;
}
} // namespace V8ContentSearchUtil
std::unique_ptr<protocol::Value> toProtocolValue(v8::Local<v8::Context> context, v8::Local<v8::Value> value, int maxDepth)
{
if (value.IsEmpty()) {
NOTREACHED();
return nullptr;
}
if (!maxDepth)
return nullptr;
maxDepth--;
if (value->IsNull() || value->IsUndefined())
return protocol::Value::null();
if (value->IsBoolean())
return protocol::FundamentalValue::create(value.As<v8::Boolean>()->Value());
if (value->IsNumber())
return protocol::FundamentalValue::create(value.As<v8::Number>()->Value());
if (value->IsString())
return protocol::StringValue::create(toProtocolString(value.As<v8::String>()));
if (value->IsArray()) {
v8::Local<v8::Array> array = value.As<v8::Array>();
std::unique_ptr<protocol::ListValue> inspectorArray = protocol::ListValue::create();
uint32_t length = array->Length();
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> value;
if (!array->Get(context, i).ToLocal(&value))
return nullptr;
std::unique_ptr<protocol::Value> element = toProtocolValue(context, value, maxDepth);
if (!element)
return nullptr;
inspectorArray->pushValue(std::move(element));
}
return std::move(inspectorArray);
}
if (value->IsObject()) {
std::unique_ptr<protocol::DictionaryValue> jsonObject = protocol::DictionaryValue::create();
v8::Local<v8::Object> object = v8::Local<v8::Object>::Cast(value);
v8::Local<v8::Array> propertyNames;
if (!object->GetPropertyNames(context).ToLocal(&propertyNames))
return nullptr;
uint32_t length = propertyNames->Length();
for (uint32_t i = 0; i < length; i++) {
v8::Local<v8::Value> name;
if (!propertyNames->Get(context, i).ToLocal(&name))
return nullptr;
// FIXME(yurys): v8::Object should support GetOwnPropertyNames
if (name->IsString()) {
v8::Maybe<bool> hasRealNamedProperty = object->HasRealNamedProperty(context, v8::Local<v8::String>::Cast(name));
if (!hasRealNamedProperty.IsJust() || !hasRealNamedProperty.FromJust())
continue;
}
v8::Local<v8::String> propertyName;
if (!name->ToString(context).ToLocal(&propertyName))
continue;
v8::Local<v8::Value> property;
if (!object->Get(context, name).ToLocal(&property))
return nullptr;
std::unique_ptr<protocol::Value> propertyValue = toProtocolValue(context, property, maxDepth);
if (!propertyValue)
return nullptr;
jsonObject->setValue(toProtocolString(propertyName), std::move(propertyValue));
}
return std::move(jsonObject);
}
NOTREACHED();
return nullptr;
}
} // namespace blink
|
// -*- mode: C++ -*-
//
// Copyright (c) 2007, 2008, 2009, 2010, 2011, 2015, 2017 The University of Utah
// All rights reserved.
//
// This file is part of `csmith', a random generator of C programs.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// This file was derived from a random program generator written by Bryan
// Turner. The attributions in that file was:
//
// Random Program Generator
// Bryan Turner (bryan.turner@pobox.com)
// July, 2005
//
// ---------------------------------------
// Platform-Specific code to get a unique seed value (usually from the tick counter, etc)
//
#if HAVE_CONFIG_H
# include <config.h>
#endif
#include "platform.h"
#include <stdlib.h>
#if HAVE_BSD_STDLIB_H
# include <bsd/stdlib.h>
#endif
///////////////////////////////////////////////////////////////////////////////
// If this platform does not have `arc4random_buf', define a static,
// platform-specific function `read_time' so that we can set the random seed
// from the current time.
//
#ifndef HAVE_ARC4RANDOM_BUF
# if defined(__powerpc__) || defined(__powerpc64__) || defined(__powerpc64le__)
static inline unsigned long read_time(void)
{
unsigned long a;
asm volatile("mftb %0" : "=r" (a));
return a;
}
# elif defined(_MSC_VER) && defined(_M_IX86)
static unsigned __int64 read_time(void)
{
unsigned l, h;
_asm {
rdtsc
mov l, eax
mov h, edx
}
return (h << 32) + l;
}
# elif defined(__s390__)
static unsigned long long read_time(void)
{
unsigned long long clk;
asm volatile("stckf %0" : "=Q" (clk) : : "cc");
return clk;
}
# elif defined(__i386__) || defined(__x86_64__)
static long long read_time(void)
{
long long l;
asm volatile("rdtsc\n\t"
: "=A" (l)
);
return l;
}
# else
# include <time.h>
static long long read_time(void)
{
time_t t = time(NULL);
return t;
}
# endif
#endif // HAVE_ARC4RANDOM_BUF
#if HAVE_ARC4RANDOM_BUF
unsigned long platform_gen_seed()
{
unsigned long seed;
arc4random_buf(&seed, sizeof seed);
return seed;
}
#else
unsigned long platform_gen_seed()
{
return (long) read_time();
}
#endif
//////////// platform specific mkdir /////////////////
#ifndef WIN32
# include <sys/stat.h>
# include <unistd.h>
#else
# include <direct.h>
#endif
#include <cerrno>
bool create_dir(const char *dir)
{
#ifndef WIN32
if (mkdir(dir, 0770) == -1) {
#else
if (mkdir(dir) == -1) {
#endif
return (errno == EEXIST) ? true : false;
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// Local Variables:
// c-basic-offset: 4
// tab-width: 4
// End:
// End of file.
|
//
// UserActivityLoggerScriptingInterface.h
// libraries/networking/src
//
// Created by Ryan Huffman on 6/06/16.
// Copyright 2016 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "UserActivityLoggerScriptingInterface.h"
#include "UserActivityLogger.h"
void UserActivityLoggerScriptingInterface::enabledEdit() {
doLogAction("enabled_edit");
}
void UserActivityLoggerScriptingInterface::openedTablet(bool visibleToOthers) {
doLogAction("opened_tablet", { { "visible_to_others", visibleToOthers } });
}
void UserActivityLoggerScriptingInterface::closedTablet() {
doLogAction("closed_tablet");
}
void UserActivityLoggerScriptingInterface::openedMarketplace() {
doLogAction("opened_marketplace");
}
void UserActivityLoggerScriptingInterface::toggledAway(bool isAway) {
doLogAction("toggled_away", { { "is_away", isAway } });
}
void UserActivityLoggerScriptingInterface::tutorialProgress( QString stepName, int stepNumber, float secondsToComplete,
float tutorialElapsedTime, QString tutorialRunID, int tutorialVersion, QString controllerType) {
doLogAction("tutorial_progress", {
{ "tutorial_run_id", tutorialRunID },
{ "tutorial_version", tutorialVersion },
{ "step", stepName },
{ "step_number", stepNumber },
{ "seconds_to_complete", secondsToComplete },
{ "tutorial_elapsed_seconds", tutorialElapsedTime },
{ "controller_type", controllerType }
});
}
void UserActivityLoggerScriptingInterface::palAction(QString action, QString target) {
QJsonObject payload;
payload["action"] = action;
if (target.length() > 0) {
payload["target"] = target;
}
doLogAction("pal_activity", payload);
}
void UserActivityLoggerScriptingInterface::palOpened(float secondsOpened) {
doLogAction("pal_opened", {
{ "seconds_opened", secondsOpened }
});
}
void UserActivityLoggerScriptingInterface::makeUserConnection(QString otherID, bool success, QString detailsString) {
QJsonObject payload;
payload["otherUser"] = otherID;
payload["success"] = success;
if (detailsString.length() > 0) {
payload["details"] = detailsString;
}
doLogAction("makeUserConnection", payload);
}
void UserActivityLoggerScriptingInterface::logAction(QString action, QVariantMap details) {
doLogAction(action, QJsonObject::fromVariantMap(details));
}
void UserActivityLoggerScriptingInterface::doLogAction(QString action, QJsonObject details) {
QMetaObject::invokeMethod(&UserActivityLogger::getInstance(), "logAction",
Q_ARG(QString, action),
Q_ARG(QJsonObject, details));
}
|
// Copyright (c) 2018-2019, NuoDB, Inc.
// All rights reserved.
//
// Redistribution and use permitted under the terms of the 3-clause BSD license.
#include "NuoJsResultSet.h"
#include "NuoJsErrMsg.h"
#include "NuoJsValue.h"
#include "NuoJsTypes.h"
#include "NuoJsNan.h"
#include "NuoJsNanDate.h"
#include "NuoDB.h"
namespace NuoJs
{
Nan::Persistent<Function> ResultSet::constructor;
ResultSet::ResultSet()
: Nan::ObjectWrap(), statement(nullptr), result(nullptr)
{
TRACE("ResultSet::ResultSet");
}
/* virtual */
ResultSet::~ResultSet()
{
TRACE("ResultSet::~ResultSet");
}
/* static */
NAN_MODULE_INIT(ResultSet::init)
{
TRACE("ResultSet::init");
Nan::HandleScope scope;
// prepare constructor template...
Local<FunctionTemplate> tpl = Nan::New<FunctionTemplate>(ResultSet::newInstance);
tpl->SetClassName(Nan::New("ResultSet").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// prototypes...
Nan::SetPrototypeMethod(tpl, "getRows", getRows);
Nan::SetPrototypeMethod(tpl, "close", close);
constructor.Reset(Nan::GetFunction(tpl).ToLocalChecked());
Nan::Set(target, Nan::New<v8::String>("ResultSet").ToLocalChecked(),
Nan::GetFunction(tpl).ToLocalChecked());
}
/* static */
NAN_METHOD(ResultSet::newInstance)
{
TRACE("ResultSet::newInstance");
Nan::HandleScope scope;
if (info.IsConstructCall()) {
ResultSet* obj = new ResultSet();
obj->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
Local<Function> cons = Nan::New<Function>(constructor);
info.GetReturnValue().Set(Nan::NewInstance(cons).ToLocalChecked());
}
}
/* static */
Local<Object> ResultSet::createFrom(class NuoDB::Statement* statement, Options options)
{
TRACE("ResultSet::createFrom");
Nan::EscapableHandleScope scope;
Local<Function> cons = Nan::New<Function>(ResultSet::constructor);
Local<Object> obj = Nan::NewInstance(cons).ToLocalChecked();
ResultSet* self = Nan::ObjectWrap::Unwrap<ResultSet>(obj);
self->statement = statement;
self->options = options;
return scope.Escape(obj);
}
class ResultSetCloseWorker : public Nan::AsyncWorker
{
public:
ResultSetCloseWorker(Nan::Callback* callback, ResultSet* self)
: Nan::AsyncWorker(callback), self(self)
{
TRACE("ResultSetCloseWorker::ResultSetCloseWorker");
}
virtual ~ResultSetCloseWorker()
{
TRACE("ResultSetCloseWorker::~ResultSetCloseWorker");
}
/**
* Executes on the worker thread.
* It is unsafe to access JS engine data structures on worker threads.
* All input and output MUST occur on this->.
*/
virtual void Execute()
{
TRACE("ResultSetCloseWorker::Execute");
try {
self->doClose();
} catch (std::exception& e) {
std::string message = ErrMsg::get(ErrMsgType::errFailedCloseResultSet, e.what());
SetErrorMessage(message.c_str());
}
}
/**
* Executes on the main event loop, so it's safe to access JS engine data
* structures. Called when async work is complete.
*/
virtual void HandleOKCallback()
{
TRACE("ResultSetCloseWorker::OnOK");
Nan::HandleScope scope;
Local<Value> argv[] = {
Nan::Null()
};
callback->Call(1, argv, async_resource);
}
private:
ResultSet* self;
};
/* static */
NAN_METHOD(ResultSet::close)
{
TRACE("ResultSet::close");
Nan::HandleScope scope;
ResultSet* self = Nan::ObjectWrap::Unwrap<ResultSet>(info.This());
if (!info.Length() || !info[(info.Length() - 1)]->IsFunction()) {
Nan::ThrowError("connect arg count zero, or last arg is not a function");
return;
}
Nan::Callback* callback = new Nan::Callback(info[0].As<Function>());
ResultSetCloseWorker* worker = new ResultSetCloseWorker(callback, self);
worker->SaveToPersistent("nuodb:ResultSet", info.This());
Nan::AsyncQueueWorker(worker);
}
void ResultSet::doClose()
{
TRACE("ResultSet::doClose");
if (result) {
result->close();
result = nullptr;
}
if (statement) {
statement->close();
statement = nullptr;
}
}
class GetRowsWorker : public Nan::AsyncWorker
{
public:
GetRowsWorker(Nan::Callback* callback, ResultSet* self, size_t count)
: Nan::AsyncWorker(callback), self(self), count(count)
{
TRACE("GetRowsWorker::GetRowsWorker");
}
virtual ~GetRowsWorker()
{
TRACE("GetRowsWorker::~GetRowsWorker");
}
/**
* Executes on the worker thread.
* It is unsafe to access JS engine data structures on worker threads.
* All input and output MUST occur on this->.
*/
virtual void Execute()
{
TRACE("GetRowsWorker::Execute");
try {
self->doGetRows(count);
} catch (std::exception& e) {
std::string message = ErrMsg::get(ErrMsgType::errGetRows, e.what());
SetErrorMessage(message.c_str());
}
}
/**
* Executes on the main event loop, so it's safe to access JS engine data
* structures. Called when async work is complete.
*/
virtual void HandleOKCallback()
{
TRACE("GetRowsWorker::HandleOKCallback");
Nan::HandleScope scope;
Local<Value> rows = self->getRowsAsJsValue();
Local<Value> argv[] = {
Nan::Null(),
rows
};
callback->Call(2, argv, async_resource);
}
private:
ResultSet* self;
size_t count;
};
/**
* getRows is used to retrieve rows from the result set.
*
* getRows can have two or fewer parameters.
*
* (optional) Number : an integer indicating the count of rows to be
* returned. If unspecified, the method returns all
* rows. This must be the first parameter.
* Negative zero (0) is a sentinel value that means
* "all".
* (optional) Function : an error-first callback if this method is called
* asynchronously; if omitted, then a promise is
* returned.
*/
NAN_METHOD(ResultSet::getRows)
{
TRACE("ResultSet::getRows");
Nan::HandleScope scope;
ResultSet* self = Nan::ObjectWrap::Unwrap<ResultSet>(info.This());
auto infoIdx = 0;
auto infoLen = info.Length();
size_t rowsToRead = 0;
if (infoLen > 0 && info[infoIdx]->IsInt32()) {
rowsToRead = (size_t)toInt32(info[infoIdx++]);
}
if (!info[infoIdx]->IsFunction()) {
std::string message = ErrMsg::get(ErrMsgType::errInvalidParamType, 1);
Nan::ThrowError(Nan::New<String>(message).ToLocalChecked());
return;
}
Nan::Callback* callback = new Nan::Callback(info[infoIdx].As<Function>());
GetRowsWorker* worker = new GetRowsWorker(callback, self, rowsToRead);
worker->SaveToPersistent("nuodb:ResultSet", info.This());
Nan::AsyncQueueWorker(worker);
}
static Local<Function> dateConstructor = Local<Function>::Cast(
Nan::Get(Nan::New<v8::Date>(0).ToLocalChecked(),
Nan::New("constructor").ToLocalChecked()).ToLocalChecked());
Local<Value> sqlToEsValue(SqlValue sqlValue)
{
TRACE("ResultSet::sqlToEsValue");
Nan::EscapableHandleScope scope;
int sqlType = sqlValue.getSqlType();
int esType = Type::toEsType(sqlType);
switch (esType) {
case ES_BOOLEAN:
return scope.Escape(Nan::New<Boolean>(sqlValue.getBoolean()));
case ES_STRING:
return scope.Escape(Nan::New<String>(sqlValue.getString()).ToLocalChecked());
case ES_NUMBER: {
switch (sqlType) {
case NuoDB::NUOSQL_SMALLINT:
return scope.Escape(Nan::New<Number>(sqlValue.getShort()));
case NuoDB::NUOSQL_INTEGER:
return scope.Escape(Nan::New<Number>(sqlValue.getInt()));
case NuoDB::NUOSQL_DOUBLE:
return scope.Escape(Nan::New<Number>(sqlValue.getDouble()));
}
return scope.Escape(Nan::New<Number>(sqlValue.getDouble()));
}
case ES_NULL:
return scope.Escape(Nan::Null());
case ES_DATE: {
switch (sqlType) {
// See: https://stackoverflow.com/questions/34158318/are-there-some-v8-functions-to-create-a-c-v8date-object-from-a-string-like
case NuoDB::NUOSQL_TIME: {
// Hackish, but ES doesn't actually support TIME
return scope.Escape(NanDate::toDate(std::string("1970-01-01T") + sqlValue.getString()));
}
case NuoDB::NUOSQL_DATE:
case NuoDB::NUOSQL_TIMESTAMP: {
return scope.Escape(NanDate::toDate(sqlValue.getString()));
}
default:
throw std::runtime_error("ES DATE type is unknown NUOSQL type");
break;
}
}
case ES_UNDEFINED: {
// check for types not directly supported in the ES type system...
switch (sqlType) {
case NuoDB::NUOSQL_BIGINT: {
int64_t v = sqlValue.getLong();
if (MIN_SAFE_INTEGER <= v && v <= MAX_SAFE_INTEGER) {
return scope.Escape(Nan::New<Number>(sqlValue.getLong()));
} else {
return scope.Escape(Nan::New<String>(int64ToString(v).c_str()).ToLocalChecked());
}
}
}
}
}
TRACE("sqlToEsValue : RETURNING UNDEFINED");
return scope.Escape(Nan::Undefined());
}
Local<Value> ResultSet::getRowsAsJsValue()
{
TRACE("ResultSet::getRowsAsJsValue");
Nan::EscapableHandleScope scope;
Isolate* isolate = Isolate::GetCurrent();
Local<Context> ctx = isolate->GetCurrentContext();
size_t count = rows.size();
Local<Array> array = Nan::New<Array>(count);
for (size_t rowIdx = 0; rowIdx < count; rowIdx++) {
std::vector<SqlValue> sqlRow = rows.back();
rows.pop_back();
if (options.getRowMode() == RowMode::ROWS_AS_OBJECT) {
Local<Object> jsObject = Nan::New<Object>();
for (size_t colIdx = 0; colIdx < sqlRow.size(); colIdx++) {
SqlValue sqlValue = sqlRow[colIdx];
Local<Value> jsKey = Nan::New<String>(sqlValue.getName()).ToLocalChecked();
TRACE("Object << sqlToEsValue");
Local<Value> jsValue = sqlToEsValue(sqlValue);
jsObject->Set(ctx, jsKey, jsValue).Check();
TRACE("Object >> sqlToEsValue");
}
array->Set(ctx, rowIdx, jsObject).Check();
} else {
Local<Array> jsArray = Nan::New<Array>();
for (size_t colIdx = 0; colIdx < sqlRow.size(); colIdx++) {
SqlValue sqlValue = sqlRow[colIdx];
TRACE("Array << sqlToEsValue");
Local<Value> jsValue = sqlToEsValue(sqlValue);
TRACE("Array >> sqlToEsValue");
jsArray->Set(ctx, colIdx, jsValue).Check();
}
array->Set(ctx, rowIdx, jsArray).Check();
}
}
return scope.Escape(array);
}
bool ResultSet::isStatementOpen() const
{
return statement != nullptr;
}
bool ResultSet::isResultOpen() const
{
return result != nullptr;
}
void ResultSet::doGetRows(size_t count)
{
TRACE("ResultSet::doGetRows");
if (!isStatementOpen()) {
std::string message = ErrMsg::get(ErrMsgType::errNoStatement);
throw std::runtime_error(message);
}
if (!isResultOpen()) {
result = statement->getResultSet();
}
if(result == nullptr){
// if the result set is still null at this point, there is the potential that one connection is being used for multiple queries.
throw std::runtime_error("Cannot access result set. Please ensure there is only one actively executing query per connection.");
}
bool fetchAll = count == 0;
NuoDB::ResultSetMetaData* metaData = result->getMetaData();
auto columns = metaData->getColumnCount();
while ((fetchAll || count > 0) && result->next()) {
TRACE("HANDLE ROW...");
std::vector<SqlValue> row;
for (auto index = 0; index < columns; index++) {
auto column = index + 1;
int sqlType = metaData->getColumnType(column);
SqlValue sqlValue;
sqlValue.setName(metaData->getColumnLabel(column));
sqlValue.setTable(metaData->getTableName(column));
sqlValue.setSqlType(sqlType);
switch (sqlType) {
case NuoDB::NUOSQL_SMALLINT:
sqlValue.setShort(result->getShort(column));
break;
case NuoDB::NUOSQL_INTEGER:
sqlValue.setInt(result->getInt(column));
break;
case NuoDB::NUOSQL_BIGINT:
sqlValue.setLong(result->getLong(column));
break;
case NuoDB::NUOSQL_FLOAT: // AN ALIAS FOR DOUBLE!!!
case NuoDB::NUOSQL_DOUBLE:
sqlValue.setDouble(result->getDouble(column));
break;
case NuoDB::NUOSQL_BOOLEAN:
sqlValue.setBoolean(result->getBoolean(column));
break;
case NuoDB::NUOSQL_DATE:
case NuoDB::NUOSQL_TIME:
case NuoDB::NUOSQL_TIMESTAMP:
case NuoDB::NUOSQL_CHAR:
case NuoDB::NUOSQL_VARCHAR:
case NuoDB::NUOSQL_LONGVARCHAR: {
const char* s = result->getString(column);
if (!result->wasNull()) {
sqlValue.setString(s);
}
break;
}
default:
const char* s = result->getString(column);
if (!result->wasNull()) {
sqlValue.setString(s);
sqlValue.setSqlType(NuoDB::NUOSQL_VARCHAR);
}
break;
}
// if the last value was null, set the value to null...
if (result->wasNull()) {
sqlValue.setSqlType(NuoDB::NUOSQL_NULL);
}
row.push_back(sqlValue);
}
count--;
rows.push_back(row);
}
}
} // namespace NuoJs
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/experimental/crypto/Blake2xb.h>
#include <vector>
#include <sodium.h>
#include <folly/Benchmark.h>
#include <folly/Random.h>
#include <folly/init/Init.h>
#include <folly/io/IOBuf.h>
#include <glog/logging.h>
using namespace ::folly::crypto;
void benchmarkBlake2b(size_t inputSize, size_t n) {
std::array<uint8_t, crypto_generichash_blake2b_BYTES_MAX> result;
std::vector<uint8_t> input;
BENCHMARK_SUSPEND {
input.resize(inputSize);
};
for (size_t i = 0; i < static_cast<size_t>(n); ++i) {
int res = crypto_generichash_blake2b(
result.data(), sizeof(result), input.data(), input.size(), nullptr, 0);
if (res != 0) {
throw std::runtime_error("blake2b hash failed");
}
}
}
void benchmarkBlake2bMultiple(size_t inputSize, size_t m, size_t n) {
std::vector<uint8_t> input;
std::vector<uint8_t> output;
std::vector<uint8_t> personalization;
std::array<uint8_t, crypto_generichash_blake2b_BYTES_MAX> h0;
BENCHMARK_SUSPEND {
output.resize(crypto_generichash_blake2b_BYTES_MAX * m);
input.resize(inputSize);
personalization.resize(crypto_generichash_blake2b_PERSONALBYTES);
};
for (size_t i = 0; i < static_cast<size_t>(n); ++i) {
int res = crypto_generichash_blake2b(
h0.data(), sizeof(h0), input.data(), input.size(), nullptr, 0);
if (res != 0) {
throw std::runtime_error("blake2b hash failed");
}
for (size_t j = 0; j < m; j++) {
res = crypto_generichash_blake2b_salt_personal(
output.data() + (crypto_generichash_blake2b_BYTES_MAX * j),
crypto_generichash_blake2b_BYTES_MAX,
h0.data(),
h0.size(),
nullptr /* key */,
0 /* keylen */,
nullptr /* salt */,
personalization.data());
if (res != 0) {
throw std::runtime_error("blake2b hash failed");
}
sodium_increment(
personalization.data(), crypto_generichash_blake2b_PERSONALBYTES);
}
}
}
void benchmarkBlake2xb(size_t inputSize, size_t outputSize, size_t n) {
std::vector<uint8_t> input;
std::vector<uint8_t> output;
BENCHMARK_SUSPEND {
input.resize(inputSize);
output.resize(outputSize);
};
for (size_t i = 0; i < static_cast<size_t>(n); ++i) {
Blake2xb::hash({output.data(), output.size()}, folly::range(input));
}
}
BENCHMARK(blake2b_100b_in_64b_out, n) {
benchmarkBlake2b(100, n);
}
BENCHMARK_RELATIVE(blake2xb_100b_in_64b_out, n) {
benchmarkBlake2xb(100, 64, n);
}
BENCHMARK(blake2b_100b_in_128b_out, n) {
benchmarkBlake2bMultiple(100, 128 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_100b_in_128b_out, n) {
benchmarkBlake2xb(100, 128, n);
}
BENCHMARK(blake2b_100b_in_1024b_out, n) {
benchmarkBlake2bMultiple(100, 1024 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_100b_in_1024b_out, n) {
benchmarkBlake2xb(100, 1024, n);
}
BENCHMARK(blake2b_100b_in_4096b_out, n) {
benchmarkBlake2bMultiple(100, 4096 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_100b_in_4096b_out, n) {
benchmarkBlake2xb(100, 4096, n);
}
BENCHMARK(blake2b_1000b_in_64b_out, n) {
benchmarkBlake2b(1000, n);
}
BENCHMARK_RELATIVE(blake2xb_1000b_in_64b_out, n) {
benchmarkBlake2xb(1000, 64, n);
}
BENCHMARK(blake2b_1000b_in_128b_out, n) {
benchmarkBlake2bMultiple(1000, 128 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_1000b_in_128b_out, n) {
benchmarkBlake2xb(1000, 128, n);
}
BENCHMARK(blake2b_1000b_in_1024b_out, n) {
benchmarkBlake2bMultiple(1000, 1024 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_1000b_in_1024b_out, n) {
benchmarkBlake2xb(1000, 1024, n);
}
BENCHMARK(blake2b_1000b_in_4096b_out, n) {
benchmarkBlake2bMultiple(1000, 4096 / 64, n);
}
BENCHMARK_RELATIVE(blake2xb_1000b_in_4096b_out, n) {
benchmarkBlake2xb(1000, 4096, n);
}
int main(int argc, char** argv) {
folly::init(&argc, &argv);
folly::runBenchmarks();
return 0;
}
|
#include "CPUBackend.hpp"
#include "Etaler/Core/Views.hpp"
#include "Etaler/Core/Random.hpp"
#include "Etaler/Core/TypeList.hpp"
#include <numeric>
#include <cmath>
#include <tbb/parallel_for.h>
#include <tbb/blocked_range.h>
#include <tbb/parallel_sort.h>
#include <tbb/parallel_reduce.h>
using namespace et;
//Helper functions
template <typename T>
void apply_permutation_in_place(
T* start,
T* end,
const std::vector<std::size_t>& p)
{
size_t size = std::distance(start, end);
et_assert(size == p.size());
std::vector<bool> done(size);
for (size_t i=0; i < size; ++i) {
if (done[i])
continue;
done[i] = true;
size_t prev_j = i;
size_t j = p[i];
while (i != j) {
std::swap(start[prev_j], start[j]);
done[j] = true;
prev_j = j;
j = p[j];
}
}
}
template <typename T>
void apply_permutation(
const T* start,
const T* end,
T* dest,
const std::vector<std::size_t>& p)
{
std::vector<T> sorted_vec(p.size());
std::transform(p.begin(), p.end(), dest,
[&](std::size_t i){ return start[i]; });
}
void* CPUBuffer::data() const
{
assert(dtype() != DType::Unknown);
return std::visit([](const auto& v){return (void*)v;}, storage_);
}
using DefaultTypeList = type_list_t<int32_t, float, bool, half>;
template <typename TypeList = DefaultTypeList, typename Func = void>
inline void dispatch(DType dtype, Func f)
{
static_assert(std::is_same_v<Func, void> == false); //void is just a dummy value
if constexpr(std::is_same_v<TypeList, null_t> == false) {
using T = typename TypeList::head;
if(typeToDType<T>() == dtype) {
f(T());
return;
}
dispatch<typename TypeList::tail, Func>(dtype, f);
}
else
throw EtError("Cannot dispatch such dtype: " + to_ctype_string(dtype));
}
template <typename TL1 = DefaultTypeList, typename TL2 = DefaultTypeList, typename Func = void>
inline void dispatch2d(DType t1, DType t2, Func f)
{
dispatch<TL1>(t1, [&](auto v1){
using T1 = decltype(v1);
dispatch<TL2>(t2, [&](auto v2){
using T2 = decltype(v2);
f(T1(), T2());
});
});
}
CPUBuffer::~CPUBuffer()
{
std::visit([](auto& ptr){delete [] ptr;}, storage_);
}
namespace et::detail
{
template <typename PermType>
static std::shared_ptr<TensorImpl> cellActivity(const TensorImpl* x, const TensorImpl* connections, const TensorImpl* permeances
, float connected_permeance, size_t active_threshold, bool has_unconnected_synapse, CPUBackend* backend)
{
//Checks the input are sane
requireProperties(x, backend, DType::Bool, IsPlain());
requireProperties(connections, backend, DType::Int32, IsPlain(), permeances->shape());
requireProperties(permeances, backend, typeToDType<PermType>(), IsPlain());
et_check(connections->dimensions() >= 2);
Shape s = connections->shape();
s.pop_back();
auto y = backend->createTensor(s, DType::Int32);
const bool* input = (const bool*)x->data();
const int32_t* synapses = (const int32_t*)connections->data();
const PermType* synapse_strengths = (PermType*)permeances->data();
int32_t* result = (int32_t*)y->data();
size_t max_connections_per_cell = connections->shape().back();
size_t num_cells = connections->size()/max_connections_per_cell;
size_t block_size = std::min(size_t(128), (size_t)num_cells);
tbb::parallel_for(tbb::blocked_range<size_t>(size_t(0), num_cells, block_size), [&](const auto& r) {
for(size_t i=r.begin();i!=r.end();i++) {
size_t sum = 0;
for(size_t j=0;j<max_connections_per_cell;j++) {
size_t index = i*max_connections_per_cell+j;
int32_t target = synapses[index];
if(target == -1)
break;
assert(target < (int32_t)x->size());
if(input[target] == false)
continue;
PermType strength = synapse_strengths[index];
if(strength > connected_permeance)
sum += 1;
}
if(sum >= active_threshold)
result[i] = sum;
else
result[i] = 0;
}
});
return y;
}
template <typename PermType>
void learnCorrilation(const TensorImpl* x, const TensorImpl* learn, const TensorImpl* connections, TensorImpl* permeances
, float perm_inc, float perm_dec, bool has_unconnected_synapse, CPUBackend* backend)
{
requireProperties(x, backend, DType::Bool, IsPlain());
requireProperties(learn, backend, DType::Bool, IsPlain());
requireProperties(connections, backend, DType::Int32, IsPlain(), permeances->shape());
requireProperties(permeances, backend, typeToDType<PermType>(), IsPlain());
const bool* input = (const bool*)x->data();
const bool* learning = (const bool*)learn->data();
const int32_t* synapses = (const int32_t*)connections->data();
PermType* synapse_strengths = (PermType*)permeances->data();
size_t max_connections_per_cell = connections->shape().back();
size_t num_cells = connections->size()/max_connections_per_cell;
tbb::parallel_for(size_t(0), learn->size(), [&](size_t i) {
if(learning[i] == false)
return;
for(size_t j=0; j<max_connections_per_cell;j++) {
size_t idx = i*max_connections_per_cell+j;
auto connection = synapses[idx];
if(connection == -1)
break;
ASSERT((size_t)connection < num_cells);
PermType& perm = synapse_strengths[idx];
if(input[connection] == true)
perm += perm_inc;
else
perm -= perm_dec;
perm = std::clamp(perm, PermType(0), PermType(1));
}
});
}
template <typename PermType>
void sortSynapse(TensorImpl* connections, TensorImpl* permeances, CPUBackend* backend)
{
requireProperties(connections, backend, DType::Int32, IsPlain());
requireProperties(permeances, backend, typeToDType<PermType>(), IsPlain());
et_assert(connections->shape() == permeances->shape());
size_t max_synapse_per_cell = connections->shape().back();
size_t num_cells = connections->size()/max_synapse_per_cell;
uint32_t* conns = (uint32_t*)connections->data(); //HACK: -1s should be at the end of the arrays.
PermType* perms = (PermType*)permeances->data();
tbb::parallel_for(size_t(0), num_cells, [&](size_t i) {
size_t start_index = i*max_synapse_per_cell;
size_t end_index = (i+1)*max_synapse_per_cell;
std::vector<size_t> sort_indices(max_synapse_per_cell);
std::iota(sort_indices.begin(), sort_indices.end(), 0);
std::sort(sort_indices.begin(), sort_indices.end(),
[&](size_t i, size_t j)->bool {
return conns[i+start_index] < conns[j+start_index];
});
apply_permutation_in_place(conns+start_index, conns+end_index, sort_indices);
apply_permutation_in_place(perms+start_index, perms+end_index, sort_indices);
});
}
template <typename PermType>
void growSynapses(const TensorImpl* x, const TensorImpl* y, TensorImpl* connections
, TensorImpl* permeances, float initial_perm, CPUBackend* backend)
{
requireProperties(x, backend, DType::Bool, IsPlain());
requireProperties(y, backend, DType::Bool, IsPlain());
requireProperties(connections, backend, DType::Int32, IsPlain(), permeances->shape());
requireProperties(permeances, backend, typeToDType<PermType>(), IsPlain());
Shape s = connections->shape();
s.pop_back();
et_check(s == y->shape());
size_t max_synapses_per_cell = connections->shape().back();
size_t input_cell_count = x->size();
const bool* in = (const bool*) x->data();
const bool* out = (const bool*) y->data();
int32_t* conns = (int32_t*)connections->data();
PermType* perms = (PermType*)permeances->data();
std::vector<uint32_t> on_bits;
on_bits.reserve(input_cell_count*0.1);
for(size_t i=0;i<input_cell_count;i++) {
if(in[i] == true)
on_bits.push_back(i);
}
size_t block_size = std::min(size_t(16), (size_t)y->shape().back());
tbb::parallel_for(tbb::blocked_range<size_t>(size_t(0), y->size(), block_size), [&](const auto& r) {
for(size_t i=r.begin();i!=r.end();i++) {
if(out[i] == 0)
continue;
uint32_t* synapses = (uint32_t*)conns+i*max_synapses_per_cell;
PermType* strengths = perms+i*max_synapses_per_cell;
uint32_t* end = synapses+max_synapses_per_cell;
if(synapses[max_synapses_per_cell-1] != uint32_t(-1)) //If there is no space for new synapse. Ignore
continue;
uint32_t* it = std::lower_bound(synapses, end, uint32_t(-1));
size_t used_space = it - synapses;
size_t write_idx = it - synapses;
size_t read_idx = 0;
for(size_t j=0;write_idx!=max_synapses_per_cell && j < on_bits.size();j++) {
bool connected = false;
for(;read_idx<used_space;read_idx++) {
if(synapses[read_idx] == on_bits[j]) {
connected = true;
break;
}
if(synapses[read_idx] > on_bits[j])
break;
}
if(connected == false) {
synapses[write_idx] = on_bits[j];
strengths[write_idx] = initial_perm;
write_idx++;
}
}
std::vector<size_t> sort_indices(write_idx);
std::iota(sort_indices.begin(), sort_indices.begin()+write_idx, 0);
std::sort(sort_indices.begin(), sort_indices.begin()+write_idx,
[&](size_t i, size_t j)->bool {
return ((uint32_t*)synapses)[i] < ((uint32_t*)synapses)[j];
});
apply_permutation_in_place(synapses, synapses+write_idx, sort_indices);
apply_permutation_in_place(strengths, strengths+write_idx, sort_indices);
}
});
}
template <typename PermType>
void decaySynapses(TensorImpl* connections, TensorImpl* permeances, float threshold, CPUBackend* backend)
{
requireProperties(connections, backend, DType::Int32, IsPlain(), permeances->shape());
requireProperties(permeances, backend, typeToDType<PermType>(), IsPlain());
PermType* perms = (PermType*)permeances->data();
uint32_t* conns = (uint32_t*)connections->data();
size_t max_synapses_per_cell = connections->shape().back();
size_t input_cell_count = connections->size()/max_synapses_per_cell;
tbb::parallel_for(size_t(0), input_cell_count, [&](size_t i) {
uint32_t* synapses = (uint32_t*)conns+i*max_synapses_per_cell;
PermType* strengths = perms+i*max_synapses_per_cell;
uint32_t* end = synapses+max_synapses_per_cell;
uint32_t* it = std::lower_bound(synapses, end, uint32_t(-1));
size_t used_space = it - synapses;
for(size_t j=0;j<used_space;j++) {
if(strengths[j] < threshold)
synapses[j] = uint32_t(-1);
}
std::vector<size_t> sort_indices(used_space);
std::iota(sort_indices.begin(), sort_indices.begin()+used_space, 0);
std::sort(sort_indices.begin(), sort_indices.begin()+used_space,
[&](size_t i, size_t j)->bool {
return ((uint32_t*)synapses)[i] < ((uint32_t*)synapses)[j];
});
apply_permutation_in_place(synapses, synapses+used_space, sort_indices);
apply_permutation_in_place(strengths, strengths+used_space, sort_indices);
});
}
}
std::shared_ptr<TensorImpl> CPUBackend::cellActivity(const TensorImpl* x, const TensorImpl* connections, const TensorImpl* permeances
, float connected_permeance, size_t active_threshold, bool has_unconnected_synapse)
{
std::shared_ptr<TensorImpl> res;
dispatch<type_list_t<float, half>>(permeances->dtype(), [&](auto v){
res = detail::cellActivity<decltype(v)>(x, connections, permeances, connected_permeance, active_threshold, has_unconnected_synapse, this);
});
return res;
}
void CPUBackend::learnCorrilation(const TensorImpl* x, const TensorImpl* learn, const TensorImpl* connections, TensorImpl* permeances
, float perm_inc, float perm_dec, bool has_unconnected_synapse)
{
dispatch<type_list_t<float, half>>(permeances->dtype(), [&](auto v){
detail::learnCorrilation<decltype(v)>(x, learn, connections, permeances, perm_inc, perm_dec, has_unconnected_synapse, this);
});
}
std::shared_ptr<TensorImpl> CPUBackend::globalInhibition(const TensorImpl* x, float fraction)
{
requireProperties(x, this, DType::Int32, IsPlain());
auto y = createTensor(x->shape(), DType::Bool);
const int32_t* input = (const int32_t*)x->data();
bool* output = (bool*)y->data();
std::vector<std::pair<int32_t, size_t>> v;
size_t target_size = x->size()*fraction;
v.reserve(target_size);//Some sane value
for(size_t i=0;i<x->size();i++) {
if(input[i] != 0)
v.push_back({input[i], i});
}
//If we have a empty input
if(v.size() == 0)
return y;
tbb::parallel_sort(v.begin(), v.end(), [](const auto& a, const auto&b){return a.first > b.first;});
for(size_t i=0;i<y->size();i++)
output[i] = false;
size_t accept_index = std::min((target_size==0? 0 : target_size-1), v.size()-1);
int32_t min_accept_val = v[accept_index].first;
auto bound_end = std::upper_bound(v.begin()+accept_index, v.end(), min_accept_val, [](const auto& a, const auto& b){return a > b.first;});
for(auto it=v.begin();it!=bound_end;++it)
output[it->second] = true;
return y;
}
template <typename To, typename From>
static auto castData(const From* ptr, size_t n)
{
// Deal with the special case of bool
if constexpr(std::is_same_v<std::decay_t<To>, bool>) {
std::vector<uint8_t> res(n);
std::transform(ptr, ptr+n, res.begin(), [](auto a){ return (bool)a; });
return res;
}
else
return std::vector<To>(ptr, ptr+n);
}
std::shared_ptr<TensorImpl> CPUBackend::cast(const TensorImpl* x, DType toType)
{
requireProperties(x, this, IsPlain());
auto res = createTensor(x->shape(), toType);
dispatch(toType, [&](auto v0){
using ToType = decltype(v0);
dispatch(x->dtype(), [&](auto v1){
using FromType = decltype(v1);
auto casted_data = castData<ToType>((FromType*)x->data(), x->size());
static_assert(sizeof(typename decltype(casted_data)::value_type) == sizeof(ToType));
memcpy(res->data(), casted_data.data(), casted_data.size()*sizeof(ToType));
});
});
return res;
}
void CPUBackend::copyToHost(const TensorImpl* t, void* ptr)
{
requireProperties(t, this, IsPlain());
memcpy(ptr, t->data(), t->size()*dtypeToSize(t->dtype()));
}
std::shared_ptr<TensorImpl> CPUBackend::copy(const TensorImpl* x)
{
requireProperties(x, this, IsContingous());
size_t offset_bytes = x->offset()*dtypeToSize(x->dtype());
return createTensor(x->shape(), x->dtype(), (const char*)x->data()+offset_bytes);
}
void CPUBackend::sortSynapse(TensorImpl* connections, TensorImpl* permeances)
{
dispatch<type_list_t<float, half>>(permeances->dtype(), [&](auto v) {
detail::sortSynapse<decltype(v)>(connections, permeances, this);
});
}
std::shared_ptr<TensorImpl> CPUBackend::burst(const TensorImpl* x, const TensorImpl* s)
{
requireProperties(x, this, DType::Bool, IsPlain());
requireProperties(s, this, DType::Bool, IsPlain());
Shape shape = s->shape();
shape.pop_back();
requireProperties(x, shape);
auto y = createTensor(s->shape(), DType::Bool);
const bool* in = (const bool*)x->data();
const bool* state = (const bool*)s->data();
bool* out = (bool*)y->data();
size_t column_size = y->shape().back();
tbb::parallel_for(size_t(0), x->size(), [&](size_t i) {
if(in[i] == false)
std::generate(out+i*column_size, out+(i+1)*column_size, [](){return 0;});
else {
if(std::accumulate(state+i*column_size, state+(i+1)*column_size, 0) == 0)
std::generate(out+i*column_size, out+(i+1)*column_size, [](){return 1;});
else
std::copy(state+i*column_size, state+(i+1)*column_size, out+i*column_size);
}
});
return y;
}
std::shared_ptr<TensorImpl> CPUBackend::reverseBurst(const TensorImpl* x)
{
requireProperties(x, this, DType::Bool, IsPlain());
size_t cells_per_column = x->shape().back();
size_t num_columns = x->size()/cells_per_column;
static pcg64 rng; //Static so the behavor hangees every time, breaking symmetry
std::uniform_int_distribution<size_t> dist(0, cells_per_column-1);
auto y = createTensor(x->shape(), DType::Bool);
const bool* in = (const bool*) x->data();
bool* out = (bool*) y->data();
tbb::parallel_for(size_t(0), num_columns, [&](size_t i) {
if(std::accumulate(in+i*cells_per_column, in+(i+1)*cells_per_column, size_t(0)) == cells_per_column) {
std::generate(out+i*cells_per_column, out+(i+1)*cells_per_column, [](){return 0;});
out[i*cells_per_column+dist(rng)] = 1;
}
else
std::copy(in+i*cells_per_column, in+(i+1)*cells_per_column, out+i*cells_per_column);
});
return y;
}
void CPUBackend::growSynapses(const TensorImpl* x, const TensorImpl* y, TensorImpl* connections
, TensorImpl* permeances, float initial_perm)
{
dispatch<type_list_t<float, half>>(permeances->dtype(), [&](auto v) {
detail::growSynapses<decltype(v)>(x, y, connections, permeances, initial_perm, this);
});
}
template <typename T>
const T* getPtrToValue(size_t parent_idx, const TensorImpl* t)
{
// Optimized case for contnigous input
if(t->iscontiguous())
return (const T*)t->data()+t->offset()+parent_idx;
Shape s = foldIndex(parent_idx, t->shape());
s = Shape(t->stride().size()-s.size(), 0) + s;
size_t offset = t->offset() + unfold(s, t->stride());
return ((const T*)t->data())+offset;
}
template <typename T2, typename T1>
void write(T2* ptr, T1 v)
{
*ptr = v;
}
template <typename Op>
static std::shared_ptr<TensorImpl> uniaryOp(const TensorImpl* src, Op op)
{
std::shared_ptr<TensorImpl> dest;
dispatch(src->dtype(), [&](auto v){
using T = decltype(v);
using ResType = std::invoke_result_t<Op, T>;
//We don't have support to double percition now. Cast it to float
using StoreType = typename std::conditional_t<std::is_same_v<ResType, bool>, bool
, typename std::conditional_t<std::is_same_v<T, half>, half
, typename std::conditional_t<std::is_same_v<ResType, double>, float, ResType>>>;
dest = src->backend()->createTensor(src->shape(), typeToDType<StoreType>());
tbb::parallel_for(size_t(0), src->size(), [&](size_t i) {
auto ptr = getPtrToValue<T>(i, src);
auto res = op(*ptr);
reinterpret_cast<StoreType*>(dest->data())[i] = res;
});
});
et_assert((bool)dest);
return dest;
}
template <typename Op>
static std::shared_ptr<TensorImpl> binaryOp(const TensorImpl* src, const TensorImpl* src2, Op op)
{
std::shared_ptr<TensorImpl> dest;
et_assert(src->shape() == src2->shape());
dispatch(src->dtype(), [&](auto v){
using T1 = decltype(v);
dispatch(src2->dtype(), [&](auto v){
using T2 = decltype(v);
using ResType = std::invoke_result_t<Op, T1, T2>;
//We don't have support to double percition now. Cast it to float
using StoreType = typename std::conditional<std::is_same<ResType, double>::value, float, ResType>::type;
dest = src->backend()->createTensor(src->shape(), typeToDType<StoreType>());
tbb::parallel_for(size_t(0), src->size(), [&](size_t i) {
auto ptr = getPtrToValue<T1>(i, src);
auto ptr2 = getPtrToValue<T2>(i, src2);
auto res = op(*ptr, *ptr2);
reinterpret_cast<StoreType*>(dest->data())[i] = res;
});
});
});
et_assert((bool)dest);
return dest;
}
std::shared_ptr<TensorImpl> CPUBackend::realize(const TensorImpl* x)
{
requireProperties(x, this);
et_assert(x->data() != nullptr);
auto res = createTensor(x->shape(), x->dtype());
dispatch(x->dtype(), [&](auto v){
using T = decltype(v);
for(size_t i=0;i<x->size();i++) {
auto ptr = (T*)res->data();
ptr[i] = *getPtrToValue<T>(i, x);
}
});
return res;
}
void CPUBackend::assign(TensorImpl* dest, const TensorImpl* src)
{
requireProperties(dest, this);
requireProperties(src, this);
if(dest->shape() != src->shape())
throw EtError("Shape mismatch in tensor assignment. Shape "
+ to_string(dest->shape()) + " and " + to_string(src->shape()));
if(dest->dtype() != src->dtype())
assign(dest, cast(src, dest->dtype()).get());
dispatch(dest->dtype(), [&](auto v) {
using T = decltype(v);
//Parallelize if the problem is big enought
if(dest->size() > 2000) {
tbb::parallel_for(size_t(0), dest->size(), [&](size_t i) {
auto s = (T*)getPtrToValue<T>(i, src);
auto ptr = (T*)getPtrToValue<T>(i, dest);
*ptr = *s;
});
}
else {
for(size_t i=0;i<dest->size();i++) {
auto s = (T*)getPtrToValue<T>(i, src);
auto ptr = (T*)getPtrToValue<T>(i, dest);
*ptr = *s;
}
}
});
}
std::shared_ptr<TensorImpl> CPUBackend::sum(const TensorImpl* x, size_t chunk_size, DType dtype)
{
requireProperties(x, this, IsPlain());
et_check(x->size() % chunk_size == 0);
DType result_dtype = dtype;
if(dtype == DType::Unknown) {
result_dtype = [x](){
DType dtype = x->dtype();
if(dtype == DType::Bool || dtype == DType::Int32)
return DType::Int32;
else if(dtype == DType::Half)
return DType::Half;
else
return DType::Float;
}();
}
size_t result_size = x->size()/chunk_size;
auto res = createTensor({intmax_t(result_size)}, result_dtype);
// Optimized case for summing everything
if(result_size == 1) {
dispatch2d(x->dtype(), result_dtype, [&](auto v1, auto v2) {
using T = decltype(v1);
auto in = (const T*)x->data();
using ResType = decltype(v2);
auto ptr = (ResType*) res->data();
*ptr = tbb::parallel_reduce(tbb::blocked_range(in, in+x->size()), ResType(0)
, [](const auto& r, ResType init){
return std::accumulate(r.begin(), r.end(), init);
},
[](auto x, auto y) {
return x + y;
});
});
}
else {
dispatch2d(x->dtype(), result_dtype, [&](auto v1, auto v2) {
using T = decltype(v1);
auto in = (const T*)x->data();
using ResType = decltype(v2);
auto ptr = (ResType*) res->data();
tbb::parallel_for(size_t(0), size_t(x->size()/chunk_size), [&](size_t i) {
size_t offset = i*chunk_size;
ResType s = std::accumulate(in+offset, in+offset+chunk_size, ResType(0));
ptr[i] = s;
});
});
}
return res;
}
void CPUBackend::decaySynapses(TensorImpl* connections, TensorImpl* permeances, float threshold)
{
dispatch<type_list_t<float, half>>(permeances->dtype(), [&](auto v) {
detail::decaySynapses<decltype(v)>(connections, permeances, threshold, this);
});
}
std::shared_ptr<TensorImpl> CPUBackend::abs(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return std::abs(v);});
}
std::shared_ptr<TensorImpl> CPUBackend::exp(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return std::exp(v);});
}
std::shared_ptr<TensorImpl> CPUBackend::negate(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return -v;});
}
std::shared_ptr<TensorImpl> CPUBackend::inverse(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return 1.f/v;});
}
std::shared_ptr<TensorImpl> CPUBackend::log(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return std::log(v);});
}
std::shared_ptr<TensorImpl> CPUBackend::logical_not(const TensorImpl* x)
{
return uniaryOp(x, [](auto v){return !((bool)v);});
}
std::shared_ptr<TensorImpl> CPUBackend::add(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a+b;});
}
std::shared_ptr<TensorImpl> CPUBackend::subtract(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a-b;});
}
std::shared_ptr<TensorImpl> CPUBackend::mul(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a*b;});
}
std::shared_ptr<TensorImpl> CPUBackend::div(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a/b;});
}
std::shared_ptr<TensorImpl> CPUBackend::equal(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a==b;});
}
std::shared_ptr<TensorImpl> CPUBackend::greater(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a>b;});
}
std::shared_ptr<TensorImpl> CPUBackend::lesser(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a<b;});
}
std::shared_ptr<TensorImpl> CPUBackend::logical_and(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a&&b;});
}
std::shared_ptr<TensorImpl> CPUBackend::logical_or(const TensorImpl* x1, const TensorImpl* x2)
{
return binaryOp(x1, x2, [](auto a, auto b) {return a||b;});
}
std::shared_ptr<TensorImpl> CPUBackend::from(const TensorImpl* x)
{
const void* ptr = x->data();
if(ptr != nullptr)
return createTensor(x->shape(), x->dtype(), ptr);
void* buffer = malloc(x->size()*dtypeToSize(x->dtype()));
x->backend()->copyToHost(x, buffer);
auto res = createTensor(x->shape(), x->dtype(), buffer);
free(buffer);
return res;
}
|
// Copyright (C) 2022 Jérôme "Lynix" Leclercq (lynix680@gmail.com)
// This file is part of the "Nazara Engine - Shader module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#pragma once
#ifndef NAZARA_SHADER_AST_ENUMS_HPP
#define NAZARA_SHADER_AST_ENUMS_HPP
#include <Nazara/Prerequisites.hpp>
#include <Nazara/Core/Flags.hpp>
namespace Nz
{
namespace ShaderAst
{
enum class AssignType
{
Simple, //< a = b
CompoundAdd, //< a += b
CompoundDivide, //< a /= b
CompoundMultiply, //< a *= b
CompoundLogicalAnd, //< a &&= b
CompoundLogicalOr, //< a ||= b
CompoundSubtract, //< a -= b
};
enum class AttributeType
{
Binding, //< Binding (external var only) - has argument index
Builtin, //< Builtin (struct member only) - has argument type
Cond, //< Conditional compilation option - has argument expr
DepthWrite, //< Depth write mode (function only) - has argument type
EarlyFragmentTests, //< Entry point (function only) - has argument on/off
Entry, //< Entry point (function only) - has argument type
Export, //< Exported (external block, function and struct only)
Layout, //< Struct layout (struct only) - has argument style
Location, //< Location (struct member only) - has argument index
LangVersion, //< NZSL version - has argument version string
Set, //< Binding set (external var only) - has argument index
Unroll, //< Unroll (for/for each only) - has argument mode
Uuid, //< Uuid (module only) - has argument string
};
enum class BinaryType
{
Add, //< +
CompEq, //< ==
CompGe, //< >=
CompGt, //< >
CompLe, //< <=
CompLt, //< <
CompNe, //< <=
Divide, //< /
Multiply, //< *
LogicalAnd, //< &&
LogicalOr, //< ||
Subtract, //< -
};
enum class BuiltinEntry
{
FragCoord = 1, // gl_FragCoord
FragDepth = 2, // gl_FragDepth
VertexPosition = 0, // gl_Position
};
enum class DepthWriteMode
{
Greater,
Less,
Replace,
Unchanged,
};
enum class ExpressionCategory
{
LValue,
RValue
};
enum class FunctionFlag
{
DoesDiscard,
DoesWriteFragDepth,
Max = DoesWriteFragDepth
};
}
template<>
struct EnumAsFlags<ShaderAst::FunctionFlag>
{
static constexpr ShaderAst::FunctionFlag max = ShaderAst::FunctionFlag::Max;
};
namespace ShaderAst
{
using FunctionFlags = Flags<FunctionFlag>;
enum class IntrinsicType
{
CrossProduct = 0,
DotProduct = 1,
Exp = 7,
Length = 3,
Max = 4,
Min = 5,
Normalize = 9,
Pow = 6,
Reflect = 8,
SampleTexture = 2,
};
enum class LoopUnroll
{
Always,
Hint,
Never
};
enum class MemoryLayout
{
Std140
};
enum class NodeType
{
None = -1,
#define NAZARA_SHADERAST_NODE(Node) Node,
#define NAZARA_SHADERAST_STATEMENT_LAST(Node) Node, Max = Node
#include <Nazara/Shader/Ast/AstNodeList.hpp>
};
enum class PrimitiveType
{
Boolean, //< bool
Float32, //< f32
Int32, //< i32
UInt32, //< ui32
String //< str
};
enum class UnaryType
{
LogicalNot, //< !v
Minus, //< -v
Plus, //< +v
};
}
}
#endif // NAZARA_SHADER_AST_ENUMS_HPP
|
#ifndef STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOG_HPP
#define STAN_MATH_PRIM_SCAL_PROB_BERNOULLI_LOG_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/prob/bernoulli_lpmf.hpp>
namespace stan {
namespace math {
/** \ingroup prob_dists
* @deprecated use <code>bernoulli_lpmf</code>
*/
template <bool propto, typename T_n, typename T_prob>
return_type_t<T_prob> bernoulli_log(const T_n& n, const T_prob& theta) {
return bernoulli_lpmf<propto, T_n, T_prob>(n, theta);
}
/** \ingroup prob_dists
* @deprecated use <code>bernoulli_lpmf</code>
*/
template <typename T_y, typename T_prob>
inline return_type_t<T_prob> bernoulli_log(const T_y& n, const T_prob& theta) {
return bernoulli_lpmf<T_y, T_prob>(n, theta);
}
} // namespace math
} // namespace stan
#endif
|
/*
* Copyright (c) 2019 SK Telecom Co., Ltd. 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.
*/
#ifndef __NUGU_DELEGATION_AGENT_H__
#define __NUGU_DELEGATION_AGENT_H__
#include <clientkit/capability.hh>
using namespace NuguClientKit;
class IDelegationListener : virtual public ICapabilityListener {
public:
virtual ~IDelegationListener() = default;
virtual void delegate(const std::string& app_id, const std::string& ps_id, const std::string& data) = 0;
virtual bool requestContext(std::string& ps_id, std::string& data) = 0;
};
class DelegationAgent final : public Capability {
public:
DelegationAgent();
virtual ~DelegationAgent() = default;
void setCapabilityListener(ICapabilityListener* clistener) override;
void updateInfoForContext(Json::Value& ctx) override;
void parsingDirective(const char* dname, const char* message) override;
bool request(const std::string& ps_id, const std::string& data);
private:
void parsingDelegate(const char* message);
bool sendEventRequest(const std::string& ps_id, const std::string& data, EventResultCallback cb = nullptr);
IDelegationListener* delegation_listener = nullptr;
};
#endif /* __NUGU_DELEGATION_AGENT_H__ */
|
//@HEADER
// ************************************************************************
//
// Kokkos v. 2.0
// Copyright (2014) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// 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 the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include<Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t***,LayoutLeft,LayoutRight, Experimental::HPX,int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t***,LayoutLeft,LayoutLeft, Experimental::HPX,int)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int64_t***,LayoutLeft,LayoutStride,Experimental::HPX,int)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int64_t***,LayoutLeft,Experimental::HPX,int)
}
}
|
#include "testing/testing.hpp"
#include "coding/coder_util.hpp"
#include "base/logging.hpp"
//namespace
//{
// size_t FixedDstSizeInfiniteMemoryEncode(char const *, size_t, char *, size_t /*dstSize*/)
// {
// // LOG(LINFO, ("DstSize", dstSize));
// return -1U;
// }
//}
/* Commented because takes too much time after memory upgrage :)
UNIT_TEST(FixedDstSizeCodeToStringInfiniteMemoryTest)
{
bool thrownDstOutOfMemoryStringCodingException = false;
try
{
char const src [] = "Test";
string dst;
FixedDstSizeCodeToString(&FixedDstSizeInfiniteMemoryEncode, src, 4, dst);
}
catch (DstOutOfMemoryStringCodingException & e)
{
thrownDstOutOfMemoryStringCodingException = true;
}
TEST(thrownDstOutOfMemoryStringCodingException, ());
}
*/
|
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int month, day;
cout << "Enter month: ";
cin >> month;
cout << "Enter day: ";
cin >> day;
if (month == 1)
cout << "January" << endl;
system("pause");
return 0;
}
|
#include "tensorflow_serving/gateway/handles.h"
namespace tensorflow {
namespace serving{
string Handles::DebugString() const
{
string ret = "{{update_handles: ";
for (auto handle :update_handles_){
ret = strings::StrCat(ret, handle.first,
handle.second->DebugString(), ", ");
}
ret = strings::StrCat(ret, "}, {read_handles: ");
for (auto handle :read_handles_){
ret = strings::StrCat(ret, handle.first,
handle.second->DebugString(), ", ");
}
ret = strings::StrCat(ret, "}}");
return ret;
}
bool Handles::AddHandle(const string& model_name, SptrSN sn)
{
mutex_lock l(mu_update_);
/*
mutlimap은 k-v가 완전히 같아도 들어가므로 체크 필요
*/
if (sn == nullptr){
return false;
}
auto range = update_handles_.equal_range(model_name);
for(auto i = range.first; i != range.second; i++){
if (i->second->GetIpPort() == sn->GetIpPort()){
return false;
}
}
update_handles_.insert(std::make_pair(model_name, sn));
return true;
}
bool Handles::RemoveHandle(const string& model_name, SptrSN sn)
{
mutex_lock l(mu_update_);
if (sn == nullptr){
update_handles_.erase(model_name);
return true;//
}
else {
auto range = update_handles_.equal_range(model_name);
for(auto i = range.first; i != range.second; i++){
if (i->second->GetIpPort() == sn->GetIpPort()){
update_handles_.erase(i);
return true;
}
}
}
return false;
}
void Handles::UpdateHandle()
{
//LOG(INFO) << "UpdateHandle";
/*
read_handles에 update_handles를 복사하면되는데,
락타임 최소화를 위해서 미리 카피를 한 뒤에 스왑.
정상 동작하는지 확인하자..
*/
/* copy contents memory to update_copy
컨테이너 엘리먼트들은 힙에 있음...
*/
mutex_lock l(mu_update_);
HandleMap update_copy = update_handles_;
/* update */
{
mutex_lock l(mu_read_);
/* move copied contents to read_handles_ */
/* swap은 무브로 구현됨. */
read_handles_.swap(update_copy);
}
}
const SptrSN Handles::GetSN(const string& model_name)
{
tf_shared_lock ls(mu_read_);
auto range = read_handles_.equal_range(model_name);
/* TODO 일단 모델은 하나만 로딩되는 것으로 가정하긴 함.
select random? rr? 정책 없음
state기반 변경이면 카운터가 있어야 하는데 모델에 넣어놔도 되나?
암튼 나중에 수정...
this is temporal code.
*/
for(auto i = range.first; i != range.second; i++){
return i->second;
}
return nullptr;
}
} //gateway
} //tensorflow
|
#pragma once
#include "Vector3.h"
#include <cmath>
#include <algorithm>
constexpr inline Vector3::Vector3(double x, double y, double z) :
X(x), Y(y), Z(z)
{
}
inline Vector3 Vector3::operator-() const
{
return Vector3(-X, -Y, -Z);
}
inline double Vector3::operator[](int index) const
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
}
}
inline double& Vector3::operator[](int index)
{
switch (index)
{
case 0: return X;
case 1: return Y;
case 2: return Z;
}
}
inline Vector3& Vector3::operator+=(const Vector3& other)
{
X += other.X;
Y += other.Y;
Z += other.Z;
return *this;
}
inline Vector3& Vector3::operator*=(const double scalar)
{
X *= scalar;
Y *= scalar;
Z *= scalar;
}
inline Vector3& Vector3::operator/=(const double scalar)
{
X /= scalar;
Y /= scalar;
Z /= scalar;
}
inline Vector3 Vector3::operator+(const Vector3& other) const
{
return Vector3(X + other.X, Y + other.Y, Z + other.Z);
}
inline Vector3 Vector3::operator-(const Vector3& other) const
{
return Vector3(X - other.X, Y - other.Y, Z - other.Z);
}
inline Vector3 Vector3::operator*(const Vector3& other) const
{
return Vector3(X * other.X, Y * other.Y, Z * other.Z);
}
inline Vector3 Vector3::operator*(const double scalar) const
{
return Vector3(X * scalar, Y * scalar, Z * scalar);
}
inline Vector3 Vector3::operator/(const double scalar) const
{
return Vector3(X / scalar, Y / scalar, Z / scalar);
}
inline std::ostream& Vector3::operator<<(std::ostream& outputStream) const
{
return outputStream << X << ", " << Y << ", " << Z;
}
inline double Vector3::GetLength() const
{
return std::sqrt(GetLengthSquared());
}
inline double Vector3::GetLengthSquared() const
{
return X * X + Y * Y + Z * Z;
}
inline double Vector3::GetDotProduct() const
{
return GetLengthSquared();
}
inline double Vector3::GetDotProduct(const Vector3& other) const
{
return X * other.X + Y * other.Y + Z * other.Z;
}
inline Vector3 Vector3::GetCrossProduct(const Vector3 other) const
{
return Vector3( Y * other.Z - Z * other.Y,
Z * other.X - X * other.Z,
X * other.Y - Y * other.X);
}
inline Vector3 Vector3::Normalize() const
{
return *this / GetLength();
}
inline bool Vector3::IsNearZero() const
{
const auto epsilon = -1e8;
return std::abs(X) < epsilon && std::abs(Y) < epsilon && std::abs(Z) < epsilon;
}
inline Vector3 Vector3::Reflect(const Vector3& normal) const
{
// Project this vector on the normal to get the length of the reflected vector
double projected_length = GetDotProduct(normal);
// Offset by normal projection * 2 to scale in opposite direction
// Assumes inward vector (this) ends at tail of normal
return *this - ( 2 * projected_length * normal);
}
inline Vector3 Vector3::Refract(const Vector3& normal, double etaOverEtaPrime) const
{
double cos_theta = std::min(GetDotProduct(-normal), 1.0);
Vector3 r_out_perpendicular = etaOverEtaPrime * (*this + cos_theta * normal);
Vector3 r_out_parallel = -std::sqrt(std::abs(1.0 - r_out_perpendicular.GetLengthSquared())) * normal;
return r_out_perpendicular + r_out_parallel;
}
constexpr inline Vector3 Vector3::GetZero()
{
return Vector3(0.0, 0.0, 0.0);
}
inline Vector3 operator*(double scalar, const Vector3& vector)
{
return vector * scalar;
}
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/importer/external_process_importer_bridge.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/string_number_conversions.h"
#include "base/task_runner.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/history/history_types.h"
#include "chrome/browser/importer/profile_import_process_messages.h"
#include "content/public/common/password_form.h"
#include "ipc/ipc_sender.h"
#if defined(OS_WIN)
#include "chrome/browser/password_manager/ie7_password.h"
#endif
namespace {
// Rather than sending all import items over IPC at once we chunk them into
// separate requests. This avoids the case of a large import causing
// oversized IPC messages.
const int kNumBookmarksToSend = 100;
const int kNumHistoryRowsToSend = 100;
const int kNumFaviconsToSend = 100;
}
ExternalProcessImporterBridge::ExternalProcessImporterBridge(
const DictionaryValue& localized_strings,
IPC::Sender* sender,
base::TaskRunner* task_runner)
: sender_(sender),
task_runner_(task_runner) {
// Bridge needs to make its own copy because OS 10.6 autoreleases the
// localized_strings value that is passed in (see http://crbug.com/46003 ).
localized_strings_.reset(localized_strings.DeepCopy());
}
void ExternalProcessImporterBridge::AddBookmarks(
const std::vector<ProfileWriter::BookmarkEntry>& bookmarks,
const string16& first_folder_name) {
Send(new ProfileImportProcessHostMsg_NotifyBookmarksImportStart(
first_folder_name, bookmarks.size()));
std::vector<ProfileWriter::BookmarkEntry>::const_iterator it;
for (it = bookmarks.begin(); it < bookmarks.end();
it = it + kNumBookmarksToSend) {
std::vector<ProfileWriter::BookmarkEntry> bookmark_group;
std::vector<ProfileWriter::BookmarkEntry>::const_iterator end_group =
it + kNumBookmarksToSend < bookmarks.end() ?
it + kNumBookmarksToSend : bookmarks.end();
bookmark_group.assign(it, end_group);
Send(new ProfileImportProcessHostMsg_NotifyBookmarksImportGroup(
bookmark_group));
}
}
void ExternalProcessImporterBridge::AddHomePage(const GURL& home_page) {
NOTIMPLEMENTED();
}
#if defined(OS_WIN)
void ExternalProcessImporterBridge::AddIE7PasswordInfo(
const IE7PasswordInfo& password_info) {
NOTIMPLEMENTED();
}
#endif
void ExternalProcessImporterBridge::SetFavicons(
const std::vector<history::ImportedFaviconUsage>& favicons) {
Send(new ProfileImportProcessHostMsg_NotifyFaviconsImportStart(
favicons.size()));
std::vector<history::ImportedFaviconUsage>::const_iterator it;
for (it = favicons.begin(); it < favicons.end();
it = it + kNumFaviconsToSend) {
std::vector<history::ImportedFaviconUsage> favicons_group;
std::vector<history::ImportedFaviconUsage>::const_iterator end_group =
std::min(it + kNumFaviconsToSend, favicons.end());
favicons_group.assign(it, end_group);
Send(new ProfileImportProcessHostMsg_NotifyFaviconsImportGroup(
favicons_group));
}
}
void ExternalProcessImporterBridge::SetHistoryItems(
const history::URLRows& rows,
history::VisitSource visit_source) {
Send(new ProfileImportProcessHostMsg_NotifyHistoryImportStart(rows.size()));
history::URLRows::const_iterator it;
for (it = rows.begin(); it < rows.end();
it = it + kNumHistoryRowsToSend) {
history::URLRows row_group;
history::URLRows::const_iterator end_group =
it + kNumHistoryRowsToSend < rows.end() ?
it + kNumHistoryRowsToSend : rows.end();
row_group.assign(it, end_group);
Send(new ProfileImportProcessHostMsg_NotifyHistoryImportGroup(row_group,
visit_source));
}
}
void ExternalProcessImporterBridge::SetKeywords(
const std::vector<TemplateURL*>& template_urls,
bool unique_on_host_and_path) {
Send(new ProfileImportProcessHostMsg_NotifyKeywordsReady(template_urls,
unique_on_host_and_path));
STLDeleteContainerPointers(template_urls.begin(), template_urls.end());
}
void ExternalProcessImporterBridge::SetPasswordForm(
const content::PasswordForm& form) {
Send(new ProfileImportProcessHostMsg_NotifyPasswordFormReady(form));
}
void ExternalProcessImporterBridge::NotifyStarted() {
Send(new ProfileImportProcessHostMsg_Import_Started());
}
void ExternalProcessImporterBridge::NotifyItemStarted(
importer::ImportItem item) {
Send(new ProfileImportProcessHostMsg_ImportItem_Started(item));
}
void ExternalProcessImporterBridge::NotifyItemEnded(importer::ImportItem item) {
Send(new ProfileImportProcessHostMsg_ImportItem_Finished(item));
}
void ExternalProcessImporterBridge::NotifyEnded() {
// The internal process detects import end when all items have been received.
}
string16 ExternalProcessImporterBridge::GetLocalizedString(int message_id) {
string16 message;
localized_strings_->GetString(base::IntToString(message_id), &message);
return message;
}
ExternalProcessImporterBridge::~ExternalProcessImporterBridge() {}
void ExternalProcessImporterBridge::Send(IPC::Message* message) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&ExternalProcessImporterBridge::SendInternal,
this, message));
}
void ExternalProcessImporterBridge::SendInternal(IPC::Message* message) {
DCHECK(task_runner_->RunsTasksOnCurrentThread());
sender_->Send(message);
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#include "FindSessionsCallbackProxyAdvanced.h"
//////////////////////////////////////////////////////////////////////////
// UFindSessionsCallbackProxyAdvanced
UFindSessionsCallbackProxyAdvanced::UFindSessionsCallbackProxyAdvanced(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
, Delegate(FOnFindSessionsCompleteDelegate::CreateUObject(this, &ThisClass::OnCompleted))
, bUseLAN(false)
{
bRunSecondSearch = false;
bIsOnSecondSearch = false;
}
UFindSessionsCallbackProxyAdvanced* UFindSessionsCallbackProxyAdvanced::FindSessionsAdvanced(UObject* WorldContextObject, class APlayerController* PlayerController, int MaxResults, bool bUseLAN, EBPServerPresenceSearchType ServerTypeToSearch, const TArray<FSessionsSearchSetting> &Filters, bool bEmptyServersOnly, bool bNonEmptyServersOnly, bool bSecureServersOnly, bool bSearchLobbies, int MinSlotsAvailable)
{
UFindSessionsCallbackProxyAdvanced* Proxy = NewObject<UFindSessionsCallbackProxyAdvanced>();
Proxy->PlayerControllerWeakPtr = PlayerController;
Proxy->bUseLAN = bUseLAN;
Proxy->MaxResults = MaxResults;
Proxy->WorldContextObject = WorldContextObject;
Proxy->SearchSettings = Filters;
Proxy->ServerSearchType = ServerTypeToSearch;
Proxy->bEmptyServersOnly = bEmptyServersOnly,
Proxy->bNonEmptyServersOnly = bNonEmptyServersOnly;
Proxy->bSecureServersOnly = bSecureServersOnly;
Proxy->bSearchLobbies = bSearchLobbies;
Proxy->MinSlotsAvailable = MinSlotsAvailable;
return Proxy;
}
void UFindSessionsCallbackProxyAdvanced::Activate()
{
FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("FindSessions"), GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull));
Helper.QueryIDFromPlayerController(PlayerControllerWeakPtr.Get());
if (Helper.IsValid())
{
auto Sessions = Helper.OnlineSub->GetSessionInterface();
if (Sessions.IsValid())
{
// Re-initialize here, otherwise I think there might be issues with people re-calling search for some reason before it is destroyed
bRunSecondSearch = false;
bIsOnSecondSearch = false;
DelegateHandle = Sessions->AddOnFindSessionsCompleteDelegate_Handle(Delegate);
SearchObject = MakeShareable(new FOnlineSessionSearch);
SearchObject->MaxSearchResults = MaxResults;
SearchObject->bIsLanQuery = bUseLAN;
//SearchObject->QuerySettings.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals);
// Create temp filter variable, because I had to re-define a blueprint version of this, it is required.
FOnlineSearchSettingsEx tem;
/* // Search only for dedicated servers (value is true/false)
#define SEARCH_DEDICATED_ONLY FName(TEXT("DEDICATEDONLY"))
// Search for empty servers only (value is true/false)
#define SEARCH_EMPTY_SERVERS_ONLY FName(TEXT("EMPTYONLY"))
// Search for non empty servers only (value is true/false)
#define SEARCH_NONEMPTY_SERVERS_ONLY FName(TEXT("NONEMPTYONLY"))
// Search for secure servers only (value is true/false)
#define SEARCH_SECURE_SERVERS_ONLY FName(TEXT("SECUREONLY"))
// Search for presence sessions only (value is true/false)
#define SEARCH_PRESENCE FName(TEXT("PRESENCESEARCH"))
// Search for a match with min player availability (value is int)
#define SEARCH_MINSLOTSAVAILABLE FName(TEXT("MINSLOTSAVAILABLE"))
// Exclude all matches where any unique ids in a given array are present (value is string of the form "uniqueid1;uniqueid2;uniqueid3")
#define SEARCH_EXCLUDE_UNIQUEIDS FName(TEXT("EXCLUDEUNIQUEIDS"))
// User ID to search for session of
#define SEARCH_USER FName(TEXT("SEARCHUSER"))
// Keywords to match in session search
#define SEARCH_KEYWORDS FName(TEXT("SEARCHKEYWORDS"))*/
/** Keywords to match in session search */
/** The matchmaking queue name to matchmake in, e.g. "TeamDeathmatch" (value is string) */
/** #define SEARCH_MATCHMAKING_QUEUE FName(TEXT("MATCHMAKINGQUEUE"))*/
/** If set, use the named Xbox Live hopper to find a session via matchmaking (value is a string) */
/** #define SEARCH_XBOX_LIVE_HOPPER_NAME FName(TEXT("LIVEHOPPERNAME"))*/
/** Which session template from the service configuration to use */
/** #define SEARCH_XBOX_LIVE_SESSION_TEMPLATE_NAME FName(TEXT("LIVESESSIONTEMPLATE"))*/
/** Selection method used to determine which match to join when multiple are returned (valid only on Switch) */
/** #define SEARCH_SWITCH_SELECTION_METHOD FName(TEXT("SWITCHSELECTIONMETHOD"))*/
/** Whether to use lobbies vs sessions */
/** #define SEARCH_LOBBIES FName(TEXT("LOBBYSEARCH"))*/
if (bEmptyServersOnly)
tem.Set(SEARCH_EMPTY_SERVERS_ONLY, true, EOnlineComparisonOp::Equals);
if (bNonEmptyServersOnly)
tem.Set(SEARCH_NONEMPTY_SERVERS_ONLY, true, EOnlineComparisonOp::Equals);
if (bSecureServersOnly)
tem.Set(SEARCH_SECURE_SERVERS_ONLY, true, EOnlineComparisonOp::Equals);
if (MinSlotsAvailable != 0)
tem.Set(SEARCH_MINSLOTSAVAILABLE, MinSlotsAvailable, EOnlineComparisonOp::GreaterThanEquals);
// Filter results
if (SearchSettings.Num() > 0)
{
for (int i = 0; i < SearchSettings.Num(); i++)
{
// Function that was added to make directly adding a FVariant possible
tem.HardSet(SearchSettings[i].PropertyKeyPair.Key, SearchSettings[i].PropertyKeyPair.Data, SearchSettings[i].ComparisonOp);
}
}
switch (ServerSearchType)
{
case EBPServerPresenceSearchType::ClientServersOnly:
{
tem.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals);
if (bSearchLobbies)
tem.Set(SEARCH_LOBBIES, true, EOnlineComparisonOp::Equals);
}
break;
case EBPServerPresenceSearchType::DedicatedServersOnly:
{
//tem.Set(SEARCH_DEDICATED_ONLY, true, EOnlineComparisonOp::Equals);
}
break;
case EBPServerPresenceSearchType::AllServers:
default:
{
// Only steam uses the separate searching flags currently
if (IOnlineSubsystem::DoesInstanceExist("STEAM"))
{
bRunSecondSearch = true;
SearchObjectDedicated = MakeShareable(new FOnlineSessionSearch);
SearchObjectDedicated->MaxSearchResults = MaxResults;
SearchObjectDedicated->bIsLanQuery = bUseLAN;
FOnlineSearchSettingsEx DedicatedOnly = tem;
tem.Set(SEARCH_PRESENCE, true, EOnlineComparisonOp::Equals);
//DedicatedOnly.Set(SEARCH_DEDICATED_ONLY, true, EOnlineComparisonOp::Equals);
SearchObjectDedicated->QuerySettings = DedicatedOnly;
}
}
break;
}
// Copy the derived temp variable over to it's base class
SearchObject->QuerySettings = tem;
Sessions->FindSessions(*Helper.UserID, SearchObject.ToSharedRef());
// OnQueryCompleted will get called, nothing more to do now
return;
}
else
{
FFrame::KismetExecutionMessage(TEXT("Sessions not supported by Online Subsystem"), ELogVerbosity::Warning);
}
}
// Fail immediately
OnFailure.Broadcast(SessionSearchResults);
}
void UFindSessionsCallbackProxyAdvanced::OnCompleted(bool bSuccess)
{
FOnlineSubsystemBPCallHelperAdvanced Helper(TEXT("FindSessionsCallback"), GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull));
Helper.QueryIDFromPlayerController(PlayerControllerWeakPtr.Get());
if (!bRunSecondSearch && Helper.IsValid())
{
auto Sessions = Helper.OnlineSub->GetSessionInterface();
if (Sessions.IsValid())
{
Sessions->ClearOnFindSessionsCompleteDelegate_Handle(DelegateHandle);
}
}
if (bSuccess)
{
if (bIsOnSecondSearch)
{
if (SearchObjectDedicated.IsValid())
{
// Just log the results for now, will need to add a blueprint-compatible search result struct
for (auto& Result : SearchObjectDedicated->SearchResults)
{
FString ResultText = FString::Printf(TEXT("Found a session. Ping is %d"), Result.PingInMs);
FFrame::KismetExecutionMessage(*ResultText, ELogVerbosity::Log);
FBlueprintSessionResult BPResult;
BPResult.OnlineResult = Result;
SessionSearchResults.Add(BPResult);
}
OnSuccess.Broadcast(SessionSearchResults);
return;
}
}
else
{
if (SearchObject.IsValid())
{
// Just log the results for now, will need to add a blueprint-compatible search result struct
for (auto& Result : SearchObject->SearchResults)
{
FString ResultText = FString::Printf(TEXT("Found a session. Ping is %d"), Result.PingInMs);
FFrame::KismetExecutionMessage(*ResultText, ELogVerbosity::Log);
FBlueprintSessionResult BPResult;
BPResult.OnlineResult = Result;
SessionSearchResults.Add(BPResult);
}
if (!bRunSecondSearch)
{
OnSuccess.Broadcast(SessionSearchResults);
return;
}
}
}
}
else
{
if (!bRunSecondSearch)
{
// Need to account for only one of the searches failing
if (SessionSearchResults.Num() > 0)
OnSuccess.Broadcast(SessionSearchResults);
else
OnFailure.Broadcast(SessionSearchResults);
return;
}
}
if (Helper.IsValid() && bRunSecondSearch && ServerSearchType == EBPServerPresenceSearchType::AllServers)
{
bRunSecondSearch = false;
bIsOnSecondSearch = true;
auto Sessions = Helper.OnlineSub->GetSessionInterface();
Sessions->FindSessions(*Helper.UserID, SearchObjectDedicated.ToSharedRef());
}
else // We lost our player controller
{
if (bSuccess && SessionSearchResults.Num() > 0)
OnSuccess.Broadcast(SessionSearchResults);
else
OnFailure.Broadcast(SessionSearchResults);
}
}
void UFindSessionsCallbackProxyAdvanced::FilterSessionResults(const TArray<FBlueprintSessionResult> &SessionResults, const TArray<FSessionsSearchSetting> &Filters, TArray<FBlueprintSessionResult> &FilteredResults)
{
for (int j = 0; j < SessionResults.Num(); j++)
{
bool bAddResult = true;
// Filter results
if (Filters.Num() > 0)
{
const FOnlineSessionSetting * setting;
for (int i = 0; i < Filters.Num(); i++)
{
setting = SessionResults[j].OnlineResult.Session.SessionSettings.Settings.Find(Filters[i].PropertyKeyPair.Key);
// Couldn't find this key
if (!setting)
continue;
if (!CompareVariants(setting->Data, Filters[i].PropertyKeyPair.Data, Filters[i].ComparisonOp))
{
bAddResult = false;
break;
}
}
}
if (bAddResult)
FilteredResults.Add(SessionResults[j]);
}
return;
}
bool UFindSessionsCallbackProxyAdvanced::CompareVariants(const FVariantData &A, const FVariantData &B, EOnlineComparisonOpRedux Comparator)
{
if (A.GetType() != B.GetType())
return false;
switch (A.GetType())
{
case EOnlineKeyValuePairDataType::Bool:
{
bool bA, bB;
A.GetValue(bA);
B.GetValue(bB);
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
default:
return false;break;
}
}
case EOnlineKeyValuePairDataType::Double:
{
double bA, bB;
A.GetValue(bA);
B.GetValue(bB);
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
case EOnlineComparisonOpRedux::GreaterThanEquals:
return (bA == bB || bA > bB); break;
case EOnlineComparisonOpRedux::LessThanEquals:
return (bA == bB || bA < bB); break;
case EOnlineComparisonOpRedux::GreaterThan:
return bA > bB; break;
case EOnlineComparisonOpRedux::LessThan:
return bA < bB; break;
default:
return false; break;
}
}
case EOnlineKeyValuePairDataType::Float:
{
float tbA, tbB;
double bA, bB;
A.GetValue(tbA);
B.GetValue(tbB);
bA = (double)tbA;
bB = (double)tbB;
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
case EOnlineComparisonOpRedux::GreaterThanEquals:
return (bA == bB || bA > bB); break;
case EOnlineComparisonOpRedux::LessThanEquals:
return (bA == bB || bA < bB); break;
case EOnlineComparisonOpRedux::GreaterThan:
return bA > bB; break;
case EOnlineComparisonOpRedux::LessThan:
return bA < bB; break;
default:
return false; break;
}
}
case EOnlineKeyValuePairDataType::Int32:
{
int32 bA, bB;
A.GetValue(bA);
B.GetValue(bB);
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
case EOnlineComparisonOpRedux::GreaterThanEquals:
return (bA == bB || bA > bB); break;
case EOnlineComparisonOpRedux::LessThanEquals:
return (bA == bB || bA < bB); break;
case EOnlineComparisonOpRedux::GreaterThan:
return bA > bB; break;
case EOnlineComparisonOpRedux::LessThan:
return bA < bB; break;
default:
return false; break;
}
}
case EOnlineKeyValuePairDataType::Int64:
{
uint64 bA, bB;
A.GetValue(bA);
B.GetValue(bB);
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
case EOnlineComparisonOpRedux::GreaterThanEquals:
return (bA == bB || bA > bB); break;
case EOnlineComparisonOpRedux::LessThanEquals:
return (bA == bB || bA < bB); break;
case EOnlineComparisonOpRedux::GreaterThan:
return bA > bB; break;
case EOnlineComparisonOpRedux::LessThan:
return bA < bB; break;
default:
return false; break;
}
}
case EOnlineKeyValuePairDataType::String:
{
FString bA, bB;
A.GetValue(bA);
B.GetValue(bB);
switch (Comparator)
{
case EOnlineComparisonOpRedux::Equals:
return bA == bB; break;
case EOnlineComparisonOpRedux::NotEquals:
return bA != bB; break;
default:
return false; break;
}
}
case EOnlineKeyValuePairDataType::Empty:
case EOnlineKeyValuePairDataType::Blob:
default:
return false; break;
}
}
|
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "db/db_test_util.h"
#include "port/stack_trace.h"
namespace rocksdb {
static int cfilter_count = 0;
// This is a static filter used for filtering
// kvs during the compaction process.
static std::string NEW_VALUE = "NewValue";
class DBTestCompactionFilter : public DBTestBase {
public:
DBTestCompactionFilter() : DBTestBase("/db_compaction_filter_test") {}
};
class KeepFilter : public CompactionFilter {
public:
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value, bool* value_changed) const
override {
cfilter_count++;
return false;
}
virtual const char* Name() const override { return "KeepFilter"; }
};
class DeleteFilter : public CompactionFilter {
public:
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value, bool* value_changed) const
override {
cfilter_count++;
return true;
}
virtual const char* Name() const override { return "DeleteFilter"; }
};
class DeleteISFilter : public CompactionFilter {
public:
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value,
bool* value_changed) const override {
cfilter_count++;
int i = std::stoi(key.ToString());
if (i > 5 && i <= 105) {
return true;
}
return false;
}
virtual bool IgnoreSnapshots() const override { return true; }
virtual const char* Name() const override { return "DeleteFilter"; }
};
class DelayFilter : public CompactionFilter {
public:
explicit DelayFilter(DBTestBase* d) : db_test(d) {}
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value,
bool* value_changed) const override {
db_test->env_->addon_time_.fetch_add(1000);
return true;
}
virtual const char* Name() const override { return "DelayFilter"; }
private:
DBTestBase* db_test;
};
class ConditionalFilter : public CompactionFilter {
public:
explicit ConditionalFilter(const std::string* filtered_value)
: filtered_value_(filtered_value) {}
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value,
bool* value_changed) const override {
return value.ToString() == *filtered_value_;
}
virtual const char* Name() const override { return "ConditionalFilter"; }
private:
const std::string* filtered_value_;
};
class ChangeFilter : public CompactionFilter {
public:
explicit ChangeFilter() {}
virtual bool Filter(int level, const Slice& key, const Slice& value,
std::string* new_value, bool* value_changed) const
override {
assert(new_value != nullptr);
*new_value = NEW_VALUE;
*value_changed = true;
return false;
}
virtual const char* Name() const override { return "ChangeFilter"; }
};
class KeepFilterFactory : public CompactionFilterFactory {
public:
explicit KeepFilterFactory(bool check_context = false,
bool check_context_cf_id = false)
: check_context_(check_context),
check_context_cf_id_(check_context_cf_id),
compaction_filter_created_(false) {}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
if (check_context_) {
EXPECT_EQ(expect_full_compaction_.load(), context.is_full_compaction);
EXPECT_EQ(expect_manual_compaction_.load(), context.is_manual_compaction);
}
if (check_context_cf_id_) {
EXPECT_EQ(expect_cf_id_.load(), context.column_family_id);
}
compaction_filter_created_ = true;
return std::unique_ptr<CompactionFilter>(new KeepFilter());
}
bool compaction_filter_created() const { return compaction_filter_created_; }
virtual const char* Name() const override { return "KeepFilterFactory"; }
bool check_context_;
bool check_context_cf_id_;
std::atomic_bool expect_full_compaction_;
std::atomic_bool expect_manual_compaction_;
std::atomic<uint32_t> expect_cf_id_;
bool compaction_filter_created_;
};
class DeleteFilterFactory : public CompactionFilterFactory {
public:
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
if (context.is_manual_compaction) {
return std::unique_ptr<CompactionFilter>(new DeleteFilter());
} else {
return std::unique_ptr<CompactionFilter>(nullptr);
}
}
virtual const char* Name() const override { return "DeleteFilterFactory"; }
};
// Delete Filter Factory which ignores snapshots
class DeleteISFilterFactory : public CompactionFilterFactory {
public:
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
if (context.is_manual_compaction) {
return std::unique_ptr<CompactionFilter>(new DeleteISFilter());
} else {
return std::unique_ptr<CompactionFilter>(nullptr);
}
}
virtual const char* Name() const override { return "DeleteFilterFactory"; }
};
class DelayFilterFactory : public CompactionFilterFactory {
public:
explicit DelayFilterFactory(DBTestBase* d) : db_test(d) {}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
return std::unique_ptr<CompactionFilter>(new DelayFilter(db_test));
}
virtual const char* Name() const override { return "DelayFilterFactory"; }
private:
DBTestBase* db_test;
};
class ConditionalFilterFactory : public CompactionFilterFactory {
public:
explicit ConditionalFilterFactory(const Slice& filtered_value)
: filtered_value_(filtered_value.ToString()) {}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
return std::unique_ptr<CompactionFilter>(
new ConditionalFilter(&filtered_value_));
}
virtual const char* Name() const override {
return "ConditionalFilterFactory";
}
private:
std::string filtered_value_;
};
class ChangeFilterFactory : public CompactionFilterFactory {
public:
explicit ChangeFilterFactory() {}
virtual std::unique_ptr<CompactionFilter> CreateCompactionFilter(
const CompactionFilter::Context& context) override {
return std::unique_ptr<CompactionFilter>(new ChangeFilter());
}
virtual const char* Name() const override { return "ChangeFilterFactory"; }
};
#ifndef ROCKSDB_LITE
TEST_F(DBTestCompactionFilter, CompactionFilter) {
Options options = CurrentOptions();
options.max_open_files = -1;
options.num_levels = 3;
options.compaction_filter_factory = std::make_shared<KeepFilterFactory>();
options = CurrentOptions(options);
CreateAndReopenWithCF({"pikachu"}, options);
// Write 100K keys, these are written to a few files in L0.
const std::string value(10, 'x');
for (int i = 0; i < 100000; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
Put(1, key, value);
}
ASSERT_OK(Flush(1));
// Push all files to the highest level L2. Verify that
// the compaction is each level invokes the filter for
// all the keys in that level.
cfilter_count = 0;
dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 100000);
cfilter_count = 0;
dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 100000);
ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
ASSERT_EQ(NumTableFilesAtLevel(1, 1), 0);
ASSERT_NE(NumTableFilesAtLevel(2, 1), 0);
cfilter_count = 0;
// All the files are in the lowest level.
// Verify that all but the 100001st record
// has sequence number zero. The 100001st record
// is at the tip of this snapshot and cannot
// be zeroed out.
int count = 0;
int total = 0;
Arena arena;
{
ScopedArenaIterator iter(
dbfull()->NewInternalIterator(&arena, handles_[1]));
iter->SeekToFirst();
ASSERT_OK(iter->status());
while (iter->Valid()) {
ParsedInternalKey ikey(Slice(), 0, kTypeValue);
ikey.sequence = -1;
ASSERT_EQ(ParseInternalKey(iter->key(), &ikey), true);
total++;
if (ikey.sequence != 0) {
count++;
}
iter->Next();
}
}
ASSERT_EQ(total, 100000);
ASSERT_EQ(count, 1);
// overwrite all the 100K keys once again.
for (int i = 0; i < 100000; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
ASSERT_OK(Put(1, key, value));
}
ASSERT_OK(Flush(1));
// push all files to the highest level L2. This
// means that all keys should pass at least once
// via the compaction filter
cfilter_count = 0;
dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 100000);
cfilter_count = 0;
dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 100000);
ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
ASSERT_EQ(NumTableFilesAtLevel(1, 1), 0);
ASSERT_NE(NumTableFilesAtLevel(2, 1), 0);
// create a new database with the compaction
// filter in such a way that it deletes all keys
options.compaction_filter_factory = std::make_shared<DeleteFilterFactory>();
options.create_if_missing = true;
DestroyAndReopen(options);
CreateAndReopenWithCF({"pikachu"}, options);
// write all the keys once again.
for (int i = 0; i < 100000; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
ASSERT_OK(Put(1, key, value));
}
ASSERT_OK(Flush(1));
ASSERT_NE(NumTableFilesAtLevel(0, 1), 0);
ASSERT_EQ(NumTableFilesAtLevel(1, 1), 0);
ASSERT_EQ(NumTableFilesAtLevel(2, 1), 0);
// Push all files to the highest level L2. This
// triggers the compaction filter to delete all keys,
// verify that at the end of the compaction process,
// nothing is left.
cfilter_count = 0;
dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 100000);
cfilter_count = 0;
dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]);
ASSERT_EQ(cfilter_count, 0);
ASSERT_EQ(NumTableFilesAtLevel(0, 1), 0);
ASSERT_EQ(NumTableFilesAtLevel(1, 1), 0);
{
// Scan the entire database to ensure that nothing is left
std::unique_ptr<Iterator> iter(
db_->NewIterator(ReadOptions(), handles_[1]));
iter->SeekToFirst();
count = 0;
while (iter->Valid()) {
count++;
iter->Next();
}
ASSERT_EQ(count, 0);
}
// The sequence number of the remaining record
// is not zeroed out even though it is at the
// level Lmax because this record is at the tip
count = 0;
{
ScopedArenaIterator iter(
dbfull()->NewInternalIterator(&arena, handles_[1]));
iter->SeekToFirst();
ASSERT_OK(iter->status());
while (iter->Valid()) {
ParsedInternalKey ikey(Slice(), 0, kTypeValue);
ASSERT_EQ(ParseInternalKey(iter->key(), &ikey), true);
ASSERT_NE(ikey.sequence, (unsigned)0);
count++;
iter->Next();
}
ASSERT_EQ(count, 0);
}
}
// Tests the edge case where compaction does not produce any output -- all
// entries are deleted. The compaction should create bunch of 'DeleteFile'
// entries in VersionEdit, but none of the 'AddFile's.
TEST_F(DBTestCompactionFilter, CompactionFilterDeletesAll) {
Options options = CurrentOptions();
options.compaction_filter_factory = std::make_shared<DeleteFilterFactory>();
options.disable_auto_compactions = true;
options.create_if_missing = true;
DestroyAndReopen(options);
// put some data
for (int table = 0; table < 4; ++table) {
for (int i = 0; i < 10 + table; ++i) {
Put(ToString(table * 100 + i), "val");
}
Flush();
}
// this will produce empty file (delete compaction filter)
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_EQ(0U, CountLiveFiles());
Reopen(options);
Iterator* itr = db_->NewIterator(ReadOptions());
itr->SeekToFirst();
// empty db
ASSERT_TRUE(!itr->Valid());
delete itr;
}
#endif // ROCKSDB_LITE
TEST_F(DBTestCompactionFilter, CompactionFilterWithValueChange) {
do {
Options options = CurrentOptions();
options.num_levels = 3;
options.compaction_filter_factory =
std::make_shared<ChangeFilterFactory>();
CreateAndReopenWithCF({"pikachu"}, options);
// Write 100K+1 keys, these are written to a few files
// in L0. We do this so that the current snapshot points
// to the 100001 key.The compaction filter is not invoked
// on keys that are visible via a snapshot because we
// anyways cannot delete it.
const std::string value(10, 'x');
for (int i = 0; i < 100001; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
Put(1, key, value);
}
// push all files to lower levels
ASSERT_OK(Flush(1));
if (option_config_ != kUniversalCompactionMultiLevel &&
option_config_ != kUniversalSubcompactions) {
dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]);
} else {
dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
nullptr);
}
// re-write all data again
for (int i = 0; i < 100001; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
Put(1, key, value);
}
// push all files to lower levels. This should
// invoke the compaction filter for all 100000 keys.
ASSERT_OK(Flush(1));
if (option_config_ != kUniversalCompactionMultiLevel &&
option_config_ != kUniversalSubcompactions) {
dbfull()->TEST_CompactRange(0, nullptr, nullptr, handles_[1]);
dbfull()->TEST_CompactRange(1, nullptr, nullptr, handles_[1]);
} else {
dbfull()->CompactRange(CompactRangeOptions(), handles_[1], nullptr,
nullptr);
}
// verify that all keys now have the new value that
// was set by the compaction process.
for (int i = 0; i < 100001; i++) {
char key[100];
snprintf(key, sizeof(key), "B%010d", i);
std::string newvalue = Get(1, key);
ASSERT_EQ(newvalue.compare(NEW_VALUE), 0);
}
} while (ChangeCompactOptions());
}
TEST_F(DBTestCompactionFilter, CompactionFilterWithMergeOperator) {
std::string one, two, three, four;
PutFixed64(&one, 1);
PutFixed64(&two, 2);
PutFixed64(&three, 3);
PutFixed64(&four, 4);
Options options = CurrentOptions();
options.create_if_missing = true;
options.merge_operator = MergeOperators::CreateUInt64AddOperator();
options.num_levels = 3;
// Filter out keys with value is 2.
options.compaction_filter_factory =
std::make_shared<ConditionalFilterFactory>(two);
DestroyAndReopen(options);
// In the same compaction, a value type needs to be deleted based on
// compaction filter, and there is a merge type for the key. compaction
// filter result is ignored.
ASSERT_OK(db_->Put(WriteOptions(), "foo", two));
ASSERT_OK(Flush());
ASSERT_OK(db_->Merge(WriteOptions(), "foo", one));
ASSERT_OK(Flush());
std::string newvalue = Get("foo");
ASSERT_EQ(newvalue, three);
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
newvalue = Get("foo");
ASSERT_EQ(newvalue, three);
// value key can be deleted based on compaction filter, leaving only
// merge keys.
ASSERT_OK(db_->Put(WriteOptions(), "bar", two));
ASSERT_OK(Flush());
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
newvalue = Get("bar");
ASSERT_EQ("NOT_FOUND", newvalue);
ASSERT_OK(db_->Merge(WriteOptions(), "bar", two));
ASSERT_OK(Flush());
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
newvalue = Get("bar");
ASSERT_EQ(two, two);
// Compaction filter never applies to merge keys.
ASSERT_OK(db_->Put(WriteOptions(), "foobar", one));
ASSERT_OK(Flush());
ASSERT_OK(db_->Merge(WriteOptions(), "foobar", two));
ASSERT_OK(Flush());
newvalue = Get("foobar");
ASSERT_EQ(newvalue, three);
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
newvalue = Get("foobar");
ASSERT_EQ(newvalue, three);
// In the same compaction, both of value type and merge type keys need to be
// deleted based on compaction filter, and there is a merge type for the key.
// For both keys, compaction filter results are ignored.
ASSERT_OK(db_->Put(WriteOptions(), "barfoo", two));
ASSERT_OK(Flush());
ASSERT_OK(db_->Merge(WriteOptions(), "barfoo", two));
ASSERT_OK(Flush());
newvalue = Get("barfoo");
ASSERT_EQ(newvalue, four);
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
newvalue = Get("barfoo");
ASSERT_EQ(newvalue, four);
}
#ifndef ROCKSDB_LITE
TEST_F(DBTestCompactionFilter, CompactionFilterContextManual) {
KeepFilterFactory* filter = new KeepFilterFactory(true, true);
Options options = CurrentOptions();
options.compaction_style = kCompactionStyleUniversal;
options.compaction_filter_factory.reset(filter);
options.compression = kNoCompression;
options.level0_file_num_compaction_trigger = 8;
Reopen(options);
int num_keys_per_file = 400;
for (int j = 0; j < 3; j++) {
// Write several keys.
const std::string value(10, 'x');
for (int i = 0; i < num_keys_per_file; i++) {
char key[100];
snprintf(key, sizeof(key), "B%08d%02d", i, j);
Put(key, value);
}
dbfull()->TEST_FlushMemTable();
// Make sure next file is much smaller so automatic compaction will not
// be triggered.
num_keys_per_file /= 2;
}
dbfull()->TEST_WaitForCompact();
// Force a manual compaction
cfilter_count = 0;
filter->expect_manual_compaction_.store(true);
filter->expect_full_compaction_.store(true);
filter->expect_cf_id_.store(0);
dbfull()->CompactRange(CompactRangeOptions(), nullptr, nullptr);
ASSERT_EQ(cfilter_count, 700);
ASSERT_EQ(NumSortedRuns(0), 1);
ASSERT_TRUE(filter->compaction_filter_created());
// Verify total number of keys is correct after manual compaction.
{
int count = 0;
int total = 0;
Arena arena;
ScopedArenaIterator iter(dbfull()->NewInternalIterator(&arena));
iter->SeekToFirst();
ASSERT_OK(iter->status());
while (iter->Valid()) {
ParsedInternalKey ikey(Slice(), 0, kTypeValue);
ikey.sequence = -1;
ASSERT_EQ(ParseInternalKey(iter->key(), &ikey), true);
total++;
if (ikey.sequence != 0) {
count++;
}
iter->Next();
}
ASSERT_EQ(total, 700);
ASSERT_EQ(count, 2);
}
}
#endif // ROCKSDB_LITE
TEST_F(DBTestCompactionFilter, CompactionFilterContextCfId) {
KeepFilterFactory* filter = new KeepFilterFactory(false, true);
filter->expect_cf_id_.store(1);
Options options = CurrentOptions();
options.compaction_filter_factory.reset(filter);
options.compression = kNoCompression;
options.level0_file_num_compaction_trigger = 2;
CreateAndReopenWithCF({"pikachu"}, options);
int num_keys_per_file = 400;
for (int j = 0; j < 3; j++) {
// Write several keys.
const std::string value(10, 'x');
for (int i = 0; i < num_keys_per_file; i++) {
char key[100];
snprintf(key, sizeof(key), "B%08d%02d", i, j);
Put(1, key, value);
}
Flush(1);
// Make sure next file is much smaller so automatic compaction will not
// be triggered.
num_keys_per_file /= 2;
}
dbfull()->TEST_WaitForCompact();
ASSERT_TRUE(filter->compaction_filter_created());
}
#ifndef ROCKSDB_LITE
// Compaction filters should only be applied to records that are newer than the
// latest snapshot. This test inserts records and applies a delete filter.
TEST_F(DBTestCompactionFilter, CompactionFilterSnapshot) {
Options options = CurrentOptions();
options.compaction_filter_factory = std::make_shared<DeleteFilterFactory>();
options.disable_auto_compactions = true;
options.create_if_missing = true;
DestroyAndReopen(options);
// Put some data.
const Snapshot* snapshot = nullptr;
for (int table = 0; table < 4; ++table) {
for (int i = 0; i < 10; ++i) {
Put(ToString(table * 100 + i), "val");
}
Flush();
if (table == 0) {
snapshot = db_->GetSnapshot();
}
}
assert(snapshot != nullptr);
cfilter_count = 0;
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// The filter should delete 10 records.
ASSERT_EQ(30U, cfilter_count);
// Release the snapshot and compact again -> now all records should be
// removed.
db_->ReleaseSnapshot(snapshot);
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
ASSERT_EQ(0U, CountLiveFiles());
}
// Compaction filters should only be applied to records that are newer than the
// latest snapshot. However, if the compaction filter asks to ignore snapshots
// records newer than the snapshot will also be processed
TEST_F(DBTestCompactionFilter, CompactionFilterIgnoreSnapshot) {
std::string five = ToString(5);
Options options = CurrentOptions();
options.compaction_filter_factory = std::make_shared<DeleteISFilterFactory>();
options.disable_auto_compactions = true;
options.create_if_missing = true;
DestroyAndReopen(options);
// Put some data.
const Snapshot* snapshot = nullptr;
for (int table = 0; table < 4; ++table) {
for (int i = 0; i < 10; ++i) {
Put(ToString(table * 100 + i), "val");
}
Flush();
if (table == 0) {
snapshot = db_->GetSnapshot();
}
}
assert(snapshot != nullptr);
cfilter_count = 0;
ASSERT_OK(db_->CompactRange(CompactRangeOptions(), nullptr, nullptr));
// The filter should delete 40 records.
ASSERT_EQ(40U, cfilter_count);
{
// Scan the entire database as of the snapshot to ensure
// that nothing is left
ReadOptions read_options;
read_options.snapshot = snapshot;
std::unique_ptr<Iterator> iter(db_->NewIterator(read_options));
iter->SeekToFirst();
int count = 0;
while (iter->Valid()) {
count++;
iter->Next();
}
ASSERT_EQ(count, 6);
read_options.snapshot = 0;
std::unique_ptr<Iterator> iter1(db_->NewIterator(read_options));
iter1->SeekToFirst();
count = 0;
while (iter1->Valid()) {
count++;
iter1->Next();
}
// We have deleted 10 keys from 40 using the compaction filter
// Keys 6-9 before the snapshot and 100-105 after the snapshot
ASSERT_EQ(count, 30);
}
// Release the snapshot and compact again -> now all records should be
// removed.
db_->ReleaseSnapshot(snapshot);
}
#endif // ROCKSDB_LITE
} // namespace rocksdb
int main(int argc, char** argv) {
rocksdb::port::InstallStackTraceHandler();
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// 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 "chrome/browser/sessions/restore_on_startup_policy_handler.h"
#include "base/strings/string_number_conversions.h"
#include "base/values.h"
#include "chrome/browser/prefs/session_startup_pref.h"
#include "chrome/common/pref_names.h"
#include "components/policy/core/browser/policy_error_map.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_value_map.h"
#include "components/strings/grit/components_strings.h"
namespace policy {
RestoreOnStartupPolicyHandler::RestoreOnStartupPolicyHandler()
: TypeCheckingPolicyHandler(key::kRestoreOnStartup,
base::Value::Type::INTEGER) {}
RestoreOnStartupPolicyHandler::~RestoreOnStartupPolicyHandler() {
}
void RestoreOnStartupPolicyHandler::ApplyPolicySettings(
const PolicyMap& policies,
PrefValueMap* prefs) {
const base::Value* restore_on_startup_value =
policies.GetValue(policy_name());
if (restore_on_startup_value) {
int restore_on_startup;
if (!restore_on_startup_value->GetAsInteger(&restore_on_startup))
return;
prefs->SetInteger(prefs::kRestoreOnStartup, restore_on_startup);
}
}
bool RestoreOnStartupPolicyHandler::CheckPolicySettings(
const PolicyMap& policies,
PolicyErrorMap* errors) {
if (!TypeCheckingPolicyHandler::CheckPolicySettings(policies, errors))
return false;
const base::Value* restore_policy = policies.GetValue(key::kRestoreOnStartup);
if (restore_policy) {
int restore_value;
CHECK(restore_policy->GetAsInteger(&restore_value)); // Passed type check.
switch (restore_value) {
case 0: // Deprecated kPrefValueHomePage.
errors->AddError(policy_name(), IDS_POLICY_VALUE_DEPRECATED);
break;
case SessionStartupPref::kPrefValueLast: {
// If the "restore last session" policy is set, session cookies are
// treated as permanent cookies and site data needed to restore the
// session is not cleared so we have to warn the user in that case.
const base::Value* cookies_policy =
policies.GetValue(key::kCookiesSessionOnlyForUrls);
const base::ListValue* cookies_value;
if (cookies_policy && cookies_policy->GetAsList(&cookies_value) &&
!cookies_value->empty()) {
errors->AddError(key::kCookiesSessionOnlyForUrls,
IDS_POLICY_OVERRIDDEN,
key::kRestoreOnStartup);
}
const base::Value* exit_policy =
policies.GetValue(key::kClearSiteDataOnExit);
bool exit_value;
if (exit_policy && exit_policy->GetAsBoolean(&exit_value) &&
exit_value) {
errors->AddError(key::kClearSiteDataOnExit,
IDS_POLICY_OVERRIDDEN,
key::kRestoreOnStartup);
}
break;
}
case SessionStartupPref::kPrefValueURLs:
case SessionStartupPref::kPrefValueNewTab:
// No error
break;
default:
errors->AddError(policy_name(),
IDS_POLICY_OUT_OF_RANGE_ERROR,
base::IntToString(restore_value));
}
}
return true;
}
} // namespace policy
|
// dear imgui, v1.84
// (tables and columns code)
/*
Index of this file:
// [SECTION] Commentary
// [SECTION] Header mess
// [SECTION] Tables: Main code
// [SECTION] Tables: Simple accessors
// [SECTION] Tables: Row changes
// [SECTION] Tables: Columns changes
// [SECTION] Tables: Columns width management
// [SECTION] Tables: Drawing
// [SECTION] Tables: Sorting
// [SECTION] Tables: Headers
// [SECTION] Tables: Context Menu
// [SECTION] Tables: Settings (.ini data)
// [SECTION] Tables: Garbage Collection
// [SECTION] Tables: Debugging
// [SECTION] Columns, BeginColumns, EndColumns, etc.
*/
// Navigating this file:
// - In Visual Studio IDE: CTRL+comma ("Edit.NavigateTo") can follow symbols in comments, whereas CTRL+F12 ("Edit.GoToImplementation") cannot.
// - With Visual Assist installed: ALT+G ("VAssistX.GoToImplementation") can also follow symbols in comments.
//-----------------------------------------------------------------------------
// [SECTION] Commentary
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Typical tables call flow: (root level is generally public API):
//-----------------------------------------------------------------------------
// - BeginTable() user begin into a table
// | BeginChild() - (if ScrollX/ScrollY is set)
// | TableBeginInitMemory() - first time table is used
// | TableResetSettings() - on settings reset
// | TableLoadSettings() - on settings load
// | TableBeginApplyRequests() - apply queued resizing/reordering/hiding requests
// | - TableSetColumnWidth() - apply resizing width (for mouse resize, often requested by previous frame)
// | - TableUpdateColumnsWeightFromWidth()- recompute columns weights (of stretch columns) from their respective width
// - TableSetupColumn() user submit columns details (optional)
// - TableSetupScrollFreeze() user submit scroll freeze information (optional)
//-----------------------------------------------------------------------------
// - TableUpdateLayout() [Internal] followup to BeginTable(): setup everything: widths, columns positions, clipping rectangles. Automatically called by the FIRST call to TableNextRow() or TableHeadersRow().
// | TableSetupDrawChannels() - setup ImDrawList channels
// | TableUpdateBorders() - detect hovering columns for resize, ahead of contents submission
// | TableDrawContextMenu() - draw right-click context menu
//-----------------------------------------------------------------------------
// - TableHeadersRow() or TableHeader() user submit a headers row (optional)
// | TableSortSpecsClickColumn() - when left-clicked: alter sort order and sort direction
// | TableOpenContextMenu() - when right-clicked: trigger opening of the default context menu
// - TableGetSortSpecs() user queries updated sort specs (optional, generally after submitting headers)
// - TableNextRow() user begin into a new row (also automatically called by TableHeadersRow())
// | TableEndRow() - finish existing row
// | TableBeginRow() - add a new row
// - TableSetColumnIndex() / TableNextColumn() user begin into a cell
// | TableEndCell() - close existing column/cell
// | TableBeginCell() - enter into current column/cell
// - [...] user emit contents
//-----------------------------------------------------------------------------
// - EndTable() user ends the table
// | TableDrawBorders() - draw outer borders, inner vertical borders
// | TableMergeDrawChannels() - merge draw channels if clipping isn't required
// | EndChild() - (if ScrollX/ScrollY is set)
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// TABLE SIZING
//-----------------------------------------------------------------------------
// (Read carefully because this is subtle but it does make sense!)
//-----------------------------------------------------------------------------
// About 'outer_size':
// Its meaning needs to differ slightly depending on if we are using ScrollX/ScrollY flags.
// Default value is ImVec2(0.0f, 0.0f).
// X
// - outer_size.x <= 0.0f -> Right-align from window/work-rect right-most edge. With -FLT_MIN or 0.0f will align exactly on right-most edge.
// - outer_size.x > 0.0f -> Set Fixed width.
// Y with ScrollX/ScrollY disabled: we output table directly in current window
// - outer_size.y < 0.0f -> Bottom-align (but will auto extend, unless _NoHostExtendY is set). Not meaningful is parent window can vertically scroll.
// - outer_size.y = 0.0f -> No minimum height (but will auto extend, unless _NoHostExtendY is set)
// - outer_size.y > 0.0f -> Set Minimum height (but will auto extend, unless _NoHostExtenY is set)
// Y with ScrollX/ScrollY enabled: using a child window for scrolling
// - outer_size.y < 0.0f -> Bottom-align. Not meaningful is parent window can vertically scroll.
// - outer_size.y = 0.0f -> Bottom-align, consistent with BeginChild(). Not recommended unless table is last item in parent window.
// - outer_size.y > 0.0f -> Set Exact height. Recommended when using Scrolling on any axis.
//-----------------------------------------------------------------------------
// Outer size is also affected by the NoHostExtendX/NoHostExtendY flags.
// Important to that note how the two flags have slightly different behaviors!
// - ImGuiTableFlags_NoHostExtendX -> Make outer width auto-fit to columns (overriding outer_size.x value). Only available when ScrollX/ScrollY are disabled and Stretch columns are not used.
// - ImGuiTableFlags_NoHostExtendY -> Make outer height stop exactly at outer_size.y (prevent auto-extending table past the limit). Only available when ScrollX/ScrollY is disabled. Data below the limit will be clipped and not visible.
// In theory ImGuiTableFlags_NoHostExtendY could be the default and any non-scrolling tables with outer_size.y != 0.0f would use exact height.
// This would be consistent but perhaps less useful and more confusing (as vertically clipped items are not easily noticeable)
//-----------------------------------------------------------------------------
// About 'inner_width':
// With ScrollX disabled:
// - inner_width -> *ignored*
// With ScrollX enabled:
// - inner_width < 0.0f -> *illegal* fit in known width (right align from outer_size.x) <-- weird
// - inner_width = 0.0f -> fit in outer_width: Fixed size columns will take space they need (if avail, otherwise shrink down), Stretch columns becomes Fixed columns.
// - inner_width > 0.0f -> override scrolling width, generally to be larger than outer_size.x. Fixed column take space they need (if avail, otherwise shrink down), Stretch columns share remaining space!
//-----------------------------------------------------------------------------
// Details:
// - If you want to use Stretch columns with ScrollX, you generally need to specify 'inner_width' otherwise the concept
// of "available space" doesn't make sense.
// - Even if not really useful, we allow 'inner_width < outer_size.x' for consistency and to facilitate understanding
// of what the value does.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// COLUMNS SIZING POLICIES
//-----------------------------------------------------------------------------
// About overriding column sizing policy and width/weight with TableSetupColumn():
// We use a default parameter of 'init_width_or_weight == -1'.
// - with ImGuiTableColumnFlags_WidthFixed, init_width <= 0 (default) --> width is automatic
// - with ImGuiTableColumnFlags_WidthFixed, init_width > 0 (explicit) --> width is custom
// - with ImGuiTableColumnFlags_WidthStretch, init_weight <= 0 (default) --> weight is 1.0f
// - with ImGuiTableColumnFlags_WidthStretch, init_weight > 0 (explicit) --> weight is custom
// Widths are specified _without_ CellPadding. If you specify a width of 100.0f, the column will be cover (100.0f + Padding * 2.0f)
// and you can fit a 100.0f wide item in it without clipping and with full padding.
//-----------------------------------------------------------------------------
// About default sizing policy (if you don't specify a ImGuiTableColumnFlags_WidthXXXX flag)
// - with Table policy ImGuiTableFlags_SizingFixedFit --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is equal to contents width
// - with Table policy ImGuiTableFlags_SizingFixedSame --> default Column policy is ImGuiTableColumnFlags_WidthFixed, default Width is max of all contents width
// - with Table policy ImGuiTableFlags_SizingStretchSame --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is 1.0f
// - with Table policy ImGuiTableFlags_SizingStretchWeight --> default Column policy is ImGuiTableColumnFlags_WidthStretch, default Weight is proportional to contents
// Default Width and default Weight can be overridden when calling TableSetupColumn().
//-----------------------------------------------------------------------------
// About mixing Fixed/Auto and Stretch columns together:
// - the typical use of mixing sizing policies is: any number of LEADING Fixed columns, followed by one or two TRAILING Stretch columns.
// - using mixed policies with ScrollX does not make much sense, as using Stretch columns with ScrollX does not make much sense in the first place!
// that is, unless 'inner_width' is passed to BeginTable() to explicitly provide a total width to layout columns in.
// - when using ImGuiTableFlags_SizingFixedSame with mixed columns, only the Fixed/Auto columns will match their widths to the width of the maximum contents.
// - when using ImGuiTableFlags_SizingStretchSame with mixed columns, only the Stretch columns will match their weight/widths.
//-----------------------------------------------------------------------------
// About using column width:
// If a column is manual resizable or has a width specified with TableSetupColumn():
// - you may use GetContentRegionAvail().x to query the width available in a given column.
// - right-side alignment features such as SetNextItemWidth(-x) or PushItemWidth(-x) will rely on this width.
// If the column is not resizable and has no width specified with TableSetupColumn():
// - its width will be automatic and be set to the max of items submitted.
// - therefore you generally cannot have ALL items of the columns use e.g. SetNextItemWidth(-FLT_MIN).
// - but if the column has one or more items of known/fixed size, this will become the reference width used by SetNextItemWidth(-FLT_MIN).
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// TABLES CLIPPING/CULLING
//-----------------------------------------------------------------------------
// About clipping/culling of Rows in Tables:
// - For large numbers of rows, it is recommended you use ImGuiListClipper to only submit visible rows.
// ImGuiListClipper is reliant on the fact that rows are of equal height.
// See 'Demo->Tables->Vertical Scrolling' or 'Demo->Tables->Advanced' for a demo of using the clipper.
// - Note that auto-resizing columns don't play well with using the clipper.
// By default a table with _ScrollX but without _Resizable will have column auto-resize.
// So, if you want to use the clipper, make sure to either enable _Resizable, either setup columns width explicitly with _WidthFixed.
//-----------------------------------------------------------------------------
// About clipping/culling of Columns in Tables:
// - Both TableSetColumnIndex() and TableNextColumn() return true when the column is visible or performing
// width measurements. Otherwise, you may skip submitting the contents of a cell/column, BUT ONLY if you know
// it is not going to contribute to row height.
// In many situations, you may skip submitting contents for every column but one (e.g. the first one).
// - Case A: column is not hidden by user, and at least partially in sight (most common case).
// - Case B: column is clipped / out of sight (because of scrolling or parent ClipRect): TableNextColumn() return false as a hint but we still allow layout output.
// - Case C: column is hidden explicitly by the user (e.g. via the context menu, or _DefaultHide column flag, etc.).
//
// [A] [B] [C]
// TableNextColumn(): true false false -> [userland] when TableNextColumn() / TableSetColumnIndex() return false, user can skip submitting items but only if the column doesn't contribute to row height.
// SkipItems: false false true -> [internal] when SkipItems is true, most widgets will early out if submitted, resulting is no layout output.
// ClipRect: normal zero-width zero-width -> [internal] when ClipRect is zero, ItemAdd() will return false and most widgets will early out mid-way.
// ImDrawList output: normal dummy dummy -> [internal] when using the dummy channel, ImDrawList submissions (if any) will be wasted (because cliprect is zero-width anyway).
//
// - We need to distinguish those cases because non-hidden columns that are clipped outside of scrolling bounds should still contribute their height to the row.
// However, in the majority of cases, the contribution to row height is the same for all columns, or the tallest cells are known by the programmer.
//-----------------------------------------------------------------------------
// About clipping/culling of whole Tables:
// - Scrolling tables with a known outer size can be clipped earlier as BeginTable() will return false.
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// [SECTION] Header mess
//-----------------------------------------------------------------------------
#include "PlaygroundPCH.h"
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
// System includes
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#if __has_warning("-Wunknown-warning-option")
#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (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 "-Wsign-conversion" // warning: implicit conversion changes signedness
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wenum-enum-conversion" // warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_')
#pragma clang diagnostic ignored "-Wdeprecated-enum-enum-conversion"// warning: bitwise operation between different enumeration types ('XXXFlags_' and 'XXXFlagsPrivate_') is deprecated
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
//-----------------------------------------------------------------------------
// [SECTION] Tables: Main code
//-----------------------------------------------------------------------------
// - TableFixFlags() [Internal]
// - TableFindByID() [Internal]
// - BeginTable()
// - BeginTableEx() [Internal]
// - TableBeginInitMemory() [Internal]
// - TableBeginApplyRequests() [Internal]
// - TableSetupColumnFlags() [Internal]
// - TableUpdateLayout() [Internal]
// - TableUpdateBorders() [Internal]
// - EndTable()
// - TableSetupColumn()
// - TableSetupScrollFreeze()
//-----------------------------------------------------------------------------
// Configuration
static const int TABLE_DRAW_CHANNEL_BG0 = 0;
static const int TABLE_DRAW_CHANNEL_BG2_FROZEN = 1;
static const int TABLE_DRAW_CHANNEL_NOCLIP = 2; // When using ImGuiTableFlags_NoClip (this becomes the last visible channel)
static const float TABLE_BORDER_SIZE = 1.0f; // FIXME-TABLE: Currently hard-coded because of clipping assumptions with outer borders rendering.
static const float TABLE_RESIZE_SEPARATOR_HALF_THICKNESS = 4.0f; // Extend outside inner borders.
static const float TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER = 0.06f; // Delay/timer before making the hover feedback (color+cursor) visible because tables/columns tends to be more cramped.
// Helper
inline ImGuiTableFlags TableFixFlags(ImGuiTableFlags flags, ImGuiWindow* outer_window)
{
// Adjust flags: set default sizing policy
if ((flags & ImGuiTableFlags_SizingMask_) == 0)
flags |= ((flags & ImGuiTableFlags_ScrollX) || (outer_window->Flags & ImGuiWindowFlags_AlwaysAutoResize)) ? ImGuiTableFlags_SizingFixedFit : ImGuiTableFlags_SizingStretchSame;
// Adjust flags: enable NoKeepColumnsVisible when using ImGuiTableFlags_SizingFixedSame
if ((flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
flags |= ImGuiTableFlags_NoKeepColumnsVisible;
// Adjust flags: enforce borders when resizable
if (flags & ImGuiTableFlags_Resizable)
flags |= ImGuiTableFlags_BordersInnerV;
// Adjust flags: disable NoHostExtendX/NoHostExtendY if we have any scrolling going on
if (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY))
flags &= ~(ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY);
// Adjust flags: NoBordersInBodyUntilResize takes priority over NoBordersInBody
if (flags & ImGuiTableFlags_NoBordersInBodyUntilResize)
flags &= ~ImGuiTableFlags_NoBordersInBody;
// Adjust flags: disable saved settings if there's nothing to save
if ((flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Hideable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Sortable)) == 0)
flags |= ImGuiTableFlags_NoSavedSettings;
// Inherit _NoSavedSettings from top-level window (child windows always have _NoSavedSettings set)
if (outer_window->RootWindow->Flags & ImGuiWindowFlags_NoSavedSettings)
flags |= ImGuiTableFlags_NoSavedSettings;
return flags;
}
ImGuiTable* ImGui::TableFindByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.Tables.GetByKey(id);
}
// Read about "TABLE SIZING" at the top of this file.
bool ImGui::BeginTable(const char* str_id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
{
ImGuiID id = GetID(str_id);
return BeginTableEx(str_id, id, columns_count, flags, outer_size, inner_width);
}
bool ImGui::BeginTableEx(const char* name, ImGuiID id, int columns_count, ImGuiTableFlags flags, const ImVec2& outer_size, float inner_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* outer_window = GetCurrentWindow();
if (outer_window->SkipItems) // Consistent with other tables + beneficial side effect that assert on miscalling EndTable() will be more visible.
return false;
// Sanity checks
IM_ASSERT(columns_count > 0 && columns_count <= IMGUI_TABLE_MAX_COLUMNS && "Only 1..64 columns allowed!");
if (flags & ImGuiTableFlags_ScrollX)
IM_ASSERT(inner_width >= 0.0f);
// If an outer size is specified ahead we will be able to early out when not visible. Exact clipping rules may evolve.
const bool use_child_window = (flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) != 0;
const ImVec2 avail_size = GetContentRegionAvail();
ImVec2 actual_outer_size = CalcItemSize(outer_size, ImMax(avail_size.x, 1.0f), use_child_window ? ImMax(avail_size.y, 1.0f) : 0.0f);
ImRect outer_rect(outer_window->DC.CursorPos, outer_window->DC.CursorPos + actual_outer_size);
if (use_child_window && IsClippedEx(outer_rect, 0, false))
{
ItemSize(outer_rect);
return false;
}
// Acquire storage for the table
ImGuiTable* table = g.Tables.GetOrAddByKey(id);
const int instance_no = (table->LastFrameActive != g.FrameCount) ? 0 : table->InstanceCurrent + 1;
const ImGuiID instance_id = id + instance_no;
const ImGuiTableFlags table_last_flags = table->Flags;
if (instance_no > 0)
IM_ASSERT(table->ColumnsCount == columns_count && "BeginTable(): Cannot change columns count mid-frame while preserving same ID");
// Acquire temporary buffers
const int table_idx = g.Tables.GetIndex(table);
g.CurrentTableStackIdx++;
if (g.CurrentTableStackIdx + 1 > g.TablesTempDataStack.Size)
g.TablesTempDataStack.resize(g.CurrentTableStackIdx + 1, ImGuiTableTempData());
ImGuiTableTempData* temp_data = table->TempData = &g.TablesTempDataStack[g.CurrentTableStackIdx];
temp_data->TableIndex = table_idx;
table->DrawSplitter = &table->TempData->DrawSplitter;
table->DrawSplitter->Clear();
// Fix flags
table->IsDefaultSizingPolicy = (flags & ImGuiTableFlags_SizingMask_) == 0;
flags = TableFixFlags(flags, outer_window);
// Initialize
table->ID = id;
table->Flags = flags;
table->InstanceCurrent = (ImS16)instance_no;
table->LastFrameActive = g.FrameCount;
table->OuterWindow = table->InnerWindow = outer_window;
table->ColumnsCount = columns_count;
table->IsLayoutLocked = false;
table->InnerWidth = inner_width;
temp_data->UserOuterSize = outer_size;
// When not using a child window, WorkRect.Max will grow as we append contents.
if (use_child_window)
{
// Ensure no vertical scrollbar appears if we only want horizontal one, to make flag consistent
// (we have no other way to disable vertical scrollbar of a window while keeping the horizontal one showing)
ImVec2 override_content_size(FLT_MAX, FLT_MAX);
if ((flags & ImGuiTableFlags_ScrollX) && !(flags & ImGuiTableFlags_ScrollY))
override_content_size.y = FLT_MIN;
// Ensure specified width (when not specified, Stretched columns will act as if the width == OuterWidth and
// never lead to any scrolling). We don't handle inner_width < 0.0f, we could potentially use it to right-align
// based on the right side of the child window work rect, which would require knowing ahead if we are going to
// have decoration taking horizontal spaces (typically a vertical scrollbar).
if ((flags & ImGuiTableFlags_ScrollX) && inner_width > 0.0f)
override_content_size.x = inner_width;
if (override_content_size.x != FLT_MAX || override_content_size.y != FLT_MAX)
SetNextWindowContentSize(ImVec2(override_content_size.x != FLT_MAX ? override_content_size.x : 0.0f, override_content_size.y != FLT_MAX ? override_content_size.y : 0.0f));
// Reset scroll if we are reactivating it
if ((table_last_flags & (ImGuiTableFlags_ScrollX | ImGuiTableFlags_ScrollY)) == 0)
SetNextWindowScroll(ImVec2(0.0f, 0.0f));
// Create scrolling region (without border and zero window padding)
ImGuiWindowFlags child_flags = (flags & ImGuiTableFlags_ScrollX) ? ImGuiWindowFlags_HorizontalScrollbar : ImGuiWindowFlags_None;
BeginChildEx(name, instance_id, outer_rect.GetSize(), false, child_flags);
table->InnerWindow = g.CurrentWindow;
table->WorkRect = table->InnerWindow->WorkRect;
table->OuterRect = table->InnerWindow->Rect();
table->InnerRect = table->InnerWindow->InnerRect;
IM_ASSERT(table->InnerWindow->WindowPadding.x == 0.0f && table->InnerWindow->WindowPadding.y == 0.0f && table->InnerWindow->WindowBorderSize == 0.0f);
}
else
{
// For non-scrolling tables, WorkRect == OuterRect == InnerRect.
// But at this point we do NOT have a correct value for .Max.y (unless a height has been explicitly passed in). It will only be updated in EndTable().
table->WorkRect = table->OuterRect = table->InnerRect = outer_rect;
}
// Push a standardized ID for both child-using and not-child-using tables
PushOverrideID(instance_id);
// Backup a copy of host window members we will modify
ImGuiWindow* inner_window = table->InnerWindow;
table->HostIndentX = inner_window->DC.Indent.x;
table->HostClipRect = inner_window->ClipRect;
table->HostSkipItems = inner_window->SkipItems;
temp_data->HostBackupWorkRect = inner_window->WorkRect;
temp_data->HostBackupParentWorkRect = inner_window->ParentWorkRect;
temp_data->HostBackupColumnsOffset = outer_window->DC.ColumnsOffset;
temp_data->HostBackupPrevLineSize = inner_window->DC.PrevLineSize;
temp_data->HostBackupCurrLineSize = inner_window->DC.CurrLineSize;
temp_data->HostBackupCursorMaxPos = inner_window->DC.CursorMaxPos;
temp_data->HostBackupItemWidth = outer_window->DC.ItemWidth;
temp_data->HostBackupItemWidthStackSize = outer_window->DC.ItemWidthStack.Size;
inner_window->DC.PrevLineSize = inner_window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
// Padding and Spacing
// - None ........Content..... Pad .....Content........
// - PadOuter | Pad ..Content..... Pad .....Content.. Pad |
// - PadInner ........Content.. Pad | Pad ..Content........
// - PadOuter+PadInner | Pad ..Content.. Pad | Pad ..Content.. Pad |
const bool pad_outer_x = (flags & ImGuiTableFlags_NoPadOuterX) ? false : (flags & ImGuiTableFlags_PadOuterX) ? true : (flags & ImGuiTableFlags_BordersOuterV) != 0;
const bool pad_inner_x = (flags & ImGuiTableFlags_NoPadInnerX) ? false : true;
const float inner_spacing_for_border = (flags & ImGuiTableFlags_BordersInnerV) ? TABLE_BORDER_SIZE : 0.0f;
const float inner_spacing_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) == 0) ? g.Style.CellPadding.x : 0.0f;
const float inner_padding_explicit = (pad_inner_x && (flags & ImGuiTableFlags_BordersInnerV) != 0) ? g.Style.CellPadding.x : 0.0f;
table->CellSpacingX1 = inner_spacing_explicit + inner_spacing_for_border;
table->CellSpacingX2 = inner_spacing_explicit;
table->CellPaddingX = inner_padding_explicit;
table->CellPaddingY = g.Style.CellPadding.y;
const float outer_padding_for_border = (flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
const float outer_padding_explicit = pad_outer_x ? g.Style.CellPadding.x : 0.0f;
table->OuterPaddingX = (outer_padding_for_border + outer_padding_explicit) - table->CellPaddingX;
table->CurrentColumn = -1;
table->CurrentRow = -1;
table->RowBgColorCounter = 0;
table->LastRowFlags = ImGuiTableRowFlags_None;
table->InnerClipRect = (inner_window == outer_window) ? table->WorkRect : inner_window->ClipRect;
table->InnerClipRect.ClipWith(table->WorkRect); // We need this to honor inner_width
table->InnerClipRect.ClipWithFull(table->HostClipRect);
table->InnerClipRect.Max.y = (flags & ImGuiTableFlags_NoHostExtendY) ? ImMin(table->InnerClipRect.Max.y, inner_window->WorkRect.Max.y) : inner_window->ClipRect.Max.y;
table->RowPosY1 = table->RowPosY2 = table->WorkRect.Min.y; // This is needed somehow
table->RowTextBaseline = 0.0f; // This will be cleared again by TableBeginRow()
table->FreezeRowsRequest = table->FreezeRowsCount = 0; // This will be setup by TableSetupScrollFreeze(), if any
table->FreezeColumnsRequest = table->FreezeColumnsCount = 0;
table->IsUnfrozenRows = true;
table->DeclColumnsCount = 0;
// Using opaque colors facilitate overlapping elements of the grid
table->BorderColorStrong = GetColorU32(ImGuiCol_TableBorderStrong);
table->BorderColorLight = GetColorU32(ImGuiCol_TableBorderLight);
// Make table current
g.CurrentTable = table;
outer_window->DC.CurrentTableIdx = table_idx;
if (inner_window != outer_window) // So EndChild() within the inner window can restore the table properly.
inner_window->DC.CurrentTableIdx = table_idx;
if ((table_last_flags & ImGuiTableFlags_Reorderable) && (flags & ImGuiTableFlags_Reorderable) == 0)
table->IsResetDisplayOrderRequest = true;
// Mark as used
if (table_idx >= g.TablesLastTimeActive.Size)
g.TablesLastTimeActive.resize(table_idx + 1, -1.0f);
g.TablesLastTimeActive[table_idx] = (float)g.Time;
temp_data->LastTimeActive = (float)g.Time;
table->MemoryCompacted = false;
// Setup memory buffer (clear data if columns count changed)
ImGuiTableColumn* old_columns_to_preserve = NULL;
void* old_columns_raw_data = NULL;
const int old_columns_count = table->Columns.size();
if (old_columns_count != 0 && old_columns_count != columns_count)
{
// Attempt to preserve width on column count change (#4046)
old_columns_to_preserve = table->Columns.Data;
old_columns_raw_data = table->RawData;
table->RawData = NULL;
}
if (table->RawData == NULL)
{
TableBeginInitMemory(table, columns_count);
table->IsInitializing = table->IsSettingsRequestLoad = true;
}
if (table->IsResetAllRequest)
TableResetSettings(table);
if (table->IsInitializing)
{
// Initialize
table->SettingsOffset = -1;
table->IsSortSpecsDirty = true;
table->InstanceInteracted = -1;
table->ContextPopupColumn = -1;
table->ReorderColumn = table->ResizedColumn = table->LastResizedColumn = -1;
table->AutoFitSingleColumn = -1;
table->HoveredColumnBody = table->HoveredColumnBorder = -1;
for (int n = 0; n < columns_count; n++)
{
ImGuiTableColumn* column = &table->Columns[n];
if (old_columns_to_preserve && n < old_columns_count)
{
// FIXME: We don't attempt to preserve column order in this path.
*column = old_columns_to_preserve[n];
}
else
{
float width_auto = column->WidthAuto;
*column = ImGuiTableColumn();
column->WidthAuto = width_auto;
column->IsPreserveWidthAuto = true; // Preserve WidthAuto when reinitializing a live table: not technically necessary but remove a visible flicker
column->IsEnabled = column->IsUserEnabled = column->IsUserEnabledNextFrame = true;
}
column->DisplayOrder = table->DisplayOrderToIndex[n] = (ImGuiTableColumnIdx)n;
}
}
if (old_columns_raw_data)
IM_FREE(old_columns_raw_data);
// Load settings
if (table->IsSettingsRequestLoad)
TableLoadSettings(table);
// Handle DPI/font resize
// This is designed to facilitate DPI changes with the assumption that e.g. style.CellPadding has been scaled as well.
// It will also react to changing fonts with mixed results. It doesn't need to be perfect but merely provide a decent transition.
// FIXME-DPI: Provide consistent standards for reference size. Perhaps using g.CurrentDpiScale would be more self explanatory.
// This is will lead us to non-rounded WidthRequest in columns, which should work but is a poorly tested path.
const float new_ref_scale_unit = g.FontSize; // g.Font->GetCharAdvance('A') ?
if (table->RefScale != 0.0f && table->RefScale != new_ref_scale_unit)
{
const float scale_factor = new_ref_scale_unit / table->RefScale;
//IMGUI_DEBUG_LOG("[table] %08X RefScaleUnit %.3f -> %.3f, scaling width by %.3f\n", table->ID, table->RefScaleUnit, new_ref_scale_unit, scale_factor);
for (int n = 0; n < columns_count; n++)
table->Columns[n].WidthRequest = table->Columns[n].WidthRequest * scale_factor;
}
table->RefScale = new_ref_scale_unit;
// Disable output until user calls TableNextRow() or TableNextColumn() leading to the TableUpdateLayout() call..
// This is not strictly necessary but will reduce cases were "out of table" output will be misleading to the user.
// Because we cannot safely assert in EndTable() when no rows have been created, this seems like our best option.
inner_window->SkipItems = true;
// Clear names
// At this point the ->NameOffset field of each column will be invalid until TableUpdateLayout() or the first call to TableSetupColumn()
if (table->ColumnsNames.Buf.Size > 0)
table->ColumnsNames.Buf.resize(0);
// Apply queued resizing/reordering/hiding requests
TableBeginApplyRequests(table);
return true;
}
// For reference, the average total _allocation count_ for a table is:
// + 0 (for ImGuiTable instance, we are pooling allocations in g.Tables)
// + 1 (for table->RawData allocated below)
// + 1 (for table->ColumnsNames, if names are used)
// + 1 (for table->Splitter._Channels)
// + 2 * active_channels_count (for ImDrawCmd and ImDrawIdx buffers inside channels)
// Where active_channels_count is variable but often == columns_count or columns_count + 1, see TableSetupDrawChannels() for details.
// Unused channels don't perform their +2 allocations.
void ImGui::TableBeginInitMemory(ImGuiTable* table, int columns_count)
{
// Allocate single buffer for our arrays
ImSpanAllocator<3> span_allocator;
span_allocator.Reserve(0, columns_count * sizeof(ImGuiTableColumn));
span_allocator.Reserve(1, columns_count * sizeof(ImGuiTableColumnIdx));
span_allocator.Reserve(2, columns_count * sizeof(ImGuiTableCellData), 4);
table->RawData = IM_ALLOC(span_allocator.GetArenaSizeInBytes());
memset(table->RawData, 0, span_allocator.GetArenaSizeInBytes());
span_allocator.SetArenaBasePtr(table->RawData);
span_allocator.GetSpan(0, &table->Columns);
span_allocator.GetSpan(1, &table->DisplayOrderToIndex);
span_allocator.GetSpan(2, &table->RowCellData);
}
// Apply queued resizing/reordering/hiding requests
void ImGui::TableBeginApplyRequests(ImGuiTable* table)
{
// Handle resizing request
// (We process this at the first TableBegin of the frame)
// FIXME-TABLE: Contains columns if our work area doesn't allow for scrolling?
if (table->InstanceCurrent == 0)
{
if (table->ResizedColumn != -1 && table->ResizedColumnNextWidth != FLT_MAX)
TableSetColumnWidth(table->ResizedColumn, table->ResizedColumnNextWidth);
table->LastResizedColumn = table->ResizedColumn;
table->ResizedColumnNextWidth = FLT_MAX;
table->ResizedColumn = -1;
// Process auto-fit for single column, which is a special case for stretch columns and fixed columns with FixedSame policy.
// FIXME-TABLE: Would be nice to redistribute available stretch space accordingly to other weights, instead of giving it all to siblings.
if (table->AutoFitSingleColumn != -1)
{
TableSetColumnWidth(table->AutoFitSingleColumn, table->Columns[table->AutoFitSingleColumn].WidthAuto);
table->AutoFitSingleColumn = -1;
}
}
// Handle reordering request
// Note: we don't clear ReorderColumn after handling the request.
if (table->InstanceCurrent == 0)
{
if (table->HeldHeaderColumn == -1 && table->ReorderColumn != -1)
table->ReorderColumn = -1;
table->HeldHeaderColumn = -1;
if (table->ReorderColumn != -1 && table->ReorderColumnDir != 0)
{
// We need to handle reordering across hidden columns.
// In the configuration below, moving C to the right of E will lead to:
// ... C [D] E ---> ... [D] E C (Column name/index)
// ... 2 3 4 ... 2 3 4 (Display order)
const int reorder_dir = table->ReorderColumnDir;
IM_ASSERT(reorder_dir == -1 || reorder_dir == +1);
IM_ASSERT(table->Flags & ImGuiTableFlags_Reorderable);
ImGuiTableColumn* src_column = &table->Columns[table->ReorderColumn];
ImGuiTableColumn* dst_column = &table->Columns[(reorder_dir == -1) ? src_column->PrevEnabledColumn : src_column->NextEnabledColumn];
IM_UNUSED(dst_column);
const int src_order = src_column->DisplayOrder;
const int dst_order = dst_column->DisplayOrder;
src_column->DisplayOrder = (ImGuiTableColumnIdx)dst_order;
for (int order_n = src_order + reorder_dir; order_n != dst_order + reorder_dir; order_n += reorder_dir)
table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder -= (ImGuiTableColumnIdx)reorder_dir;
IM_ASSERT(dst_column->DisplayOrder == dst_order - reorder_dir);
// Display order is stored in both columns->IndexDisplayOrder and table->DisplayOrder[],
// rebuild the later from the former.
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;
table->ReorderColumnDir = 0;
table->IsSettingsDirty = true;
}
}
// Handle display order reset request
if (table->IsResetDisplayOrderRequest)
{
for (int n = 0; n < table->ColumnsCount; n++)
table->DisplayOrderToIndex[n] = table->Columns[n].DisplayOrder = (ImGuiTableColumnIdx)n;
table->IsResetDisplayOrderRequest = false;
table->IsSettingsDirty = true;
}
}
// Adjust flags: default width mode + stretch columns are not allowed when auto extending
static void TableSetupColumnFlags(ImGuiTable* table, ImGuiTableColumn* column, ImGuiTableColumnFlags flags_in)
{
ImGuiTableColumnFlags flags = flags_in;
// Sizing Policy
if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0)
{
const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
if (table_sizing_policy == ImGuiTableFlags_SizingFixedFit || table_sizing_policy == ImGuiTableFlags_SizingFixedSame)
flags |= ImGuiTableColumnFlags_WidthFixed;
else
flags |= ImGuiTableColumnFlags_WidthStretch;
}
else
{
IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_WidthMask_)); // Check that only 1 of each set is used.
}
// Resize
if ((table->Flags & ImGuiTableFlags_Resizable) == 0)
flags |= ImGuiTableColumnFlags_NoResize;
// Sorting
if ((flags & ImGuiTableColumnFlags_NoSortAscending) && (flags & ImGuiTableColumnFlags_NoSortDescending))
flags |= ImGuiTableColumnFlags_NoSort;
// Indentation
if ((flags & ImGuiTableColumnFlags_IndentMask_) == 0)
flags |= (table->Columns.index_from_ptr(column) == 0) ? ImGuiTableColumnFlags_IndentEnable : ImGuiTableColumnFlags_IndentDisable;
// Alignment
//if ((flags & ImGuiTableColumnFlags_AlignMask_) == 0)
// flags |= ImGuiTableColumnFlags_AlignCenter;
//IM_ASSERT(ImIsPowerOfTwo(flags & ImGuiTableColumnFlags_AlignMask_)); // Check that only 1 of each set is used.
// Preserve status flags
column->Flags = flags | (column->Flags & ImGuiTableColumnFlags_StatusMask_);
// Build an ordered list of available sort directions
column->SortDirectionsAvailCount = column->SortDirectionsAvailMask = column->SortDirectionsAvailList = 0;
if (table->Flags & ImGuiTableFlags_Sortable)
{
int count = 0, mask = 0, list = 0;
if ((flags & ImGuiTableColumnFlags_PreferSortAscending) != 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
if ((flags & ImGuiTableColumnFlags_PreferSortDescending) != 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
if ((flags & ImGuiTableColumnFlags_PreferSortAscending) == 0 && (flags & ImGuiTableColumnFlags_NoSortAscending) == 0) { mask |= 1 << ImGuiSortDirection_Ascending; list |= ImGuiSortDirection_Ascending << (count << 1); count++; }
if ((flags & ImGuiTableColumnFlags_PreferSortDescending) == 0 && (flags & ImGuiTableColumnFlags_NoSortDescending) == 0) { mask |= 1 << ImGuiSortDirection_Descending; list |= ImGuiSortDirection_Descending << (count << 1); count++; }
if ((table->Flags & ImGuiTableFlags_SortTristate) || count == 0) { mask |= 1 << ImGuiSortDirection_None; count++; }
column->SortDirectionsAvailList = (ImU8)list;
column->SortDirectionsAvailMask = (ImU8)mask;
column->SortDirectionsAvailCount = (ImU8)count;
ImGui::TableFixColumnSortDirection(table, column);
}
}
// Layout columns for the frame. This is in essence the followup to BeginTable().
// Runs on the first call to TableNextRow(), to give a chance for TableSetupColumn() to be called first.
// FIXME-TABLE: Our width (and therefore our WorkRect) will be minimal in the first frame for _WidthAuto columns.
// Increase feedback side-effect with widgets relying on WorkRect.Max.x... Maybe provide a default distribution for _WidthAuto columns?
void ImGui::TableUpdateLayout(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(table->IsLayoutLocked == false);
const ImGuiTableFlags table_sizing_policy = (table->Flags & ImGuiTableFlags_SizingMask_);
table->IsDefaultDisplayOrder = true;
table->ColumnsEnabledCount = 0;
table->EnabledMaskByIndex = 0x00;
table->EnabledMaskByDisplayOrder = 0x00;
table->LeftMostEnabledColumn = -1;
table->MinColumnWidth = ImMax(1.0f, g.Style.FramePadding.x * 1.0f); // g.Style.ColumnsMinSpacing; // FIXME-TABLE
// [Part 1] Apply/lock Enabled and Order states. Calculate auto/ideal width for columns. Count fixed/stretch columns.
// Process columns in their visible orders as we are building the Prev/Next indices.
int count_fixed = 0; // Number of columns that have fixed sizing policies
int count_stretch = 0; // Number of columns that have stretch sizing policies
int prev_visible_column_idx = -1;
bool has_auto_fit_request = false;
bool has_resizable = false;
float stretch_sum_width_auto = 0.0f;
float fixed_max_width_auto = 0.0f;
for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
{
const int column_n = table->DisplayOrderToIndex[order_n];
if (column_n != order_n)
table->IsDefaultDisplayOrder = false;
ImGuiTableColumn* column = &table->Columns[column_n];
// Clear column setup if not submitted by user. Currently we make it mandatory to call TableSetupColumn() every frame.
// It would easily work without but we're not ready to guarantee it since e.g. names need resubmission anyway.
// We take a slight shortcut but in theory we could be calling TableSetupColumn() here with dummy values, it should yield the same effect.
if (table->DeclColumnsCount <= column_n)
{
TableSetupColumnFlags(table, column, ImGuiTableColumnFlags_None);
column->NameOffset = -1;
column->UserID = 0;
column->InitStretchWeightOrWidth = -1.0f;
}
// Update Enabled state, mark settings and sort specs dirty
if (!(table->Flags & ImGuiTableFlags_Hideable) || (column->Flags & ImGuiTableColumnFlags_NoHide))
column->IsUserEnabledNextFrame = true;
if (column->IsUserEnabled != column->IsUserEnabledNextFrame)
{
column->IsUserEnabled = column->IsUserEnabledNextFrame;
table->IsSettingsDirty = true;
}
column->IsEnabled = column->IsUserEnabled && (column->Flags & ImGuiTableColumnFlags_Disabled) == 0;
if (column->SortOrder != -1 && !column->IsEnabled)
table->IsSortSpecsDirty = true;
if (column->SortOrder > 0 && !(table->Flags & ImGuiTableFlags_SortMulti))
table->IsSortSpecsDirty = true;
// Auto-fit unsized columns
const bool start_auto_fit = (column->Flags & ImGuiTableColumnFlags_WidthFixed) ? (column->WidthRequest < 0.0f) : (column->StretchWeight < 0.0f);
if (start_auto_fit)
column->AutoFitQueue = column->CannotSkipItemsQueue = (1 << 3) - 1; // Fit for three frames
if (!column->IsEnabled)
{
column->IndexWithinEnabledSet = -1;
continue;
}
// Mark as enabled and link to previous/next enabled column
column->PrevEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
column->NextEnabledColumn = -1;
if (prev_visible_column_idx != -1)
table->Columns[prev_visible_column_idx].NextEnabledColumn = (ImGuiTableColumnIdx)column_n;
else
table->LeftMostEnabledColumn = (ImGuiTableColumnIdx)column_n;
column->IndexWithinEnabledSet = table->ColumnsEnabledCount++;
table->EnabledMaskByIndex |= (ImU64)1 << column_n;
table->EnabledMaskByDisplayOrder |= (ImU64)1 << column->DisplayOrder;
prev_visible_column_idx = column_n;
IM_ASSERT(column->IndexWithinEnabledSet <= column->DisplayOrder);
// Calculate ideal/auto column width (that's the width required for all contents to be visible without clipping)
// Combine width from regular rows + width from headers unless requested not to.
if (!column->IsPreserveWidthAuto)
column->WidthAuto = TableGetColumnWidthAuto(table, column);
// Non-resizable columns keep their requested width (apply user value regardless of IsPreserveWidthAuto)
const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
if (column_is_resizable)
has_resizable = true;
if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f && !column_is_resizable)
column->WidthAuto = column->InitStretchWeightOrWidth;
if (column->AutoFitQueue != 0x00)
has_auto_fit_request = true;
if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
{
stretch_sum_width_auto += column->WidthAuto;
count_stretch++;
}
else
{
fixed_max_width_auto = ImMax(fixed_max_width_auto, column->WidthAuto);
count_fixed++;
}
}
if ((table->Flags & ImGuiTableFlags_Sortable) && table->SortSpecsCount == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
table->IsSortSpecsDirty = true;
table->RightMostEnabledColumn = (ImGuiTableColumnIdx)prev_visible_column_idx;
IM_ASSERT(table->LeftMostEnabledColumn >= 0 && table->RightMostEnabledColumn >= 0);
// [Part 2] Disable child window clipping while fitting columns. This is not strictly necessary but makes it possible
// to avoid the column fitting having to wait until the first visible frame of the child container (may or not be a good thing).
// FIXME-TABLE: for always auto-resizing columns may not want to do that all the time.
if (has_auto_fit_request && table->OuterWindow != table->InnerWindow)
table->InnerWindow->SkipItems = false;
if (has_auto_fit_request)
table->IsSettingsDirty = true;
// [Part 3] Fix column flags and record a few extra information.
float sum_width_requests = 0.0f; // Sum of all width for fixed and auto-resize columns, excluding width contributed by Stretch columns but including spacing/padding.
float stretch_sum_weights = 0.0f; // Sum of all weights for stretch columns.
table->LeftMostStretchedColumn = table->RightMostStretchedColumn = -1;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))
continue;
ImGuiTableColumn* column = &table->Columns[column_n];
const bool column_is_resizable = (column->Flags & ImGuiTableColumnFlags_NoResize) == 0;
if (column->Flags & ImGuiTableColumnFlags_WidthFixed)
{
// Apply same widths policy
float width_auto = column->WidthAuto;
if (table_sizing_policy == ImGuiTableFlags_SizingFixedSame && (column->AutoFitQueue != 0x00 || !column_is_resizable))
width_auto = fixed_max_width_auto;
// Apply automatic width
// Latch initial size for fixed columns and update it constantly for auto-resizing column (unless clipped!)
if (column->AutoFitQueue != 0x00)
column->WidthRequest = width_auto;
else if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !column_is_resizable && (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)))
column->WidthRequest = width_auto;
// FIXME-TABLE: Increase minimum size during init frame to avoid biasing auto-fitting widgets
// (e.g. TextWrapped) too much. Otherwise what tends to happen is that TextWrapped would output a very
// large height (= first frame scrollbar display very off + clipper would skip lots of items).
// This is merely making the side-effect less extreme, but doesn't properly fixes it.
// FIXME: Move this to ->WidthGiven to avoid temporary lossyless?
// FIXME: This break IsPreserveWidthAuto from not flickering if the stored WidthAuto was smaller.
if (column->AutoFitQueue > 0x01 && table->IsInitializing && !column->IsPreserveWidthAuto)
column->WidthRequest = ImMax(column->WidthRequest, table->MinColumnWidth * 4.0f); // FIXME-TABLE: Another constant/scale?
sum_width_requests += column->WidthRequest;
}
else
{
// Initialize stretch weight
if (column->AutoFitQueue != 0x00 || column->StretchWeight < 0.0f || !column_is_resizable)
{
if (column->InitStretchWeightOrWidth > 0.0f)
column->StretchWeight = column->InitStretchWeightOrWidth;
else if (table_sizing_policy == ImGuiTableFlags_SizingStretchProp)
column->StretchWeight = (column->WidthAuto / stretch_sum_width_auto) * count_stretch;
else
column->StretchWeight = 1.0f;
}
stretch_sum_weights += column->StretchWeight;
if (table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder > column->DisplayOrder)
table->LeftMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
if (table->RightMostStretchedColumn == -1 || table->Columns[table->RightMostStretchedColumn].DisplayOrder < column->DisplayOrder)
table->RightMostStretchedColumn = (ImGuiTableColumnIdx)column_n;
}
column->IsPreserveWidthAuto = false;
sum_width_requests += table->CellPaddingX * 2.0f;
}
table->ColumnsEnabledFixedCount = (ImGuiTableColumnIdx)count_fixed;
// [Part 4] Apply final widths based on requested widths
const ImRect work_rect = table->WorkRect;
const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
const float width_avail = ((table->Flags & ImGuiTableFlags_ScrollX) && table->InnerWidth == 0.0f) ? table->InnerClipRect.GetWidth() : work_rect.GetWidth();
const float width_avail_for_stretched_columns = width_avail - width_spacings - sum_width_requests;
float width_remaining_for_stretched_columns = width_avail_for_stretched_columns;
table->ColumnsGivenWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
if (!(table->EnabledMaskByIndex & ((ImU64)1 << column_n)))
continue;
ImGuiTableColumn* column = &table->Columns[column_n];
// Allocate width for stretched/weighted columns (StretchWeight gets converted into WidthRequest)
if (column->Flags & ImGuiTableColumnFlags_WidthStretch)
{
float weight_ratio = column->StretchWeight / stretch_sum_weights;
column->WidthRequest = IM_FLOOR(ImMax(width_avail_for_stretched_columns * weight_ratio, table->MinColumnWidth) + 0.01f);
width_remaining_for_stretched_columns -= column->WidthRequest;
}
// [Resize Rule 1] The right-most Visible column is not resizable if there is at least one Stretch column
// See additional comments in TableSetColumnWidth().
if (column->NextEnabledColumn == -1 && table->LeftMostStretchedColumn != -1)
column->Flags |= ImGuiTableColumnFlags_NoDirectResize_;
// Assign final width, record width in case we will need to shrink
column->WidthGiven = ImFloor(ImMax(column->WidthRequest, table->MinColumnWidth));
table->ColumnsGivenWidth += column->WidthGiven;
}
// [Part 5] Redistribute stretch remainder width due to rounding (remainder width is < 1.0f * number of Stretch column).
// Using right-to-left distribution (more likely to match resizing cursor).
if (width_remaining_for_stretched_columns >= 1.0f && !(table->Flags & ImGuiTableFlags_PreciseWidths))
for (int order_n = table->ColumnsCount - 1; stretch_sum_weights > 0.0f && width_remaining_for_stretched_columns >= 1.0f && order_n >= 0; order_n--)
{
if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
continue;
ImGuiTableColumn* column = &table->Columns[table->DisplayOrderToIndex[order_n]];
if (!(column->Flags & ImGuiTableColumnFlags_WidthStretch))
continue;
column->WidthRequest += 1.0f;
column->WidthGiven += 1.0f;
width_remaining_for_stretched_columns -= 1.0f;
}
table->HoveredColumnBody = -1;
table->HoveredColumnBorder = -1;
const ImRect mouse_hit_rect(table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.Max.x, ImMax(table->OuterRect.Max.y, table->OuterRect.Min.y + table->LastOuterHeight));
const bool is_hovering_table = ItemHoverable(mouse_hit_rect, 0);
// [Part 6] Setup final position, offset, skip/clip states and clipping rectangles, detect hovered column
// Process columns in their visible orders as we are comparing the visible order and adjusting host_clip_rect while looping.
int visible_n = 0;
bool offset_x_frozen = (table->FreezeColumnsCount > 0);
float offset_x = ((table->FreezeColumnsCount > 0) ? table->OuterRect.Min.x : work_rect.Min.x) + table->OuterPaddingX - table->CellSpacingX1;
ImRect host_clip_rect = table->InnerClipRect;
//host_clip_rect.Max.x += table->CellPaddingX + table->CellSpacingX2;
table->VisibleMaskByIndex = 0x00;
table->RequestOutputMaskByIndex = 0x00;
for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
{
const int column_n = table->DisplayOrderToIndex[order_n];
ImGuiTableColumn* column = &table->Columns[column_n];
column->NavLayerCurrent = (ImS8)((table->FreezeRowsCount > 0 || column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);
if (offset_x_frozen && table->FreezeColumnsCount == visible_n)
{
offset_x += work_rect.Min.x - table->OuterRect.Min.x;
offset_x_frozen = false;
}
// Clear status flags
column->Flags &= ~ImGuiTableColumnFlags_StatusMask_;
if ((table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)) == 0)
{
// Hidden column: clear a few fields and we are done with it for the remainder of the function.
// We set a zero-width clip rect but set Min.y/Max.y properly to not interfere with the clipper.
column->MinX = column->MaxX = column->WorkMinX = column->ClipRect.Min.x = column->ClipRect.Max.x = offset_x;
column->WidthGiven = 0.0f;
column->ClipRect.Min.y = work_rect.Min.y;
column->ClipRect.Max.y = FLT_MAX;
column->ClipRect.ClipWithFull(host_clip_rect);
column->IsVisibleX = column->IsVisibleY = column->IsRequestOutput = false;
column->IsSkipItems = true;
column->ItemWidth = 1.0f;
continue;
}
// Detect hovered column
if (is_hovering_table && g.IO.MousePos.x >= column->ClipRect.Min.x && g.IO.MousePos.x < column->ClipRect.Max.x)
table->HoveredColumnBody = (ImGuiTableColumnIdx)column_n;
// Lock start position
column->MinX = offset_x;
// Lock width based on start position and minimum/maximum width for this position
float max_width = TableGetMaxColumnWidth(table, column_n);
column->WidthGiven = ImMin(column->WidthGiven, max_width);
column->WidthGiven = ImMax(column->WidthGiven, ImMin(column->WidthRequest, table->MinColumnWidth));
column->MaxX = offset_x + column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
// Lock other positions
// - ClipRect.Min.x: Because merging draw commands doesn't compare min boundaries, we make ClipRect.Min.x match left bounds to be consistent regardless of merging.
// - ClipRect.Max.x: using WorkMaxX instead of MaxX (aka including padding) makes things more consistent when resizing down, tho slightly detrimental to visibility in very-small column.
// - ClipRect.Max.x: using MaxX makes it easier for header to receive hover highlight with no discontinuity and display sorting arrow.
// - FIXME-TABLE: We want equal width columns to have equal (ClipRect.Max.x - WorkMinX) width, which means ClipRect.max.x cannot stray off host_clip_rect.Max.x else right-most column may appear shorter.
column->WorkMinX = column->MinX + table->CellPaddingX + table->CellSpacingX1;
column->WorkMaxX = column->MaxX - table->CellPaddingX - table->CellSpacingX2; // Expected max
column->ItemWidth = ImFloor(column->WidthGiven * 0.65f);
column->ClipRect.Min.x = column->MinX;
column->ClipRect.Min.y = work_rect.Min.y;
column->ClipRect.Max.x = column->MaxX; //column->WorkMaxX;
column->ClipRect.Max.y = FLT_MAX;
column->ClipRect.ClipWithFull(host_clip_rect);
// Mark column as Clipped (not in sight)
// Note that scrolling tables (where inner_window != outer_window) handle Y clipped earlier in BeginTable() so IsVisibleY really only applies to non-scrolling tables.
// FIXME-TABLE: Because InnerClipRect.Max.y is conservatively ==outer_window->ClipRect.Max.y, we never can mark columns _Above_ the scroll line as not IsVisibleY.
// Taking advantage of LastOuterHeight would yield good results there...
// FIXME-TABLE: Y clipping is disabled because it effectively means not submitting will reduce contents width which is fed to outer_window->DC.CursorMaxPos.x,
// and this may be used (e.g. typically by outer_window using AlwaysAutoResize or outer_window's horizontal scrollbar, but could be something else).
// Possible solution to preserve last known content width for clipped column. Test 'table_reported_size' fails when enabling Y clipping and window is resized small.
column->IsVisibleX = (column->ClipRect.Max.x > column->ClipRect.Min.x);
column->IsVisibleY = true; // (column->ClipRect.Max.y > column->ClipRect.Min.y);
const bool is_visible = column->IsVisibleX; //&& column->IsVisibleY;
if (is_visible)
table->VisibleMaskByIndex |= ((ImU64)1 << column_n);
// Mark column as requesting output from user. Note that fixed + non-resizable sets are auto-fitting at all times and therefore always request output.
column->IsRequestOutput = is_visible || column->AutoFitQueue != 0 || column->CannotSkipItemsQueue != 0;
if (column->IsRequestOutput)
table->RequestOutputMaskByIndex |= ((ImU64)1 << column_n);
// Mark column as SkipItems (ignoring all items/layout)
column->IsSkipItems = !column->IsEnabled || table->HostSkipItems;
if (column->IsSkipItems)
IM_ASSERT(!is_visible);
// Update status flags
column->Flags |= ImGuiTableColumnFlags_IsEnabled;
if (is_visible)
column->Flags |= ImGuiTableColumnFlags_IsVisible;
if (column->SortOrder != -1)
column->Flags |= ImGuiTableColumnFlags_IsSorted;
if (table->HoveredColumnBody == column_n)
column->Flags |= ImGuiTableColumnFlags_IsHovered;
// Alignment
// FIXME-TABLE: This align based on the whole column width, not per-cell, and therefore isn't useful in
// many cases (to be able to honor this we might be able to store a log of cells width, per row, for
// visible rows, but nav/programmatic scroll would have visible artifacts.)
//if (column->Flags & ImGuiTableColumnFlags_AlignRight)
// column->WorkMinX = ImMax(column->WorkMinX, column->MaxX - column->ContentWidthRowsUnfrozen);
//else if (column->Flags & ImGuiTableColumnFlags_AlignCenter)
// column->WorkMinX = ImLerp(column->WorkMinX, ImMax(column->StartX, column->MaxX - column->ContentWidthRowsUnfrozen), 0.5f);
// Reset content width variables
column->ContentMaxXFrozen = column->ContentMaxXUnfrozen = column->WorkMinX;
column->ContentMaxXHeadersUsed = column->ContentMaxXHeadersIdeal = column->WorkMinX;
// Don't decrement auto-fit counters until container window got a chance to submit its items
if (table->HostSkipItems == false)
{
column->AutoFitQueue >>= 1;
column->CannotSkipItemsQueue >>= 1;
}
if (visible_n < table->FreezeColumnsCount)
host_clip_rect.Min.x = ImClamp(column->MaxX + TABLE_BORDER_SIZE, host_clip_rect.Min.x, host_clip_rect.Max.x);
offset_x += column->WidthGiven + table->CellSpacingX1 + table->CellSpacingX2 + table->CellPaddingX * 2.0f;
visible_n++;
}
// [Part 7] Detect/store when we are hovering the unused space after the right-most column (so e.g. context menus can react on it)
// Clear Resizable flag if none of our column are actually resizable (either via an explicit _NoResize flag, either
// because of using _WidthAuto/_WidthStretch). This will hide the resizing option from the context menu.
const float unused_x1 = ImMax(table->WorkRect.Min.x, table->Columns[table->RightMostEnabledColumn].ClipRect.Max.x);
if (is_hovering_table && table->HoveredColumnBody == -1)
{
if (g.IO.MousePos.x >= unused_x1)
table->HoveredColumnBody = (ImGuiTableColumnIdx)table->ColumnsCount;
}
if (has_resizable == false && (table->Flags & ImGuiTableFlags_Resizable))
table->Flags &= ~ImGuiTableFlags_Resizable;
// [Part 8] Lock actual OuterRect/WorkRect right-most position.
// This is done late to handle the case of fixed-columns tables not claiming more widths that they need.
// Because of this we are careful with uses of WorkRect and InnerClipRect before this point.
if (table->RightMostStretchedColumn != -1)
table->Flags &= ~ImGuiTableFlags_NoHostExtendX;
if (table->Flags & ImGuiTableFlags_NoHostExtendX)
{
table->OuterRect.Max.x = table->WorkRect.Max.x = unused_x1;
table->InnerClipRect.Max.x = ImMin(table->InnerClipRect.Max.x, unused_x1);
}
table->InnerWindow->ParentWorkRect = table->WorkRect;
table->BorderX1 = table->InnerClipRect.Min.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : -1.0f);
table->BorderX2 = table->InnerClipRect.Max.x;// +((table->Flags & ImGuiTableFlags_BordersOuter) ? 0.0f : +1.0f);
// [Part 9] Allocate draw channels and setup background cliprect
TableSetupDrawChannels(table);
// [Part 10] Hit testing on borders
if (table->Flags & ImGuiTableFlags_Resizable)
TableUpdateBorders(table);
table->LastFirstRowHeight = 0.0f;
table->IsLayoutLocked = true;
table->IsUsingHeaders = false;
// [Part 11] Context menu
if (table->IsContextPopupOpen && table->InstanceCurrent == table->InstanceInteracted)
{
const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
if (BeginPopupEx(context_menu_id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings))
{
TableDrawContextMenu(table);
EndPopup();
}
else
{
table->IsContextPopupOpen = false;
}
}
// [Part 13] Sanitize and build sort specs before we have a change to use them for display.
// This path will only be exercised when sort specs are modified before header rows (e.g. init or visibility change)
if (table->IsSortSpecsDirty && (table->Flags & ImGuiTableFlags_Sortable))
TableSortSpecsBuild(table);
// Initial state
ImGuiWindow* inner_window = table->InnerWindow;
if (table->Flags & ImGuiTableFlags_NoClip)
table->DrawSplitter->SetCurrentChannel(inner_window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
else
inner_window->DrawList->PushClipRect(inner_window->ClipRect.Min, inner_window->ClipRect.Max, false);
}
// Process hit-testing on resizing borders. Actual size change will be applied in EndTable()
// - Set table->HoveredColumnBorder with a short delay/timer to reduce feedback noise
// - Submit ahead of table contents and header, use ImGuiButtonFlags_AllowItemOverlap to prioritize widgets
// overlapping the same area.
void ImGui::TableUpdateBorders(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(table->Flags & ImGuiTableFlags_Resizable);
// At this point OuterRect height may be zero or under actual final height, so we rely on temporal coherency and
// use the final height from last frame. Because this is only affecting _interaction_ with columns, it is not
// really problematic (whereas the actual visual will be displayed in EndTable() and using the current frame height).
// Actual columns highlight/render will be performed in EndTable() and not be affected.
const float hit_half_width = TABLE_RESIZE_SEPARATOR_HALF_THICKNESS;
const float hit_y1 = table->OuterRect.Min.y;
const float hit_y2_body = ImMax(table->OuterRect.Max.y, hit_y1 + table->LastOuterHeight);
const float hit_y2_head = hit_y1 + table->LastFirstRowHeight;
for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
{
if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
continue;
const int column_n = table->DisplayOrderToIndex[order_n];
ImGuiTableColumn* column = &table->Columns[column_n];
if (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_))
continue;
// ImGuiTableFlags_NoBordersInBodyUntilResize will be honored in TableDrawBorders()
const float border_y2_hit = (table->Flags & ImGuiTableFlags_NoBordersInBody) ? hit_y2_head : hit_y2_body;
if ((table->Flags & ImGuiTableFlags_NoBordersInBody) && table->IsUsingHeaders == false)
continue;
if (!column->IsVisibleX && table->LastResizedColumn != column_n)
continue;
ImGuiID column_id = TableGetColumnResizeID(table, column_n, table->InstanceCurrent);
ImRect hit_rect(column->MaxX - hit_half_width, hit_y1, column->MaxX + hit_half_width, border_y2_hit);
//GetForegroundDrawList()->AddRect(hit_rect.Min, hit_rect.Max, IM_COL32(255, 0, 0, 100));
KeepAliveID(column_id);
bool hovered = false, held = false;
bool pressed = ButtonBehavior(hit_rect, column_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_AllowItemOverlap | ImGuiButtonFlags_PressedOnClick | ImGuiButtonFlags_PressedOnDoubleClick);
if (pressed && IsMouseDoubleClicked(0))
{
TableSetColumnWidthAutoSingle(table, column_n);
ClearActiveID();
held = hovered = false;
}
if (held)
{
if (table->LastResizedColumn == -1)
table->ResizeLockMinContentsX2 = table->RightMostEnabledColumn != -1 ? table->Columns[table->RightMostEnabledColumn].MaxX : -FLT_MAX;
table->ResizedColumn = (ImGuiTableColumnIdx)column_n;
table->InstanceInteracted = table->InstanceCurrent;
}
if ((hovered && g.HoveredIdTimer > TABLE_RESIZE_SEPARATOR_FEEDBACK_TIMER) || held)
{
table->HoveredColumnBorder = (ImGuiTableColumnIdx)column_n;
SetMouseCursor(ImGuiMouseCursor_ResizeEW);
}
}
}
void ImGui::EndTable()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && "Only call EndTable() if BeginTable() returns true!");
// This assert would be very useful to catch a common error... unfortunately it would probably trigger in some
// cases, and for consistency user may sometimes output empty tables (and still benefit from e.g. outer border)
//IM_ASSERT(table->IsLayoutLocked && "Table unused: never called TableNextRow(), is that the intent?");
// If the user never got to call TableNextRow() or TableNextColumn(), we call layout ourselves to ensure all our
// code paths are consistent (instead of just hoping that TableBegin/TableEnd will work), get borders drawn, etc.
if (!table->IsLayoutLocked)
TableUpdateLayout(table);
const ImGuiTableFlags flags = table->Flags;
ImGuiWindow* inner_window = table->InnerWindow;
ImGuiWindow* outer_window = table->OuterWindow;
ImGuiTableTempData* temp_data = table->TempData;
IM_ASSERT(inner_window == g.CurrentWindow);
IM_ASSERT(outer_window == inner_window || outer_window == inner_window->ParentWindow);
if (table->IsInsideRow)
TableEndRow(table);
// Context menu in columns body
if (flags & ImGuiTableFlags_ContextMenuInBody)
if (table->HoveredColumnBody != -1 && !IsAnyItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
TableOpenContextMenu((int)table->HoveredColumnBody);
// Finalize table height
inner_window->DC.PrevLineSize = temp_data->HostBackupPrevLineSize;
inner_window->DC.CurrLineSize = temp_data->HostBackupCurrLineSize;
inner_window->DC.CursorMaxPos = temp_data->HostBackupCursorMaxPos;
const float inner_content_max_y = table->RowPosY2;
IM_ASSERT(table->RowPosY2 == inner_window->DC.CursorPos.y);
if (inner_window != outer_window)
inner_window->DC.CursorMaxPos.y = inner_content_max_y;
else if (!(flags & ImGuiTableFlags_NoHostExtendY))
table->OuterRect.Max.y = table->InnerRect.Max.y = ImMax(table->OuterRect.Max.y, inner_content_max_y); // Patch OuterRect/InnerRect height
table->WorkRect.Max.y = ImMax(table->WorkRect.Max.y, table->OuterRect.Max.y);
table->LastOuterHeight = table->OuterRect.GetHeight();
// Setup inner scrolling range
// FIXME: This ideally should be done earlier, in BeginTable() SetNextWindowContentSize call, just like writing to inner_window->DC.CursorMaxPos.y,
// but since the later is likely to be impossible to do we'd rather update both axises together.
if (table->Flags & ImGuiTableFlags_ScrollX)
{
const float outer_padding_for_border = (table->Flags & ImGuiTableFlags_BordersOuterV) ? TABLE_BORDER_SIZE : 0.0f;
float max_pos_x = table->InnerWindow->DC.CursorMaxPos.x;
if (table->RightMostEnabledColumn != -1)
max_pos_x = ImMax(max_pos_x, table->Columns[table->RightMostEnabledColumn].WorkMaxX + table->CellPaddingX + table->OuterPaddingX - outer_padding_for_border);
if (table->ResizedColumn != -1)
max_pos_x = ImMax(max_pos_x, table->ResizeLockMinContentsX2);
table->InnerWindow->DC.CursorMaxPos.x = max_pos_x;
}
// Pop clipping rect
if (!(flags & ImGuiTableFlags_NoClip))
inner_window->DrawList->PopClipRect();
inner_window->ClipRect = inner_window->DrawList->_ClipRectStack.back();
// Draw borders
if ((flags & ImGuiTableFlags_Borders) != 0)
TableDrawBorders(table);
#if 0
// Strip out dummy channel draw calls
// We have no way to prevent user submitting direct ImDrawList calls into a hidden column (but ImGui:: calls will be clipped out)
// Pros: remove draw calls which will have no effect. since they'll have zero-size cliprect they may be early out anyway.
// Cons: making it harder for users watching metrics/debugger to spot the wasted vertices.
if (table->DummyDrawChannel != (ImGuiTableColumnIdx)-1)
{
ImDrawChannel* dummy_channel = &table->DrawSplitter._Channels[table->DummyDrawChannel];
dummy_channel->_CmdBuffer.resize(0);
dummy_channel->_IdxBuffer.resize(0);
}
#endif
// Flatten channels and merge draw calls
ImDrawListSplitter* splitter = table->DrawSplitter;
splitter->SetCurrentChannel(inner_window->DrawList, 0);
if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
TableMergeDrawChannels(table);
splitter->Merge(inner_window->DrawList);
// Update ColumnsAutoFitWidth to get us ahead for host using our size to auto-resize without waiting for next BeginTable()
const float width_spacings = (table->OuterPaddingX * 2.0f) + (table->CellSpacingX1 + table->CellSpacingX2) * (table->ColumnsEnabledCount - 1);
table->ColumnsAutoFitWidth = width_spacings + (table->CellPaddingX * 2.0f) * table->ColumnsEnabledCount;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
if (table->EnabledMaskByIndex & ((ImU64)1 << column_n))
{
ImGuiTableColumn* column = &table->Columns[column_n];
if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && !(column->Flags & ImGuiTableColumnFlags_NoResize))
table->ColumnsAutoFitWidth += column->WidthRequest;
else
table->ColumnsAutoFitWidth += TableGetColumnWidthAuto(table, column);
}
// Update scroll
if ((table->Flags & ImGuiTableFlags_ScrollX) == 0 && inner_window != outer_window)
{
inner_window->Scroll.x = 0.0f;
}
else if (table->LastResizedColumn != -1 && table->ResizedColumn == -1 && inner_window->ScrollbarX && table->InstanceInteracted == table->InstanceCurrent)
{
// When releasing a column being resized, scroll to keep the resulting column in sight
const float neighbor_width_to_keep_visible = table->MinColumnWidth + table->CellPaddingX * 2.0f;
ImGuiTableColumn* column = &table->Columns[table->LastResizedColumn];
if (column->MaxX < table->InnerClipRect.Min.x)
SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x - neighbor_width_to_keep_visible, 1.0f);
else if (column->MaxX > table->InnerClipRect.Max.x)
SetScrollFromPosX(inner_window, column->MaxX - inner_window->Pos.x + neighbor_width_to_keep_visible, 1.0f);
}
// Apply resizing/dragging at the end of the frame
if (table->ResizedColumn != -1 && table->InstanceCurrent == table->InstanceInteracted)
{
ImGuiTableColumn* column = &table->Columns[table->ResizedColumn];
const float new_x2 = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + TABLE_RESIZE_SEPARATOR_HALF_THICKNESS);
const float new_width = ImFloor(new_x2 - column->MinX - table->CellSpacingX1 - table->CellPaddingX * 2.0f);
table->ResizedColumnNextWidth = new_width;
}
// Pop from id stack
IM_ASSERT_USER_ERROR(inner_window->IDStack.back() == table->ID + table->InstanceCurrent, "Mismatching PushID/PopID!");
IM_ASSERT_USER_ERROR(outer_window->DC.ItemWidthStack.Size >= temp_data->HostBackupItemWidthStackSize, "Too many PopItemWidth!");
PopID();
// Restore window data that we modified
const ImVec2 backup_outer_max_pos = outer_window->DC.CursorMaxPos;
inner_window->WorkRect = temp_data->HostBackupWorkRect;
inner_window->ParentWorkRect = temp_data->HostBackupParentWorkRect;
inner_window->SkipItems = table->HostSkipItems;
outer_window->DC.CursorPos = table->OuterRect.Min;
outer_window->DC.ItemWidth = temp_data->HostBackupItemWidth;
outer_window->DC.ItemWidthStack.Size = temp_data->HostBackupItemWidthStackSize;
outer_window->DC.ColumnsOffset = temp_data->HostBackupColumnsOffset;
// Layout in outer window
// (FIXME: To allow auto-fit and allow desirable effect of SameLine() we dissociate 'used' vs 'ideal' size by overriding
// CursorPosPrevLine and CursorMaxPos manually. That should be a more general layout feature, see same problem e.g. #3414)
if (inner_window != outer_window)
{
EndChild();
}
else
{
ItemSize(table->OuterRect.GetSize());
ItemAdd(table->OuterRect, 0);
}
// Override declared contents width/height to enable auto-resize while not needlessly adding a scrollbar
if (table->Flags & ImGuiTableFlags_NoHostExtendX)
{
// FIXME-TABLE: Could we remove this section?
// ColumnsAutoFitWidth may be one frame ahead here since for Fixed+NoResize is calculated from latest contents
IM_ASSERT((table->Flags & ImGuiTableFlags_ScrollX) == 0);
outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth);
}
else if (temp_data->UserOuterSize.x <= 0.0f)
{
const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollX) ? inner_window->ScrollbarSizes.x : 0.0f;
outer_window->DC.IdealMaxPos.x = ImMax(outer_window->DC.IdealMaxPos.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth + decoration_size - temp_data->UserOuterSize.x);
outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, ImMin(table->OuterRect.Max.x, table->OuterRect.Min.x + table->ColumnsAutoFitWidth));
}
else
{
outer_window->DC.CursorMaxPos.x = ImMax(backup_outer_max_pos.x, table->OuterRect.Max.x);
}
if (temp_data->UserOuterSize.y <= 0.0f)
{
const float decoration_size = (table->Flags & ImGuiTableFlags_ScrollY) ? inner_window->ScrollbarSizes.y : 0.0f;
outer_window->DC.IdealMaxPos.y = ImMax(outer_window->DC.IdealMaxPos.y, inner_content_max_y + decoration_size - temp_data->UserOuterSize.y);
outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, ImMin(table->OuterRect.Max.y, inner_content_max_y));
}
else
{
// OuterRect.Max.y may already have been pushed downward from the initial value (unless ImGuiTableFlags_NoHostExtendY is set)
outer_window->DC.CursorMaxPos.y = ImMax(backup_outer_max_pos.y, table->OuterRect.Max.y);
}
// Save settings
if (table->IsSettingsDirty)
TableSaveSettings(table);
table->IsInitializing = false;
// Clear or restore current table, if any
IM_ASSERT(g.CurrentWindow == outer_window && g.CurrentTable == table);
IM_ASSERT(g.CurrentTableStackIdx >= 0);
g.CurrentTableStackIdx--;
temp_data = g.CurrentTableStackIdx >= 0 ? &g.TablesTempDataStack[g.CurrentTableStackIdx] : NULL;
g.CurrentTable = temp_data ? g.Tables.GetByIndex(temp_data->TableIndex) : NULL;
if (g.CurrentTable)
{
g.CurrentTable->TempData = temp_data;
g.CurrentTable->DrawSplitter = &temp_data->DrawSplitter;
}
outer_window->DC.CurrentTableIdx = g.CurrentTable ? g.Tables.GetIndex(g.CurrentTable) : -1;
}
// See "COLUMN SIZING POLICIES" comments at the top of this file
// If (init_width_or_weight <= 0.0f) it is ignored
void ImGui::TableSetupColumn(const char* label, ImGuiTableColumnFlags flags, float init_width_or_weight, ImGuiID user_id)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
IM_ASSERT(table->IsLayoutLocked == false && "Need to call call TableSetupColumn() before first row!");
IM_ASSERT((flags & ImGuiTableColumnFlags_StatusMask_) == 0 && "Illegal to pass StatusMask values to TableSetupColumn()");
if (table->DeclColumnsCount >= table->ColumnsCount)
{
IM_ASSERT_USER_ERROR(table->DeclColumnsCount < table->ColumnsCount, "Called TableSetupColumn() too many times!");
return;
}
ImGuiTableColumn* column = &table->Columns[table->DeclColumnsCount];
table->DeclColumnsCount++;
// Assert when passing a width or weight if policy is entirely left to default, to avoid storing width into weight and vice-versa.
// Give a grace to users of ImGuiTableFlags_ScrollX.
if (table->IsDefaultSizingPolicy && (flags & ImGuiTableColumnFlags_WidthMask_) == 0 && (flags & ImGuiTableFlags_ScrollX) == 0)
IM_ASSERT(init_width_or_weight <= 0.0f && "Can only specify width/weight if sizing policy is set explicitly in either Table or Column.");
// When passing a width automatically enforce WidthFixed policy
// (whereas TableSetupColumnFlags would default to WidthAuto if table is not Resizable)
if ((flags & ImGuiTableColumnFlags_WidthMask_) == 0 && init_width_or_weight > 0.0f)
if ((table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedFit || (table->Flags & ImGuiTableFlags_SizingMask_) == ImGuiTableFlags_SizingFixedSame)
flags |= ImGuiTableColumnFlags_WidthFixed;
TableSetupColumnFlags(table, column, flags);
column->UserID = user_id;
flags = column->Flags;
// Initialize defaults
column->InitStretchWeightOrWidth = init_width_or_weight;
if (table->IsInitializing)
{
// Init width or weight
if (column->WidthRequest < 0.0f && column->StretchWeight < 0.0f)
{
if ((flags & ImGuiTableColumnFlags_WidthFixed) && init_width_or_weight > 0.0f)
column->WidthRequest = init_width_or_weight;
if (flags & ImGuiTableColumnFlags_WidthStretch)
column->StretchWeight = (init_width_or_weight > 0.0f) ? init_width_or_weight : -1.0f;
// Disable auto-fit if an explicit width/weight has been specified
if (init_width_or_weight > 0.0f)
column->AutoFitQueue = 0x00;
}
// Init default visibility/sort state
if ((flags & ImGuiTableColumnFlags_DefaultHide) && (table->SettingsLoadedFlags & ImGuiTableFlags_Hideable) == 0)
column->IsUserEnabled = column->IsUserEnabledNextFrame = false;
if (flags & ImGuiTableColumnFlags_DefaultSort && (table->SettingsLoadedFlags & ImGuiTableFlags_Sortable) == 0)
{
column->SortOrder = 0; // Multiple columns using _DefaultSort will be reassigned unique SortOrder values when building the sort specs.
column->SortDirection = (column->Flags & ImGuiTableColumnFlags_PreferSortDescending) ? (ImS8)ImGuiSortDirection_Descending : (ImU8)(ImGuiSortDirection_Ascending);
}
}
// Store name (append with zero-terminator in contiguous buffer)
column->NameOffset = -1;
if (label != NULL && label[0] != 0)
{
column->NameOffset = (ImS16)table->ColumnsNames.size();
table->ColumnsNames.append(label, label + strlen(label) + 1);
}
}
// [Public]
void ImGui::TableSetupScrollFreeze(int columns, int rows)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && "Need to call TableSetupColumn() after BeginTable()!");
IM_ASSERT(table->IsLayoutLocked == false && "Need to call TableSetupColumn() before first row!");
IM_ASSERT(columns >= 0 && columns < IMGUI_TABLE_MAX_COLUMNS);
IM_ASSERT(rows >= 0 && rows < 128); // Arbitrary limit
table->FreezeColumnsRequest = (table->Flags & ImGuiTableFlags_ScrollX) ? (ImGuiTableColumnIdx)ImMin(columns, table->ColumnsCount) : 0;
table->FreezeColumnsCount = (table->InnerWindow->Scroll.x != 0.0f) ? table->FreezeColumnsRequest : 0;
table->FreezeRowsRequest = (table->Flags & ImGuiTableFlags_ScrollY) ? (ImGuiTableColumnIdx)rows : 0;
table->FreezeRowsCount = (table->InnerWindow->Scroll.y != 0.0f) ? table->FreezeRowsRequest : 0;
table->IsUnfrozenRows = (table->FreezeRowsCount == 0); // Make sure this is set before TableUpdateLayout() so ImGuiListClipper can benefit from it.b
// Ensure frozen columns are ordered in their section. We still allow multiple frozen columns to be reordered.
for (int column_n = 0; column_n < table->FreezeColumnsRequest; column_n++)
{
int order_n = table->DisplayOrderToIndex[column_n];
if (order_n != column_n && order_n >= table->FreezeColumnsRequest)
{
ImSwap(table->Columns[table->DisplayOrderToIndex[order_n]].DisplayOrder, table->Columns[table->DisplayOrderToIndex[column_n]].DisplayOrder);
ImSwap(table->DisplayOrderToIndex[order_n], table->DisplayOrderToIndex[column_n]);
}
}
}
//-----------------------------------------------------------------------------
// [SECTION] Tables: Simple accessors
//-----------------------------------------------------------------------------
// - TableGetColumnCount()
// - TableGetColumnName()
// - TableGetColumnName() [Internal]
// - TableSetColumnEnabled()
// - TableGetColumnFlags()
// - TableGetCellBgRect() [Internal]
// - TableGetColumnResizeID() [Internal]
// - TableGetHoveredColumn() [Internal]
// - TableSetBgColor()
//-----------------------------------------------------------------------------
int ImGui::TableGetColumnCount()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
return table ? table->ColumnsCount : 0;
}
const char* ImGui::TableGetColumnName(int column_n)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return NULL;
if (column_n < 0)
column_n = table->CurrentColumn;
return TableGetColumnName(table, column_n);
}
const char* ImGui::TableGetColumnName(const ImGuiTable* table, int column_n)
{
if (table->IsLayoutLocked == false && column_n >= table->DeclColumnsCount)
return ""; // NameOffset is invalid at this point
const ImGuiTableColumn* column = &table->Columns[column_n];
if (column->NameOffset == -1)
return "";
return &table->ColumnsNames.Buf[column->NameOffset];
}
// Change user accessible enabled/disabled state of a column (often perceived as "showing/hiding" from users point of view)
// Note that end-user can use the context menu to change this themselves (right-click in headers, or right-click in columns body with ImGuiTableFlags_ContextMenuInBody)
// - Require table to have the ImGuiTableFlags_Hideable flag because we are manipulating user accessible state.
// - Request will be applied during next layout, which happens on the first call to TableNextRow() after BeginTable().
// - For the getter you can test (TableGetColumnFlags() & ImGuiTableColumnFlags_IsEnabled) != 0.
// - Alternative: the ImGuiTableColumnFlags_Disabled is an overriding/master disable flag which will also hide the column from context menu.
void ImGui::TableSetColumnEnabled(int column_n, bool enabled)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL);
if (!table)
return;
IM_ASSERT(table->Flags & ImGuiTableFlags_Hideable); // See comments above
if (column_n < 0)
column_n = table->CurrentColumn;
IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
ImGuiTableColumn* column = &table->Columns[column_n];
column->IsUserEnabledNextFrame = enabled;
}
// We allow querying for an extra column in order to poll the IsHovered state of the right-most section
ImGuiTableColumnFlags ImGui::TableGetColumnFlags(int column_n)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return ImGuiTableColumnFlags_None;
if (column_n < 0)
column_n = table->CurrentColumn;
if (column_n == table->ColumnsCount)
return (table->HoveredColumnBody == column_n) ? ImGuiTableColumnFlags_IsHovered : ImGuiTableColumnFlags_None;
return table->Columns[column_n].Flags;
}
// Return the cell rectangle based on currently known height.
// - Important: we generally don't know our row height until the end of the row, so Max.y will be incorrect in many situations.
// The only case where this is correct is if we provided a min_row_height to TableNextRow() and don't go below it.
// - Important: if ImGuiTableFlags_PadOuterX is set but ImGuiTableFlags_PadInnerX is not set, the outer-most left and right
// columns report a small offset so their CellBgRect can extend up to the outer border.
ImRect ImGui::TableGetCellBgRect(const ImGuiTable* table, int column_n)
{
const ImGuiTableColumn* column = &table->Columns[column_n];
float x1 = column->MinX;
float x2 = column->MaxX;
if (column->PrevEnabledColumn == -1)
x1 -= table->CellSpacingX1;
if (column->NextEnabledColumn == -1)
x2 += table->CellSpacingX2;
return ImRect(x1, table->RowPosY1, x2, table->RowPosY2);
}
// Return the resizing ID for the right-side of the given column.
ImGuiID ImGui::TableGetColumnResizeID(const ImGuiTable* table, int column_n, int instance_no)
{
IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
ImGuiID id = table->ID + 1 + (instance_no * table->ColumnsCount) + column_n;
return id;
}
// Return -1 when table is not hovered. return columns_count if the unused space at the right of visible columns is hovered.
int ImGui::TableGetHoveredColumn()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return -1;
return (int)table->HoveredColumnBody;
}
void ImGui::TableSetBgColor(ImGuiTableBgTarget target, ImU32 color, int column_n)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(target != ImGuiTableBgTarget_None);
if (color == IM_COL32_DISABLE)
color = 0;
// We cannot draw neither the cell or row background immediately as we don't know the row height at this point in time.
switch (target)
{
case ImGuiTableBgTarget_CellBg:
{
if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
return;
if (column_n == -1)
column_n = table->CurrentColumn;
if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)
return;
if (table->RowCellDataCurrent < 0 || table->RowCellData[table->RowCellDataCurrent].Column != column_n)
table->RowCellDataCurrent++;
ImGuiTableCellData* cell_data = &table->RowCellData[table->RowCellDataCurrent];
cell_data->BgColor = color;
cell_data->Column = (ImGuiTableColumnIdx)column_n;
break;
}
case ImGuiTableBgTarget_RowBg0:
case ImGuiTableBgTarget_RowBg1:
{
if (table->RowPosY1 > table->InnerClipRect.Max.y) // Discard
return;
IM_ASSERT(column_n == -1);
int bg_idx = (target == ImGuiTableBgTarget_RowBg1) ? 1 : 0;
table->RowBgColor[bg_idx] = color;
break;
}
default:
IM_ASSERT(0);
}
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Row changes
//-------------------------------------------------------------------------
// - TableGetRowIndex()
// - TableNextRow()
// - TableBeginRow() [Internal]
// - TableEndRow() [Internal]
//-------------------------------------------------------------------------
// [Public] Note: for row coloring we use ->RowBgColorCounter which is the same value without counting header rows
int ImGui::TableGetRowIndex()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return 0;
return table->CurrentRow;
}
// [Public] Starts into the first cell of a new row
void ImGui::TableNextRow(ImGuiTableRowFlags row_flags, float row_min_height)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table->IsLayoutLocked)
TableUpdateLayout(table);
if (table->IsInsideRow)
TableEndRow(table);
table->LastRowFlags = table->RowFlags;
table->RowFlags = row_flags;
table->RowMinHeight = row_min_height;
TableBeginRow(table);
// We honor min_row_height requested by user, but cannot guarantee per-row maximum height,
// because that would essentially require a unique clipping rectangle per-cell.
table->RowPosY2 += table->CellPaddingY * 2.0f;
table->RowPosY2 = ImMax(table->RowPosY2, table->RowPosY1 + row_min_height);
// Disable output until user calls TableNextColumn()
table->InnerWindow->SkipItems = true;
}
// [Internal] Called by TableNextRow()
void ImGui::TableBeginRow(ImGuiTable* table)
{
ImGuiWindow* window = table->InnerWindow;
IM_ASSERT(!table->IsInsideRow);
// New row
table->CurrentRow++;
table->CurrentColumn = -1;
table->RowBgColor[0] = table->RowBgColor[1] = IM_COL32_DISABLE;
table->RowCellDataCurrent = -1;
table->IsInsideRow = true;
// Begin frozen rows
float next_y1 = table->RowPosY2;
if (table->CurrentRow == 0 && table->FreezeRowsCount > 0)
next_y1 = window->DC.CursorPos.y = table->OuterRect.Min.y;
table->RowPosY1 = table->RowPosY2 = next_y1;
table->RowTextBaseline = 0.0f;
table->RowIndentOffsetX = window->DC.Indent.x - table->HostIndentX; // Lock indent
window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.CursorMaxPos.y = next_y1;
// Making the header BG color non-transparent will allow us to overlay it multiple times when handling smooth dragging.
if (table->RowFlags & ImGuiTableRowFlags_Headers)
{
TableSetBgColor(ImGuiTableBgTarget_RowBg0, GetColorU32(ImGuiCol_TableHeaderBg));
if (table->CurrentRow == 0)
table->IsUsingHeaders = true;
}
}
// [Internal] Called by TableNextRow()
void ImGui::TableEndRow(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window == table->InnerWindow);
IM_ASSERT(table->IsInsideRow);
if (table->CurrentColumn != -1)
TableEndCell(table);
// Logging
if (g.LogEnabled)
LogRenderedText(NULL, "|");
// Position cursor at the bottom of our row so it can be used for e.g. clipping calculation. However it is
// likely that the next call to TableBeginCell() will reposition the cursor to take account of vertical padding.
window->DC.CursorPos.y = table->RowPosY2;
// Row background fill
const float bg_y1 = table->RowPosY1;
const float bg_y2 = table->RowPosY2;
const bool unfreeze_rows_actual = (table->CurrentRow + 1 == table->FreezeRowsCount);
const bool unfreeze_rows_request = (table->CurrentRow + 1 == table->FreezeRowsRequest);
if (table->CurrentRow == 0)
table->LastFirstRowHeight = bg_y2 - bg_y1;
const bool is_visible = (bg_y2 >= table->InnerClipRect.Min.y && bg_y1 <= table->InnerClipRect.Max.y);
if (is_visible)
{
// Decide of background color for the row
ImU32 bg_col0 = 0;
ImU32 bg_col1 = 0;
if (table->RowBgColor[0] != IM_COL32_DISABLE)
bg_col0 = table->RowBgColor[0];
else if (table->Flags & ImGuiTableFlags_RowBg)
bg_col0 = GetColorU32((table->RowBgColorCounter & 1) ? ImGuiCol_TableRowBgAlt : ImGuiCol_TableRowBg);
if (table->RowBgColor[1] != IM_COL32_DISABLE)
bg_col1 = table->RowBgColor[1];
// Decide of top border color
ImU32 border_col = 0;
const float border_size = TABLE_BORDER_SIZE;
if (table->CurrentRow > 0 || table->InnerWindow == table->OuterWindow)
if (table->Flags & ImGuiTableFlags_BordersInnerH)
border_col = (table->LastRowFlags & ImGuiTableRowFlags_Headers) ? table->BorderColorStrong : table->BorderColorLight;
const bool draw_cell_bg_color = table->RowCellDataCurrent >= 0;
const bool draw_strong_bottom_border = unfreeze_rows_actual;
if ((bg_col0 | bg_col1 | border_col) != 0 || draw_strong_bottom_border || draw_cell_bg_color)
{
// In theory we could call SetWindowClipRectBeforeSetChannel() but since we know TableEndRow() is
// always followed by a change of clipping rectangle we perform the smallest overwrite possible here.
if ((table->Flags & ImGuiTableFlags_NoClip) == 0)
window->DrawList->_CmdHeader.ClipRect = table->Bg0ClipRectForDrawCmd.ToVec4();
table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_BG0);
}
// Draw row background
// We soft/cpu clip this so all backgrounds and borders can share the same clipping rectangle
if (bg_col0 || bg_col1)
{
ImRect row_rect(table->WorkRect.Min.x, bg_y1, table->WorkRect.Max.x, bg_y2);
row_rect.ClipWith(table->BgClipRect);
if (bg_col0 != 0 && row_rect.Min.y < row_rect.Max.y)
window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col0);
if (bg_col1 != 0 && row_rect.Min.y < row_rect.Max.y)
window->DrawList->AddRectFilled(row_rect.Min, row_rect.Max, bg_col1);
}
// Draw cell background color
if (draw_cell_bg_color)
{
ImGuiTableCellData* cell_data_end = &table->RowCellData[table->RowCellDataCurrent];
for (ImGuiTableCellData* cell_data = &table->RowCellData[0]; cell_data <= cell_data_end; cell_data++)
{
const ImGuiTableColumn* column = &table->Columns[cell_data->Column];
ImRect cell_bg_rect = TableGetCellBgRect(table, cell_data->Column);
cell_bg_rect.ClipWith(table->BgClipRect);
cell_bg_rect.Min.x = ImMax(cell_bg_rect.Min.x, column->ClipRect.Min.x); // So that first column after frozen one gets clipped
cell_bg_rect.Max.x = ImMin(cell_bg_rect.Max.x, column->MaxX);
window->DrawList->AddRectFilled(cell_bg_rect.Min, cell_bg_rect.Max, cell_data->BgColor);
}
}
// Draw top border
if (border_col && bg_y1 >= table->BgClipRect.Min.y && bg_y1 < table->BgClipRect.Max.y)
window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y1), ImVec2(table->BorderX2, bg_y1), border_col, border_size);
// Draw bottom border at the row unfreezing mark (always strong)
if (draw_strong_bottom_border && bg_y2 >= table->BgClipRect.Min.y && bg_y2 < table->BgClipRect.Max.y)
window->DrawList->AddLine(ImVec2(table->BorderX1, bg_y2), ImVec2(table->BorderX2, bg_y2), table->BorderColorStrong, border_size);
}
// End frozen rows (when we are past the last frozen row line, teleport cursor and alter clipping rectangle)
// We need to do that in TableEndRow() instead of TableBeginRow() so the list clipper can mark end of row and
// get the new cursor position.
if (unfreeze_rows_request)
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
column->NavLayerCurrent = (ImS8)((column_n < table->FreezeColumnsCount) ? ImGuiNavLayer_Menu : ImGuiNavLayer_Main);
}
if (unfreeze_rows_actual)
{
IM_ASSERT(table->IsUnfrozenRows == false);
table->IsUnfrozenRows = true;
// BgClipRect starts as table->InnerClipRect, reduce it now and make BgClipRectForDrawCmd == BgClipRect
float y0 = ImMax(table->RowPosY2 + 1, window->InnerClipRect.Min.y);
table->BgClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y = ImMin(y0, window->InnerClipRect.Max.y);
table->BgClipRect.Max.y = table->Bg2ClipRectForDrawCmd.Max.y = window->InnerClipRect.Max.y;
table->Bg2DrawChannelCurrent = table->Bg2DrawChannelUnfrozen;
IM_ASSERT(table->Bg2ClipRectForDrawCmd.Min.y <= table->Bg2ClipRectForDrawCmd.Max.y);
float row_height = table->RowPosY2 - table->RowPosY1;
table->RowPosY2 = window->DC.CursorPos.y = table->WorkRect.Min.y + table->RowPosY2 - table->OuterRect.Min.y;
table->RowPosY1 = table->RowPosY2 - row_height;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
column->DrawChannelCurrent = column->DrawChannelUnfrozen;
column->ClipRect.Min.y = table->Bg2ClipRectForDrawCmd.Min.y;
}
// Update cliprect ahead of TableBeginCell() so clipper can access to new ClipRect->Min.y
SetWindowClipRectBeforeSetChannel(window, table->Columns[0].ClipRect);
table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Columns[0].DrawChannelCurrent);
}
if (!(table->RowFlags & ImGuiTableRowFlags_Headers))
table->RowBgColorCounter++;
table->IsInsideRow = false;
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Columns changes
//-------------------------------------------------------------------------
// - TableGetColumnIndex()
// - TableSetColumnIndex()
// - TableNextColumn()
// - TableBeginCell() [Internal]
// - TableEndCell() [Internal]
//-------------------------------------------------------------------------
int ImGui::TableGetColumnIndex()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return 0;
return table->CurrentColumn;
}
// [Public] Append into a specific column
bool ImGui::TableSetColumnIndex(int column_n)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return false;
if (table->CurrentColumn != column_n)
{
if (table->CurrentColumn != -1)
TableEndCell(table);
IM_ASSERT(column_n >= 0 && table->ColumnsCount);
TableBeginCell(table, column_n);
}
// Return whether the column is visible. User may choose to skip submitting items based on this return value,
// however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;
}
// [Public] Append into the next column, wrap and create a new row when already on last column
bool ImGui::TableNextColumn()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!table)
return false;
if (table->IsInsideRow && table->CurrentColumn + 1 < table->ColumnsCount)
{
if (table->CurrentColumn != -1)
TableEndCell(table);
TableBeginCell(table, table->CurrentColumn + 1);
}
else
{
TableNextRow();
TableBeginCell(table, 0);
}
// Return whether the column is visible. User may choose to skip submitting items based on this return value,
// however they shouldn't skip submitting for columns that may have the tallest contribution to row height.
int column_n = table->CurrentColumn;
return (table->RequestOutputMaskByIndex & ((ImU64)1 << column_n)) != 0;
}
// [Internal] Called by TableSetColumnIndex()/TableNextColumn()
// This is called very frequently, so we need to be mindful of unnecessary overhead.
// FIXME-TABLE FIXME-OPT: Could probably shortcut some things for non-active or clipped columns.
void ImGui::TableBeginCell(ImGuiTable* table, int column_n)
{
ImGuiTableColumn* column = &table->Columns[column_n];
ImGuiWindow* window = table->InnerWindow;
table->CurrentColumn = column_n;
// Start position is roughly ~~ CellRect.Min + CellPadding + Indent
float start_x = column->WorkMinX;
if (column->Flags & ImGuiTableColumnFlags_IndentEnable)
start_x += table->RowIndentOffsetX; // ~~ += window.DC.Indent.x - table->HostIndentX, except we locked it for the row.
window->DC.CursorPos.x = start_x;
window->DC.CursorPos.y = table->RowPosY1 + table->CellPaddingY;
window->DC.CursorMaxPos.x = window->DC.CursorPos.x;
window->DC.ColumnsOffset.x = start_x - window->Pos.x - window->DC.Indent.x; // FIXME-WORKRECT
window->DC.CurrLineTextBaseOffset = table->RowTextBaseline;
window->DC.NavLayerCurrent = (ImGuiNavLayer)column->NavLayerCurrent;
window->WorkRect.Min.y = window->DC.CursorPos.y;
window->WorkRect.Min.x = column->WorkMinX;
window->WorkRect.Max.x = column->WorkMaxX;
window->DC.ItemWidth = column->ItemWidth;
// To allow ImGuiListClipper to function we propagate our row height
if (!column->IsEnabled)
window->DC.CursorPos.y = ImMax(window->DC.CursorPos.y, table->RowPosY2);
window->SkipItems = column->IsSkipItems;
if (column->IsSkipItems)
{
ImGuiContext& g = *GImGui;
g.LastItemData.ID = 0;
g.LastItemData.StatusFlags = 0;
}
if (table->Flags & ImGuiTableFlags_NoClip)
{
// FIXME: if we end up drawing all borders/bg in EndTable, could remove this and just assert that channel hasn't changed.
table->DrawSplitter->SetCurrentChannel(window->DrawList, TABLE_DRAW_CHANNEL_NOCLIP);
//IM_ASSERT(table->DrawSplitter._Current == TABLE_DRAW_CHANNEL_NOCLIP);
}
else
{
// FIXME-TABLE: Could avoid this if draw channel is dummy channel?
SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
}
// Logging
ImGuiContext& g = *GImGui;
if (g.LogEnabled && !column->IsSkipItems)
{
LogRenderedText(&window->DC.CursorPos, "|");
g.LogLinePosY = FLT_MAX;
}
}
// [Internal] Called by TableNextRow()/TableSetColumnIndex()/TableNextColumn()
void ImGui::TableEndCell(ImGuiTable* table)
{
ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
ImGuiWindow* window = table->InnerWindow;
// Report maximum position so we can infer content size per column.
float* p_max_pos_x;
if (table->RowFlags & ImGuiTableRowFlags_Headers)
p_max_pos_x = &column->ContentMaxXHeadersUsed; // Useful in case user submit contents in header row that is not a TableHeader() call
else
p_max_pos_x = table->IsUnfrozenRows ? &column->ContentMaxXUnfrozen : &column->ContentMaxXFrozen;
*p_max_pos_x = ImMax(*p_max_pos_x, window->DC.CursorMaxPos.x);
table->RowPosY2 = ImMax(table->RowPosY2, window->DC.CursorMaxPos.y + table->CellPaddingY);
column->ItemWidth = window->DC.ItemWidth;
// Propagate text baseline for the entire row
// FIXME-TABLE: Here we propagate text baseline from the last line of the cell.. instead of the first one.
table->RowTextBaseline = ImMax(table->RowTextBaseline, window->DC.PrevLineTextBaseOffset);
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Columns width management
//-------------------------------------------------------------------------
// - TableGetMaxColumnWidth() [Internal]
// - TableGetColumnWidthAuto() [Internal]
// - TableSetColumnWidth()
// - TableSetColumnWidthAutoSingle() [Internal]
// - TableSetColumnWidthAutoAll() [Internal]
// - TableUpdateColumnsWeightFromWidth() [Internal]
//-------------------------------------------------------------------------
// Maximum column content width given current layout. Use column->MinX so this value on a per-column basis.
float ImGui::TableGetMaxColumnWidth(const ImGuiTable* table, int column_n)
{
const ImGuiTableColumn* column = &table->Columns[column_n];
float max_width = FLT_MAX;
const float min_column_distance = table->MinColumnWidth + table->CellPaddingX * 2.0f + table->CellSpacingX1 + table->CellSpacingX2;
if (table->Flags & ImGuiTableFlags_ScrollX)
{
// Frozen columns can't reach beyond visible width else scrolling will naturally break.
// (we use DisplayOrder as within a set of multiple frozen column reordering is possible)
if (column->DisplayOrder < table->FreezeColumnsRequest)
{
max_width = (table->InnerClipRect.Max.x - (table->FreezeColumnsRequest - column->DisplayOrder) * min_column_distance) - column->MinX;
max_width = max_width - table->OuterPaddingX - table->CellPaddingX - table->CellSpacingX2;
}
}
else if ((table->Flags & ImGuiTableFlags_NoKeepColumnsVisible) == 0)
{
// If horizontal scrolling if disabled, we apply a final lossless shrinking of columns in order to make
// sure they are all visible. Because of this we also know that all of the columns will always fit in
// table->WorkRect and therefore in table->InnerRect (because ScrollX is off)
// FIXME-TABLE: This is solved incorrectly but also quite a difficult problem to fix as we also want ClipRect width to match.
// See "table_width_distrib" and "table_width_keep_visible" tests
max_width = table->WorkRect.Max.x - (table->ColumnsEnabledCount - column->IndexWithinEnabledSet - 1) * min_column_distance - column->MinX;
//max_width -= table->CellSpacingX1;
max_width -= table->CellSpacingX2;
max_width -= table->CellPaddingX * 2.0f;
max_width -= table->OuterPaddingX;
}
return max_width;
}
// Note this is meant to be stored in column->WidthAuto, please generally use the WidthAuto field
float ImGui::TableGetColumnWidthAuto(ImGuiTable* table, ImGuiTableColumn* column)
{
const float content_width_body = ImMax(column->ContentMaxXFrozen, column->ContentMaxXUnfrozen) - column->WorkMinX;
const float content_width_headers = column->ContentMaxXHeadersIdeal - column->WorkMinX;
float width_auto = content_width_body;
if (!(column->Flags & ImGuiTableColumnFlags_NoHeaderWidth))
width_auto = ImMax(width_auto, content_width_headers);
// Non-resizable fixed columns preserve their requested width
if ((column->Flags & ImGuiTableColumnFlags_WidthFixed) && column->InitStretchWeightOrWidth > 0.0f)
if (!(table->Flags & ImGuiTableFlags_Resizable) || (column->Flags & ImGuiTableColumnFlags_NoResize))
width_auto = column->InitStretchWeightOrWidth;
return ImMax(width_auto, table->MinColumnWidth);
}
// 'width' = inner column width, without padding
void ImGui::TableSetColumnWidth(int column_n, float width)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && table->IsLayoutLocked == false);
IM_ASSERT(column_n >= 0 && column_n < table->ColumnsCount);
ImGuiTableColumn* column_0 = &table->Columns[column_n];
float column_0_width = width;
// Apply constraints early
// Compare both requested and actual given width to avoid overwriting requested width when column is stuck (minimum size, bounded)
IM_ASSERT(table->MinColumnWidth > 0.0f);
const float min_width = table->MinColumnWidth;
const float max_width = ImMax(min_width, TableGetMaxColumnWidth(table, column_n));
column_0_width = ImClamp(column_0_width, min_width, max_width);
if (column_0->WidthGiven == column_0_width || column_0->WidthRequest == column_0_width)
return;
//IMGUI_DEBUG_LOG("TableSetColumnWidth(%d, %.1f->%.1f)\n", column_0_idx, column_0->WidthGiven, column_0_width);
ImGuiTableColumn* column_1 = (column_0->NextEnabledColumn != -1) ? &table->Columns[column_0->NextEnabledColumn] : NULL;
// In this surprisingly not simple because of how we support mixing Fixed and multiple Stretch columns.
// - All fixed: easy.
// - All stretch: easy.
// - One or more fixed + one stretch: easy.
// - One or more fixed + more than one stretch: tricky.
// Qt when manual resize is enabled only support a single _trailing_ stretch column.
// When forwarding resize from Wn| to Fn+1| we need to be considerate of the _NoResize flag on Fn+1.
// FIXME-TABLE: Find a way to rewrite all of this so interactions feel more consistent for the user.
// Scenarios:
// - F1 F2 F3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. Subsequent columns will be offset.
// - F1 F2 F3 resize from F3| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered.
// - F1 F2 W3 resize from F1| or F2| --> ok: alter ->WidthRequested of Fixed column. If active, ScrollX extent can be altered, but it doesn't make much sense as the Stretch column will always be minimal size.
// - F1 F2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
// - W1 W2 W3 resize from W1| or W2| --> ok
// - W1 W2 W3 resize from W3| --> ok: no-op (disabled by Resize Rule 1)
// - W1 F2 F3 resize from F3| --> ok: no-op (disabled by Resize Rule 1)
// - W1 F2 resize from F2| --> ok: no-op (disabled by Resize Rule 1)
// - W1 W2 F3 resize from W1| or W2| --> ok
// - W1 F2 W3 resize from W1| or F2| --> ok
// - F1 W2 F3 resize from W2| --> ok
// - F1 W3 F2 resize from W3| --> ok
// - W1 F2 F3 resize from W1| --> ok: equivalent to resizing |F2. F3 will not move.
// - W1 F2 F3 resize from F2| --> ok
// All resizes from a Wx columns are locking other columns.
// Possible improvements:
// - W1 W2 W3 resize W1| --> to not be stuck, both W2 and W3 would stretch down. Seems possible to fix. Would be most beneficial to simplify resize of all-weighted columns.
// - W3 F1 F2 resize W3| --> to not be stuck past F1|, both F1 and F2 would need to stretch down, which would be lossy or ambiguous. Seems hard to fix.
// [Resize Rule 1] Can't resize from right of right-most visible column if there is any Stretch column. Implemented in TableUpdateLayout().
// If we have all Fixed columns OR resizing a Fixed column that doesn't come after a Stretch one, we can do an offsetting resize.
// This is the preferred resize path
if (column_0->Flags & ImGuiTableColumnFlags_WidthFixed)
if (!column_1 || table->LeftMostStretchedColumn == -1 || table->Columns[table->LeftMostStretchedColumn].DisplayOrder >= column_0->DisplayOrder)
{
column_0->WidthRequest = column_0_width;
table->IsSettingsDirty = true;
return;
}
// We can also use previous column if there's no next one (this is used when doing an auto-fit on the right-most stretch column)
if (column_1 == NULL)
column_1 = (column_0->PrevEnabledColumn != -1) ? &table->Columns[column_0->PrevEnabledColumn] : NULL;
if (column_1 == NULL)
return;
// Resizing from right-side of a Stretch column before a Fixed column forward sizing to left-side of fixed column.
// (old_a + old_b == new_a + new_b) --> (new_a == old_a + old_b - new_b)
float column_1_width = ImMax(column_1->WidthRequest - (column_0_width - column_0->WidthRequest), min_width);
column_0_width = column_0->WidthRequest + column_1->WidthRequest - column_1_width;
IM_ASSERT(column_0_width > 0.0f && column_1_width > 0.0f);
column_0->WidthRequest = column_0_width;
column_1->WidthRequest = column_1_width;
if ((column_0->Flags | column_1->Flags) & ImGuiTableColumnFlags_WidthStretch)
TableUpdateColumnsWeightFromWidth(table);
table->IsSettingsDirty = true;
}
// Disable clipping then auto-fit, will take 2 frames
// (we don't take a shortcut for unclipped columns to reduce inconsistencies when e.g. resizing multiple columns)
void ImGui::TableSetColumnWidthAutoSingle(ImGuiTable* table, int column_n)
{
// Single auto width uses auto-fit
ImGuiTableColumn* column = &table->Columns[column_n];
if (!column->IsEnabled)
return;
column->CannotSkipItemsQueue = (1 << 0);
table->AutoFitSingleColumn = (ImGuiTableColumnIdx)column_n;
}
void ImGui::TableSetColumnWidthAutoAll(ImGuiTable* table)
{
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (!column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_WidthStretch)) // Cannot reset weight of hidden stretch column
continue;
column->CannotSkipItemsQueue = (1 << 0);
column->AutoFitQueue = (1 << 1);
}
}
void ImGui::TableUpdateColumnsWeightFromWidth(ImGuiTable* table)
{
IM_ASSERT(table->LeftMostStretchedColumn != -1 && table->RightMostStretchedColumn != -1);
// Measure existing quantity
float visible_weight = 0.0f;
float visible_width = 0.0f;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
continue;
IM_ASSERT(column->StretchWeight > 0.0f);
visible_weight += column->StretchWeight;
visible_width += column->WidthRequest;
}
IM_ASSERT(visible_weight > 0.0f && visible_width > 0.0f);
// Apply new weights
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (!column->IsEnabled || !(column->Flags & ImGuiTableColumnFlags_WidthStretch))
continue;
column->StretchWeight = (column->WidthRequest / visible_width) * visible_weight;
IM_ASSERT(column->StretchWeight > 0.0f);
}
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Drawing
//-------------------------------------------------------------------------
// - TablePushBackgroundChannel() [Internal]
// - TablePopBackgroundChannel() [Internal]
// - TableSetupDrawChannels() [Internal]
// - TableMergeDrawChannels() [Internal]
// - TableDrawBorders() [Internal]
//-------------------------------------------------------------------------
// Bg2 is used by Selectable (and possibly other widgets) to render to the background.
// Unlike our Bg0/1 channel which we uses for RowBg/CellBg/Borders and where we guarantee all shapes to be CPU-clipped, the Bg2 channel being widgets-facing will rely on regular ClipRect.
void ImGui::TablePushBackgroundChannel()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiTable* table = g.CurrentTable;
// Optimization: avoid SetCurrentChannel() + PushClipRect()
table->HostBackupInnerClipRect = window->ClipRect;
SetWindowClipRectBeforeSetChannel(window, table->Bg2ClipRectForDrawCmd);
table->DrawSplitter->SetCurrentChannel(window->DrawList, table->Bg2DrawChannelCurrent);
}
void ImGui::TablePopBackgroundChannel()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiTable* table = g.CurrentTable;
ImGuiTableColumn* column = &table->Columns[table->CurrentColumn];
// Optimization: avoid PopClipRect() + SetCurrentChannel()
SetWindowClipRectBeforeSetChannel(window, table->HostBackupInnerClipRect);
table->DrawSplitter->SetCurrentChannel(window->DrawList, column->DrawChannelCurrent);
}
// Allocate draw channels. Called by TableUpdateLayout()
// - We allocate them following storage order instead of display order so reordering columns won't needlessly
// increase overall dormant memory cost.
// - We isolate headers draw commands in their own channels instead of just altering clip rects.
// This is in order to facilitate merging of draw commands.
// - After crossing FreezeRowsCount, all columns see their current draw channel changed to a second set of channels.
// - We only use the dummy draw channel so we can push a null clipping rectangle into it without affecting other
// channels, while simplifying per-row/per-cell overhead. It will be empty and discarded when merged.
// - We allocate 1 or 2 background draw channels. This is because we know TablePushBackgroundChannel() is only used for
// horizontal spanning. If we allowed vertical spanning we'd need one background draw channel per merge group (1-4).
// Draw channel allocation (before merging):
// - NoClip --> 2+D+1 channels: bg0/1 + bg2 + foreground (same clip rect == always 1 draw call)
// - Clip --> 2+D+N channels
// - FreezeRows --> 2+D+N*2 (unless scrolling value is zero)
// - FreezeRows || FreezeColunns --> 3+D+N*2 (unless scrolling value is zero)
// Where D is 1 if any column is clipped or hidden (dummy channel) otherwise 0.
void ImGui::TableSetupDrawChannels(ImGuiTable* table)
{
const int freeze_row_multiplier = (table->FreezeRowsCount > 0) ? 2 : 1;
const int channels_for_row = (table->Flags & ImGuiTableFlags_NoClip) ? 1 : table->ColumnsEnabledCount;
const int channels_for_bg = 1 + 1 * freeze_row_multiplier;
const int channels_for_dummy = (table->ColumnsEnabledCount < table->ColumnsCount || table->VisibleMaskByIndex != table->EnabledMaskByIndex) ? +1 : 0;
const int channels_total = channels_for_bg + (channels_for_row * freeze_row_multiplier) + channels_for_dummy;
table->DrawSplitter->Split(table->InnerWindow->DrawList, channels_total);
table->DummyDrawChannel = (ImGuiTableDrawChannelIdx)((channels_for_dummy > 0) ? channels_total - 1 : -1);
table->Bg2DrawChannelCurrent = TABLE_DRAW_CHANNEL_BG2_FROZEN;
table->Bg2DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)((table->FreezeRowsCount > 0) ? 2 + channels_for_row : TABLE_DRAW_CHANNEL_BG2_FROZEN);
int draw_channel_current = 2;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (column->IsVisibleX && column->IsVisibleY)
{
column->DrawChannelFrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current);
column->DrawChannelUnfrozen = (ImGuiTableDrawChannelIdx)(draw_channel_current + (table->FreezeRowsCount > 0 ? channels_for_row + 1 : 0));
if (!(table->Flags & ImGuiTableFlags_NoClip))
draw_channel_current++;
}
else
{
column->DrawChannelFrozen = column->DrawChannelUnfrozen = table->DummyDrawChannel;
}
column->DrawChannelCurrent = column->DrawChannelFrozen;
}
// Initial draw cmd starts with a BgClipRect that matches the one of its host, to facilitate merge draw commands by default.
// All our cell highlight are manually clipped with BgClipRect. When unfreezing it will be made smaller to fit scrolling rect.
// (This technically isn't part of setting up draw channels, but is reasonably related to be done here)
table->BgClipRect = table->InnerClipRect;
table->Bg0ClipRectForDrawCmd = table->OuterWindow->ClipRect;
table->Bg2ClipRectForDrawCmd = table->HostClipRect;
IM_ASSERT(table->BgClipRect.Min.y <= table->BgClipRect.Max.y);
}
// This function reorder draw channels based on matching clip rectangle, to facilitate merging them. Called by EndTable().
// For simplicity we call it TableMergeDrawChannels() but in fact it only reorder channels + overwrite ClipRect,
// actual merging is done by table->DrawSplitter.Merge() which is called right after TableMergeDrawChannels().
//
// Columns where the contents didn't stray off their local clip rectangle can be merged. To achieve
// this we merge their clip rect and make them contiguous in the channel list, so they can be merged
// by the call to DrawSplitter.Merge() following to the call to this function.
// We reorder draw commands by arranging them into a maximum of 4 distinct groups:
//
// 1 group: 2 groups: 2 groups: 4 groups:
// [ 0. ] no freeze [ 0. ] row freeze [ 01 ] col freeze [ 01 ] row+col freeze
// [ .. ] or no scroll [ 2. ] and v-scroll [ .. ] and h-scroll [ 23 ] and v+h-scroll
//
// Each column itself can use 1 channel (row freeze disabled) or 2 channels (row freeze enabled).
// When the contents of a column didn't stray off its limit, we move its channels into the corresponding group
// based on its position (within frozen rows/columns groups or not).
// At the end of the operation our 1-4 groups will each have a ImDrawCmd using the same ClipRect.
// This function assume that each column are pointing to a distinct draw channel,
// otherwise merge_group->ChannelsCount will not match set bit count of merge_group->ChannelsMask.
//
// Column channels will not be merged into one of the 1-4 groups in the following cases:
// - The contents stray off its clipping rectangle (we only compare the MaxX value, not the MinX value).
// Direct ImDrawList calls won't be taken into account by default, if you use them make sure the ImGui:: bounds
// matches, by e.g. calling SetCursorScreenPos().
// - The channel uses more than one draw command itself. We drop all our attempt at merging stuff here..
// we could do better but it's going to be rare and probably not worth the hassle.
// Columns for which the draw channel(s) haven't been merged with other will use their own ImDrawCmd.
//
// This function is particularly tricky to understand.. take a breath.
void ImGui::TableMergeDrawChannels(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
ImDrawListSplitter* splitter = table->DrawSplitter;
const bool has_freeze_v = (table->FreezeRowsCount > 0);
const bool has_freeze_h = (table->FreezeColumnsCount > 0);
IM_ASSERT(splitter->_Current == 0);
// Track which groups we are going to attempt to merge, and which channels goes into each group.
struct MergeGroup
{
ImRect ClipRect;
int ChannelsCount;
ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> ChannelsMask;
MergeGroup() { ChannelsCount = 0; }
};
int merge_group_mask = 0x00;
MergeGroup merge_groups[4];
// 1. Scan channels and take note of those which can be merged
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
if ((table->VisibleMaskByIndex & ((ImU64)1 << column_n)) == 0)
continue;
ImGuiTableColumn* column = &table->Columns[column_n];
const int merge_group_sub_count = has_freeze_v ? 2 : 1;
for (int merge_group_sub_n = 0; merge_group_sub_n < merge_group_sub_count; merge_group_sub_n++)
{
const int channel_no = (merge_group_sub_n == 0) ? column->DrawChannelFrozen : column->DrawChannelUnfrozen;
// Don't attempt to merge if there are multiple draw calls within the column
ImDrawChannel* src_channel = &splitter->_Channels[channel_no];
if (src_channel->_CmdBuffer.Size > 0 && src_channel->_CmdBuffer.back().ElemCount == 0)
src_channel->_CmdBuffer.pop_back();
if (src_channel->_CmdBuffer.Size != 1)
continue;
// Find out the width of this merge group and check if it will fit in our column
// (note that we assume that rendering didn't stray on the left direction. we should need a CursorMinPos to detect it)
if (!(column->Flags & ImGuiTableColumnFlags_NoClip))
{
float content_max_x;
if (!has_freeze_v)
content_max_x = ImMax(column->ContentMaxXUnfrozen, column->ContentMaxXHeadersUsed); // No row freeze
else if (merge_group_sub_n == 0)
content_max_x = ImMax(column->ContentMaxXFrozen, column->ContentMaxXHeadersUsed); // Row freeze: use width before freeze
else
content_max_x = column->ContentMaxXUnfrozen; // Row freeze: use width after freeze
if (content_max_x > column->ClipRect.Max.x)
continue;
}
const int merge_group_n = (has_freeze_h && column_n < table->FreezeColumnsCount ? 0 : 1) + (has_freeze_v && merge_group_sub_n == 0 ? 0 : 2);
IM_ASSERT(channel_no < IMGUI_TABLE_MAX_DRAW_CHANNELS);
MergeGroup* merge_group = &merge_groups[merge_group_n];
if (merge_group->ChannelsCount == 0)
merge_group->ClipRect = ImRect(+FLT_MAX, +FLT_MAX, -FLT_MAX, -FLT_MAX);
merge_group->ChannelsMask.SetBit(channel_no);
merge_group->ChannelsCount++;
merge_group->ClipRect.Add(src_channel->_CmdBuffer[0].ClipRect);
merge_group_mask |= (1 << merge_group_n);
}
// Invalidate current draw channel
// (we don't clear DrawChannelFrozen/DrawChannelUnfrozen solely to facilitate debugging/later inspection of data)
column->DrawChannelCurrent = (ImGuiTableDrawChannelIdx)-1;
}
// [DEBUG] Display merge groups
#if 0
if (g.IO.KeyShift)
for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
{
MergeGroup* merge_group = &merge_groups[merge_group_n];
if (merge_group->ChannelsCount == 0)
continue;
char buf[32];
ImFormatString(buf, 32, "MG%d:%d", merge_group_n, merge_group->ChannelsCount);
ImVec2 text_pos = merge_group->ClipRect.Min + ImVec2(4, 4);
ImVec2 text_size = CalcTextSize(buf, NULL);
GetForegroundDrawList()->AddRectFilled(text_pos, text_pos + text_size, IM_COL32(0, 0, 0, 255));
GetForegroundDrawList()->AddText(text_pos, IM_COL32(255, 255, 0, 255), buf, NULL);
GetForegroundDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 255, 0, 255));
}
#endif
// 2. Rewrite channel list in our preferred order
if (merge_group_mask != 0)
{
// We skip channel 0 (Bg0/Bg1) and 1 (Bg2 frozen) from the shuffling since they won't move - see channels allocation in TableSetupDrawChannels().
const int LEADING_DRAW_CHANNELS = 2;
g.DrawChannelsTempMergeBuffer.resize(splitter->_Count - LEADING_DRAW_CHANNELS); // Use shared temporary storage so the allocation gets amortized
ImDrawChannel* dst_tmp = g.DrawChannelsTempMergeBuffer.Data;
ImBitArray<IMGUI_TABLE_MAX_DRAW_CHANNELS> remaining_mask; // We need 132-bit of storage
remaining_mask.SetBitRange(LEADING_DRAW_CHANNELS, splitter->_Count);
remaining_mask.ClearBit(table->Bg2DrawChannelUnfrozen);
IM_ASSERT(has_freeze_v == false || table->Bg2DrawChannelUnfrozen != TABLE_DRAW_CHANNEL_BG2_FROZEN);
int remaining_count = splitter->_Count - (has_freeze_v ? LEADING_DRAW_CHANNELS + 1 : LEADING_DRAW_CHANNELS);
//ImRect host_rect = (table->InnerWindow == table->OuterWindow) ? table->InnerClipRect : table->HostClipRect;
ImRect host_rect = table->HostClipRect;
for (int merge_group_n = 0; merge_group_n < IM_ARRAYSIZE(merge_groups); merge_group_n++)
{
if (int merge_channels_count = merge_groups[merge_group_n].ChannelsCount)
{
MergeGroup* merge_group = &merge_groups[merge_group_n];
ImRect merge_clip_rect = merge_group->ClipRect;
// Extend outer-most clip limits to match those of host, so draw calls can be merged even if
// outer-most columns have some outer padding offsetting them from their parent ClipRect.
// The principal cases this is dealing with are:
// - On a same-window table (not scrolling = single group), all fitting columns ClipRect -> will extend and match host ClipRect -> will merge
// - Columns can use padding and have left-most ClipRect.Min.x and right-most ClipRect.Max.x != from host ClipRect -> will extend and match host ClipRect -> will merge
// FIXME-TABLE FIXME-WORKRECT: We are wasting a merge opportunity on tables without scrolling if column doesn't fit
// within host clip rect, solely because of the half-padding difference between window->WorkRect and window->InnerClipRect.
if ((merge_group_n & 1) == 0 || !has_freeze_h)
merge_clip_rect.Min.x = ImMin(merge_clip_rect.Min.x, host_rect.Min.x);
if ((merge_group_n & 2) == 0 || !has_freeze_v)
merge_clip_rect.Min.y = ImMin(merge_clip_rect.Min.y, host_rect.Min.y);
if ((merge_group_n & 1) != 0)
merge_clip_rect.Max.x = ImMax(merge_clip_rect.Max.x, host_rect.Max.x);
if ((merge_group_n & 2) != 0 && (table->Flags & ImGuiTableFlags_NoHostExtendY) == 0)
merge_clip_rect.Max.y = ImMax(merge_clip_rect.Max.y, host_rect.Max.y);
#if 0
GetOverlayDrawList()->AddRect(merge_group->ClipRect.Min, merge_group->ClipRect.Max, IM_COL32(255, 0, 0, 200), 0.0f, 0, 1.0f);
GetOverlayDrawList()->AddLine(merge_group->ClipRect.Min, merge_clip_rect.Min, IM_COL32(255, 100, 0, 200));
GetOverlayDrawList()->AddLine(merge_group->ClipRect.Max, merge_clip_rect.Max, IM_COL32(255, 100, 0, 200));
#endif
remaining_count -= merge_group->ChannelsCount;
for (int n = 0; n < IM_ARRAYSIZE(remaining_mask.Storage); n++)
remaining_mask.Storage[n] &= ~merge_group->ChannelsMask.Storage[n];
for (int n = 0; n < splitter->_Count && merge_channels_count != 0; n++)
{
// Copy + overwrite new clip rect
if (!merge_group->ChannelsMask.TestBit(n))
continue;
merge_group->ChannelsMask.ClearBit(n);
merge_channels_count--;
ImDrawChannel* channel = &splitter->_Channels[n];
IM_ASSERT(channel->_CmdBuffer.Size == 1 && merge_clip_rect.Contains(ImRect(channel->_CmdBuffer[0].ClipRect)));
channel->_CmdBuffer[0].ClipRect = merge_clip_rect.ToVec4();
memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
}
}
// Make sure Bg2DrawChannelUnfrozen appears in the middle of our groups (whereas Bg0/Bg1 and Bg2 frozen are fixed to 0 and 1)
if (merge_group_n == 1 && has_freeze_v)
memcpy(dst_tmp++, &splitter->_Channels[table->Bg2DrawChannelUnfrozen], sizeof(ImDrawChannel));
}
// Append unmergeable channels that we didn't reorder at the end of the list
for (int n = 0; n < splitter->_Count && remaining_count != 0; n++)
{
if (!remaining_mask.TestBit(n))
continue;
ImDrawChannel* channel = &splitter->_Channels[n];
memcpy(dst_tmp++, channel, sizeof(ImDrawChannel));
remaining_count--;
}
IM_ASSERT(dst_tmp == g.DrawChannelsTempMergeBuffer.Data + g.DrawChannelsTempMergeBuffer.Size);
memcpy(splitter->_Channels.Data + LEADING_DRAW_CHANNELS, g.DrawChannelsTempMergeBuffer.Data, (splitter->_Count - LEADING_DRAW_CHANNELS) * sizeof(ImDrawChannel));
}
}
// FIXME-TABLE: This is a mess, need to redesign how we render borders (as some are also done in TableEndRow)
void ImGui::TableDrawBorders(ImGuiTable* table)
{
ImGuiWindow* inner_window = table->InnerWindow;
if (!table->OuterWindow->ClipRect.Overlaps(table->OuterRect))
return;
ImDrawList* inner_drawlist = inner_window->DrawList;
table->DrawSplitter->SetCurrentChannel(inner_drawlist, TABLE_DRAW_CHANNEL_BG0);
inner_drawlist->PushClipRect(table->Bg0ClipRectForDrawCmd.Min, table->Bg0ClipRectForDrawCmd.Max, false);
// Draw inner border and resizing feedback
const float border_size = TABLE_BORDER_SIZE;
const float draw_y1 = table->InnerRect.Min.y;
const float draw_y2_body = table->InnerRect.Max.y;
const float draw_y2_head = table->IsUsingHeaders ? ImMin(table->InnerRect.Max.y, (table->FreezeRowsCount >= 1 ? table->InnerRect.Min.y : table->WorkRect.Min.y) + table->LastFirstRowHeight) : draw_y1;
if (table->Flags & ImGuiTableFlags_BordersInnerV)
{
for (int order_n = 0; order_n < table->ColumnsCount; order_n++)
{
if (!(table->EnabledMaskByDisplayOrder & ((ImU64)1 << order_n)))
continue;
const int column_n = table->DisplayOrderToIndex[order_n];
ImGuiTableColumn* column = &table->Columns[column_n];
const bool is_hovered = (table->HoveredColumnBorder == column_n);
const bool is_resized = (table->ResizedColumn == column_n) && (table->InstanceInteracted == table->InstanceCurrent);
const bool is_resizable = (column->Flags & (ImGuiTableColumnFlags_NoResize | ImGuiTableColumnFlags_NoDirectResize_)) == 0;
const bool is_frozen_separator = (table->FreezeColumnsCount == order_n + 1);
if (column->MaxX > table->InnerClipRect.Max.x && !is_resized)
continue;
// Decide whether right-most column is visible
if (column->NextEnabledColumn == -1 && !is_resizable)
if ((table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame || (table->Flags & ImGuiTableFlags_NoHostExtendX))
continue;
if (column->MaxX <= column->ClipRect.Min.x) // FIXME-TABLE FIXME-STYLE: Assume BorderSize==1, this is problematic if we want to increase the border size..
continue;
// Draw in outer window so right-most column won't be clipped
// Always draw full height border when being resized/hovered, or on the delimitation of frozen column scrolling.
ImU32 col;
float draw_y2;
if (is_hovered || is_resized || is_frozen_separator)
{
draw_y2 = draw_y2_body;
col = is_resized ? GetColorU32(ImGuiCol_SeparatorActive) : is_hovered ? GetColorU32(ImGuiCol_SeparatorHovered) : table->BorderColorStrong;
}
else
{
draw_y2 = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? draw_y2_head : draw_y2_body;
col = (table->Flags & (ImGuiTableFlags_NoBordersInBody | ImGuiTableFlags_NoBordersInBodyUntilResize)) ? table->BorderColorStrong : table->BorderColorLight;
}
if (draw_y2 > draw_y1)
inner_drawlist->AddLine(ImVec2(column->MaxX, draw_y1), ImVec2(column->MaxX, draw_y2), col, border_size);
}
}
// Draw outer border
// FIXME: could use AddRect or explicit VLine/HLine helper?
if (table->Flags & ImGuiTableFlags_BordersOuter)
{
// Display outer border offset by 1 which is a simple way to display it without adding an extra draw call
// (Without the offset, in outer_window it would be rendered behind cells, because child windows are above their
// parent. In inner_window, it won't reach out over scrollbars. Another weird solution would be to display part
// of it in inner window, and the part that's over scrollbars in the outer window..)
// Either solution currently won't allow us to use a larger border size: the border would clipped.
const ImRect outer_border = table->OuterRect;
const ImU32 outer_col = table->BorderColorStrong;
if ((table->Flags & ImGuiTableFlags_BordersOuter) == ImGuiTableFlags_BordersOuter)
{
inner_drawlist->AddRect(outer_border.Min, outer_border.Max, outer_col, 0.0f, 0, border_size);
}
else if (table->Flags & ImGuiTableFlags_BordersOuterV)
{
inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Min.x, outer_border.Max.y), outer_col, border_size);
inner_drawlist->AddLine(ImVec2(outer_border.Max.x, outer_border.Min.y), outer_border.Max, outer_col, border_size);
}
else if (table->Flags & ImGuiTableFlags_BordersOuterH)
{
inner_drawlist->AddLine(outer_border.Min, ImVec2(outer_border.Max.x, outer_border.Min.y), outer_col, border_size);
inner_drawlist->AddLine(ImVec2(outer_border.Min.x, outer_border.Max.y), outer_border.Max, outer_col, border_size);
}
}
if ((table->Flags & ImGuiTableFlags_BordersInnerH) && table->RowPosY2 < table->OuterRect.Max.y)
{
// Draw bottom-most row border
const float border_y = table->RowPosY2;
if (border_y >= table->BgClipRect.Min.y && border_y < table->BgClipRect.Max.y)
inner_drawlist->AddLine(ImVec2(table->BorderX1, border_y), ImVec2(table->BorderX2, border_y), table->BorderColorLight, border_size);
}
inner_drawlist->PopClipRect();
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Sorting
//-------------------------------------------------------------------------
// - TableGetSortSpecs()
// - TableFixColumnSortDirection() [Internal]
// - TableGetColumnNextSortDirection() [Internal]
// - TableSetColumnSortDirection() [Internal]
// - TableSortSpecsSanitize() [Internal]
// - TableSortSpecsBuild() [Internal]
//-------------------------------------------------------------------------
// Return NULL if no sort specs (most often when ImGuiTableFlags_Sortable is not set)
// You can sort your data again when 'SpecsChanged == true'. It will be true with sorting specs have changed since
// last call, or the first time.
// Lifetime: don't hold on this pointer over multiple frames or past any subsequent call to BeginTable()!
ImGuiTableSortSpecs* ImGui::TableGetSortSpecs()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL);
if (!(table->Flags & ImGuiTableFlags_Sortable))
return NULL;
// Require layout (in case TableHeadersRow() hasn't been called) as it may alter IsSortSpecsDirty in some paths.
if (!table->IsLayoutLocked)
TableUpdateLayout(table);
TableSortSpecsBuild(table);
return &table->SortSpecs;
}
static inline ImGuiSortDirection TableGetColumnAvailSortDirection(ImGuiTableColumn* column, int n)
{
IM_ASSERT(n < column->SortDirectionsAvailCount);
return (column->SortDirectionsAvailList >> (n << 1)) & 0x03;
}
// Fix sort direction if currently set on a value which is unavailable (e.g. activating NoSortAscending/NoSortDescending)
void ImGui::TableFixColumnSortDirection(ImGuiTable* table, ImGuiTableColumn* column)
{
if (column->SortOrder == -1 || (column->SortDirectionsAvailMask & (1 << column->SortDirection)) != 0)
return;
column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
table->IsSortSpecsDirty = true;
}
// Calculate next sort direction that would be set after clicking the column
// - If the PreferSortDescending flag is set, we will default to a Descending direction on the first click.
// - Note that the PreferSortAscending flag is never checked, it is essentially the default and therefore a no-op.
IM_STATIC_ASSERT(ImGuiSortDirection_None == 0 && ImGuiSortDirection_Ascending == 1 && ImGuiSortDirection_Descending == 2);
ImGuiSortDirection ImGui::TableGetColumnNextSortDirection(ImGuiTableColumn* column)
{
IM_ASSERT(column->SortDirectionsAvailCount > 0);
if (column->SortOrder == -1)
return TableGetColumnAvailSortDirection(column, 0);
for (int n = 0; n < 3; n++)
if (column->SortDirection == TableGetColumnAvailSortDirection(column, n))
return TableGetColumnAvailSortDirection(column, (n + 1) % column->SortDirectionsAvailCount);
IM_ASSERT(0);
return ImGuiSortDirection_None;
}
// Note that the NoSortAscending/NoSortDescending flags are processed in TableSortSpecsSanitize(), and they may change/revert
// the value of SortDirection. We could technically also do it here but it would be unnecessary and duplicate code.
void ImGui::TableSetColumnSortDirection(int column_n, ImGuiSortDirection sort_direction, bool append_to_sort_specs)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (!(table->Flags & ImGuiTableFlags_SortMulti))
append_to_sort_specs = false;
if (!(table->Flags & ImGuiTableFlags_SortTristate))
IM_ASSERT(sort_direction != ImGuiSortDirection_None);
ImGuiTableColumnIdx sort_order_max = 0;
if (append_to_sort_specs)
for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
sort_order_max = ImMax(sort_order_max, table->Columns[other_column_n].SortOrder);
ImGuiTableColumn* column = &table->Columns[column_n];
column->SortDirection = (ImU8)sort_direction;
if (column->SortDirection == ImGuiSortDirection_None)
column->SortOrder = -1;
else if (column->SortOrder == -1 || !append_to_sort_specs)
column->SortOrder = append_to_sort_specs ? sort_order_max + 1 : 0;
for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
{
ImGuiTableColumn* other_column = &table->Columns[other_column_n];
if (other_column != column && !append_to_sort_specs)
other_column->SortOrder = -1;
TableFixColumnSortDirection(table, other_column);
}
table->IsSettingsDirty = true;
table->IsSortSpecsDirty = true;
}
void ImGui::TableSortSpecsSanitize(ImGuiTable* table)
{
IM_ASSERT(table->Flags & ImGuiTableFlags_Sortable);
// Clear SortOrder from hidden column and verify that there's no gap or duplicate.
int sort_order_count = 0;
ImU64 sort_order_mask = 0x00;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (column->SortOrder != -1 && !column->IsEnabled)
column->SortOrder = -1;
if (column->SortOrder == -1)
continue;
sort_order_count++;
sort_order_mask |= ((ImU64)1 << column->SortOrder);
IM_ASSERT(sort_order_count < (int)sizeof(sort_order_mask) * 8);
}
const bool need_fix_linearize = ((ImU64)1 << sort_order_count) != (sort_order_mask + 1);
const bool need_fix_single_sort_order = (sort_order_count > 1) && !(table->Flags & ImGuiTableFlags_SortMulti);
if (need_fix_linearize || need_fix_single_sort_order)
{
ImU64 fixed_mask = 0x00;
for (int sort_n = 0; sort_n < sort_order_count; sort_n++)
{
// Fix: Rewrite sort order fields if needed so they have no gap or duplicate.
// (e.g. SortOrder 0 disappeared, SortOrder 1..2 exists --> rewrite then as SortOrder 0..1)
int column_with_smallest_sort_order = -1;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
if ((fixed_mask & ((ImU64)1 << (ImU64)column_n)) == 0 && table->Columns[column_n].SortOrder != -1)
if (column_with_smallest_sort_order == -1 || table->Columns[column_n].SortOrder < table->Columns[column_with_smallest_sort_order].SortOrder)
column_with_smallest_sort_order = column_n;
IM_ASSERT(column_with_smallest_sort_order != -1);
fixed_mask |= ((ImU64)1 << column_with_smallest_sort_order);
table->Columns[column_with_smallest_sort_order].SortOrder = (ImGuiTableColumnIdx)sort_n;
// Fix: Make sure only one column has a SortOrder if ImGuiTableFlags_MultiSortable is not set.
if (need_fix_single_sort_order)
{
sort_order_count = 1;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
if (column_n != column_with_smallest_sort_order)
table->Columns[column_n].SortOrder = -1;
break;
}
}
}
// Fallback default sort order (if no column had the ImGuiTableColumnFlags_DefaultSort flag)
if (sort_order_count == 0 && !(table->Flags & ImGuiTableFlags_SortTristate))
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (column->IsEnabled && !(column->Flags & ImGuiTableColumnFlags_NoSort))
{
sort_order_count = 1;
column->SortOrder = 0;
column->SortDirection = (ImU8)TableGetColumnAvailSortDirection(column, 0);
break;
}
}
table->SortSpecsCount = (ImGuiTableColumnIdx)sort_order_count;
}
void ImGui::TableSortSpecsBuild(ImGuiTable* table)
{
bool dirty = table->IsSortSpecsDirty;
if (dirty)
{
TableSortSpecsSanitize(table);
table->SortSpecsMulti.resize(table->SortSpecsCount <= 1 ? 0 : table->SortSpecsCount);
table->SortSpecs.SpecsDirty = true; // Mark as dirty for user
table->IsSortSpecsDirty = false; // Mark as not dirty for us
}
// Write output
ImGuiTableColumnSortSpecs* sort_specs = (table->SortSpecsCount == 0) ? NULL : (table->SortSpecsCount == 1) ? &table->SortSpecsSingle : table->SortSpecsMulti.Data;
if (dirty && sort_specs != NULL)
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImGuiTableColumn* column = &table->Columns[column_n];
if (column->SortOrder == -1)
continue;
IM_ASSERT(column->SortOrder < table->SortSpecsCount);
ImGuiTableColumnSortSpecs* sort_spec = &sort_specs[column->SortOrder];
sort_spec->ColumnUserID = column->UserID;
sort_spec->ColumnIndex = (ImGuiTableColumnIdx)column_n;
sort_spec->SortOrder = (ImGuiTableColumnIdx)column->SortOrder;
sort_spec->SortDirection = column->SortDirection;
}
table->SortSpecs.Specs = sort_specs;
table->SortSpecs.SpecsCount = table->SortSpecsCount;
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Headers
//-------------------------------------------------------------------------
// - TableGetHeaderRowHeight() [Internal]
// - TableHeadersRow()
// - TableHeader()
//-------------------------------------------------------------------------
float ImGui::TableGetHeaderRowHeight()
{
// Caring for a minor edge case:
// Calculate row height, for the unlikely case that some labels may be taller than others.
// If we didn't do that, uneven header height would highlight but smaller one before the tallest wouldn't catch input for all height.
// In your custom header row you may omit this all together and just call TableNextRow() without a height...
float row_height = GetTextLineHeight();
int columns_count = TableGetColumnCount();
for (int column_n = 0; column_n < columns_count; column_n++)
{
ImGuiTableColumnFlags flags = TableGetColumnFlags(column_n);
if ((flags & ImGuiTableColumnFlags_IsEnabled) && !(flags & ImGuiTableColumnFlags_NoHeaderLabel))
row_height = ImMax(row_height, CalcTextSize(TableGetColumnName(column_n)).y);
}
row_height += GetStyle().CellPadding.y * 2.0f;
return row_height;
}
// [Public] This is a helper to output TableHeader() calls based on the column names declared in TableSetupColumn().
// The intent is that advanced users willing to create customized headers would not need to use this helper
// and can create their own! For example: TableHeader() may be preceeded by Checkbox() or other custom widgets.
// See 'Demo->Tables->Custom headers' for a demonstration of implementing a custom version of this.
// This code is constructed to not make much use of internal functions, as it is intended to be a template to copy.
// FIXME-TABLE: TableOpenContextMenu() and TableGetHeaderRowHeight() are not public.
void ImGui::TableHeadersRow()
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && "Need to call TableHeadersRow() after BeginTable()!");
// Layout if not already done (this is automatically done by TableNextRow, we do it here solely to facilitate stepping in debugger as it is frequent to step in TableUpdateLayout)
if (!table->IsLayoutLocked)
TableUpdateLayout(table);
// Open row
const float row_y1 = GetCursorScreenPos().y;
const float row_height = TableGetHeaderRowHeight();
TableNextRow(ImGuiTableRowFlags_Headers, row_height);
if (table->HostSkipItems) // Merely an optimization, you may skip in your own code.
return;
const int columns_count = TableGetColumnCount();
for (int column_n = 0; column_n < columns_count; column_n++)
{
if (!TableSetColumnIndex(column_n))
continue;
// Push an id to allow unnamed labels (generally accidental, but let's behave nicely with them)
// - in your own code you may omit the PushID/PopID all-together, provided you know they won't collide
// - table->InstanceCurrent is only >0 when we use multiple BeginTable/EndTable calls with same identifier.
const char* name = (TableGetColumnFlags(column_n) & ImGuiTableColumnFlags_NoHeaderLabel) ? "" : TableGetColumnName(column_n);
PushID(table->InstanceCurrent * table->ColumnsCount + column_n);
TableHeader(name);
PopID();
}
// Allow opening popup from the right-most section after the last column.
ImVec2 mouse_pos = ImGui::GetMousePos();
if (IsMouseReleased(1) && TableGetHoveredColumn() == columns_count)
if (mouse_pos.y >= row_y1 && mouse_pos.y < row_y1 + row_height)
TableOpenContextMenu(-1); // Will open a non-column-specific popup.
}
// Emit a column header (text + optional sort order)
// We cpu-clip text here so that all columns headers can be merged into a same draw call.
// Note that because of how we cpu-clip and display sorting indicators, you _cannot_ use SameLine() after a TableHeader()
void ImGui::TableHeader(const char* label)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
ImGuiTable* table = g.CurrentTable;
IM_ASSERT(table != NULL && "Need to call TableHeader() after BeginTable()!");
IM_ASSERT(table->CurrentColumn != -1);
const int column_n = table->CurrentColumn;
ImGuiTableColumn* column = &table->Columns[column_n];
// Label
if (label == NULL)
label = "";
const char* label_end = FindRenderedTextEnd(label);
ImVec2 label_size = CalcTextSize(label, label_end, true);
ImVec2 label_pos = window->DC.CursorPos;
// If we already got a row height, there's use that.
// FIXME-TABLE: Padding problem if the correct outer-padding CellBgRect strays off our ClipRect?
ImRect cell_r = TableGetCellBgRect(table, column_n);
float label_height = ImMax(label_size.y, table->RowMinHeight - table->CellPaddingY * 2.0f);
// Calculate ideal size for sort order arrow
float w_arrow = 0.0f;
float w_sort_text = 0.0f;
char sort_order_suf[4] = "";
const float ARROW_SCALE = 0.65f;
if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
{
w_arrow = ImFloor(g.FontSize * ARROW_SCALE + g.Style.FramePadding.x);
if (column->SortOrder > 0)
{
ImFormatString(sort_order_suf, IM_ARRAYSIZE(sort_order_suf), "%d", column->SortOrder + 1);
w_sort_text = g.Style.ItemInnerSpacing.x + CalcTextSize(sort_order_suf).x;
}
}
// We feed our unclipped width to the column without writing on CursorMaxPos, so that column is still considering for merging.
float max_pos_x = label_pos.x + label_size.x + w_sort_text + w_arrow;
column->ContentMaxXHeadersUsed = ImMax(column->ContentMaxXHeadersUsed, column->WorkMaxX);
column->ContentMaxXHeadersIdeal = ImMax(column->ContentMaxXHeadersIdeal, max_pos_x);
// Keep header highlighted when context menu is open.
const bool selected = (table->IsContextPopupOpen && table->ContextPopupColumn == column_n && table->InstanceInteracted == table->InstanceCurrent);
ImGuiID id = window->GetID(label);
ImRect bb(cell_r.Min.x, cell_r.Min.y, cell_r.Max.x, ImMax(cell_r.Max.y, cell_r.Min.y + label_height + g.Style.CellPadding.y * 2.0f));
ItemSize(ImVec2(0.0f, label_height)); // Don't declare unclipped width, it'll be fed ContentMaxPosHeadersIdeal
if (!ItemAdd(bb, id))
return;
//GetForegroundDrawList()->AddRect(cell_r.Min, cell_r.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
//GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 0, 0, 255)); // [DEBUG]
// Using AllowItemOverlap mode because we cover the whole cell, and we want user to be able to submit subsequent items.
bool hovered, held;
bool pressed = ButtonBehavior(bb, id, &hovered, &held, ImGuiButtonFlags_AllowItemOverlap);
if (g.ActiveId != id)
SetItemAllowOverlap();
if (held || hovered || selected)
{
const ImU32 col = GetColorU32(held ? ImGuiCol_HeaderActive : hovered ? ImGuiCol_HeaderHovered : ImGuiCol_Header);
//RenderFrame(bb.Min, bb.Max, col, false, 0.0f);
TableSetBgColor(ImGuiTableBgTarget_CellBg, col, table->CurrentColumn);
}
else
{
// Submit single cell bg color in the case we didn't submit a full header row
if ((table->RowFlags & ImGuiTableRowFlags_Headers) == 0)
TableSetBgColor(ImGuiTableBgTarget_CellBg, GetColorU32(ImGuiCol_TableHeaderBg), table->CurrentColumn);
}
RenderNavHighlight(bb, id, ImGuiNavHighlightFlags_TypeThin | ImGuiNavHighlightFlags_NoRounding);
if (held)
table->HeldHeaderColumn = (ImGuiTableColumnIdx)column_n;
window->DC.CursorPos.y -= g.Style.ItemSpacing.y * 0.5f;
// Drag and drop to re-order columns.
// FIXME-TABLE: Scroll request while reordering a column and it lands out of the scrolling zone.
if (held && (table->Flags & ImGuiTableFlags_Reorderable) && IsMouseDragging(0) && !g.DragDropActive)
{
// While moving a column it will jump on the other side of the mouse, so we also test for MouseDelta.x
table->ReorderColumn = (ImGuiTableColumnIdx)column_n;
table->InstanceInteracted = table->InstanceCurrent;
// We don't reorder: through the frozen<>unfrozen line, or through a column that is marked with ImGuiTableColumnFlags_NoReorder.
if (g.IO.MouseDelta.x < 0.0f && g.IO.MousePos.x < cell_r.Min.x)
if (ImGuiTableColumn* prev_column = (column->PrevEnabledColumn != -1) ? &table->Columns[column->PrevEnabledColumn] : NULL)
if (!((column->Flags | prev_column->Flags) & ImGuiTableColumnFlags_NoReorder))
if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (prev_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))
table->ReorderColumnDir = -1;
if (g.IO.MouseDelta.x > 0.0f && g.IO.MousePos.x > cell_r.Max.x)
if (ImGuiTableColumn* next_column = (column->NextEnabledColumn != -1) ? &table->Columns[column->NextEnabledColumn] : NULL)
if (!((column->Flags | next_column->Flags) & ImGuiTableColumnFlags_NoReorder))
if ((column->IndexWithinEnabledSet < table->FreezeColumnsRequest) == (next_column->IndexWithinEnabledSet < table->FreezeColumnsRequest))
table->ReorderColumnDir = +1;
}
// Sort order arrow
const float ellipsis_max = cell_r.Max.x - w_arrow - w_sort_text;
if ((table->Flags & ImGuiTableFlags_Sortable) && !(column->Flags & ImGuiTableColumnFlags_NoSort))
{
if (column->SortOrder != -1)
{
float x = ImMax(cell_r.Min.x, cell_r.Max.x - w_arrow - w_sort_text);
float y = label_pos.y;
if (column->SortOrder > 0)
{
PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_Text, 0.70f));
RenderText(ImVec2(x + g.Style.ItemInnerSpacing.x, y), sort_order_suf);
PopStyleColor();
x += w_sort_text;
}
RenderArrow(window->DrawList, ImVec2(x, y), GetColorU32(ImGuiCol_Text), column->SortDirection == ImGuiSortDirection_Ascending ? ImGuiDir_Up : ImGuiDir_Down, ARROW_SCALE);
}
// Handle clicking on column header to adjust Sort Order
if (pressed && table->ReorderColumn != column_n)
{
ImGuiSortDirection sort_direction = TableGetColumnNextSortDirection(column);
TableSetColumnSortDirection(column_n, sort_direction, g.IO.KeyShift);
}
}
// Render clipped label. Clipping here ensure that in the majority of situations, all our header cells will
// be merged into a single draw call.
//window->DrawList->AddCircleFilled(ImVec2(ellipsis_max, label_pos.y), 40, IM_COL32_WHITE);
RenderTextEllipsis(window->DrawList, label_pos, ImVec2(ellipsis_max, label_pos.y + label_height + g.Style.FramePadding.y), ellipsis_max, ellipsis_max, label, label_end, &label_size);
const bool text_clipped = label_size.x > (ellipsis_max - label_pos.x);
if (text_clipped && hovered && g.HoveredIdNotActiveTimer > g.TooltipSlowDelay)
SetTooltip("%.*s", (int)(label_end - label), label);
// We don't use BeginPopupContextItem() because we want the popup to stay up even after the column is hidden
if (IsMouseReleased(1) && IsItemHovered())
TableOpenContextMenu(column_n);
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Context Menu
//-------------------------------------------------------------------------
// - TableOpenContextMenu() [Internal]
// - TableDrawContextMenu() [Internal]
//-------------------------------------------------------------------------
// Use -1 to open menu not specific to a given column.
void ImGui::TableOpenContextMenu(int column_n)
{
ImGuiContext& g = *GImGui;
ImGuiTable* table = g.CurrentTable;
if (column_n == -1 && table->CurrentColumn != -1) // When called within a column automatically use this one (for consistency)
column_n = table->CurrentColumn;
if (column_n == table->ColumnsCount) // To facilitate using with TableGetHoveredColumn()
column_n = -1;
IM_ASSERT(column_n >= -1 && column_n < table->ColumnsCount);
if (table->Flags & (ImGuiTableFlags_Resizable | ImGuiTableFlags_Reorderable | ImGuiTableFlags_Hideable))
{
table->IsContextPopupOpen = true;
table->ContextPopupColumn = (ImGuiTableColumnIdx)column_n;
table->InstanceInteracted = table->InstanceCurrent;
const ImGuiID context_menu_id = ImHashStr("##ContextMenu", 0, table->ID);
OpenPopupEx(context_menu_id, ImGuiPopupFlags_None);
}
}
// Output context menu into current window (generally a popup)
// FIXME-TABLE: Ideally this should be writable by the user. Full programmatic access to that data?
void ImGui::TableDrawContextMenu(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
bool want_separator = false;
const int column_n = (table->ContextPopupColumn >= 0 && table->ContextPopupColumn < table->ColumnsCount) ? table->ContextPopupColumn : -1;
ImGuiTableColumn* column = (column_n != -1) ? &table->Columns[column_n] : NULL;
// Sizing
if (table->Flags & ImGuiTableFlags_Resizable)
{
if (column != NULL)
{
const bool can_resize = !(column->Flags & ImGuiTableColumnFlags_NoResize) && column->IsEnabled;
if (MenuItem("Size column to fit###SizeOne", NULL, false, can_resize))
TableSetColumnWidthAutoSingle(table, column_n);
}
const char* size_all_desc;
if (table->ColumnsEnabledFixedCount == table->ColumnsEnabledCount && (table->Flags & ImGuiTableFlags_SizingMask_) != ImGuiTableFlags_SizingFixedSame)
size_all_desc = "Size all columns to fit###SizeAll"; // All fixed
else
size_all_desc = "Size all columns to default###SizeAll"; // All stretch or mixed
if (MenuItem(size_all_desc, NULL))
TableSetColumnWidthAutoAll(table);
want_separator = true;
}
// Ordering
if (table->Flags & ImGuiTableFlags_Reorderable)
{
if (MenuItem("Reset order", NULL, false, !table->IsDefaultDisplayOrder))
table->IsResetDisplayOrderRequest = true;
want_separator = true;
}
// Reset all (should work but seems unnecessary/noisy to expose?)
//if (MenuItem("Reset all"))
// table->IsResetAllRequest = true;
// Sorting
// (modify TableOpenContextMenu() to add _Sortable flag if enabling this)
#if 0
if ((table->Flags & ImGuiTableFlags_Sortable) && column != NULL && (column->Flags & ImGuiTableColumnFlags_NoSort) == 0)
{
if (want_separator)
Separator();
want_separator = true;
bool append_to_sort_specs = g.IO.KeyShift;
if (MenuItem("Sort in Ascending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Ascending, (column->Flags & ImGuiTableColumnFlags_NoSortAscending) == 0))
TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Ascending, append_to_sort_specs);
if (MenuItem("Sort in Descending Order", NULL, column->SortOrder != -1 && column->SortDirection == ImGuiSortDirection_Descending, (column->Flags & ImGuiTableColumnFlags_NoSortDescending) == 0))
TableSetColumnSortDirection(table, column_n, ImGuiSortDirection_Descending, append_to_sort_specs);
}
#endif
// Hiding / Visibility
if (table->Flags & ImGuiTableFlags_Hideable)
{
if (want_separator)
Separator();
want_separator = true;
PushItemFlag(ImGuiItemFlags_SelectableDontClosePopup, true);
for (int other_column_n = 0; other_column_n < table->ColumnsCount; other_column_n++)
{
ImGuiTableColumn* other_column = &table->Columns[other_column_n];
if (other_column->Flags & ImGuiTableColumnFlags_Disabled)
continue;
const char* name = TableGetColumnName(table, other_column_n);
if (name == NULL || name[0] == 0)
name = "<Unknown>";
// Make sure we can't hide the last active column
bool menu_item_active = (other_column->Flags & ImGuiTableColumnFlags_NoHide) ? false : true;
if (other_column->IsUserEnabled && table->ColumnsEnabledCount <= 1)
menu_item_active = false;
if (MenuItem(name, NULL, other_column->IsUserEnabled, menu_item_active))
other_column->IsUserEnabledNextFrame = !other_column->IsUserEnabled;
}
PopItemFlag();
}
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Settings (.ini data)
//-------------------------------------------------------------------------
// FIXME: The binding/finding/creating flow are too confusing.
//-------------------------------------------------------------------------
// - TableSettingsInit() [Internal]
// - TableSettingsCalcChunkSize() [Internal]
// - TableSettingsCreate() [Internal]
// - TableSettingsFindByID() [Internal]
// - TableGetBoundSettings() [Internal]
// - TableResetSettings()
// - TableSaveSettings() [Internal]
// - TableLoadSettings() [Internal]
// - TableSettingsHandler_ClearAll() [Internal]
// - TableSettingsHandler_ApplyAll() [Internal]
// - TableSettingsHandler_ReadOpen() [Internal]
// - TableSettingsHandler_ReadLine() [Internal]
// - TableSettingsHandler_WriteAll() [Internal]
// - TableSettingsInstallHandler() [Internal]
//-------------------------------------------------------------------------
// [Init] 1: TableSettingsHandler_ReadXXXX() Load and parse .ini file into TableSettings.
// [Main] 2: TableLoadSettings() When table is created, bind Table to TableSettings, serialize TableSettings data into Table.
// [Main] 3: TableSaveSettings() When table properties are modified, serialize Table data into bound or new TableSettings, mark .ini as dirty.
// [Main] 4: TableSettingsHandler_WriteAll() When .ini file is dirty (which can come from other source), save TableSettings into .ini file.
//-------------------------------------------------------------------------
// Clear and initialize empty settings instance
static void TableSettingsInit(ImGuiTableSettings* settings, ImGuiID id, int columns_count, int columns_count_max)
{
IM_PLACEMENT_NEW(settings) ImGuiTableSettings();
ImGuiTableColumnSettings* settings_column = settings->GetColumnSettings();
for (int n = 0; n < columns_count_max; n++, settings_column++)
IM_PLACEMENT_NEW(settings_column) ImGuiTableColumnSettings();
settings->ID = id;
settings->ColumnsCount = (ImGuiTableColumnIdx)columns_count;
settings->ColumnsCountMax = (ImGuiTableColumnIdx)columns_count_max;
settings->WantApply = true;
}
static size_t TableSettingsCalcChunkSize(int columns_count)
{
return sizeof(ImGuiTableSettings) + (size_t)columns_count * sizeof(ImGuiTableColumnSettings);
}
ImGuiTableSettings* ImGui::TableSettingsCreate(ImGuiID id, int columns_count)
{
ImGuiContext& g = *GImGui;
ImGuiTableSettings* settings = g.SettingsTables.alloc_chunk(TableSettingsCalcChunkSize(columns_count));
TableSettingsInit(settings, id, columns_count, columns_count);
return settings;
}
// Find existing settings
ImGuiTableSettings* ImGui::TableSettingsFindByID(ImGuiID id)
{
// FIXME-OPT: Might want to store a lookup map for this?
ImGuiContext& g = *GImGui;
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
if (settings->ID == id)
return settings;
return NULL;
}
// Get settings for a given table, NULL if none
ImGuiTableSettings* ImGui::TableGetBoundSettings(ImGuiTable* table)
{
if (table->SettingsOffset != -1)
{
ImGuiContext& g = *GImGui;
ImGuiTableSettings* settings = g.SettingsTables.ptr_from_offset(table->SettingsOffset);
IM_ASSERT(settings->ID == table->ID);
if (settings->ColumnsCountMax >= table->ColumnsCount)
return settings; // OK
settings->ID = 0; // Invalidate storage, we won't fit because of a count change
}
return NULL;
}
// Restore initial state of table (with or without saved settings)
void ImGui::TableResetSettings(ImGuiTable* table)
{
table->IsInitializing = table->IsSettingsDirty = true;
table->IsResetAllRequest = false;
table->IsSettingsRequestLoad = false; // Don't reload from ini
table->SettingsLoadedFlags = ImGuiTableFlags_None; // Mark as nothing loaded so our initialized data becomes authoritative
}
void ImGui::TableSaveSettings(ImGuiTable* table)
{
table->IsSettingsDirty = false;
if (table->Flags & ImGuiTableFlags_NoSavedSettings)
return;
// Bind or create settings data
ImGuiContext& g = *GImGui;
ImGuiTableSettings* settings = TableGetBoundSettings(table);
if (settings == NULL)
{
settings = TableSettingsCreate(table->ID, table->ColumnsCount);
table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
}
settings->ColumnsCount = (ImGuiTableColumnIdx)table->ColumnsCount;
// Serialize ImGuiTable/ImGuiTableColumn into ImGuiTableSettings/ImGuiTableColumnSettings
IM_ASSERT(settings->ID == table->ID);
IM_ASSERT(settings->ColumnsCount == table->ColumnsCount && settings->ColumnsCountMax >= settings->ColumnsCount);
ImGuiTableColumn* column = table->Columns.Data;
ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
bool save_ref_scale = false;
settings->SaveFlags = ImGuiTableFlags_None;
for (int n = 0; n < table->ColumnsCount; n++, column++, column_settings++)
{
const float width_or_weight = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? column->StretchWeight : column->WidthRequest;
column_settings->WidthOrWeight = width_or_weight;
column_settings->Index = (ImGuiTableColumnIdx)n;
column_settings->DisplayOrder = column->DisplayOrder;
column_settings->SortOrder = column->SortOrder;
column_settings->SortDirection = column->SortDirection;
column_settings->IsEnabled = column->IsUserEnabled;
column_settings->IsStretch = (column->Flags & ImGuiTableColumnFlags_WidthStretch) ? 1 : 0;
if ((column->Flags & ImGuiTableColumnFlags_WidthStretch) == 0)
save_ref_scale = true;
// We skip saving some data in the .ini file when they are unnecessary to restore our state.
// Note that fixed width where initial width was derived from auto-fit will always be saved as InitStretchWeightOrWidth will be 0.0f.
// FIXME-TABLE: We don't have logic to easily compare SortOrder to DefaultSortOrder yet so it's always saved when present.
if (width_or_weight != column->InitStretchWeightOrWidth)
settings->SaveFlags |= ImGuiTableFlags_Resizable;
if (column->DisplayOrder != n)
settings->SaveFlags |= ImGuiTableFlags_Reorderable;
if (column->SortOrder != -1)
settings->SaveFlags |= ImGuiTableFlags_Sortable;
if (column->IsUserEnabled != ((column->Flags & ImGuiTableColumnFlags_DefaultHide) == 0))
settings->SaveFlags |= ImGuiTableFlags_Hideable;
}
settings->SaveFlags &= table->Flags;
settings->RefScale = save_ref_scale ? table->RefScale : 0.0f;
MarkIniSettingsDirty();
}
void ImGui::TableLoadSettings(ImGuiTable* table)
{
ImGuiContext& g = *GImGui;
table->IsSettingsRequestLoad = false;
if (table->Flags & ImGuiTableFlags_NoSavedSettings)
return;
// Bind settings
ImGuiTableSettings* settings;
if (table->SettingsOffset == -1)
{
settings = TableSettingsFindByID(table->ID);
if (settings == NULL)
return;
if (settings->ColumnsCount != table->ColumnsCount) // Allow settings if columns count changed. We could otherwise decide to return...
table->IsSettingsDirty = true;
table->SettingsOffset = g.SettingsTables.offset_from_ptr(settings);
}
else
{
settings = TableGetBoundSettings(table);
}
table->SettingsLoadedFlags = settings->SaveFlags;
table->RefScale = settings->RefScale;
// Serialize ImGuiTableSettings/ImGuiTableColumnSettings into ImGuiTable/ImGuiTableColumn
ImGuiTableColumnSettings* column_settings = settings->GetColumnSettings();
ImU64 display_order_mask = 0;
for (int data_n = 0; data_n < settings->ColumnsCount; data_n++, column_settings++)
{
int column_n = column_settings->Index;
if (column_n < 0 || column_n >= table->ColumnsCount)
continue;
ImGuiTableColumn* column = &table->Columns[column_n];
if (settings->SaveFlags & ImGuiTableFlags_Resizable)
{
if (column_settings->IsStretch)
column->StretchWeight = column_settings->WidthOrWeight;
else
column->WidthRequest = column_settings->WidthOrWeight;
column->AutoFitQueue = 0x00;
}
if (settings->SaveFlags & ImGuiTableFlags_Reorderable)
column->DisplayOrder = column_settings->DisplayOrder;
else
column->DisplayOrder = (ImGuiTableColumnIdx)column_n;
display_order_mask |= (ImU64)1 << column->DisplayOrder;
column->IsUserEnabled = column->IsUserEnabledNextFrame = column_settings->IsEnabled;
column->SortOrder = column_settings->SortOrder;
column->SortDirection = column_settings->SortDirection;
}
// Validate and fix invalid display order data
const ImU64 expected_display_order_mask = (settings->ColumnsCount == 64) ? ~0 : ((ImU64)1 << settings->ColumnsCount) - 1;
if (display_order_mask != expected_display_order_mask)
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
table->Columns[column_n].DisplayOrder = (ImGuiTableColumnIdx)column_n;
// Rebuild index
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
table->DisplayOrderToIndex[table->Columns[column_n].DisplayOrder] = (ImGuiTableColumnIdx)column_n;
}
static void TableSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Tables.GetMapSize(); i++)
if (ImGuiTable* table = g.Tables.TryGetMapData(i))
table->SettingsOffset = -1;
g.SettingsTables.clear();
}
// Apply to existing windows (if any)
static void TableSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Tables.GetMapSize(); i++)
if (ImGuiTable* table = g.Tables.TryGetMapData(i))
{
table->IsSettingsRequestLoad = true;
table->SettingsOffset = -1;
}
}
static void* TableSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiID id = 0;
int columns_count = 0;
if (sscanf(name, "0x%08X,%d", &id, &columns_count) < 2)
return NULL;
if (ImGuiTableSettings* settings = ImGui::TableSettingsFindByID(id))
{
if (settings->ColumnsCountMax >= columns_count)
{
TableSettingsInit(settings, id, columns_count, settings->ColumnsCountMax); // Recycle
return settings;
}
settings->ID = 0; // Invalidate storage, we won't fit because of a count change
}
return ImGui::TableSettingsCreate(id, columns_count);
}
static void TableSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
// "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
ImGuiTableSettings* settings = (ImGuiTableSettings*)entry;
float f = 0.0f;
int column_n = 0, r = 0, n = 0;
if (sscanf(line, "RefScale=%f", &f) == 1) { settings->RefScale = f; return; }
if (sscanf(line, "Column %d%n", &column_n, &r) == 1)
{
if (column_n < 0 || column_n >= settings->ColumnsCount)
return;
line = ImStrSkipBlank(line + r);
char c = 0;
ImGuiTableColumnSettings* column = settings->GetColumnSettings() + column_n;
column->Index = (ImGuiTableColumnIdx)column_n;
if (sscanf(line, "UserID=0x%08X%n", (ImU32*)&n, &r)==1) { line = ImStrSkipBlank(line + r); column->UserID = (ImGuiID)n; }
if (sscanf(line, "Width=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = (float)n; column->IsStretch = 0; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
if (sscanf(line, "Weight=%f%n", &f, &r) == 1) { line = ImStrSkipBlank(line + r); column->WidthOrWeight = f; column->IsStretch = 1; settings->SaveFlags |= ImGuiTableFlags_Resizable; }
if (sscanf(line, "Visible=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->IsEnabled = (ImU8)n; settings->SaveFlags |= ImGuiTableFlags_Hideable; }
if (sscanf(line, "Order=%d%n", &n, &r) == 1) { line = ImStrSkipBlank(line + r); column->DisplayOrder = (ImGuiTableColumnIdx)n; settings->SaveFlags |= ImGuiTableFlags_Reorderable; }
if (sscanf(line, "Sort=%d%c%n", &n, &c, &r) == 2) { line = ImStrSkipBlank(line + r); column->SortOrder = (ImGuiTableColumnIdx)n; column->SortDirection = (c == '^') ? ImGuiSortDirection_Descending : ImGuiSortDirection_Ascending; settings->SaveFlags |= ImGuiTableFlags_Sortable; }
}
}
static void TableSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
ImGuiContext& g = *ctx;
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
{
if (settings->ID == 0) // Skip ditched settings
continue;
// TableSaveSettings() may clear some of those flags when we establish that the data can be stripped
// (e.g. Order was unchanged)
const bool save_size = (settings->SaveFlags & ImGuiTableFlags_Resizable) != 0;
const bool save_visible = (settings->SaveFlags & ImGuiTableFlags_Hideable) != 0;
const bool save_order = (settings->SaveFlags & ImGuiTableFlags_Reorderable) != 0;
const bool save_sort = (settings->SaveFlags & ImGuiTableFlags_Sortable) != 0;
if (!save_size && !save_visible && !save_order && !save_sort)
continue;
buf->reserve(buf->size() + 30 + settings->ColumnsCount * 50); // ballpark reserve
buf->appendf("[%s][0x%08X,%d]\n", handler->TypeName, settings->ID, settings->ColumnsCount);
if (settings->RefScale != 0.0f)
buf->appendf("RefScale=%g\n", settings->RefScale);
ImGuiTableColumnSettings* column = settings->GetColumnSettings();
for (int column_n = 0; column_n < settings->ColumnsCount; column_n++, column++)
{
// "Column 0 UserID=0x42AD2D21 Width=100 Visible=1 Order=0 Sort=0v"
bool save_column = column->UserID != 0 || save_size || save_visible || save_order || (save_sort && column->SortOrder != -1);
if (!save_column)
continue;
buf->appendf("Column %-2d", column_n);
if (column->UserID != 0) buf->appendf(" UserID=%08X", column->UserID);
if (save_size && column->IsStretch) buf->appendf(" Weight=%.4f", column->WidthOrWeight);
if (save_size && !column->IsStretch) buf->appendf(" Width=%d", (int)column->WidthOrWeight);
if (save_visible) buf->appendf(" Visible=%d", column->IsEnabled);
if (save_order) buf->appendf(" Order=%d", column->DisplayOrder);
if (save_sort && column->SortOrder != -1) buf->appendf(" Sort=%d%c", column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? 'v' : '^');
buf->append("\n");
}
buf->append("\n");
}
}
void ImGui::TableSettingsInstallHandler(ImGuiContext* context)
{
ImGuiContext& g = *context;
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Table";
ini_handler.TypeHash = ImHashStr("Table");
ini_handler.ClearAllFn = TableSettingsHandler_ClearAll;
ini_handler.ReadOpenFn = TableSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = TableSettingsHandler_ReadLine;
ini_handler.ApplyAllFn = TableSettingsHandler_ApplyAll;
ini_handler.WriteAllFn = TableSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Garbage Collection
//-------------------------------------------------------------------------
// - TableRemove() [Internal]
// - TableGcCompactTransientBuffers() [Internal]
// - TableGcCompactSettings() [Internal]
//-------------------------------------------------------------------------
// Remove Table (currently only used by TestEngine)
void ImGui::TableRemove(ImGuiTable* table)
{
//IMGUI_DEBUG_LOG("TableRemove() id=0x%08X\n", table->ID);
ImGuiContext& g = *GImGui;
int table_idx = g.Tables.GetIndex(table);
//memset(table->RawData.Data, 0, table->RawData.size_in_bytes());
//memset(table, 0, sizeof(ImGuiTable));
g.Tables.Remove(table->ID, table);
g.TablesLastTimeActive[table_idx] = -1.0f;
}
// Free up/compact internal Table buffers for when it gets unused
void ImGui::TableGcCompactTransientBuffers(ImGuiTable* table)
{
//IMGUI_DEBUG_LOG("TableGcCompactTransientBuffers() id=0x%08X\n", table->ID);
ImGuiContext& g = *GImGui;
IM_ASSERT(table->MemoryCompacted == false);
table->SortSpecs.Specs = NULL;
table->SortSpecsMulti.clear();
table->IsSortSpecsDirty = true; // FIXME: shouldn't have to leak into user performing a sort
table->ColumnsNames.clear();
table->MemoryCompacted = true;
for (int n = 0; n < table->ColumnsCount; n++)
table->Columns[n].NameOffset = -1;
g.TablesLastTimeActive[g.Tables.GetIndex(table)] = -1.0f;
}
void ImGui::TableGcCompactTransientBuffers(ImGuiTableTempData* temp_data)
{
temp_data->DrawSplitter.ClearFreeMemory();
temp_data->LastTimeActive = -1.0f;
}
// Compact and remove unused settings data (currently only used by TestEngine)
void ImGui::TableGcCompactSettings()
{
ImGuiContext& g = *GImGui;
int required_memory = 0;
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
if (settings->ID != 0)
required_memory += (int)TableSettingsCalcChunkSize(settings->ColumnsCount);
if (required_memory == g.SettingsTables.Buf.Size)
return;
ImChunkStream<ImGuiTableSettings> new_chunk_stream;
new_chunk_stream.Buf.reserve(required_memory);
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
if (settings->ID != 0)
memcpy(new_chunk_stream.alloc_chunk(TableSettingsCalcChunkSize(settings->ColumnsCount)), settings, TableSettingsCalcChunkSize(settings->ColumnsCount));
g.SettingsTables.swap(new_chunk_stream);
}
//-------------------------------------------------------------------------
// [SECTION] Tables: Debugging
//-------------------------------------------------------------------------
// - DebugNodeTable() [Internal]
//-------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
static const char* DebugNodeTableGetSizingPolicyDesc(ImGuiTableFlags sizing_policy)
{
sizing_policy &= ImGuiTableFlags_SizingMask_;
if (sizing_policy == ImGuiTableFlags_SizingFixedFit) { return "FixedFit"; }
if (sizing_policy == ImGuiTableFlags_SizingFixedSame) { return "FixedSame"; }
if (sizing_policy == ImGuiTableFlags_SizingStretchProp) { return "StretchProp"; }
if (sizing_policy == ImGuiTableFlags_SizingStretchSame) { return "StretchSame"; }
return "N/A";
}
void ImGui::DebugNodeTable(ImGuiTable* table)
{
char buf[512];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
const bool is_active = (table->LastFrameActive >= ImGui::GetFrameCount() - 2); // Note that fully clipped early out scrolling tables will appear as inactive here.
ImFormatString(p, buf_end - p, "Table 0x%08X (%d columns, in '%s')%s", table->ID, table->ColumnsCount, table->OuterWindow->Name, is_active ? "" : " *Inactive*");
if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
bool open = TreeNode(table, "%s", buf);
if (!is_active) { PopStyleColor(); }
if (IsItemHovered())
GetForegroundDrawList()->AddRect(table->OuterRect.Min, table->OuterRect.Max, IM_COL32(255, 255, 0, 255));
if (IsItemVisible() && table->HoveredColumnBody != -1)
GetForegroundDrawList()->AddRect(GetItemRectMin(), GetItemRectMax(), IM_COL32(255, 255, 0, 255));
if (!open)
return;
bool clear_settings = SmallButton("Clear settings");
BulletText("OuterRect: Pos: (%.1f,%.1f) Size: (%.1f,%.1f) Sizing: '%s'", table->OuterRect.Min.x, table->OuterRect.Min.y, table->OuterRect.GetWidth(), table->OuterRect.GetHeight(), DebugNodeTableGetSizingPolicyDesc(table->Flags));
BulletText("ColumnsGivenWidth: %.1f, ColumnsAutoFitWidth: %.1f, InnerWidth: %.1f%s", table->ColumnsGivenWidth, table->ColumnsAutoFitWidth, table->InnerWidth, table->InnerWidth == 0.0f ? " (auto)" : "");
BulletText("CellPaddingX: %.1f, CellSpacingX: %.1f/%.1f, OuterPaddingX: %.1f", table->CellPaddingX, table->CellSpacingX1, table->CellSpacingX2, table->OuterPaddingX);
BulletText("HoveredColumnBody: %d, HoveredColumnBorder: %d", table->HoveredColumnBody, table->HoveredColumnBorder);
BulletText("ResizedColumn: %d, ReorderColumn: %d, HeldHeaderColumn: %d", table->ResizedColumn, table->ReorderColumn, table->HeldHeaderColumn);
//BulletText("BgDrawChannels: %d/%d", 0, table->BgDrawChannelUnfrozen);
float sum_weights = 0.0f;
for (int n = 0; n < table->ColumnsCount; n++)
if (table->Columns[n].Flags & ImGuiTableColumnFlags_WidthStretch)
sum_weights += table->Columns[n].StretchWeight;
for (int n = 0; n < table->ColumnsCount; n++)
{
ImGuiTableColumn* column = &table->Columns[n];
const char* name = TableGetColumnName(table, n);
ImFormatString(buf, IM_ARRAYSIZE(buf),
"Column %d order %d '%s': offset %+.2f to %+.2f%s\n"
"Enabled: %d, VisibleX/Y: %d/%d, RequestOutput: %d, SkipItems: %d, DrawChannels: %d,%d\n"
"WidthGiven: %.1f, Request/Auto: %.1f/%.1f, StretchWeight: %.3f (%.1f%%)\n"
"MinX: %.1f, MaxX: %.1f (%+.1f), ClipRect: %.1f to %.1f (+%.1f)\n"
"ContentWidth: %.1f,%.1f, HeadersUsed/Ideal %.1f/%.1f\n"
"Sort: %d%s, UserID: 0x%08X, Flags: 0x%04X: %s%s%s..",
n, column->DisplayOrder, name, column->MinX - table->WorkRect.Min.x, column->MaxX - table->WorkRect.Min.x, (n < table->FreezeColumnsRequest) ? " (Frozen)" : "",
column->IsEnabled, column->IsVisibleX, column->IsVisibleY, column->IsRequestOutput, column->IsSkipItems, column->DrawChannelFrozen, column->DrawChannelUnfrozen,
column->WidthGiven, column->WidthRequest, column->WidthAuto, column->StretchWeight, column->StretchWeight > 0.0f ? (column->StretchWeight / sum_weights) * 100.0f : 0.0f,
column->MinX, column->MaxX, column->MaxX - column->MinX, column->ClipRect.Min.x, column->ClipRect.Max.x, column->ClipRect.Max.x - column->ClipRect.Min.x,
column->ContentMaxXFrozen - column->WorkMinX, column->ContentMaxXUnfrozen - column->WorkMinX, column->ContentMaxXHeadersUsed - column->WorkMinX, column->ContentMaxXHeadersIdeal - column->WorkMinX,
column->SortOrder, (column->SortDirection == ImGuiSortDirection_Ascending) ? " (Asc)" : (column->SortDirection == ImGuiSortDirection_Descending) ? " (Des)" : "", column->UserID, column->Flags,
(column->Flags & ImGuiTableColumnFlags_WidthStretch) ? "WidthStretch " : "",
(column->Flags & ImGuiTableColumnFlags_WidthFixed) ? "WidthFixed " : "",
(column->Flags & ImGuiTableColumnFlags_NoResize) ? "NoResize " : "");
Bullet();
Selectable(buf);
if (IsItemHovered())
{
ImRect r(column->MinX, table->OuterRect.Min.y, column->MaxX, table->OuterRect.Max.y);
GetForegroundDrawList()->AddRect(r.Min, r.Max, IM_COL32(255, 255, 0, 255));
}
}
if (ImGuiTableSettings* settings = TableGetBoundSettings(table))
DebugNodeTableSettings(settings);
if (clear_settings)
table->IsResetAllRequest = true;
TreePop();
}
void ImGui::DebugNodeTableSettings(ImGuiTableSettings* settings)
{
if (!TreeNode((void*)(intptr_t)settings->ID, "Settings 0x%08X (%d columns)", settings->ID, settings->ColumnsCount))
return;
BulletText("SaveFlags: 0x%08X", settings->SaveFlags);
BulletText("ColumnsCount: %d (max %d)", settings->ColumnsCount, settings->ColumnsCountMax);
for (int n = 0; n < settings->ColumnsCount; n++)
{
ImGuiTableColumnSettings* column_settings = &settings->GetColumnSettings()[n];
ImGuiSortDirection sort_dir = (column_settings->SortOrder != -1) ? (ImGuiSortDirection)column_settings->SortDirection : ImGuiSortDirection_None;
BulletText("Column %d Order %d SortOrder %d %s Vis %d %s %7.3f UserID 0x%08X",
n, column_settings->DisplayOrder, column_settings->SortOrder,
(sort_dir == ImGuiSortDirection_Ascending) ? "Asc" : (sort_dir == ImGuiSortDirection_Descending) ? "Des" : "---",
column_settings->IsEnabled, column_settings->IsStretch ? "Weight" : "Width ", column_settings->WidthOrWeight, column_settings->UserID);
}
TreePop();
}
#else // #ifndef IMGUI_DISABLE_METRICS_WINDOW
void ImGui::DebugNodeTable(ImGuiTable*) {}
void ImGui::DebugNodeTableSettings(ImGuiTableSettings*) {}
#endif
//-------------------------------------------------------------------------
// [SECTION] Columns, BeginColumns, EndColumns, etc.
// (This is a legacy API, prefer using BeginTable/EndTable!)
//-------------------------------------------------------------------------
// FIXME: sizing is lossy when columns width is very small (default width may turn negative etc.)
//-------------------------------------------------------------------------
// - SetWindowClipRectBeforeSetChannel() [Internal]
// - GetColumnIndex()
// - GetColumnsCount()
// - GetColumnOffset()
// - GetColumnWidth()
// - SetColumnOffset()
// - SetColumnWidth()
// - PushColumnClipRect() [Internal]
// - PushColumnsBackground() [Internal]
// - PopColumnsBackground() [Internal]
// - FindOrCreateColumns() [Internal]
// - GetColumnsID() [Internal]
// - BeginColumns()
// - NextColumn()
// - EndColumns()
// - Columns()
//-------------------------------------------------------------------------
// [Internal] Small optimization to avoid calls to PopClipRect/SetCurrentChannel/PushClipRect in sequences,
// they would meddle many times with the underlying ImDrawCmd.
// Instead, we do a preemptive overwrite of clipping rectangle _without_ altering the command-buffer and let
// the subsequent single call to SetCurrentChannel() does it things once.
void ImGui::SetWindowClipRectBeforeSetChannel(ImGuiWindow* window, const ImRect& clip_rect)
{
ImVec4 clip_rect_vec4 = clip_rect.ToVec4();
window->ClipRect = clip_rect;
window->DrawList->_CmdHeader.ClipRect = clip_rect_vec4;
window->DrawList->_ClipRectStack.Data[window->DrawList->_ClipRectStack.Size - 1] = clip_rect_vec4;
}
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CurrentColumns ? window->DC.CurrentColumns->Count : 1;
}
float ImGui::GetColumnOffsetFromNorm(const ImGuiOldColumns* columns, float offset_norm)
{
return offset_norm * (columns->OffMaxX - columns->OffMinX);
}
float ImGui::GetColumnNormFromOffset(const ImGuiOldColumns* columns, float offset)
{
return offset / (columns->OffMaxX - columns->OffMinX);
}
static const float COLUMNS_HIT_RECT_HALF_WIDTH = 4.0f;
static float GetDraggedColumnOffset(ImGuiOldColumns* 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 + COLUMNS_HIT_RECT_HALF_WIDTH - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiOldColumnFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return 0.0f;
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->OffMinX, columns->OffMaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiOldColumns* 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 ImGui::GetColumnOffsetFromNorm(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns == NULL)
return GetContentRegionAvail().x;
if (column_index < 0)
column_index = columns->Current;
return GetColumnOffsetFromNorm(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;
ImGuiOldColumns* columns = window->DC.CurrentColumns;
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 & ImGuiOldColumnFlags_NoPreserveWidths) && (column_index < columns->Count - 1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiOldColumnFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->OffMaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = GetColumnNormFromOffset(columns, offset - columns->OffMinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
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();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (column_index < 0)
column_index = columns->Current;
ImGuiOldColumnData* column = &columns->Columns[column_index];
PushClipRect(column->ClipRect.Min, column->ClipRect.Max, false);
}
// Get into the columns background draw command (which is generally the same draw command as before we called BeginColumns)
void ImGui::PushColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
// Optimization: avoid SetCurrentChannel() + PushClipRect()
columns->HostBackupClipRect = window->ClipRect;
SetWindowClipRectBeforeSetChannel(window, columns->HostInitialClipRect);
columns->Splitter.SetCurrentChannel(window->DrawList, 0);
}
void ImGui::PopColumnsBackground()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
return;
// Optimization: avoid PopClipRect() + SetCurrentChannel()
SetWindowClipRectBeforeSetChannel(window, columns->HostBackupClipRect);
columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
}
ImGuiOldColumns* ImGui::FindOrCreateColumns(ImGuiWindow* window, ImGuiID id)
{
// We have few columns per window so for now we don't need bother much with turning this into a faster lookup.
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiOldColumns());
ImGuiOldColumns* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
ImGuiID ImGui::GetColumnsID(const char* str_id, int columns_count)
{
ImGuiWindow* window = GetCurrentWindow();
// 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();
return id;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiOldColumnFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
IM_ASSERT(window->DC.CurrentColumns == NULL); // Nested columns are currently not supported
// Acquire storage for the columns set
ImGuiID id = GetColumnsID(str_id, columns_count);
ImGuiOldColumns* columns = FindOrCreateColumns(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.CurrentColumns = columns;
columns->HostCursorPosY = window->DC.CursorPos.y;
columns->HostCursorMaxPosX = window->DC.CursorMaxPos.x;
columns->HostInitialClipRect = window->ClipRect;
columns->HostBackupParentWorkRect = window->ParentWorkRect;
window->ParentWorkRect = window->WorkRect;
// Set state for first column
// We aim so that the right-most column will have the same clipping width as other after being clipped by parent ClipRect
const float column_padding = g.Style.ItemSpacing.x;
const float half_clip_extend_x = ImFloor(ImMax(window->WindowPadding.x * 0.5f, window->WindowBorderSize));
const float max_1 = window->WorkRect.Max.x + column_padding - ImMax(column_padding - window->WindowPadding.x, 0.0f);
const float max_2 = window->WorkRect.Max.x + half_clip_extend_x;
columns->OffMinX = window->DC.Indent.x - column_padding + ImMax(column_padding - window->WindowPadding.x, 0.0f);
columns->OffMaxX = ImMax(ImMin(max_1, max_2) - window->Pos.x, columns->OffMinX + 1.0f);
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize default widths
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++)
{
ImGuiOldColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiOldColumnData* column = &columns->Columns[n];
float clip_x1 = IM_ROUND(window->Pos.x + GetColumnOffset(n));
float clip_x2 = IM_ROUND(window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWithFull(window->ClipRect);
}
if (columns->Count > 1)
{
columns->Splitter.Split(window->DrawList, 1 + columns->Count);
columns->Splitter.SetCurrentChannel(window->DrawList, 1);
PushColumnClipRect(0);
}
// We don't generally store Indent.x inside ColumnsOffset because it may be manipulated by the user.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.CurrentColumns == NULL)
return;
ImGuiContext& g = *GImGui;
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns->Count == 1)
{
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
IM_ASSERT(columns->Current == 0);
return;
}
// Next column
if (++columns->Current == columns->Count)
columns->Current = 0;
PopItemWidth();
// Optimization: avoid PopClipRect() + SetCurrentChannel() + PushClipRect()
// (which would needlessly attempt to update commands in the wrong channel, then pop or overwrite them),
ImGuiOldColumnData* column = &columns->Columns[columns->Current];
SetWindowClipRectBeforeSetChannel(window, column->ClipRect);
columns->Splitter.SetCurrentChannel(window->DrawList, columns->Current + 1);
const float column_padding = g.Style.ItemSpacing.x;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (columns->Current > 0)
{
// Columns 1+ ignore IndentX (by canceling it out)
// FIXME-COLUMNS: Unnecessary, could be locked?
window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + column_padding;
}
else
{
// New row/line: column 0 honor IndentX.
window->DC.ColumnsOffset.x = ImMax(column_padding - window->WindowPadding.x, 0.0f);
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = 0.0f;
// FIXME-COLUMNS: Share code with BeginColumns() - move code on columns setup.
float offset_0 = GetColumnOffset(columns->Current);
float offset_1 = GetColumnOffset(columns->Current + 1);
float width = offset_1 - offset_0;
PushItemWidth(width * 0.65f);
window->WorkRect.Max.x = window->Pos.x + offset_1 - column_padding;
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiOldColumns* columns = window->DC.CurrentColumns;
IM_ASSERT(columns != NULL);
PopItemWidth();
if (columns->Count > 1)
{
PopClipRect();
columns->Splitter.Merge(window->DrawList);
}
const ImGuiOldColumnFlags flags = columns->Flags;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(flags & ImGuiOldColumnFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = columns->HostCursorMaxPosX; // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
// The IsBeingResized flag ensure we preserve pre-resize columns width so back-and-forth are not lossy
bool is_being_resized = false;
if (!(flags & ImGuiOldColumnFlags_NoBorder) && !window->SkipItems)
{
// We clip Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.
const float y1 = ImMax(columns->HostCursorPosY, window->ClipRect.Min.y);
const float y2 = ImMin(window->DC.CursorPos.y, window->ClipRect.Max.y);
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
ImGuiOldColumnData* column = &columns->Columns[n];
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hit_hw = COLUMNS_HIT_RECT_HALF_WIDTH;
const ImRect column_hit_rect(ImVec2(x - column_hit_hw, y1), ImVec2(x + column_hit_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_hit_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(flags & ImGuiOldColumnFlags_NoResize))
{
ButtonBehavior(column_hit_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(column->Flags & ImGuiOldColumnFlags_NoResize))
dragging_column = n;
}
// Draw column
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = IM_FLOOR(x);
window->DrawList->AddLine(ImVec2(xi, y1 + 1.0f), ImVec2(xi, y2), 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->WorkRect = window->ParentWorkRect;
window->ParentWorkRect = columns->HostBackupParentWorkRect;
window->DC.CurrentColumns = NULL;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
}
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
ImGuiOldColumnFlags flags = (border ? 0 : ImGuiOldColumnFlags_NoBorder);
//flags |= ImGuiOldColumnFlags_NoPreserveWidths; // NB: Legacy behavior
ImGuiOldColumns* columns = window->DC.CurrentColumns;
if (columns != NULL && columns->Count == columns_count && columns->Flags == flags)
return;
if (columns != NULL)
EndColumns();
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
//-------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
|
#include <Arduino.h>
#include <DSPI.h>
#include "SpiFlashRK.h"
DSPI0 _flash_spi;
void SpiFlash::initcs(){
pinMode(cs_pin, OUTPUT);
}
void SpiFlash::csResetFast(){
digitalWrite(cs_pin, LOW);
}
void SpiFlash::csSetFast(){
digitalWrite(cs_pin, HIGH);
}
void SpiFlash::pinResetFast(uint8_t cs_pin){
digitalWrite(cs_pin, LOW);
}
void SpiFlash::pinSetFast(uint8_t cs_pin){
digitalWrite(cs_pin, HIGH);
}
SpiFlash::SpiFlash(int cs){
cs_pin = cs;
initcs();
}
SpiFlash::~SpiFlash() {
}
void SpiFlash::begin() {
_flash_spi.begin(cs_pin);
csSetFast();
setSpiSettings();
// Send release from powerdown 0xab
wakeFromSleep();
}
bool SpiFlash::isValid() {
uint8_t foundManufacturerId = (jedecIdRead() >> 16) & 0xff;
return manufacturerId == foundManufacturerId;
}
void SpiFlash::beginTransaction() {
csResetFast();
}
void SpiFlash::endTransaction() {
csSetFast();
}
void SpiFlash::setSpiSettings() {
_flash_spi.disableInterruptTransfer();
_flash_spi.setTransferSize(DSPI_8BIT);
_flash_spi.setSpeed(20000000); // Default: 30
_flash_spi.setMode(DSPI_MODE3); // Default: SPI_MODE3
}
uint32_t SpiFlash::jedecIdRead() {
uint8_t txBuf[4], rxBuf[4];
txBuf[0] = 0x9f;
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf, rxBuf);
endTransaction();
return (rxBuf[1] << 16) | (rxBuf[2] << 8) | (rxBuf[3]);
}
uint8_t SpiFlash::readStatus() {
uint8_t txBuf[2], rxBuf[2];
txBuf[0] = 0x05; // RDSR
txBuf[1] = 0;
beginTransaction();
_flash_spi.transfer( sizeof(txBuf), txBuf, rxBuf);
endTransaction();
return rxBuf[1];
}
bool SpiFlash::isWriteInProgress() {
return (readStatus() & STATUS_WIP) != 0;
}
void SpiFlash::waitForWriteComplete(unsigned long timeout) {
unsigned long startTime = millis();
if (timeout == 0) {
timeout = waitWriteCompletionTimeoutMs;
}
// Wait for up to 500 ms. Most operations should take much less than that.
while(isWriteInProgress() && millis() - startTime < timeout) {
// For long timeouts, yield the CPU
if (timeout > 500) {
delay(1);
}
}
// Log.trace("isWriteInProgress=%d time=%u", isWriteInProgress(), millis() - startTime);
}
void SpiFlash::writeStatus(uint8_t status) {
waitForWriteComplete();
uint8_t txBuf[2];
txBuf[0] = 0x01; // WRSR
txBuf[1] = status;
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
}
void SpiFlash::readData(size_t addr, void *buf, size_t bufLen) {
uint8_t *curBuf = (uint8_t *)buf;
while(bufLen > 0) {
size_t pageOffset = addr % pageSize;
size_t pageStart = addr - pageOffset;
size_t count = (pageStart + pageSize) - addr;
if (count > bufLen) {
count = bufLen;
}
uint8_t txBuf[4];
setInstWithAddr(0x03, addr, txBuf); // READ
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
_flash_spi.transfer(bufLen, (uint8_t) 0x00, curBuf);
endTransaction();
addr += count;
curBuf += count;
bufLen -= count;
}
}
void SpiFlash::setInstWithAddr(uint8_t inst, size_t addr, uint8_t *buf) {
buf[0] = inst;
buf[1] = (uint8_t) (addr >> 16);
buf[2] = (uint8_t) (addr >> 8);
buf[3] = (uint8_t) addr;
}
void SpiFlash::writeData(size_t addr, const void *buf, size_t bufLen) {
uint8_t *curBuf = (uint8_t *)buf;
waitForWriteComplete();
while(bufLen > 0) {
size_t pageOffset = addr % pageSize;
size_t pageStart = addr - pageOffset;
size_t count = (pageStart + pageSize) - addr;
if (count > bufLen) {
count = bufLen;
}
// Log.info("writeData addr=%lx pageOffset=%lu pageStart=%lu count=%lu pageSize=%lu", addr, pageOffset, pageStart, count, pageSize);
uint8_t txBuf[4];
setInstWithAddr(0x02, addr, txBuf); // PAGE_PROG
writeEnable();
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
_flash_spi.transfer(count, curBuf);
endTransaction();
waitForWriteComplete(pageProgramTimeoutMs);
addr += count;
curBuf += count;
bufLen -= count;
}
}
void SpiFlash::sectorErase(size_t addr) {
waitForWriteComplete();
uint8_t txBuf[4];
// Log.trace("sectorEraseCmd=%02x", sectorEraseCmd);
//
// ISSI 25LQ080 uses 0x20 or 0xD7
// Winbond uses 0x20 only, so use that
setInstWithAddr(0x20, addr, txBuf); // SECTOR_ER
writeEnable();
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
waitForWriteComplete(sectorEraseTimeoutMs);
}
void SpiFlash::blockErase(size_t addr) {
waitForWriteComplete();
uint8_t txBuf[4];
setInstWithAddr(0xD8, addr, txBuf); // BLOCK_ER
writeEnable();
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
waitForWriteComplete(chipEraseTimeoutMs);
}
void SpiFlash::chipErase() {
waitForWriteComplete();
uint8_t txBuf[1];
txBuf[0] = 0xC7; // CHIP_ER
writeEnable();
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
waitForWriteComplete(chipEraseTimeoutMs);
}
void SpiFlash::resetDevice() {
waitForWriteComplete();
uint8_t txBuf[1];
txBuf[0] = 0x66; // Enable reset
beginTransaction();
_flash_spi.transfer(sizeof(txBuf),txBuf);
endTransaction();
delayMicroseconds(1);
txBuf[0] = 0x99; // Reset
beginTransaction();
_flash_spi.transfer(sizeof(txBuf),txBuf);
endTransaction();
delayMicroseconds(1);
}
void SpiFlash::wakeFromSleep() {
// Send release from powerdown 0xab
uint8_t txBuf[1];
txBuf[0] = 0xab;
beginTransaction();
_flash_spi.transfer(sizeof(txBuf),txBuf);
endTransaction();
// Need to wait tres (3 microseconds) before issuing the next command
delayMicroseconds(3);
}
// Note: not all chips support this. Macronix does.
void SpiFlash::deepPowerDown() {
uint8_t txBuf[1];
txBuf[0] = 0xb9;
beginTransaction();
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
// Need to wait tdp (10 microseconds) before issuing the next command, but since we're probably doing
// this before sleep, it's not necessary
}
void SpiFlash::writeEnable() {
uint8_t txBuf[1];
beginTransaction();
txBuf[0] = 0x06; // WREN
_flash_spi.transfer(sizeof(txBuf), txBuf);
endTransaction();
// ISSI devices require a 3us delay here, but Winbond devices do not
if (writeEnableDelayUs > 0) {
delayMicroseconds(writeEnableDelayUs);
}
}
|
#ifndef VG_STATISTICS_HPP_INCLUDED
#define VG_STATISTICS_HPP_INCLUDED
/**
* \file statistics.hpp
*
* Defines a range of statistical functions
*
*/
#include <cmath>
#include <algorithm>
#include "utility.hpp"
namespace vg {
using namespace std;
double median(std::vector<int> &v);
// Online mean-variance computation with wellfords algorithm (pass 0's to 1st 3 params to start)
void wellford_update(size_t& count, double& mean, double& M2, double new_val);
pair<double, double> wellford_mean_var(size_t count, double mean, double M2, bool sample_variance = false);
template<typename T>
double stdev(const T& v) {
double sum = std::accumulate(v.begin(), v.end(), 0.0);
double mean = sum / v.size();
std::vector<double> diff(v.size());
std::transform(v.begin(), v.end(), diff.begin(), [mean](double x) { return x - mean; });
double sq_sum = std::inner_product(diff.begin(), diff.end(), diff.begin(), 0.0);
return std::sqrt(sq_sum / v.size());
}
// Φ is the normal cumulative distribution function
// https://en.wikipedia.org/wiki/Cumulative_distribution_function
double phi(double x1, double x2);
/// Inverse CDF of a standard normal distribution. Must have 0 < quantile < 1.
double normal_inverse_cdf(double quantile);
/*
* Return the log of the sum of two log-transformed values without taking them
* out of log space.
*/
inline double add_log(double log_x, double log_y) {
return log_x > log_y ? log_x + log(1.0 + exp(log_y - log_x)) : log_y + log(1.0 + exp(log_x - log_y));
}
/*
* Return the log of the difference of two log-transformed values without taking
* them out of log space.
*/
inline double subtract_log(double log_x, double log_y) {
return log_x + log(1.0 - exp(log_y - log_x));
}
/**
* Convert a number ln to the same number log 10.
*/
inline double ln_to_log10(double ln) {
return ln / log(10);
}
/**
* Convert a number log 10 to the same number ln.
*/
inline double log10_to_ln(double l10) {
return l10 * log(10);
}
/**
* Given the log10 of a value, retunr the log10 of (that value plus one).
*/
inline double log10_add_one(double x) {
return log10(pow(10, x) + 1);
}
/**
* Return the log of the sum of two log10-transformed values without taking them
* out of log space.
*/
inline double add_log10(double i, double j) {
if (i < j) {
return log10_add_one(j - i) + ((j - i < 10) ? i : j);
}
return log10_add_one(i - j) + ((i - j <= 10) ? j : i);
}
/**
* Assume that we have n independent random events that occur with probability
* p each (p is interpreted as a real number between 0 at 0 and 1 at its
* maximum value). Return an approximate probability for at least one event
* occurring as a phred score.
*
* n must be <= MAX_AT_LEAST_ONE_EVENTS.
*/
double phred_for_at_least_one(size_t p, size_t n);
/**
* Assume that we have n independent random events that occur with probability
* p each (p is interpreted as a real number between 0 at 0 and 1 at its
* maximum value). Return an approximate probability for at least one event
* occurring as a raw probability.
*
* n must be <= MAX_AT_LEAST_ONE_EVENTS.
*/
double prob_for_at_least_one(size_t p, size_t n);
/// How many events should we allow in phred_for_at_least_one and
/// prob_for_at_least_one? Should be >= our longest supported minimizer index.
constexpr static size_t MAX_AT_LEAST_ONE_EVENTS = 32;
/// Use this many bits for approximate probabilities.
constexpr static size_t AT_LEAST_ONE_PRECISION = 8;
// normal pdf, from http://stackoverflow.com/a/10848293/238609
template <typename T>
T normal_pdf(T x, T m, T s)
{
static const T inv_sqrt_2pi = 0.3989422804014327;
T a = (x - m) / s;
return inv_sqrt_2pi / s * std::exp(-T(0.5) * a * a);
}
/// Convert a probability to a natural log probability.
inline double prob_to_logprob(double prob) {
return log(prob);
}
/// Convert natural log probability to a probability
inline double logprob_to_prob(double logprob) {
return exp(logprob);
}
/// Add two probabilities (expressed as logprobs) together and return the result
/// as a logprob.
inline double logprob_add(double logprob1, double logprob2) {
// Pull out the larger one to avoid underflows
double pulled_out = max(logprob1, logprob2);
return pulled_out + prob_to_logprob(logprob_to_prob(logprob1 - pulled_out) + logprob_to_prob(logprob2 - pulled_out));
}
/// Invert a logprob, and get the probability of its opposite.
inline double logprob_invert(double logprob) {
return prob_to_logprob(1.0 - logprob_to_prob(logprob));
}
/// Convert 8-bit Phred quality score to probability of wrongness, using a lookup table.
double phred_to_prob(uint8_t phred);
/// Convert floating point Phred quality score to probability of wrongness.
inline double phred_to_prob(double phred) {
return pow(10, -phred / 10);
}
/// Convert probability of wrongness to integer Phred quality score.
inline double prob_to_phred(double prob) {
return -10.0 * log10(prob);
}
/// Convert a Phred quality score directly to a natural log probability of wrongness.
inline double phred_to_logprob(int phred) {
return (-((double)phred) / 10) / log10(exp(1.0));
}
/// Convert a natural log probability of wrongness directly to a Phred quality score.
inline double logprob_to_phred(double logprob ) {
return -10.0 * logprob * log10(exp(1.0));
}
/// Take the geometric mean of two logprobs
inline double logprob_geometric_mean(double lnprob1, double lnprob2) {
return log(sqrt(exp(lnprob1 + lnprob2)));
}
/// Take the geometric mean of two phred-encoded probabilities
inline double phred_geometric_mean(double phred1, double phred2) {
return prob_to_phred(sqrt(phred_to_prob(phred1 + phred2)));
}
/// Add two probabilities (expressed as phred scores) together and return the result
/// as a phred score.
inline double phred_add(double phred1, double phred2) {
return logprob_to_phred(logprob_add(phred_to_logprob(phred1), phred_to_logprob(phred2)));
}
/**
* Compute the sum of the values in a collection, where the values are log
* probabilities and the result is the log of the total probability. Items must
* be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type logprob_sum(const Collection& collection) {
// Set up an alias
using Item = typename Collection::value_type;
// Pull out the minimum value
auto min_iterator = min_element(begin(collection), end(collection));
if(min_iterator == end(collection)) {
// Nothing there, p = 0
return Item(prob_to_logprob(0));
}
auto check_iterator = begin(collection);
++check_iterator;
if(check_iterator == end(collection)) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
Item pulled_out = *min_iterator;
if(logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
Item total(0);
for(auto& to_add : collection) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(to_add - pulled_out);
}
// Re-log and re-scale
return pulled_out + prob_to_logprob(total);
}
/**
* Compute the sum of the values in a collection, represented by an iterator
* range, where the values are Phred scores and the result is the Phred score
* of the total probability. Items must be convertible to/from doubles for
* math.
*/
template<typename Iterator>
typename std::iterator_traits<Iterator>::value_type phred_sum(const Iterator& begin_it, const Iterator& end_it) {
// Set up an alias for the type we're operating on
using Item = typename std::iterator_traits<Iterator>::value_type;
// Pull out the minimum probability
auto min_iterator = max_element(begin_it, end_it);
if (min_iterator == end_it) {
// Nothing there, p = 0
return Item(logprob_to_phred(prob_to_logprob(0)));
}
auto check_iterator = begin_it;
++check_iterator;
if (check_iterator == end_it) {
// We only have a single element anyway. We don't want to subtract it
// out because we'll get 0s.
return *min_iterator;
}
// Pull this much out of every logprob.
double pulled_out = phred_to_logprob(*min_iterator);
if (logprob_to_prob(pulled_out) == 0) {
// Can't divide by 0!
// TODO: fix this in selection
pulled_out = prob_to_logprob(1);
}
double total(0);
for(auto to_add_it = begin_it; to_add_it != end_it; ++to_add_it) {
// Sum up all the scaled probabilities.
total += logprob_to_prob(phred_to_logprob(*to_add_it) - pulled_out);
}
// Re-log and re-scale
return Item(logprob_to_phred(pulled_out + prob_to_logprob(total)));
}
/**
* Compute the sum of the values in a collection, where the values are Phred
* scores and the result is the Phred score of the total probability. Items
* must be convertible to/from doubles for math.
*/
template<typename Collection>
typename Collection::value_type phred_sum(const Collection& collection) {
return phred_sum(begin(collection), end(collection));
}
double slope(const std::vector<double>& x, const std::vector<double>& y);
double fit_zipf(const vector<double>& y);
/// Returns the MLE rate parameter for the distribution of (shape) iid exponential RVs
double fit_fixed_shape_max_exponential(const vector<double>& x, double shape, double tolerance = 1e-8);
/// Returns the MLE estimate for the number of iid exponential RVs the data are maxima of
double fit_fixed_rate_max_exponential(const vector<double>& x, double rate, double tolerance = 1e-8);
/// Returns the MLE rate and shape parameters of a max exponential
pair<double, double> fit_max_exponential(const vector<double>& x, double tolerance = 1e-8);
// TODO: I'm eliminating this algorithm because it is approx non-identifiable for large values of shape
///// Returns the MLE rate, shape, and location parameters of an offset max exponential
//tuple<double, double, double> fit_offset_max_exponential(const vector<double>& x, double tolerance = 1e-8);
/// Return the CDF of a max exponential with the given parameters
inline double max_exponential_cdf(double x, double rate, double shape, double location = 0.0) {
return x > location ? pow(1.0 - exp(-(x - location) * rate), shape) : 0.0;
}
/// The log likelihood of a max exponential with the given parameters on the given data
double max_exponential_log_likelihood(const vector<double>& x, double rate, double shape,
double location = 0.0);
/// Returns an estimate of the rate and shape parameters of a Weibull distribution
pair<double, double> fit_weibull(const vector<double>& x);
/// Returns an estimate of the rate, shape, and location (minimum value) of a 3-parameter Weibull distribution
tuple<double, double, double> fit_offset_weibull(const vector<double>& x,
double tolerance = 1e-8);
/// Return the CDF of a max exponential with the given parameters
inline double weibull_cdf(double x, double scale, double shape, double location = 0.0) {
return x > location ? 1.0 - exp(-pow((x - location) / scale, shape)) : 0.0;
}
/// Returns the log likelihood of some data generated by a Weibull distribution
double weibull_log_likelihood(const vector<double>& x, double scale, double shape,
double location = 0.0);
/// Returns a local maximum of a function within an interval
double golden_section_search(const function<double(double)>& f, double x_min, double x_max,
double tolerance = 1e-8);
/// A shitty set of linear algebra functions
vector<vector<double>> transpose(const vector<vector<double>>& A);
vector<vector<double>> matrix_multiply(const vector<vector<double>>& A,
const vector<vector<double>>& B);
vector<double> matrix_multiply(const vector<vector<double>>& A,
const vector<double>& b);
vector<vector<double>> matrix_invert(const vector<vector<double>>& A);
/// Returns the coefficients of a regression (does not automatically compute constant)
vector<double> regress(const vector<vector<double>>& X, vector<double>& y);
/*
*********************************
* Code ported over from FreeBayes
*********************************
*/
// We use this slightly nonstandard type for our math. We wrap it so it's easy
// to change later.
using real_t = long double;
/**
* Calculate the natural log of the gamma function of the given argument.
*/
inline real_t gamma_ln(real_t x) {
real_t cofactors[] = {76.18009173,
-86.50532033,
24.01409822,
-1.231739516,
0.120858003E-2,
-0.536382E-5};
real_t x1 = x - 1.0;
real_t tmp = x1 + 5.5;
tmp -= (x1 + 0.5) * log(tmp);
real_t ser = 1.0;
for (int j=0; j<=5; j++) {
x1 += 1.0;
ser += cofactors[j]/x1;
}
real_t y = (-1.0 * tmp + log(2.50662827465 * ser));
return y;
}
/**
* Calculate the natural log of the factorial of the given integer. TODO:
* replace with a cache or giant lookup table from Freebayes.
*/
inline real_t factorial_ln(int n) {
if (n < 0) {
return (long double)-1.0;
}
else if (n == 0) {
return (long double)0.0;
}
else {
return gamma_ln(n + 1.0);
}
}
/**
* Raise a log probability to a power
*/
inline real_t pow_ln(real_t m, int n) {
return m * n;
}
/**
* Compute the number of ways to select k items from a collection of n
* distinguishable items, ignoring order. Returns the natural log of the
* (integer) result.
*/
inline real_t choose_ln(int n, int k) {
return factorial_ln(n) - (factorial_ln(k) + factorial_ln(n - k));
}
/**
* Compute the number of ways to select k_1, k_2, ... k_i items into i buckets
* from a collection of n distinguishable items, ignoring order. All of the
* items have to go into the buckets, so all k_i must sum to n. To compute
* choose you have to call this function with a 2-element vector, to represent
* the chosen and not-chosen buckets. Returns the natural log of the (integer)
* result.
*
* TODO: Turns out we don't actually need this for the ambiguous multinomial
* after all.
*/
inline real_t multinomial_choose_ln(int n, vector<int> k) {
// We use the product-of-binomial-coefficients approach from
// <https://en.wikipedia.org/wiki/Multinomial_theorem#Multinomial_coefficients>
real_t product_of_binomials_ln = 0;
// We sum up the bucket sizes as we go
int bucket_sum = 0;
for (auto& bucket_size : k) {
// Increment the size of what we choose from
bucket_sum += bucket_size;
// Choose this many
product_of_binomials_ln += choose_ln(bucket_sum, bucket_size);
}
// Make sure they actually gave us a proper decomposition of the items into
// buckets.
assert(bucket_sum == n);
return product_of_binomials_ln;
}
/**
* Compute the log probability of a Poisson-distributed process: observed events
* in an interval where expected events happen on average.
*/
inline real_t poisson_prob_ln(int observed, real_t expected) {
return log(expected) * (real_t) observed - expected - factorial_ln(observed);
}
/**
* Get the probability for sampling the counts in obs from a set of categories
* weighted by the probabilities in probs. Works for both double and real_t
* probabilities. Also works for binomials.
*/
template <typename ProbIn>
real_t multinomial_sampling_prob_ln(const vector<ProbIn>& probs, const vector<int>& obs) {
vector<real_t> factorials;
vector<real_t> probsPowObs;
factorials.resize(obs.size());
transform(obs.begin(), obs.end(), factorials.begin(), factorial_ln);
typename vector<ProbIn>::const_iterator p = probs.begin();
vector<int>::const_iterator o = obs.begin();
for (; p != probs.end() && o != obs.end(); ++p, ++o) {
probsPowObs.push_back(pow_ln(log(*p), *o));
}
// Use the collection sum defined in utility.hpp
return factorial_ln(sum(obs)) - sum(factorials) + sum(probsPowObs);
}
/**
* Compute the probability of having the given number of successes or fewer in
* the given number of trials, with the given success probability. Returns the
* resulting log probability.
*/
template <typename ProbIn>
real_t binomial_cmf_ln(ProbIn success_logprob, size_t trials, size_t successes) {
// Compute log probabilities for all cases
vector<real_t> case_logprobs;
if(successes > trials) {
return prob_to_logprob(0);
}
for(size_t considered_successes = 0; considered_successes <= successes; considered_successes++) {
// For every number of successes up to this one, add in the probability.
case_logprobs.push_back(choose_ln(trials, considered_successes) +
success_logprob * considered_successes +
logprob_invert(success_logprob) * (trials - considered_successes));
}
// Sum up all those per-case probabilities
return logprob_sum(case_logprobs);
}
/**
* Get the log probability for sampling the given value from a geometric
* distribution with the given success log probability. The geometric
* distribution is the distribution of the number of trials, with a given
* success probability, required to observe a single success.
*/
template <typename ProbIn>
real_t geometric_sampling_prob_ln(ProbIn success_logprob, size_t trials) {
return logprob_invert(success_logprob) * (trials - 1) + success_logprob;
}
/**
* Given a split of items across a certain number of categories, as ints between
* the two given bidirectional iterators, advance to the next split and return
* true. If there is no next split, leave the collection unchanged and return
* false.
*/
template<typename Iter>
bool advance_split(Iter start, Iter end) {
if (start == end) {
// Base case: we hit the end. No more possible splits.
#ifdef debug
cerr << "Not advancing empty split" << endl;
#endif
return false;
} else {
#ifdef debug
cerr << "Trying to advance split with " << *start << " items in first category" << endl;
#endif
// Try advancing what comes after us.
auto next = start;
++next;
if (advance_split(next, end)) {
// It worked.
#ifdef debug
cerr << "Advanced child split" << endl;
#endif
return true;
}
#ifdef debug
cerr << "Could not advance child split" << endl;
#endif
// If that didn't work, try moving an item from here to what comes after us.
// We also need to reset what comes after us to its initial state of everything in the first category.
// This is easy because we know everything in what comes after us has made its way to the end.
if (*start != 0 && next != end) {
// We have something to move
// Do the reset so everything after us is in the first category
// after us.
auto next_to_last = end;
--next_to_last;
#ifdef debug
cerr << "Want to move " << *next_to_last << " items to next which has " << *next << " and also move one from start which has " << *start << endl;
#endif
if (next_to_last != next) {
(*next) += *next_to_last;
*next_to_last = 0;
}
(*start)--;
(*next)++;
#ifdef debug
cerr << "Reset child split to have " << *next << " items vs. our " << *start << endl;
#endif
return true;
}
// If that didn't work, we're out of stuff to do.
#ifdef debug
cerr << "Could not advance or reset child split" << endl;
#endif
return false;
}
}
/**
* Get the log probability for sampling any actual set of category counts that
* is consistent with the constraints specified by obs, using the per-category
* probabilities defined in probs.
*
* Obs maps from a vector of per-category flags (called a "class") to a number
* of items that might be in any of the flagged categories.
*
* For example, if there are two equally likely categories, and one item flagged
* as potentially from either category, the probability of sampling a set of
* category counts consistent with that constraint is 1. If instead there are
* three equally likely categories, and one item flagged as potentially from two
* of the three but not the third, the probability of sampling a set of category
* counts consistent with that constraint is 2/3.
*/
template<typename ProbIn>
real_t multinomial_censored_sampling_prob_ln(const vector<ProbIn>& probs, const unordered_map<vector<bool>, int>& obs) {
// We fill this with logprobs for all the different cases and then sum them
// up.
vector<real_t> case_logprobs;
// We have a state. We advance this state until we can't anymore.
//
// The state is, for each ambiguity class, a vector of length equal to
// the number of set bits in the valence, and sum equal to the number of
// reads int he category.
//
// We start with all the reads in the first spot in each class, and
// advance/reset until we have iterated over all combinations of category
// assignments for all classes.
unordered_map<vector<bool>, vector<int>> splits_by_class;
// Prepare the state
for (auto& kv : obs) {
// For each input class
if (kv.second == 0) {
// No reads are in this class, so we can skip it.
continue;
}
// Work out if it actually matches any categories
bool has_any_categories = false;
for (const auto& bit : kv.first) {
if (bit) {
has_any_categories = true;
break;
}
}
if (!has_any_categories) {
// There are reads and they match nothing.
// So this case is impossible.
return prob_to_logprob(0);
}
// Otherwise there are reads and they match something.
// For each class, find the vector we will use to describe its read-to-
// category assignments.
auto& class_state = splits_by_class[kv.first];
for (const auto& bit : kv.first) {
// Allocate a spot for each set bit
if (bit) {
class_state.push_back(0);
}
}
// Drop all the reads in the first category
class_state.front() = kv.second;
}
if (splits_by_class.empty()) {
// There are no classes with any reads.
// P(nothing happened) = 1.
return prob_to_logprob(1);
}
// Now we loop over all the combinations of class states using a stack thing.
list<decltype(splits_by_class)::iterator> stack;
// And maintain this vector of category counts for the state we are in. We
// incrementally update it so we aren't always looping over all the classes
// to rebuild it.
vector<int> category_counts(probs.size());
// We have a function to add in the contribution of a class's state
auto add_class_state = [&](const pair<vector<bool>, vector<int>>& class_state) {
auto count_it = class_state.second.begin();
for (size_t i = 0; i < category_counts.size(); i++) {
// For each category
if (class_state.first.at(i)) {
// If this ambiguity class touches it
assert(count_it != class_state.second.end());
// Add in the state's count
category_counts.at(i) += *count_it;
// And consume that state entry
++count_it;
}
}
assert(count_it == class_state.second.end());
};
// And a function to back it out again
auto remove_class_state = [&](const pair<vector<bool>, vector<int>>& class_state) {
auto count_it = class_state.second.begin();
for (size_t i = 0; i < category_counts.size(); i++) {
// For each category
if (class_state.first.at(i)) {
// If this ambiguity class touches it
assert(count_it != class_state.second.end());
// Back out the state's count
category_counts.at(i) -= *count_it;
// And consume that state entry
++count_it;
}
}
assert(count_it == class_state.second.end());
};
for (auto it = splits_by_class.begin(); it != splits_by_class.end(); ++it) {
// Populate the stack with everything
stack.push_back(it);
// And make sure the category counts are up to date.
add_class_state(*it);
}
while (!stack.empty()) {
// Emit the current state
#ifdef debug
cerr << "Category counts:" << endl;
for (auto& count : category_counts) {
cerr << count << endl;
}
#endif
auto case_logprob = multinomial_sampling_prob_ln(probs, category_counts);
#ifdef debug
cerr << "Case probability: " << logprob_to_prob(case_logprob) << endl;
#endif
// Put in the logprob for this case.
case_logprobs.push_back(case_logprob);
while (!stack.empty()) {
// See if we can advance what's at the bottom of the stack
// First clear it out of the category counts.
remove_class_state(*stack.back());
if (advance_split(stack.back()->second.begin(), stack.back()->second.end())) {
// We advanced it successfully.
#ifdef debug
cerr << "Advanced class at stack depth " << stack.size() - 1 << endl;
#endif
// Put it back in the category counts
add_class_state(*stack.back());
// We finally found something to advance, so stop ascending the stack.
break;
} else {
#ifdef debug
cerr << "Could not advanced class at stack depth " << stack.size() - 1 << endl;
#endif
// Pop off the back of the stack.
stack.pop_back();
// Keep looking up
}
}
if (!stack.empty()) {
// We found *something* to advance and haven't finished.
// Now fill in the whole stack again with the first split for every category.
auto it = stack.back();
++it;
while (it != splits_by_class.end()) {
// Reset the split to all 0s except for the first entry.
for (auto& entry : it->second) {
entry = 0;
}
it->second.front() = obs.at(it->first);
// Populate the stack with the next class
stack.push_back(it);
// And make sure the category counts are up to date.
add_class_state(*it);
#ifdef debug
cerr << "Reset class at stack depth " << stack.size() - 1 << endl;
#endif
// Look for the next class
++it;
}
}
// Otherwise we have finished looping over everything and so we should leave the stack empty.
}
// Sum up all those per-case probabilities
return logprob_sum(case_logprobs);
}
// These handy sampling distribution implementations (uniform_real_distribution
// and normal_distribution) matching the C++ <random> API are copied and
// adapted from code at https://stackoverflow.com/a/34962942
template<typename T = double>
class uniform_real_distribution {
public:
typedef T result_type;
uniform_real_distribution(T _a = 0.0, T _b = 1.0) : m_a(_a), m_b(_b) {
// Nothing to do!
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
double dScale = (m_b - m_a) / ((T)(_g.max() - _g.min()) + (T)1);
return (_g() - _g.min()) * dScale + m_a;
}
T a() const {
return m_a;
}
T b() const {
return m_b;
}
protected:
T m_a;
T m_b;
};
template<typename T = double>
class normal_distribution {
public:
typedef T result_type;
normal_distribution(T _mean = 0.0, T _stddev = 1.0) : m_mean(_mean), m_stddev(_stddev) {
// Nothing to do!
}
void reset() {
m_distU1.reset();
}
template<class Generator>
T operator()(Generator &_g) {
// Use Box-Muller algorithm
const double pi = 3.14159265358979323846264338327950288419716939937511;
double u1 = m_distU1(_g);
double u2 = m_distU1(_g);
double r = sqrt(-2.0 * log(u1));
return m_mean + m_stddev * r * sin(2.0 * pi * u2);
}
T mean() const {
return m_mean;
}
T stddev() const {
return m_stddev;
}
protected:
T m_mean;
T m_stddev;
vg::uniform_real_distribution<T> m_distU1;
};
/// We use this widerer to widen the output of a PRNG that generates only
/// numbers in a smaller range so they cover a wider int type.
template<typename PRNG, typename OutType>
class WideningPRNG {
public:
using result_type = OutType;
WideningPRNG(PRNG& to_widen) : base(to_widen) {
// Nothing to do
}
OutType min() const {
return numeric_limits<OutType>::min();
}
OutType max() const {
return numeric_limits<OutType>::max();
}
/// Generate a random number filling all OutType's bits with random bits.
OutType operator()() {
static_assert(is_unsigned<OutType>::value, "OutType must be an unsigned int type");
static_assert(numeric_limits<long long unsigned int>::digits >= numeric_limits<OutType>::digits, "OutType is too wide to bit count in");
// Work out how wide the base PRNG range is, in total (counting the inclusive bounds)
// We assume that this will fit in the wider type we are trying to fill.
// Otherwise you don't need this class.
OutType base_range = (OutType) base.max() - (OutType) base.min() + 1;
// The base range must be 1 bit at least. Otherwise we will make no progress.
assert(base_range >= 2);
// Count unset leading bits with this useful compiler builtin.
// Hope your compiler has it.
auto unused_bits = __builtin_clzll(base_range);
auto used_bits = numeric_limits<long long unsigned int>::digits - unused_bits;
// Get just that max used bit
OutType used_bit = 1 << (used_bits - 1);
// If a generated number from the RNG has this bit flag in it, it has
// passed the largest complete power of 2 it can make and needs to be
// rerolled.
OutType reroll_flag = 0;
if (base_range > used_bit) {
// We don't cover a power of 2 exactly.
// If the high bit is set we're going to need to reroll.
reroll_flag = used_bit;
// Lop off a bit for computing how many bits we actually got.
used_bit = used_bit >> 1;
used_bits--;
}
assert(used_bits > 0);
OutType generated = 0;
int generated_bits = 0;
while (generated_bits < numeric_limits<OutType>::digits) {
// Shift what's there up to make room for new bits.
generated = generated << used_bits;
OutType new_bits;
do {
// Generate bits until we're below the largest power of 2 we can generate above, if any.
new_bits = (OutType) base() - (OutType) base.min();
} while (!(new_bits & reroll_flag) && reroll_flag);
// Add in the new bits and record that they are there.
generated |= new_bits;
generated_bits += used_bits;
}
// Now we have a full type full of bits.
return generated;
}
protected:
PRNG& base;
};
/// This uniform_int_distribution implementation is based on the
/// UniformRealDistribution from https://stackoverflow.com/a/34962942
template<typename T = int>
class uniform_int_distribution {
public:
typedef T result_type;
uniform_int_distribution(T _a = 0, T _b = numeric_limits<T>::max()) : m_a(_a), m_b(_b) {
// Make sure inclusive bounds are valid
assert(_b >= _a);
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
#ifdef debug
cerr << "Source range " << _g.min() << " to " << _g.max() << endl;
cerr << "Dest range " << m_a << " to " << m_b << endl;
#endif
// Define an unsigned widest type to work in
using WorkType = typename make_unsigned<typename common_type<typename Generator::result_type, T>::type>::type;
// How big are the source and destination ranges?
// Since they are so big and inclusive we can't always hold their real sizes, so hold size-1
WorkType source_range_size_minus_1 = (WorkType) _g.max() - (WorkType) _g.min();
WorkType dest_range_size_minus_1 = (WorkType) m_b - (WorkType) m_a;
if (source_range_size_minus_1 >= dest_range_size_minus_1) {
// The generator's result is going to be wide enough
return generate_from_wide_generator(_g);
} else {
// The hard way is generating a bigger range from a smaller range.
// Wrap the generator in something to widen it to our work type
// and recurse.
WideningPRNG<Generator, WorkType> widened(_g);
// Generate with that, which had better be wide enough
return generate_from_wide_generator(widened);
}
}
T a() const {
return m_a;
}
T b() const {
return m_b;
}
protected:
/// Generate a result when we know the generator will produce a result on a
/// range as big as or bigger than ours.
template<class Generator>
T generate_from_wide_generator(Generator &_g) {
// Jordan's strategy: discard anything above the highest multiple of your range, then mod down to your range.
#ifdef debug
cerr << "Source range " << _g.min() << " to " << _g.max() << endl;
cerr << "Dest range " << m_a << " to " << m_b << endl;
#endif
// Define an unsigned widest type to work in
using WorkType = typename make_unsigned<typename common_type<typename Generator::result_type, T>::type>::type;
// How big are the source and destination ranges?
// Since they are so big and inclusive we can't always hold their real sizes, so hold size-1
WorkType source_range_size_minus_1 = (WorkType) _g.max() - (WorkType) _g.min();
WorkType dest_range_size_minus_1 = (WorkType) m_b - (WorkType) m_a;
// We must be generating a smaller range from a bigger rnage here.
assert(source_range_size_minus_1 >= dest_range_size_minus_1);
if (dest_range_size_minus_1 == source_range_size_minus_1) {
// Ranges are the same size. No real work to do.
return (WorkType) _g() - (WorkType) _g.min() + (WorkType) m_a;
}
// Otherwise the ranges differ in size. Which means the dest range must
// be smaller. Which means the dest range's real size is representable.
WorkType dest_range_size = dest_range_size_minus_1 + 1;
// Find how many numbers we have to clip off of the top of the source
// range so the rest can be covered by tiled destination ranges.
WorkType remainder = source_range_size_minus_1 % dest_range_size;
// Change the remainder from source_range_size_minus_1 to the remainder for the actual source range size
remainder = (remainder + 1) % dest_range_size;
if (remainder == 0) {
// We perfectly tiled the source range
return ((WorkType) _g() - (WorkType) _g.min()) % dest_range_size + (WorkType) m_a;
}
// Otherwise there are some values we need to reject
// Sample a value until we get one that isn't too close to the top of the range.
WorkType sampled;
do {
sampled = (WorkType) _g();
} while (_g.max() - sampled < remainder);
// Convert to destination range.
return (sampled - (WorkType) _g.min()) % dest_range_size + m_a;
}
T m_a;
T m_b;
};
/// We provide a partial discrete_distribution implementation that is just the parts we need
template<typename T = int>
class discrete_distribution {
public:
typedef T result_type;
typedef double param_type;
template<class InputIt>
discrete_distribution(InputIt first, InputIt last) : m_weights{first, last} {
// We can't use an empty weights vector
assert(!m_weights.empty());
// Compute partial sums
std::partial_sum(m_weights.begin(), m_weights.end(), std::back_inserter(m_sums));
}
discrete_distribution(initializer_list<double> weights = {1}) : discrete_distribution(weights.begin(), weights.end()) {
// Nothing to do
}
void reset() {
// Also nothing to do!
}
template<class Generator>
T operator()(Generator &_g) {
// Set up to generate a double from 0 to max weight
vg::uniform_real_distribution<double> backing_dist(0, m_sums.back());
// Do it and find which cumumative sum is greater than it
auto winning_iterator = std::lower_bound(m_sums.begin(), m_sums.end(), backing_dist(_g));
// Find its category number and return that.
return winning_iterator - m_sums.begin();
}
protected:
// If we ever want to implement the params stuff we need the weights stored.
vector<double> m_weights;
vector<double> m_sums;
};
// ewen's allele sampling distribution. for use in genotype prior (as in freebayes)
// gives Pr(a1, ...,an;theta) where ai is the number of sampled haplotypes (out of n) that
// have i different alleles at a given locus. theta is the population mutation rate.
// ex: for a single diploid genotype, a={2,0} = heterozygous: 2 alleles occur once.
// a={0,1} = homozygous: 1 allele occurs twice.
//
// https://en.wikipedia.org/wiki/Ewens%27s_sampling_formula
// https://github.com/ekg/freebayes/blob/master/src/Ewens.cpp#L17
inline real_t ewens_af_prob_ln(const vector<int>& a, real_t theta) {
// first term (wrt formula as stated on wikipedia)
// n! / (theta * (theta + 1) * ... (theta + n - 1))
real_t term1_num_ln = factorial_ln(a.size());
real_t term1_denom_ln = 0.;
for (int i = 0; i < a.size(); ++i) {
term1_denom_ln += log(theta + i);
}
real_t term1_ln = term1_num_ln - term1_denom_ln;
// second term
// prod [ (theta^aj) / (j^aj * aj!)
real_t term2_ln = 0.;
for (int j = 0; j < a.size(); ++j) {
real_t num = log(pow(theta, a[j]));
real_t denom = log(pow(1. + j, a[j]) + factorial_ln(a[j]));
term2_ln += num - denom;
}
return term1_ln + term2_ln;
}
}
#endif
|
#ifndef DRK_AUDIO_DETAIL_BUFFER_HPP
#define DRK_AUDIO_DETAIL_BUFFER_HPP
#include "Core/Base.hpp"
#include "Audio/detail/AlObject.hpp"
#include "Audio/detail/Util.hpp"
namespace DrkCraft
{
class AlBuffer : public AlObject
{
public:
AlBuffer(AudioSourceFormat format, const void* data, uint size, uint sampleRate);
virtual ~AlBuffer(void);
private:
AudioSourceFormat m_format;
};
}
#endif // DRK_AUDIO_DETAIL_BUFFER_HPP
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <limits>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <gtest/gtest.h>
#include "arrow/buffer.h"
#include "arrow/buffer_builder.h"
#include "arrow/device.h"
#include "arrow/io/interfaces.h"
#include "arrow/memory_pool.h"
#include "arrow/status.h"
#include "arrow/testing/gtest_util.h"
#include "arrow/util/checked_cast.h"
namespace arrow {
using internal::checked_cast;
using internal::checked_pointer_cast;
static const char kMyDeviceTypeName[] = "arrowtest::MyDevice";
static const int kMyDeviceAllowCopy = 1;
static const int kMyDeviceAllowView = 2;
static const int kMyDeviceDisallowCopyView = 3;
class MyDevice : public Device {
public:
explicit MyDevice(int value) : Device(), value_(value) {}
const char* type_name() const override { return kMyDeviceTypeName; }
std::string ToString() const override {
switch (value_) {
case kMyDeviceAllowCopy:
return "MyDevice[noview]";
case kMyDeviceAllowView:
return "MyDevice[nocopy]";
default:
return "MyDevice[nocopy][noview]";
}
}
bool Equals(const Device& other) const override {
if (other.type_name() != kMyDeviceTypeName) {
return false;
}
return checked_cast<const MyDevice&>(other).value_ == value_;
}
std::shared_ptr<MemoryManager> default_memory_manager() override;
int value() const { return value_; }
bool allow_copy() const { return value_ == kMyDeviceAllowCopy; }
bool allow_view() const { return value_ == kMyDeviceAllowView; }
protected:
int value_;
};
class MyMemoryManager : public MemoryManager {
public:
explicit MyMemoryManager(std::shared_ptr<Device> device) : MemoryManager(device) {}
bool allow_copy() const {
return checked_cast<const MyDevice&>(*device()).allow_copy();
}
bool allow_view() const {
return checked_cast<const MyDevice&>(*device()).allow_view();
}
Result<std::shared_ptr<io::RandomAccessFile>> GetBufferReader(
std::shared_ptr<Buffer> buf) override {
return Status::NotImplemented("");
}
Result<std::shared_ptr<Buffer>> AllocateBuffer(int64_t size) override {
return Status::NotImplemented("");
}
Result<std::shared_ptr<io::OutputStream>> GetBufferWriter(
std::shared_ptr<Buffer> buf) override {
return Status::NotImplemented("");
}
protected:
Result<std::shared_ptr<Buffer>> CopyBufferFrom(
const std::shared_ptr<Buffer>& buf,
const std::shared_ptr<MemoryManager>& from) override;
Result<std::shared_ptr<Buffer>> CopyBufferTo(
const std::shared_ptr<Buffer>& buf,
const std::shared_ptr<MemoryManager>& to) override;
Result<std::shared_ptr<Buffer>> ViewBufferFrom(
const std::shared_ptr<Buffer>& buf,
const std::shared_ptr<MemoryManager>& from) override;
Result<std::shared_ptr<Buffer>> ViewBufferTo(
const std::shared_ptr<Buffer>& buf,
const std::shared_ptr<MemoryManager>& to) override;
};
class MyBuffer : public Buffer {
public:
MyBuffer(std::shared_ptr<MemoryManager> mm, const std::shared_ptr<Buffer>& parent)
: Buffer(parent->data(), parent->size()) {
parent_ = parent;
SetMemoryManager(mm);
}
};
std::shared_ptr<MemoryManager> MyDevice::default_memory_manager() {
return std::make_shared<MyMemoryManager>(shared_from_this());
}
Result<std::shared_ptr<Buffer>> MyMemoryManager::CopyBufferFrom(
const std::shared_ptr<Buffer>& buf, const std::shared_ptr<MemoryManager>& from) {
if (!allow_copy()) {
return nullptr;
}
if (from->is_cpu()) {
// CPU to MyDevice:
// 1. CPU to CPU
ARROW_ASSIGN_OR_RAISE(auto dest,
MemoryManager::CopyBuffer(buf, default_cpu_memory_manager()));
// 2. Wrap CPU buffer result
return std::make_shared<MyBuffer>(shared_from_this(), dest);
}
return nullptr;
}
Result<std::shared_ptr<Buffer>> MyMemoryManager::CopyBufferTo(
const std::shared_ptr<Buffer>& buf, const std::shared_ptr<MemoryManager>& to) {
if (!allow_copy()) {
return nullptr;
}
if (to->is_cpu() && buf->parent()) {
// MyDevice to CPU
return MemoryManager::CopyBuffer(buf->parent(), to);
}
return nullptr;
}
Result<std::shared_ptr<Buffer>> MyMemoryManager::ViewBufferFrom(
const std::shared_ptr<Buffer>& buf, const std::shared_ptr<MemoryManager>& from) {
if (!allow_view()) {
return nullptr;
}
if (from->is_cpu()) {
// CPU on MyDevice: wrap CPU buffer
return std::make_shared<MyBuffer>(shared_from_this(), buf);
}
return nullptr;
}
Result<std::shared_ptr<Buffer>> MyMemoryManager::ViewBufferTo(
const std::shared_ptr<Buffer>& buf, const std::shared_ptr<MemoryManager>& to) {
if (!allow_view()) {
return nullptr;
}
if (to->is_cpu() && buf->parent()) {
// MyDevice on CPU: unwrap buffer
return buf->parent();
}
return nullptr;
}
// Like AssertBufferEqual, but doesn't call Buffer::data()
void AssertMyBufferEqual(const Buffer& buffer, util::string_view expected) {
ASSERT_EQ(util::string_view(buffer), expected);
}
void AssertIsCPUBuffer(const Buffer& buf) {
ASSERT_TRUE(buf.is_cpu());
ASSERT_EQ(*buf.device(), *CPUDevice::Instance());
}
class TestDevice : public ::testing::Test {
public:
void SetUp() {
cpu_device_ = CPUDevice::Instance();
my_copy_device_ = std::make_shared<MyDevice>(kMyDeviceAllowCopy);
my_view_device_ = std::make_shared<MyDevice>(kMyDeviceAllowView);
my_other_device_ = std::make_shared<MyDevice>(kMyDeviceDisallowCopyView);
cpu_mm_ = cpu_device_->default_memory_manager();
my_copy_mm_ = my_copy_device_->default_memory_manager();
my_view_mm_ = my_view_device_->default_memory_manager();
my_other_mm_ = my_other_device_->default_memory_manager();
cpu_src_ = Buffer::FromString("some data");
my_copy_src_ = std::make_shared<MyBuffer>(my_copy_mm_, cpu_src_);
my_view_src_ = std::make_shared<MyBuffer>(my_view_mm_, cpu_src_);
my_other_src_ = std::make_shared<MyBuffer>(my_other_mm_, cpu_src_);
}
protected:
std::shared_ptr<Device> cpu_device_, my_copy_device_, my_view_device_, my_other_device_;
std::shared_ptr<MemoryManager> cpu_mm_, my_copy_mm_, my_view_mm_, my_other_mm_;
std::shared_ptr<Buffer> cpu_src_, my_copy_src_, my_view_src_, my_other_src_;
};
TEST_F(TestDevice, Basics) {
ASSERT_TRUE(cpu_device_->is_cpu());
ASSERT_EQ(*cpu_device_, *cpu_device_);
ASSERT_EQ(*my_copy_device_, *my_copy_device_);
ASSERT_NE(*cpu_device_, *my_copy_device_);
ASSERT_NE(*my_copy_device_, *cpu_device_);
ASSERT_TRUE(cpu_mm_->is_cpu());
ASSERT_FALSE(my_copy_mm_->is_cpu());
ASSERT_FALSE(my_other_mm_->is_cpu());
}
TEST_F(TestDevice, Copy) {
// CPU-to-CPU
ASSERT_OK_AND_ASSIGN(auto buffer, MemoryManager::CopyBuffer(cpu_src_, cpu_mm_));
ASSERT_EQ(buffer->device(), cpu_device_);
ASSERT_TRUE(buffer->is_cpu());
ASSERT_NE(buffer->address(), cpu_src_->address());
ASSERT_NE(buffer->data(), nullptr);
AssertBufferEqual(*buffer, "some data");
// CPU-to-device
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::CopyBuffer(cpu_src_, my_copy_mm_));
ASSERT_EQ(buffer->device(), my_copy_device_);
ASSERT_FALSE(buffer->is_cpu());
ASSERT_NE(buffer->address(), cpu_src_->address());
#ifdef NDEBUG
ASSERT_EQ(buffer->data(), nullptr);
#endif
AssertMyBufferEqual(*buffer, "some data");
// Device-to-CPU
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::CopyBuffer(my_copy_src_, cpu_mm_));
ASSERT_EQ(buffer->device(), cpu_device_);
ASSERT_TRUE(buffer->is_cpu());
ASSERT_NE(buffer->address(), my_copy_src_->address());
ASSERT_NE(buffer->data(), nullptr);
AssertBufferEqual(*buffer, "some data");
// Device-to-device with an intermediate CPU copy
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::CopyBuffer(my_copy_src_, my_copy_mm_));
ASSERT_EQ(buffer->device(), my_copy_device_);
ASSERT_FALSE(buffer->is_cpu());
ASSERT_NE(buffer->address(), my_copy_src_->address());
#ifdef NDEBUG
ASSERT_EQ(buffer->data(), nullptr);
#endif
AssertMyBufferEqual(*buffer, "some data");
// Device-to-device with an intermediate view on CPU, then a copy from CPU to device
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::CopyBuffer(my_view_src_, my_copy_mm_));
ASSERT_EQ(buffer->device(), my_copy_device_);
ASSERT_FALSE(buffer->is_cpu());
ASSERT_NE(buffer->address(), my_copy_src_->address());
#ifdef NDEBUG
ASSERT_EQ(buffer->data(), nullptr);
#endif
AssertMyBufferEqual(*buffer, "some data");
ASSERT_RAISES(NotImplemented, MemoryManager::CopyBuffer(cpu_src_, my_other_mm_));
ASSERT_RAISES(NotImplemented, MemoryManager::CopyBuffer(my_other_src_, cpu_mm_));
}
TEST_F(TestDevice, View) {
// CPU-on-CPU
ASSERT_OK_AND_ASSIGN(auto buffer, MemoryManager::ViewBuffer(cpu_src_, cpu_mm_));
ASSERT_EQ(buffer->device(), cpu_device_);
ASSERT_TRUE(buffer->is_cpu());
ASSERT_EQ(buffer->address(), cpu_src_->address());
ASSERT_NE(buffer->data(), nullptr);
AssertBufferEqual(*buffer, "some data");
// CPU-on-device
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::ViewBuffer(cpu_src_, my_view_mm_));
ASSERT_EQ(buffer->device(), my_view_device_);
ASSERT_FALSE(buffer->is_cpu());
ASSERT_EQ(buffer->address(), cpu_src_->address());
#ifdef NDEBUG
ASSERT_EQ(buffer->data(), nullptr);
#endif
AssertMyBufferEqual(*buffer, "some data");
// Device-on-CPU
ASSERT_OK_AND_ASSIGN(buffer, MemoryManager::ViewBuffer(my_view_src_, cpu_mm_));
ASSERT_EQ(buffer->device(), cpu_device_);
ASSERT_TRUE(buffer->is_cpu());
ASSERT_EQ(buffer->address(), my_copy_src_->address());
ASSERT_NE(buffer->data(), nullptr);
AssertBufferEqual(*buffer, "some data");
ASSERT_RAISES(NotImplemented, MemoryManager::CopyBuffer(cpu_src_, my_other_mm_));
ASSERT_RAISES(NotImplemented, MemoryManager::CopyBuffer(my_other_src_, cpu_mm_));
}
TEST(TestAllocate, Basics) {
ASSERT_OK_AND_ASSIGN(auto new_buffer, AllocateBuffer(1024));
auto mm = new_buffer->memory_manager();
ASSERT_TRUE(mm->is_cpu());
ASSERT_EQ(mm.get(), default_cpu_memory_manager().get());
auto cpu_mm = checked_pointer_cast<CPUMemoryManager>(mm);
ASSERT_EQ(cpu_mm->pool(), default_memory_pool());
auto pool = std::make_shared<ProxyMemoryPool>(default_memory_pool());
ASSERT_OK_AND_ASSIGN(new_buffer, AllocateBuffer(1024, pool.get()));
mm = new_buffer->memory_manager();
ASSERT_TRUE(mm->is_cpu());
cpu_mm = checked_pointer_cast<CPUMemoryManager>(mm);
ASSERT_EQ(cpu_mm->pool(), pool.get());
new_buffer.reset(); // Destroy before pool
}
TEST(TestAllocate, Bitmap) {
ASSERT_OK_AND_ASSIGN(auto new_buffer, AllocateBitmap(100));
AssertIsCPUBuffer(*new_buffer);
EXPECT_GE(new_buffer->size(), 13);
EXPECT_EQ(new_buffer->capacity() % 8, 0);
}
TEST(TestAllocate, EmptyBitmap) {
ASSERT_OK_AND_ASSIGN(auto new_buffer, AllocateEmptyBitmap(100));
AssertIsCPUBuffer(*new_buffer);
EXPECT_EQ(new_buffer->size(), 13);
EXPECT_EQ(new_buffer->capacity() % 8, 0);
EXPECT_TRUE(std::all_of(new_buffer->data(), new_buffer->data() + new_buffer->capacity(),
[](int8_t byte) { return byte == 0; }));
}
TEST(TestBuffer, FromStdString) {
std::string val = "hello, world";
Buffer buf(val);
AssertIsCPUBuffer(buf);
ASSERT_EQ(0, memcmp(buf.data(), val.c_str(), val.size()));
ASSERT_EQ(static_cast<int64_t>(val.size()), buf.size());
}
TEST(TestBuffer, FromStdStringWithMemory) {
std::string expected = "hello, world";
std::shared_ptr<Buffer> buf;
{
std::string temp = "hello, world";
buf = Buffer::FromString(temp);
AssertIsCPUBuffer(*buf);
ASSERT_EQ(0, memcmp(buf->data(), temp.c_str(), temp.size()));
ASSERT_EQ(static_cast<int64_t>(temp.size()), buf->size());
}
// Now temp goes out of scope and we check if created buffer
// is still valid to make sure it actually owns its space
ASSERT_EQ(0, memcmp(buf->data(), expected.c_str(), expected.size()));
ASSERT_EQ(static_cast<int64_t>(expected.size()), buf->size());
}
TEST(TestBuffer, EqualsWithSameContent) {
MemoryPool* pool = default_memory_pool();
const int32_t bufferSize = 128 * 1024;
uint8_t* rawBuffer1;
ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer1));
memset(rawBuffer1, 12, bufferSize);
uint8_t* rawBuffer2;
ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer2));
memset(rawBuffer2, 12, bufferSize);
uint8_t* rawBuffer3;
ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer3));
memset(rawBuffer3, 3, bufferSize);
Buffer buffer1(rawBuffer1, bufferSize);
Buffer buffer2(rawBuffer2, bufferSize);
Buffer buffer3(rawBuffer3, bufferSize);
ASSERT_TRUE(buffer1.Equals(buffer2));
ASSERT_FALSE(buffer1.Equals(buffer3));
pool->Free(rawBuffer1, bufferSize);
pool->Free(rawBuffer2, bufferSize);
pool->Free(rawBuffer3, bufferSize);
}
TEST(TestBuffer, EqualsWithSameBuffer) {
MemoryPool* pool = default_memory_pool();
const int32_t bufferSize = 128 * 1024;
uint8_t* rawBuffer;
ASSERT_OK(pool->Allocate(bufferSize, &rawBuffer));
memset(rawBuffer, 111, bufferSize);
Buffer buffer1(rawBuffer, bufferSize);
Buffer buffer2(rawBuffer, bufferSize);
ASSERT_TRUE(buffer1.Equals(buffer2));
const int64_t nbytes = bufferSize / 2;
Buffer buffer3(rawBuffer, nbytes);
ASSERT_TRUE(buffer1.Equals(buffer3, nbytes));
ASSERT_FALSE(buffer1.Equals(buffer3, nbytes + 1));
pool->Free(rawBuffer, bufferSize);
}
TEST(TestBuffer, CopySlice) {
std::string data_str = "some data to copy";
auto data = reinterpret_cast<const uint8_t*>(data_str.c_str());
Buffer buf(data, data_str.size());
ASSERT_OK_AND_ASSIGN(auto out, buf.CopySlice(5, 4));
AssertIsCPUBuffer(*out);
Buffer expected(data + 5, 4);
ASSERT_TRUE(out->Equals(expected));
// assert the padding is zeroed
std::vector<uint8_t> zeros(out->capacity() - out->size());
ASSERT_EQ(0, memcmp(out->data() + out->size(), zeros.data(), zeros.size()));
}
TEST(TestBuffer, CopySliceEmpty) {
auto buf = std::make_shared<Buffer>("");
ASSERT_OK_AND_ASSIGN(auto out, buf->CopySlice(0, 0));
AssertBufferEqual(*out, "");
buf = std::make_shared<Buffer>("1234");
ASSERT_OK_AND_ASSIGN(out, buf->CopySlice(0, 0));
AssertBufferEqual(*out, "");
ASSERT_OK_AND_ASSIGN(out, buf->CopySlice(4, 0));
AssertBufferEqual(*out, "");
}
TEST(TestBuffer, ToHexString) {
const uint8_t data_array[] = "\a0hex string\xa9";
std::basic_string<uint8_t> data_str = data_array;
auto data = reinterpret_cast<const uint8_t*>(data_str.c_str());
Buffer buf(data, data_str.size());
ASSERT_EQ(buf.ToHexString(), std::string("073068657820737472696E67A9"));
}
TEST(TestBuffer, SliceBuffer) {
std::string data_str = "some data to slice";
auto data = reinterpret_cast<const uint8_t*>(data_str.c_str());
auto buf = std::make_shared<Buffer>(data, data_str.size());
std::shared_ptr<Buffer> out = SliceBuffer(buf, 5, 4);
AssertIsCPUBuffer(*out);
Buffer expected(data + 5, 4);
ASSERT_TRUE(out->Equals(expected));
ASSERT_EQ(2, buf.use_count());
}
TEST(TestMutableBuffer, Wrap) {
std::vector<int32_t> values = {1, 2, 3};
auto buf = MutableBuffer::Wrap(values.data(), values.size());
AssertIsCPUBuffer(*buf);
reinterpret_cast<int32_t*>(buf->mutable_data())[1] = 4;
ASSERT_EQ(4, values[1]);
}
TEST(TestBuffer, FromStringRvalue) {
std::string expected = "input data";
std::shared_ptr<Buffer> buffer;
{
std::string data_str = "input data";
buffer = Buffer::FromString(std::move(data_str));
AssertIsCPUBuffer(*buffer);
}
ASSERT_FALSE(buffer->is_mutable());
ASSERT_EQ(0, memcmp(buffer->data(), expected.c_str(), expected.size()));
ASSERT_EQ(static_cast<int64_t>(expected.size()), buffer->size());
}
TEST(TestBuffer, SliceMutableBuffer) {
std::string data_str = "some data to slice";
auto data = reinterpret_cast<const uint8_t*>(data_str.c_str());
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Buffer> buffer, AllocateBuffer(50));
memcpy(buffer->mutable_data(), data, data_str.size());
std::shared_ptr<Buffer> slice = SliceMutableBuffer(buffer, 5, 10);
AssertIsCPUBuffer(*slice);
ASSERT_TRUE(slice->is_mutable());
ASSERT_EQ(10, slice->size());
Buffer expected(data + 5, 10);
ASSERT_TRUE(slice->Equals(expected));
}
TEST(TestBuffer, GetReader) {
const std::string data_str = "some data to read";
auto data = reinterpret_cast<const uint8_t*>(data_str.c_str());
auto buf = std::make_shared<Buffer>(data, data_str.size());
ASSERT_OK_AND_ASSIGN(auto reader, Buffer::GetReader(buf));
ASSERT_OK_AND_EQ(static_cast<int64_t>(data_str.size()), reader->GetSize());
ASSERT_OK_AND_ASSIGN(auto read_buf, reader->ReadAt(5, 4));
AssertBufferEqual(*read_buf, "data");
}
TEST(TestBuffer, GetWriter) {
ASSERT_OK_AND_ASSIGN(std::shared_ptr<Buffer> buf, AllocateBuffer(9));
ASSERT_OK_AND_ASSIGN(auto writer, Buffer::GetWriter(buf));
ASSERT_OK(writer->Write(reinterpret_cast<const uint8_t*>("some data"), 9));
AssertBufferEqual(*buf, "some data");
// Non-mutable buffer
buf = std::make_shared<Buffer>(reinterpret_cast<const uint8_t*>("xxx"), 3);
ASSERT_RAISES(Invalid, Buffer::GetWriter(buf));
}
template <typename AllocateFunction>
void TestZeroSizeAllocateBuffer(MemoryPool* pool, AllocateFunction&& allocate_func) {
auto allocated_bytes = pool->bytes_allocated();
{
std::shared_ptr<Buffer> buffer, buffer2;
ASSERT_OK(allocate_func(pool, 0, &buffer));
AssertIsCPUBuffer(*buffer);
ASSERT_EQ(buffer->size(), 0);
// Even 0-sized buffers should not have a null data pointer
auto data = buffer->data();
ASSERT_NE(data, nullptr);
ASSERT_EQ(buffer->mutable_data(), data);
// As an optimization, another 0-size buffer should share the same memory "area"
ASSERT_OK(allocate_func(pool, 0, &buffer2));
AssertIsCPUBuffer(*buffer2);
ASSERT_EQ(buffer2->size(), 0);
ASSERT_EQ(buffer2->data(), data);
ASSERT_GE(pool->bytes_allocated(), allocated_bytes);
}
ASSERT_EQ(pool->bytes_allocated(), allocated_bytes);
}
TEST(TestAllocateBuffer, ZeroSize) {
MemoryPool* pool = default_memory_pool();
auto allocate_func = [](MemoryPool* pool, int64_t size, std::shared_ptr<Buffer>* out) {
return AllocateBuffer(size, pool).Value(out);
};
TestZeroSizeAllocateBuffer(pool, allocate_func);
}
TEST(TestAllocateResizableBuffer, ZeroSize) {
MemoryPool* pool = default_memory_pool();
auto allocate_func = [](MemoryPool* pool, int64_t size, std::shared_ptr<Buffer>* out) {
ARROW_ASSIGN_OR_RAISE(auto resizable, AllocateResizableBuffer(size, pool));
*out = std::move(resizable);
return Status::OK();
};
TestZeroSizeAllocateBuffer(pool, allocate_func);
}
TEST(TestAllocateResizableBuffer, ZeroResize) {
MemoryPool* pool = default_memory_pool();
auto allocated_bytes = pool->bytes_allocated();
{
std::shared_ptr<ResizableBuffer> buffer;
ASSERT_OK_AND_ASSIGN(buffer, AllocateResizableBuffer(1000, pool));
ASSERT_EQ(buffer->size(), 1000);
ASSERT_NE(buffer->data(), nullptr);
ASSERT_EQ(buffer->mutable_data(), buffer->data());
ASSERT_GE(pool->bytes_allocated(), allocated_bytes + 1000);
ASSERT_OK(buffer->Resize(0));
ASSERT_NE(buffer->data(), nullptr);
ASSERT_EQ(buffer->mutable_data(), buffer->data());
ASSERT_GE(pool->bytes_allocated(), allocated_bytes);
ASSERT_LT(pool->bytes_allocated(), allocated_bytes + 1000);
}
ASSERT_EQ(pool->bytes_allocated(), allocated_bytes);
}
TEST(TestBufferBuilder, ResizeReserve) {
const std::string data = "some data";
auto data_ptr = data.c_str();
BufferBuilder builder;
ASSERT_OK(builder.Append(data_ptr, 9));
ASSERT_EQ(9, builder.length());
ASSERT_OK(builder.Resize(128));
ASSERT_EQ(128, builder.capacity());
// Do not shrink to fit
ASSERT_OK(builder.Resize(64, false));
ASSERT_EQ(128, builder.capacity());
// Shrink to fit
ASSERT_OK(builder.Resize(64));
ASSERT_EQ(64, builder.capacity());
// Reserve elements
ASSERT_OK(builder.Reserve(60));
ASSERT_EQ(128, builder.capacity());
}
template <typename T>
class TypedTestBufferBuilder : public ::testing::Test {};
using BufferBuilderElements = ::testing::Types<int16_t, uint32_t, double>;
TYPED_TEST_SUITE(TypedTestBufferBuilder, BufferBuilderElements);
TYPED_TEST(TypedTestBufferBuilder, BasicTypedBufferBuilderUsage) {
TypedBufferBuilder<TypeParam> builder;
ASSERT_OK(builder.Append(static_cast<TypeParam>(0)));
ASSERT_EQ(builder.length(), 1);
ASSERT_EQ(builder.capacity(), 64 / sizeof(TypeParam));
constexpr int nvalues = 4;
TypeParam values[nvalues];
for (int i = 0; i != nvalues; ++i) {
values[i] = static_cast<TypeParam>(i);
}
ASSERT_OK(builder.Append(values, nvalues));
ASSERT_EQ(builder.length(), nvalues + 1);
std::shared_ptr<Buffer> built;
ASSERT_OK(builder.Finish(&built));
AssertIsCPUBuffer(*built);
auto data = reinterpret_cast<const TypeParam*>(built->data());
ASSERT_EQ(data[0], static_cast<TypeParam>(0));
for (auto value : values) {
++data;
ASSERT_EQ(*data, value);
}
}
TYPED_TEST(TypedTestBufferBuilder, AppendCopies) {
TypedBufferBuilder<TypeParam> builder;
ASSERT_OK(builder.Append(13, static_cast<TypeParam>(1)));
ASSERT_OK(builder.Append(17, static_cast<TypeParam>(0)));
ASSERT_EQ(builder.length(), 13 + 17);
std::shared_ptr<Buffer> built;
ASSERT_OK(builder.Finish(&built));
auto data = reinterpret_cast<const TypeParam*>(built->data());
for (int i = 0; i != 13 + 17; ++i, ++data) {
ASSERT_EQ(*data, static_cast<TypeParam>(i < 13)) << "index = " << i;
}
}
TEST(TestBufferBuilder, BasicBoolBufferBuilderUsage) {
TypedBufferBuilder<bool> builder;
ASSERT_OK(builder.Append(false));
ASSERT_EQ(builder.length(), 1);
ASSERT_EQ(builder.capacity(), 64 * 8);
constexpr int nvalues = 4;
uint8_t values[nvalues];
for (int i = 0; i != nvalues; ++i) {
values[i] = static_cast<uint8_t>(i);
}
ASSERT_OK(builder.Append(values, nvalues));
ASSERT_EQ(builder.length(), nvalues + 1);
ASSERT_EQ(builder.false_count(), 2);
std::shared_ptr<Buffer> built;
ASSERT_OK(builder.Finish(&built));
AssertIsCPUBuffer(*built);
ASSERT_EQ(BitUtil::GetBit(built->data(), 0), false);
for (int i = 0; i != nvalues; ++i) {
ASSERT_EQ(BitUtil::GetBit(built->data(), i + 1), static_cast<bool>(values[i]));
}
ASSERT_EQ(built->size(), BitUtil::BytesForBits(nvalues + 1));
}
TEST(TestBufferBuilder, BoolBufferBuilderAppendCopies) {
TypedBufferBuilder<bool> builder;
ASSERT_OK(builder.Append(13, true));
ASSERT_OK(builder.Append(17, false));
ASSERT_EQ(builder.length(), 13 + 17);
ASSERT_EQ(builder.capacity(), 64 * 8);
ASSERT_EQ(builder.false_count(), 17);
std::shared_ptr<Buffer> built;
ASSERT_OK(builder.Finish(&built));
AssertIsCPUBuffer(*built);
for (int i = 0; i != 13 + 17; ++i) {
EXPECT_EQ(BitUtil::GetBit(built->data(), i), i < 13) << "index = " << i;
}
ASSERT_EQ(built->size(), BitUtil::BytesForBits(13 + 17));
}
template <typename T>
class TypedTestBuffer : public ::testing::Test {};
using BufferPtrs =
::testing::Types<std::shared_ptr<ResizableBuffer>, std::unique_ptr<ResizableBuffer>>;
TYPED_TEST_SUITE(TypedTestBuffer, BufferPtrs);
TYPED_TEST(TypedTestBuffer, IsMutableFlag) {
Buffer buf(nullptr, 0);
ASSERT_FALSE(buf.is_mutable());
MutableBuffer mbuf(nullptr, 0);
ASSERT_TRUE(mbuf.is_mutable());
AssertIsCPUBuffer(mbuf);
TypeParam pool_buf;
ASSERT_OK_AND_ASSIGN(pool_buf, AllocateResizableBuffer(0));
ASSERT_TRUE(pool_buf->is_mutable());
AssertIsCPUBuffer(*pool_buf);
}
TYPED_TEST(TypedTestBuffer, Resize) {
TypeParam buf;
ASSERT_OK_AND_ASSIGN(buf, AllocateResizableBuffer(0));
AssertIsCPUBuffer(*buf);
ASSERT_EQ(0, buf->size());
ASSERT_OK(buf->Resize(100));
ASSERT_EQ(100, buf->size());
ASSERT_OK(buf->Resize(200));
ASSERT_EQ(200, buf->size());
// Make it smaller, too
ASSERT_OK(buf->Resize(50, true));
ASSERT_EQ(50, buf->size());
// We have actually shrunken in size
// The spec requires that capacity is a multiple of 64
ASSERT_EQ(64, buf->capacity());
// Resize to a larger capacity again to test shrink_to_fit = false
ASSERT_OK(buf->Resize(100));
ASSERT_EQ(128, buf->capacity());
ASSERT_OK(buf->Resize(50, false));
ASSERT_EQ(128, buf->capacity());
}
TYPED_TEST(TypedTestBuffer, TypedResize) {
TypeParam buf;
ASSERT_OK_AND_ASSIGN(buf, AllocateResizableBuffer(0));
ASSERT_EQ(0, buf->size());
ASSERT_OK(buf->template TypedResize<double>(100));
ASSERT_EQ(800, buf->size());
ASSERT_OK(buf->template TypedResize<double>(200));
ASSERT_EQ(1600, buf->size());
ASSERT_OK(buf->template TypedResize<double>(50, true));
ASSERT_EQ(400, buf->size());
ASSERT_EQ(448, buf->capacity());
ASSERT_OK(buf->template TypedResize<double>(100));
ASSERT_EQ(832, buf->capacity());
ASSERT_OK(buf->template TypedResize<double>(50, false));
ASSERT_EQ(832, buf->capacity());
}
TYPED_TEST(TypedTestBuffer, ResizeOOM) {
// This test doesn't play nice with AddressSanitizer
#ifndef ADDRESS_SANITIZER
// realloc fails, even though there may be no explicit limit
TypeParam buf;
ASSERT_OK_AND_ASSIGN(buf, AllocateResizableBuffer(0));
ASSERT_OK(buf->Resize(100));
int64_t to_alloc = std::min<uint64_t>(std::numeric_limits<int64_t>::max(),
std::numeric_limits<size_t>::max());
// subtract 63 to prevent overflow after the size is aligned
to_alloc -= 63;
ASSERT_RAISES(OutOfMemory, buf->Resize(to_alloc));
#endif
}
} // namespace arrow
|
// Copyright (c) 2009-2018 The Bitcoin Core developers
// Copyright (c) 2021 The ogfuncoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include <config/ogfuncoin-config.h>
#endif
#include <consensus/merkle.h>
#include <primitives/block.h>
#include <script/script.h>
#include <addrman.h>
#include <chain.h>
#include <coins.h>
#include <compressor.h>
#include <net.h>
#include <protocol.h>
#include <streams.h>
#include <undo.h>
#include <version.h>
#include <pubkey.h>
#include <blockencodings.h>
#include <stdint.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
#include <vector>
enum TEST_ID {
CBLOCK_DESERIALIZE=0,
CTRANSACTION_DESERIALIZE,
CBLOCKLOCATOR_DESERIALIZE,
CBLOCKMERKLEROOT,
CADDRMAN_DESERIALIZE,
CBLOCKHEADER_DESERIALIZE,
CBANENTRY_DESERIALIZE,
CTXUNDO_DESERIALIZE,
CBLOCKUNDO_DESERIALIZE,
CCOINS_DESERIALIZE,
CNETADDR_DESERIALIZE,
CSERVICE_DESERIALIZE,
CMESSAGEHEADER_DESERIALIZE,
CADDRESS_DESERIALIZE,
CINV_DESERIALIZE,
CBLOOMFILTER_DESERIALIZE,
CDISKBLOCKINDEX_DESERIALIZE,
CTXOUTCOMPRESSOR_DESERIALIZE,
BLOCKTRANSACTIONS_DESERIALIZE,
BLOCKTRANSACTIONSREQUEST_DESERIALIZE,
TEST_ID_END
};
static bool read_stdin(std::vector<uint8_t> &data) {
uint8_t buffer[1024];
ssize_t length=0;
while((length = read(STDIN_FILENO, buffer, 1024)) > 0) {
data.insert(data.end(), buffer, buffer+length);
if (data.size() > (1<<20)) return false;
}
return length==0;
}
static int test_one_input(std::vector<uint8_t> buffer) {
if (buffer.size() < sizeof(uint32_t)) return 0;
uint32_t test_id = 0xffffffff;
memcpy(&test_id, buffer.data(), sizeof(uint32_t));
buffer.erase(buffer.begin(), buffer.begin() + sizeof(uint32_t));
if (test_id >= TEST_ID_END) return 0;
CDataStream ds(buffer, SER_NETWORK, INIT_PROTO_VERSION);
try {
int nVersion;
ds >> nVersion;
ds.SetVersion(nVersion);
} catch (const std::ios_base::failure& e) {
return 0;
}
switch(test_id) {
case CBLOCK_DESERIALIZE:
{
try
{
CBlock block;
ds >> block;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTRANSACTION_DESERIALIZE:
{
try
{
CTransaction tx(deserialize, ds);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKLOCATOR_DESERIALIZE:
{
try
{
CBlockLocator bl;
ds >> bl;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKMERKLEROOT:
{
try
{
CBlock block;
ds >> block;
bool mutated;
BlockMerkleRoot(block, &mutated);
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRMAN_DESERIALIZE:
{
try
{
CAddrMan am;
ds >> am;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKHEADER_DESERIALIZE:
{
try
{
CBlockHeader bh;
ds >> bh;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBANENTRY_DESERIALIZE:
{
try
{
CBanEntry be;
ds >> be;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXUNDO_DESERIALIZE:
{
try
{
CTxUndo tu;
ds >> tu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOCKUNDO_DESERIALIZE:
{
try
{
CBlockUndo bu;
ds >> bu;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CCOINS_DESERIALIZE:
{
try
{
Coin coin;
ds >> coin;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CNETADDR_DESERIALIZE:
{
try
{
CNetAddr na;
ds >> na;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CSERVICE_DESERIALIZE:
{
try
{
CService s;
ds >> s;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CMESSAGEHEADER_DESERIALIZE:
{
CMessageHeader::MessageStartChars pchMessageStart = {0x00, 0x00, 0x00, 0x00};
try
{
CMessageHeader mh(pchMessageStart);
ds >> mh;
if (!mh.IsValid(pchMessageStart)) {return 0;}
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CADDRESS_DESERIALIZE:
{
try
{
CAddress a;
ds >> a;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CINV_DESERIALIZE:
{
try
{
CInv i;
ds >> i;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CBLOOMFILTER_DESERIALIZE:
{
try
{
CBloomFilter bf;
ds >> bf;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CDISKBLOCKINDEX_DESERIALIZE:
{
try
{
CDiskBlockIndex dbi;
ds >> dbi;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case CTXOUTCOMPRESSOR_DESERIALIZE:
{
CTxOut to;
CTxOutCompressor toc(to);
try
{
ds >> toc;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case BLOCKTRANSACTIONS_DESERIALIZE:
{
try
{
BlockTransactions bt;
ds >> bt;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
case BLOCKTRANSACTIONSREQUEST_DESERIALIZE:
{
try
{
BlockTransactionsRequest btr;
ds >> btr;
} catch (const std::ios_base::failure& e) {return 0;}
break;
}
default:
return 0;
}
return 0;
}
static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle;
void initialize() {
globalVerifyHandle = std::unique_ptr<ECCVerifyHandle>(new ECCVerifyHandle());
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
test_one_input(std::vector<uint8_t>(data, data + size));
return 0;
}
// This function is used by libFuzzer
extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) {
initialize();
return 0;
}
// Disabled under WIN32 due to clash with Cygwin's WinMain.
#ifndef WIN32
// Declare main(...) "weak" to allow for libFuzzer linking. libFuzzer provides
// the main(...) function.
__attribute__((weak))
#endif
int main(int argc, char **argv)
{
initialize();
#ifdef __AFL_INIT
// Enable AFL deferred forkserver mode. Requires compilation using
// afl-clang-fast++. See fuzzing.md for details.
__AFL_INIT();
#endif
#ifdef __AFL_LOOP
// Enable AFL persistent mode. Requires compilation using afl-clang-fast++.
// See fuzzing.md for details.
int ret = 0;
while (__AFL_LOOP(1000)) {
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
continue;
}
ret = test_one_input(buffer);
}
return ret;
#else
std::vector<uint8_t> buffer;
if (!read_stdin(buffer)) {
return 0;
}
return test_one_input(buffer);
#endif
}
|
//===- LLVMDialect.cpp - MLIR SPIR-V dialect ------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the SPIR-V dialect in MLIR.
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/SPIRV/SPIRVDialect.h"
#include "mlir/Dialect/SPIRV/SPIRVOps.h"
#include "mlir/Dialect/SPIRV/SPIRVTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/StandardTypes.h"
#include "mlir/Parser.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/Sequence.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/raw_ostream.h"
namespace mlir {
namespace spirv {
#include "mlir/Dialect/SPIRV/SPIRVOpUtils.inc"
} // namespace spirv
} // namespace mlir
using namespace mlir;
using namespace mlir::spirv;
//===----------------------------------------------------------------------===//
// SPIR-V Dialect
//===----------------------------------------------------------------------===//
SPIRVDialect::SPIRVDialect(MLIRContext *context)
: Dialect(getDialectNamespace(), context) {
addTypes<ArrayType, ImageType, PointerType, RuntimeArrayType, StructType>();
addOperations<
#define GET_OP_LIST
#include "mlir/Dialect/SPIRV/SPIRVOps.cpp.inc"
>();
// Allow unknown operations because SPIR-V is extensible.
allowUnknownOperations();
}
//===----------------------------------------------------------------------===//
// Type Parsing
//===----------------------------------------------------------------------===//
// Parses "<number> x" from the beginning of `spec`.
static bool parseNumberX(StringRef &spec, int64_t &number) {
spec = spec.ltrim();
if (spec.empty() || !llvm::isDigit(spec.front()))
return false;
number = 0;
do {
number = number * 10 + spec.front() - '0';
spec = spec.drop_front();
} while (!spec.empty() && llvm::isDigit(spec.front()));
spec = spec.ltrim();
if (!spec.consume_front("x"))
return false;
return true;
}
static bool isValidSPIRVScalarType(Type type) {
if (type.isa<FloatType>()) {
return !type.isBF16();
}
if (auto intType = type.dyn_cast<IntegerType>()) {
return llvm::is_contained(llvm::ArrayRef<unsigned>({1, 8, 16, 32, 64}),
intType.getWidth());
}
return false;
}
bool SPIRVDialect::isValidSPIRVType(Type type) const {
// Allow SPIR-V dialect types
if (&type.getDialect() == this) {
return true;
}
if (isValidSPIRVScalarType(type)) {
return true;
}
if (auto vectorType = type.dyn_cast<VectorType>()) {
return (isValidSPIRVScalarType(vectorType.getElementType()) &&
vectorType.getNumElements() >= 2 &&
vectorType.getNumElements() <= 4);
}
return false;
}
static Type parseAndVerifyType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
spec = spec.trim();
auto *context = dialect.getContext();
auto type = mlir::parseType(spec.trim(), context);
if (!type) {
emitError(loc, "cannot parse type: ") << spec;
return Type();
}
// Allow SPIR-V dialect types
if (&type.getDialect() == &dialect)
return type;
// Check other allowed types
if (auto t = type.dyn_cast<FloatType>()) {
if (type.isBF16()) {
emitError(loc, "cannot use 'bf16' to compose SPIR-V types");
return Type();
}
} else if (auto t = type.dyn_cast<IntegerType>()) {
if (!llvm::is_contained(llvm::ArrayRef<unsigned>({8, 16, 32, 64}),
t.getWidth())) {
emitError(loc, "only 8/16/32/64-bit integer type allowed but found ")
<< type;
return Type();
}
} else if (auto t = type.dyn_cast<VectorType>()) {
if (t.getRank() != 1) {
emitError(loc, "only 1-D vector allowed but found ") << t;
return Type();
}
if (t.getNumElements() > 4) {
emitError(loc,
"vector length has to be less than or equal to 4 but found ")
<< t.getNumElements();
return Type();
}
} else {
emitError(loc, "cannot use ") << type << " to compose SPIR-V types";
return Type();
}
return type;
}
// element-type ::= integer-type
// | floating-point-type
// | vector-type
// | spirv-type
//
// array-type ::= `!spv.array<` integer-literal `x` element-type `>`
static Type parseArrayType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
if (!spec.consume_front("array<") || !spec.consume_back(">")) {
emitError(loc, "spv.array delimiter <...> mismatch");
return Type();
}
int64_t count = 0;
spec = spec.trim();
if (!parseNumberX(spec, count)) {
emitError(loc, "expected array element count followed by 'x' but found '")
<< spec << "'";
return Type();
}
if (spec.trim().empty()) {
emitError(loc, "expected element type");
return Type();
}
Type elementType = parseAndVerifyType(dialect, spec, loc);
if (!elementType)
return Type();
return ArrayType::get(elementType, count);
}
// TODO(ravishankarm) : Reorder methods to be utilities first and parse*Type
// methods in alphabetical order
//
// storage-class ::= `UniformConstant`
// | `Uniform`
// | `Workgroup`
// | <and other storage classes...>
//
// pointer-type ::= `!spv.ptr<` element-type `,` storage-class `>`
static Type parsePointerType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
if (!spec.consume_front("ptr<") || !spec.consume_back(">")) {
emitError(loc, "spv.ptr delimiter <...> mismatch");
return Type();
}
// Split into pointee type and storage class
StringRef scSpec, ptSpec;
std::tie(ptSpec, scSpec) = spec.rsplit(',');
if (scSpec.empty()) {
emitError(loc,
"expected comma to separate pointee type and storage class in '")
<< spec << "'";
return Type();
}
scSpec = scSpec.trim();
auto storageClass = symbolizeStorageClass(scSpec);
if (!storageClass) {
emitError(loc, "unknown storage class: ") << scSpec;
return Type();
}
if (ptSpec.trim().empty()) {
emitError(loc, "expected pointee type");
return Type();
}
auto pointeeType = parseAndVerifyType(dialect, ptSpec, loc);
if (!pointeeType)
return Type();
return PointerType::get(pointeeType, *storageClass);
}
// runtime-array-type ::= `!spv.rtarray<` element-type `>`
static Type parseRuntimeArrayType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
if (!spec.consume_front("rtarray<") || !spec.consume_back(">")) {
emitError(loc, "spv.rtarray delimiter <...> mismatch");
return Type();
}
if (spec.trim().empty()) {
emitError(loc, "expected element type");
return Type();
}
Type elementType = parseAndVerifyType(dialect, spec, loc);
if (!elementType)
return Type();
return RuntimeArrayType::get(elementType);
}
// Specialize this function to parse each of the parameters that define an
// ImageType. By default it assumes this is an enum type.
template <typename ValTy>
static Optional<ValTy> parseAndVerify(SPIRVDialect const &dialect, Location loc,
StringRef spec) {
auto val = spirv::symbolizeEnum<ValTy>()(spec);
if (!val) {
emitError(loc, "unknown attribute: '") << spec << "'";
}
return val;
}
template <>
Optional<Type> parseAndVerify<Type>(SPIRVDialect const &dialect, Location loc,
StringRef spec) {
// TODO(ravishankarm): Further verify that the element type can be sampled
auto ty = parseAndVerifyType(dialect, spec, loc);
if (!ty) {
return llvm::None;
}
return ty;
}
template <>
Optional<spirv::StructType::LayoutInfo>
parseAndVerify(SPIRVDialect const &dialect, Location loc, StringRef spec) {
uint64_t offsetVal = std::numeric_limits<uint64_t>::max();
if (!spec.consume_front("[")) {
emitError(loc, "expected '[' while parsing layout specification in '")
<< spec << "'";
return llvm::None;
}
if (spec.consumeInteger(10, offsetVal)) {
emitError(
loc,
"expected unsigned integer to specify offset of member in struct: '")
<< spec << "'";
return llvm::None;
}
spec = spec.trim();
if (!spec.consume_front("]")) {
emitError(loc, "missing ']' in decorations spec: '") << spec << "'";
return llvm::None;
}
if (spec != "") {
emitError(loc, "unexpected extra tokens in layout information: '")
<< spec << "'";
return llvm::None;
}
return spirv::StructType::LayoutInfo{offsetVal};
}
// Functor object to parse a comma separated list of specs. The function
// parseAndVerify does the actual parsing and verification of individual
// elements. This is a functor since parsing the last element of the list
// (termination condition) needs partial specialization.
template <typename ParseType, typename... Args> struct parseCommaSeparatedList {
Optional<std::tuple<ParseType, Args...>>
operator()(SPIRVDialect const &dialect, Location loc, StringRef spec) const {
auto numArgs = std::tuple_size<std::tuple<Args...>>::value;
StringRef parseSpec, restSpec;
std::tie(parseSpec, restSpec) = spec.split(',');
parseSpec = parseSpec.trim();
if (numArgs != 0 && restSpec.empty()) {
emitError(loc, "expected more parameters for image type '")
<< parseSpec << "'";
return llvm::None;
}
auto parseVal = parseAndVerify<ParseType>(dialect, loc, parseSpec);
if (!parseVal) {
return llvm::None;
}
auto remainingValues =
parseCommaSeparatedList<Args...>{}(dialect, loc, restSpec);
if (!remainingValues) {
return llvm::None;
}
return std::tuple_cat(std::tuple<ParseType>(parseVal.getValue()),
remainingValues.getValue());
}
};
// Partial specialization of the function to parse a comma separated list of
// specs to parse the last element of the list.
template <typename ParseType> struct parseCommaSeparatedList<ParseType> {
Optional<std::tuple<ParseType>>
operator()(SPIRVDialect const &dialect, Location loc, StringRef spec) const {
spec = spec.trim();
auto value = parseAndVerify<ParseType>(dialect, loc, spec);
if (!value) {
return llvm::None;
}
return std::tuple<ParseType>(value.getValue());
}
};
// dim ::= `1D` | `2D` | `3D` | `Cube` | <and other SPIR-V Dim specifiers...>
//
// depth-info ::= `NoDepth` | `IsDepth` | `DepthUnknown`
//
// arrayed-info ::= `NonArrayed` | `Arrayed`
//
// sampling-info ::= `SingleSampled` | `MultiSampled`
//
// sampler-use-info ::= `SamplerUnknown` | `NeedSampler` | `NoSampler`
//
// format ::= `Unknown` | `Rgba32f` | <and other SPIR-V Image formats...>
//
// image-type ::= `!spv.image<` element-type `,` dim `,` depth-info `,`
// arrayed-info `,` sampling-info `,`
// sampler-use-info `,` format `>`
static Type parseImageType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
if (!spec.consume_front("image<") || !spec.consume_back(">")) {
emitError(loc, "spv.image delimiter <...> mismatch");
return Type();
}
auto value =
parseCommaSeparatedList<Type, Dim, ImageDepthInfo, ImageArrayedInfo,
ImageSamplingInfo, ImageSamplerUseInfo,
ImageFormat>{}(dialect, loc, spec);
if (!value) {
return Type();
}
return ImageType::get(value.getValue());
}
// Method to parse one member of a struct (including Layout information)
static ParseResult
parseStructElement(SPIRVDialect const &dialect, StringRef spec, Location loc,
SmallVectorImpl<Type> &memberTypes,
SmallVectorImpl<StructType::LayoutInfo> &layoutInfo) {
// Check for a '[' <layoutInfo> ']'
auto lastLSquare = spec.rfind('[');
auto typeSpec = spec.substr(0, lastLSquare);
auto layoutSpec = (lastLSquare == StringRef::npos ? StringRef("")
: spec.substr(lastLSquare));
auto type = parseAndVerify<Type>(dialect, loc, typeSpec);
if (!type) {
return failure();
}
memberTypes.push_back(type.getValue());
if (layoutSpec.empty()) {
return success();
}
if (layoutInfo.size() != memberTypes.size() - 1) {
emitError(loc, "layout specification must be given for all members");
return failure();
}
auto layout =
parseAndVerify<StructType::LayoutInfo>(dialect, loc, layoutSpec);
if (!layout) {
return failure();
}
layoutInfo.push_back(layout.getValue());
return success();
}
// Helper method to record the position of the corresponding '>' for every '<'
// encountered when parsing the string left to right. The relative position of
// '>' w.r.t to the '<' is recorded.
static bool
computeMatchingRAngles(Location loc, StringRef const &spec,
SmallVectorImpl<size_t> &matchingRAngleOffset) {
SmallVector<size_t, 4> openBrackets;
for (size_t i = 0, e = spec.size(); i != e; ++i) {
if (spec[i] == '<') {
openBrackets.push_back(i);
} else if (spec[i] == '>') {
if (openBrackets.empty()) {
emitError(loc, "unbalanced '<' in '") << spec << "'";
return false;
}
matchingRAngleOffset.push_back(i - openBrackets.pop_back_val());
}
}
return true;
}
static ParseResult
parseStructHelper(SPIRVDialect const &dialect, StringRef spec, Location loc,
ArrayRef<size_t> matchingRAngleOffset,
SmallVectorImpl<Type> &memberTypes,
SmallVectorImpl<StructType::LayoutInfo> &layoutInfo) {
// Check if the occurrence of ',' or '<' is before. If former, split using
// ','. If latter, split using matching '>' to get the entire type
// description
auto firstComma = spec.find(',');
auto firstLAngle = spec.find('<');
if (firstLAngle == StringRef::npos && firstComma == StringRef::npos) {
return parseStructElement(dialect, spec, loc, memberTypes, layoutInfo);
}
if (firstLAngle == StringRef::npos || firstComma < firstLAngle) {
// Parse the type before the ','
if (parseStructElement(dialect, spec.substr(0, firstComma), loc,
memberTypes, layoutInfo)) {
return failure();
}
return parseStructHelper(dialect, spec.substr(firstComma + 1).ltrim(), loc,
matchingRAngleOffset, memberTypes, layoutInfo);
}
auto matchingRAngle = matchingRAngleOffset.front() + firstLAngle;
// Find the next ',' or '>'
auto endLoc = std::min(spec.find(',', matchingRAngle + 1), spec.size());
if (parseStructElement(dialect, spec.substr(0, endLoc), loc, memberTypes,
layoutInfo)) {
return failure();
}
auto rest = spec.substr(endLoc + 1).ltrim();
if (rest.empty()) {
return success();
}
if (rest.front() == ',') {
return parseStructHelper(
dialect, rest.drop_front().trim(), loc,
ArrayRef<size_t>(std::next(matchingRAngleOffset.begin()),
matchingRAngleOffset.end()),
memberTypes, layoutInfo);
}
emitError(loc, "unexpected string : '") << rest << "'";
return failure();
}
// struct-type ::= `!spv.struct<` spirv-type (` [` integer-literal `]`)?
// (`, ` spirv-type ( ` [` integer-literal `] ` )? )*
static Type parseStructType(SPIRVDialect const &dialect, StringRef spec,
Location loc) {
if (!spec.consume_front("struct<") || !spec.consume_back(">")) {
emitError(loc, "spv.struct delimiter <...> mismatch");
return Type();
}
if (spec.trim().empty()) {
emitError(loc, "expected SPIR-V type");
return Type();
}
SmallVector<Type, 4> memberTypes;
SmallVector<StructType::LayoutInfo, 4> layoutInfo;
SmallVector<size_t, 4> matchingRAngleOffset;
if (!computeMatchingRAngles(loc, spec, matchingRAngleOffset) ||
parseStructHelper(dialect, spec, loc, matchingRAngleOffset, memberTypes,
layoutInfo)) {
return Type();
}
if (layoutInfo.empty()) {
return StructType::get(memberTypes);
}
if (memberTypes.size() != layoutInfo.size()) {
emitError(loc, "layout specification must be given for all members");
return Type();
}
return StructType::get(memberTypes, layoutInfo);
}
// spirv-type ::= array-type
// | element-type
// | image-type
// | pointer-type
// | runtime-array-type
// | struct-type
Type SPIRVDialect::parseType(StringRef spec, Location loc) const {
if (spec.startswith("array"))
return parseArrayType(*this, spec, loc);
if (spec.startswith("image"))
return parseImageType(*this, spec, loc);
if (spec.startswith("ptr"))
return parsePointerType(*this, spec, loc);
if (spec.startswith("rtarray"))
return parseRuntimeArrayType(*this, spec, loc);
if (spec.startswith("struct"))
return parseStructType(*this, spec, loc);
emitError(loc, "unknown SPIR-V type: ") << spec;
return Type();
}
//===----------------------------------------------------------------------===//
// Type Printing
//===----------------------------------------------------------------------===//
static void print(ArrayType type, llvm::raw_ostream &os) {
os << "array<" << type.getNumElements() << " x " << type.getElementType()
<< ">";
}
static void print(RuntimeArrayType type, llvm::raw_ostream &os) {
os << "rtarray<" << type.getElementType() << ">";
}
static void print(PointerType type, llvm::raw_ostream &os) {
os << "ptr<" << type.getPointeeType() << ", "
<< stringifyStorageClass(type.getStorageClass()) << ">";
}
static void print(ImageType type, llvm::raw_ostream &os) {
os << "image<" << type.getElementType() << ", " << stringifyDim(type.getDim())
<< ", " << stringifyImageDepthInfo(type.getDepthInfo()) << ", "
<< stringifyImageArrayedInfo(type.getArrayedInfo()) << ", "
<< stringifyImageSamplingInfo(type.getSamplingInfo()) << ", "
<< stringifyImageSamplerUseInfo(type.getSamplerUseInfo()) << ", "
<< stringifyImageFormat(type.getImageFormat()) << ">";
}
static void print(StructType type, llvm::raw_ostream &os) {
os << "struct<";
auto printMember = [&](unsigned i) {
os << type.getElementType(i);
if (type.hasLayout()) {
os << " [" << type.getOffset(i) << "]";
}
};
mlir::interleaveComma(llvm::seq<unsigned>(0, type.getNumElements()), os,
printMember);
os << ">";
}
void SPIRVDialect::printType(Type type, llvm::raw_ostream &os) const {
switch (type.getKind()) {
case TypeKind::Array:
print(type.cast<ArrayType>(), os);
return;
case TypeKind::Pointer:
print(type.cast<PointerType>(), os);
return;
case TypeKind::RuntimeArray:
print(type.cast<RuntimeArrayType>(), os);
return;
case TypeKind::Image:
print(type.cast<ImageType>(), os);
return;
case TypeKind::Struct:
print(type.cast<StructType>(), os);
return;
default:
llvm_unreachable("unhandled SPIR-V type");
}
}
|
//===--- ParseGeneric.cpp - Swift Language Parser for Generics ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Generic Parsing and AST Building
//
//===----------------------------------------------------------------------===//
#include "swift/Parse/Parser.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/Parse/Lexer.h"
using namespace swift;
/// parseGenericParameters - Parse a sequence of generic parameters, e.g.,
/// < T : Comparable, U : Container> along with an optional requires clause.
///
/// generic-params:
/// '<' generic-param (',' generic-param)* where-clause? '>'
///
/// generic-param:
/// identifier
/// identifier ':' type-identifier
/// identifier ':' type-composition
///
/// When parsing the generic parameters, this routine establishes a new scope
/// and adds those parameters to the scope.
ParserResult<GenericParamList> Parser::parseGenericParameters() {
// Parse the opening '<'.
assert(startsWithLess(Tok) && "Generic parameter list must start with '<'");
return parseGenericParameters(consumeStartingLess());
}
ParserResult<GenericParamList>
Parser::parseGenericParameters(SourceLoc LAngleLoc) {
// Parse the generic parameter list.
SmallVector<GenericTypeParamDecl *, 4> GenericParams;
bool Invalid = false;
do {
// Note that we're parsing a declaration.
StructureMarkerRAII ParsingDecl(*this, Tok.getLoc(),
StructureMarkerKind::Declaration);
// Parse attributes.
DeclAttributes attributes;
if (Tok.hasComment())
attributes.add(new (Context) RawDocCommentAttr(Tok.getCommentRange()));
bool foundCCTokenInAttr;
parseDeclAttributeList(attributes, foundCCTokenInAttr);
// Parse the name of the parameter.
Identifier Name;
SourceLoc NameLoc;
if (parseIdentifier(Name, NameLoc,
diag::expected_generics_parameter_name)) {
Invalid = true;
break;
}
// Parse the ':' followed by a type.
SmallVector<TypeLoc, 1> Inherited;
if (Tok.is(tok::colon)) {
(void)consumeToken();
ParserResult<TypeRepr> Ty;
if (Tok.getKind() == tok::identifier ||
Tok.getKind() == tok::code_complete) {
Ty = parseTypeIdentifier();
} else if (Tok.getKind() == tok::kw_protocol) {
Ty = parseTypeComposition();
} else if (Tok.getKind() == tok::kw_class) {
diagnose(Tok, diag::unexpected_class_constraint);
diagnose(Tok, diag::suggest_anyobject, Name)
.fixItReplace(Tok.getLoc(), "AnyObject");
consumeToken();
Invalid = true;
} else {
diagnose(Tok, diag::expected_generics_type_restriction, Name);
Invalid = true;
}
if (Ty.hasCodeCompletion())
return makeParserCodeCompletionStatus();
if (Ty.isNonNull())
Inherited.push_back(Ty.get());
}
// We always create generic type parameters with a depth of zero.
// Semantic analysis fills in the depth when it processes the generic
// parameter list.
auto Param = new (Context) GenericTypeParamDecl(CurDeclContext, Name,
NameLoc, /*Depth=*/0,
GenericParams.size());
if (!Inherited.empty())
Param->setInherited(Context.AllocateCopy(Inherited));
GenericParams.push_back(Param);
// Attach attributes.
Param->getAttrs() = attributes;
// Add this parameter to the scope.
addToScope(Param);
// Parse the comma, if the list continues.
} while (consumeIf(tok::comma));
// Parse the optional where-clause.
SourceLoc WhereLoc;
SmallVector<RequirementRepr, 4> Requirements;
bool FirstTypeInComplete;
if (Tok.is(tok::kw_where) &&
parseGenericWhereClause(WhereLoc, Requirements,
FirstTypeInComplete).isError()) {
Invalid = true;
}
// Parse the closing '>'.
SourceLoc RAngleLoc;
if (!startsWithGreater(Tok)) {
if (!Invalid) {
diagnose(Tok, diag::expected_rangle_generics_param);
diagnose(LAngleLoc, diag::opening_angle);
Invalid = true;
}
// Skip until we hit the '>'.
skipUntilGreaterInTypeList();
if (startsWithGreater(Tok))
RAngleLoc = consumeStartingGreater();
else
RAngleLoc = Tok.getLoc();
} else {
RAngleLoc = consumeStartingGreater();
}
if (GenericParams.empty())
return nullptr;
return makeParserResult(GenericParamList::create(Context, LAngleLoc,
GenericParams, WhereLoc,
Requirements, RAngleLoc));
}
ParserResult<GenericParamList> Parser::maybeParseGenericParams() {
if (!startsWithLess(Tok))
return nullptr;
if (!isInSILMode())
return parseGenericParameters();
// In SIL mode, we can have multiple generic parameter lists, with the
// first one being the outmost generic parameter list.
GenericParamList *gpl = nullptr, *outer_gpl = nullptr;
do {
gpl = parseGenericParameters().getPtrOrNull();
if (!gpl)
return nullptr;
if (outer_gpl)
gpl->setOuterParameters(outer_gpl);
outer_gpl = gpl;
} while (startsWithLess(Tok));
return makeParserResult(gpl);
}
/// parseGenericWhereClause - Parse a 'where' clause, which places additional
/// constraints on generic parameters or types based on them.
///
/// where-clause:
/// 'where' requirement (',' requirement) *
///
/// requirement:
/// conformance-requirement
/// same-type-requirement
///
/// conformance-requirement:
/// type-identifier ':' type-identifier
/// type-identifier ':' type-composition
///
/// same-type-requirement:
/// type-identifier '==' type
ParserStatus Parser::parseGenericWhereClause(
SourceLoc &WhereLoc,
SmallVectorImpl<RequirementRepr> &Requirements,
bool &FirstTypeInComplete) {
ParserStatus Status;
// Parse the 'where'.
WhereLoc = consumeToken(tok::kw_where);
FirstTypeInComplete = false;
do {
// Parse the leading type-identifier.
ParserResult<TypeRepr> FirstType = parseTypeIdentifier();
if (FirstType.isNull()) {
Status.setIsParseError();
if (FirstType.hasCodeCompletion()) {
Status.setHasCodeCompletion();
FirstTypeInComplete = true;
}
break;
}
if (Tok.is(tok::colon)) {
// A conformance-requirement.
SourceLoc ColonLoc = consumeToken();
// Parse the protocol or composition.
ParserResult<TypeRepr> Protocol;
if (Tok.is(tok::kw_protocol)) {
Protocol = parseTypeComposition();
} else {
Protocol = parseTypeIdentifier();
}
if (Protocol.isNull()) {
Status.setIsParseError();
if (Protocol.hasCodeCompletion())
Status.setHasCodeCompletion();
break;
}
// Add the requirement.
Requirements.push_back(RequirementRepr::getTypeConstraint(FirstType.get(),
ColonLoc, Protocol.get()));
} else if ((Tok.isAnyOperator() && Tok.getText() == "==") ||
Tok.is(tok::equal)) {
// A same-type-requirement
if (Tok.is(tok::equal)) {
diagnose(Tok, diag::requires_single_equal)
.fixItReplace(SourceRange(Tok.getLoc()), "==");
}
SourceLoc EqualLoc = consumeToken();
// Parse the second type.
ParserResult<TypeRepr> SecondType = parseType();
if (SecondType.isNull()) {
Status.setIsParseError();
if (SecondType.hasCodeCompletion())
Status.setHasCodeCompletion();
break;
}
// Add the requirement
Requirements.push_back(RequirementRepr::getSameType(FirstType.get(),
EqualLoc,
SecondType.get()));
} else {
diagnose(Tok, diag::expected_requirement_delim);
Status.setIsParseError();
break;
}
// If there's a comma, keep parsing the list.
} while (consumeIf(tok::comma));
return Status;
}
/// Parse a free-standing where clause attached to a declaration, adding it to
/// a generic parameter list that may (or may not) already exist.
ParserStatus Parser::
parseFreestandingGenericWhereClause(GenericParamList *&genericParams) {
assert(Tok.is(tok::kw_where) && "Shouldn't call this without a where");
// Push the generic arguments back into a local scope so that references will
// find them.
Scope S(this, ScopeKind::Generics);
if (genericParams)
for (auto pd : genericParams->getParams())
addToScope(pd);
SmallVector<RequirementRepr, 4> Requirements;
if (genericParams)
Requirements.append(genericParams->getRequirements().begin(),
genericParams->getRequirements().end());
SourceLoc WhereLoc;
bool FirstTypeInComplete;
auto result = parseGenericWhereClause(WhereLoc, Requirements,
FirstTypeInComplete);
if (result.shouldStopParsing() || Requirements.empty())
return result;
if (!genericParams)
genericParams = GenericParamList::create(Context, SourceLoc(),
{}, WhereLoc, Requirements,
SourceLoc());
else
genericParams = GenericParamList::create(Context,
genericParams->getLAngleLoc(),
genericParams->getParams(),
WhereLoc, Requirements,
genericParams->getRAngleLoc());
return ParserStatus();
}
|
#include "metis_cpu.h"
#ifdef WITH_METIS
#include <metis.h>
#endif
#ifdef WITH_MTMETIS
#include <mtmetis.h>
#endif
#include "utils.h"
torch::Tensor partition_cpu(torch::Tensor rowptr, torch::Tensor col,
torch::optional<torch::Tensor> optional_value,
int64_t num_parts, bool recursive) {
#ifdef WITH_METIS
CHECK_CPU(rowptr);
CHECK_CPU(col);
if (optional_value.has_value()) {
CHECK_CPU(optional_value.value());
CHECK_INPUT(optional_value.value().dim() == 1);
CHECK_INPUT(optional_value.value().numel() == col.numel());
}
int64_t nvtxs = rowptr.numel() - 1;
int64_t ncon = 1;
auto *xadj = rowptr.data_ptr<int64_t>();
auto *adjncy = col.data_ptr<int64_t>();
int64_t *adjwgt = NULL;
if (optional_value.has_value())
adjwgt = optional_value.value().data_ptr<int64_t>();
int64_t objval = -1;
auto part = torch::empty(nvtxs, rowptr.options());
auto part_data = part.data_ptr<int64_t>();
if (recursive) {
METIS_PartGraphRecursive(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&num_parts, NULL, NULL, NULL, &objval, part_data);
} else {
METIS_PartGraphKway(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&num_parts, NULL, NULL, NULL, &objval, part_data);
}
return part;
#else
AT_ERROR("Not compiled with METIS support");
#endif
}
// needs mt-metis installed via:
// ./configure --shared --edges64bit --vertices64bit --weights64bit
// --partitions64bit
torch::Tensor mt_partition_cpu(torch::Tensor rowptr, torch::Tensor col,
torch::optional<torch::Tensor> optional_value,
int64_t num_parts, bool recursive,
int64_t num_workers) {
#ifdef WITH_MTMETIS
CHECK_CPU(rowptr);
CHECK_CPU(col);
if (optional_value.has_value()) {
CHECK_CPU(optional_value.value());
CHECK_INPUT(optional_value.value().dim() == 1);
CHECK_INPUT(optional_value.value().numel() == col.numel());
}
mtmetis_vtx_type nvtxs = rowptr.numel() - 1;
mtmetis_vtx_type ncon = 1;
mtmetis_adj_type *xadj = (mtmetis_adj_type *)rowptr.data_ptr<int64_t>();
mtmetis_vtx_type *adjncy = (mtmetis_vtx_type *)col.data_ptr<int64_t>();
mtmetis_wgt_type *adjwgt = NULL;
if (optional_value.has_value())
adjwgt = optional_value.value().data_ptr<int64_t>();
mtmetis_pid_type nparts = num_parts;
mtmetis_wgt_type objval = -1;
auto part = torch::empty(nvtxs, rowptr.options());
mtmetis_pid_type *part_data = (mtmetis_pid_type *)part.data_ptr<int64_t>();
double *opts = mtmetis_init_options();
opts[MTMETIS_OPTION_NTHREADS] = num_workers;
if (recursive) {
MTMETIS_PartGraphRecursive(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&nparts, NULL, NULL, opts, &objval, part_data);
} else {
MTMETIS_PartGraphKway(&nvtxs, &ncon, xadj, adjncy, NULL, NULL, adjwgt,
&nparts, NULL, NULL, opts, &objval, part_data);
}
return part;
#else
AT_ERROR("Not compiled with MTMETIS support");
#endif
}
|
#include "Directories.h"
#include "Font_Control.h"
#include "MapScreen.h"
#include "Map_Screen_Helicopter.h"
#include "LaptopSave.h"
#include "MessageBoxScreen.h"
#include "Vehicles.h"
#include "Finances.h"
#include "Quests.h"
#include "Game_Clock.h"
#include "Queen_Command.h"
#include "Strategic_Pathing.h"
#include "Random.h"
#include "Game_Event_Hook.h"
#include "Dialogue_Control.h"
#include "Message.h"
#include "Strategic_Movement.h"
#include "Soldier_Profile.h"
#include "Assignments.h"
#include "PreBattle_Interface.h"
#include "StrategicMap.h"
#include "WorldDef.h"
#include "WorldMan.h"
#include "TileDat.h"
#include "Map_Screen_Interface.h"
#include "Text.h"
#include "Squads.h"
#include "Player_Command.h"
#include "Sound_Control.h"
#include "Meanwhile.h"
#include "Map_Screen_Interface_Border.h"
#include "Strategic_Event_Handler.h"
#include "Overhead.h"
#include "Soldier_Create.h"
#include "RenderWorld.h"
#include "SoundMan.h"
#include "Isometric_Utils.h"
#include "Scheduling.h"
#include "Debug.h"
#include "UILayout.h"
// the amounts of time to wait for hover stuff
#define TIME_DELAY_FOR_HOVER_WAIT 10 // minutes
#define TIME_DELAY_FOR_HOVER_WAIT_TOO_LONG 20 // mintues
#define MIN_DAYS_BETWEEN_SKYRIDER_MONOLOGUES 1
// maximum chance out of a hundred per unsafe sector that a SAM site in decent working condition will hit Skyrider
#define MAX_SAM_SITE_ACCURACY 33
// current temp path for dest char
extern PathSt* pTempHelicopterPath;
extern UINT8 ubSAMControlledSectors[ MAP_WORLD_X ][ MAP_WORLD_Y ];
// whether helicopted variables have been set up
BOOLEAN fSkyRiderSetUp = FALSE;
// plotting for a helicopter
BOOLEAN fPlotForHelicopter = FALSE;
// helicopter vehicle id
INT32 iHelicopterVehicleId = -1;
// total owed to player
INT32 iTotalAccumulatedCostByPlayer = 0;
// helicopter destroyed
BOOLEAN fHelicopterDestroyed = FALSE;
struct RefuelSite
{
INT16 sector;
GridNo grid_no;
INT16 heli_ostruct;
};
// list of sector locations where SkyRider can be refueled
static RefuelSite const g_refuel_site[] =
{
{ CALCULATE_STRATEGIC_INDEX(13, 2), 9001, FIRSTOSTRUCT1 }, // Drassen airport
{ CALCULATE_STRATEGIC_INDEX(6, 9), 13067, FOURTHOSTRUCT1 } // Estoni
};
enum SkyriderMonologueEvent
{
SKYRIDER_MONOLOGUE_EVENT_DRASSEN_SAM_SITE = 0,
SKYRIDER_MONOLOGUE_EVENT_OTHER_SAM_SITES,
SKYRIDER_MONOLOGUE_EVENT_ESTONI_REFUEL,
SKYRIDER_MONOLOGUE_EVENT_CAMBRIA_HOSPITAL
};
// whether or not helicopter can refuel at this site
BOOLEAN fRefuelingSiteAvailable[ NUMBER_OF_REFUEL_SITES ] = { FALSE, FALSE };
// is the heli in the air?
BOOLEAN fHelicopterIsAirBorne = FALSE;
// is the pilot returning straight to base?
BOOLEAN fHeliReturnStraightToBase = FALSE;
// heli hovering
BOOLEAN fHoveringHelicopter = FALSE;
// time started hovering
UINT32 uiStartHoverTime = 0;
// what state are skyrider's monologues in in?
UINT32 guiHelicopterSkyriderTalkState = 0;
// the flags for skyrider events
BOOLEAN fShowEstoniRefuelHighLight = FALSE;
BOOLEAN fShowOtherSAMHighLight = FALSE;
BOOLEAN fShowDrassenSAMHighLight = FALSE;
BOOLEAN fShowCambriaHospitalHighLight = FALSE;
UINT32 guiTimeOfLastSkyriderMonologue = 0;
UINT8 gubHelicopterHitsTaken = 0;
BOOLEAN gfSkyriderSaidCongratsOnTakingSAM = FALSE;
UINT8 gubPlayerProgressSkyriderLastCommentedOn = 0;
static BOOLEAN DoesSkyriderNoticeEnemiesInSector(UINT8 ubNumEnemies);
static BOOLEAN HandleSAMSiteAttackOfHelicopterInSector(INT16 sSectorX, INT16 sSectorY);
static void HeliCharacterDialogue(UINT16 usQuoteNum);
static void PaySkyriderBill(void);
static void StartHoverTime(void);
static RefuelSite const* FindClosestRefuelSite(bool must_be_available);
static void LandHelicopter(void);
static void MakeHeliReturnToBase(void);
static void HandleSkyRiderMonologueEvent(SkyriderMonologueEvent, UINT32 uiSpecialCode);
static void HandleSkyRiderMonologueAboutCambriaHospital(UINT32 uiSpecialCode);
static void HandleSkyRiderMonologueAboutDrassenSAMSite(UINT32 uiSpecialCode);
static void HandleSkyRiderMonologueAboutEstoniRefuel(UINT32 uiSpecialCode);
static void HandleSkyRiderMonologueAboutOtherSAMSites(UINT32 uiSpecialCode);
static void AddHelicopterToMaps(bool add, RefuelSite const&);
static bool IsHelicopterOnGroundAtRefuelingSite(RefuelSite const&);
void InitializeHelicopter( void )
{
// must be called whenever a new game starts up!
iHelicopterVehicleId = -1;
fSkyRiderSetUp = FALSE;
fHelicopterIsAirBorne = FALSE;
fHeliReturnStraightToBase = FALSE;
fHoveringHelicopter = FALSE;
uiStartHoverTime = 0;
fPlotForHelicopter = FALSE;
pTempHelicopterPath = NULL;
iTotalAccumulatedCostByPlayer = 0;
fHelicopterDestroyed = FALSE;
guiHelicopterSkyriderTalkState = 0;
guiTimeOfLastSkyriderMonologue = 0;
fShowEstoniRefuelHighLight = FALSE;
fShowOtherSAMHighLight = FALSE;
fShowDrassenSAMHighLight = FALSE;
fShowCambriaHospitalHighLight = FALSE;
gfSkyriderEmptyHelpGiven = FALSE;
gubHelicopterHitsTaken = 0;
gfSkyriderSaidCongratsOnTakingSAM = FALSE;
gubPlayerProgressSkyriderLastCommentedOn = 0;
}
BOOLEAN RemoveSoldierFromHelicopter( SOLDIERTYPE *pSoldier )
{
// attempt to add soldier to helicopter
if( iHelicopterVehicleId == -1 )
{
// no heli yet
return( FALSE );
}
// check if heli is in motion or if on the ground
if (fHelicopterIsAirBorne && !fHoveringHelicopter) return FALSE;
// is the heli returning to base?..he ain't waiting if so
if (fHeliReturnStraightToBase) return FALSE;
VEHICLETYPE const& v = GetHelicopter();
pSoldier->sSectorX = v.sSectorX;
pSoldier->sSectorY = v.sSectorY;
pSoldier->bSectorZ = 0;
// reset between sectors
pSoldier->fBetweenSectors = FALSE;
// remove from the vehicle
return( TakeSoldierOutOfVehicle( pSoldier ) );
}
BOOLEAN HandleHeliEnteringSector( INT16 sX, INT16 sY )
{
UINT8 ubNumEnemies;
BOOLEAN endOfHelicoptersPath;
VEHICLETYPE const& v = GetHelicopter();
endOfHelicoptersPath = (!v.pMercPath || !v.pMercPath->pNext);
// check for SAM attack upon the chopper. If it's destroyed by the attack, do nothing else here
if (HandleSAMSiteAttackOfHelicopterInSector(sX, sY))
{
// destroyed
return( TRUE );
}
// count how many enemies are camped there or passing through
ubNumEnemies = NumEnemiesInSector( sX, sY );
// any baddies?
if( ubNumEnemies > 0 )
{
// if the player didn't know about these prior to the chopper's arrival
if( WhatPlayerKnowsAboutEnemiesInSector( sX, sY ) == KNOWS_NOTHING )
{
// but Skyrider notices them
if (DoesSkyriderNoticeEnemiesInSector(ubNumEnemies))
{
// if just passing through (different quotes are used below if it's his final destination)
if( !endOfHelicoptersPath )
{
// stop time compression and inform player that there are enemies in the sector below
StopTimeCompression();
if( Random( 2 ) )
{
HeliCharacterDialogue(ENEMIES_SPOTTED_EN_ROUTE_IN_FRIENDLY_SECTOR_A);
}
else
{
HeliCharacterDialogue(ENEMIES_SPOTTED_EN_ROUTE_IN_FRIENDLY_SECTOR_B);
}
}
// make their presence appear on the map while Skyrider remains in the sector
SectorInfo[ SECTOR( sX, sY ) ].uiFlags |= SF_SKYRIDER_NOTICED_ENEMIES_HERE;
}
}
}
// player pays for travel if Skyrider is NOT returning to base (even if empty while scouting/going for pickup)
if (!fHeliReturnStraightToBase)
{
// charge cost for flying another sector
INT32 iCost;
if( !StrategicMap[CALCULATE_STRATEGIC_INDEX(sX, sY)].fEnemyAirControlled)
iCost = COST_AIRSPACE_SAFE;
else
iCost = COST_AIRSPACE_UNSAFE;
iTotalAccumulatedCostByPlayer += iCost;
}
// check if heli has any real path left
if( endOfHelicoptersPath )
{
// start hovering
StartHoverTime( );
// if sector is safe, or Skyrider MUST land anyway (returning to base)
if ( ( ubNumEnemies == 0 ) || fHeliReturnStraightToBase )
{
// if he has passengers, or he's not going straight to base, tell player he's arrived
// (i.e. don't say anything nor stop time compression if he's empty and just returning to base)
if ( ( GetNumberInVehicle(v) > 0 ) || !fHeliReturnStraightToBase )
{
// arrived at destination
HeliCharacterDialogue(ARRIVED_IN_NON_HOSTILE_SECTOR);
StopTimeCompression();
}
// destination reached, payment due. If player can't pay, mercs get kicked off and heli flies to base!
PaySkyriderBill();
}
else
{
// Say quote: "Gonna have to abort. Enemies below"
HeliCharacterDialogue(ARRIVED_IN_HOSTILE_SECTOR);
StopTimeCompression();
}
if( IsRefuelSiteInSector( CALCULATE_STRATEGIC_INDEX(sX, sY) ) )
{
LandHelicopter();
}
}
return( FALSE );
}
static RefuelSite const& NearestRefuelPoint(bool const fNotifyPlayerIfNoSafeLZ)
{
// Try to find one, any one under the players control
RefuelSite const* closest_site = FindClosestRefuelSite(TRUE);
if (closest_site) return *closest_site;
if (fNotifyPlayerIfNoSafeLZ)
{ // No refueling sites available, might wanna warn player about this
ScreenMsg(FONT_MCOLOR_DKRED, MSG_INTERFACE, pHelicopterEtaStrings[5]);
}
// Find the closest location regardless
closest_site = FindClosestRefuelSite(FALSE);
// Always returns a valid refuel point, picking a hostile one if unavoidable
Assert(closest_site);
return *closest_site;
}
// find the location sector of closest refuel point for heli..and the criteria if the sector must be under the players control
static RefuelSite const* FindClosestRefuelSite(bool const must_be_available)
{
INT32 shortest_distance = 9999;
RefuelSite const* closest_site = 0;
VEHICLETYPE const& v = GetHelicopter();
INT16 sectorID = CALCULATE_STRATEGIC_INDEX(v.sSectorX , v.sSectorY);
GROUP& g = *GetGroup(v.ubMovementGroup);
// find shortest distance to refuel site
for (INT32 i = 0; i < NUMBER_OF_REFUEL_SITES; ++i)
{
// if this refuelling site is available
if (!fRefuelingSiteAvailable[i] && must_be_available) continue;
// find if sector is under control, find distance from heli to it
RefuelSite const& r = g_refuel_site[i];
INT16 const dest = r.sector;
INT32 const distance = FindStratPath( sectorID, dest, g, FALSE);
if (distance >= shortest_distance) continue;
// shorter, copy over
shortest_distance = distance;
closest_site = &r;
}
return closest_site;
}
// helicopter shot down, kill all on board
static void SkyriderDestroyed(void)
{
// remove any arrival events for the helicopter's group
VEHICLETYPE& v = GetHelicopter();
DeleteStrategicEvent(EVENT_GROUP_ARRIVAL, v.ubMovementGroup);
KillAllInVehicle(v);
// kill skyrider
gMercProfiles[ SKYRIDER ].bLife = 0;
// destroy helicopter
fHelicopterDestroyed = TRUE;
// zero out balance due
gMercProfiles[ SKYRIDER ].iBalance = 0;
iTotalAccumulatedCostByPlayer = 0;
// remove vehicle and reset
RemoveVehicleFromList(v);
iHelicopterVehicleId = -1;
}
BOOLEAN CanHelicopterFly( void )
{
// check if heli is available for flight?
// is the heli available
if (iHelicopterVehicleId == -1) return FALSE;
// is the pilot alive, well, and willing to help us?
if (!IsHelicopterPilotAvailable()) return FALSE;
if (fHeliReturnStraightToBase) return FALSE;
// grounded by enemies in sector?
if (!CanHelicopterTakeOff()) return FALSE;
// everything A-OK!
return( TRUE );
}
BOOLEAN IsHelicopterPilotAvailable( void )
{
// what is state of skyrider?
if (iHelicopterVehicleId == -1) return FALSE;
// owe any money to skyrider?
if( gMercProfiles[ SKYRIDER ].iBalance < 0 ) return( FALSE );
// last case: Drassen too disloyal to wanna help player? if not, return true
return ( !CheckFact( FACT_LOYALTY_LOW, SKYRIDER ) );
}
// land the helicopter here
static void LandHelicopter(void)
{
// set the helictoper down, call arrive callback for this mvt group
fHelicopterIsAirBorne = FALSE;
// no longer hovering
fHoveringHelicopter = FALSE;
// reset fact that we might have returned straight here
fHeliReturnStraightToBase = FALSE;
HandleHelicopterOnGround(true);
// if we'll be unable to take off again (because there are enemies in the sector, or we owe pilot money)
if (!CanHelicopterFly())
{
// kick everyone out!
MoveAllInHelicopterToFootMovementGroup( );
}
else
{
// play meanwhile scene if it hasn't been used yet
HandleKillChopperMeanwhileScene();
}
}
void TakeOffHelicopter( void )
{
// heli in the air
fHelicopterIsAirBorne = TRUE;
// no longer hovering
fHoveringHelicopter = FALSE;
HandleHelicopterOnGround(true);
}
// start the heli hover time
static void StartHoverTime(void)
{
// start hover in this sector
fHoveringHelicopter = TRUE;
// post event for x mins in future, save start time, if event time - delay = start time, then hover has gone on too long
uiStartHoverTime = GetWorldTotalMin( );
// post event..to call handle hover
AddStrategicEvent( EVENT_HELICOPTER_HOVER_TOO_LONG, GetWorldTotalMin() + TIME_DELAY_FOR_HOVER_WAIT, 0 );
}
void HandleHeliHoverLong( void )
{
// post message about hovering too long
if( fHoveringHelicopter )
{
// proper event, post next one
AddStrategicEvent( EVENT_HELICOPTER_HOVER_WAY_TOO_LONG, uiStartHoverTime + TIME_DELAY_FOR_HOVER_WAIT_TOO_LONG, 0 );
// inform player
HeliCharacterDialogue(HOVERING_A_WHILE);
// stop time compression if it's on
StopTimeCompression( );
}
else
{
// reset
uiStartHoverTime = 0;
}
}
void HandleHeliHoverTooLong( void )
{
// reset hover time
uiStartHoverTime = 0;
if (!fHoveringHelicopter) return;
// hovered too long, inform player heli is returning to base
HeliCharacterDialogue(RETURN_TO_BASE);
VEHICLETYPE const& v = GetHelicopter();
// If the sector is safe
if (NumEnemiesInSector(v.sSectorX, v.sSectorY) == 0)
{
// kick everyone out!
MoveAllInHelicopterToFootMovementGroup( );
}
MakeHeliReturnToBase();
}
// check if anyone in the chopper sees any baddies in sector
static BOOLEAN DoesSkyriderNoticeEnemiesInSector(UINT8 ubNumEnemies)
{
UINT8 ubChance;
// is the pilot and heli around?
if (!CanHelicopterFly()) return FALSE;
// if there aren't any, he obviously won't see them
if( ubNumEnemies == 0 )
{
return( FALSE );
}
// figure out what the chance is of seeing them
// make this relatively accurate most of the time, to encourage helicopter scouting by making it useful
ubChance = 60 + ubNumEnemies;
if( PreRandom( 100 ) < ubChance )
{
return( TRUE );
}
return( FALSE );
}
// if the heli is on the move, what is the distance it will move..the length of the merc path, less the first node
INT32 DistanceOfIntendedHelicopterPath( void )
{
INT32 iLength = 0;
if (!CanHelicopterFly())
{
// big number, no go
return( 9999 );
}
PathSt const* pNode = GetHelicopter().pMercPath;
// any path yet?
if( pNode != NULL )
{
while( pNode -> pNext )
{
iLength++;
pNode = pNode ->pNext;
}
}
pNode = pTempHelicopterPath;
// any path yet?
if( pNode != NULL )
{
while( pNode -> pNext )
{
iLength++;
pNode = pNode ->pNext;
}
}
return( iLength );
}
void SetUpHelicopterForMovement( void )
{
// check if helicopter vehicle has a mvt group, if not, assign one in this sector
VEHICLETYPE& v = GetHelicopter();
// if no group, create one for vehicle
if (v.ubMovementGroup == 0)
{
// get the vehicle a mvt group
GROUP& g = *CreateNewVehicleGroupDepartingFromSector(v.sSectorX, v.sSectorY);
v.ubMovementGroup = g.ubGroupID;
// add everyone in vehicle to this mvt group
CFOR_EACH_PASSENGER(v, i)
{
AddPlayerToGroup(g, **i);
}
}
}
static void SkyriderDialogue(UINT16 const quote)
{
CharacterDialogue(SKYRIDER, quote, uiExternalStaticNPCFaces[SKYRIDER_EXTERNAL_FACE], DIALOGUE_EXTERNAL_NPC_UI, FALSE);
}
static void SkyriderDialogueWithSpecialEvent(SkyriderMonologueEvent const event, UINT32 const special_code)
{
class DialogueEventSkyriderMapScreenEvent : public DialogueEvent
{
public:
DialogueEventSkyriderMapScreenEvent(SkyriderMonologueEvent const event, UINT32 const special_code) :
event_(event),
special_code_(special_code)
{}
bool Execute()
{
HandleSkyRiderMonologueEvent(event_, special_code_);
return false;
}
private:
SkyriderMonologueEvent const event_;
UINT32 const special_code_;
};
DialogueEvent::Add(new DialogueEventSkyriderMapScreenEvent(event, special_code));
}
static void HeliCharacterDialogue(UINT16 const usQuoteNum)
{
// ARM: we could just return, but since various flags are often being set it's safer to honk so it gets fixed right!
Assert(iHelicopterVehicleId != -1);
SkyriderDialogue(usQuoteNum);
}
bool IsRefuelSiteInSector(INT16 const sector)
{
FOR_EACH(RefuelSite const, i, g_refuel_site)
{
if (i->sector == sector) return true;
}
return false;
}
void UpdateRefuelSiteAvailability( void )
{
INT32 iCounter = 0;
// Generally, only Drassen is initially available for refuelling
// Estoni must first be captured (although player may already have it when he gets Skyrider!)
for( iCounter = 0; iCounter < NUMBER_OF_REFUEL_SITES; iCounter++ )
{
// if enemy controlled sector (ground OR air, don't want to fly into enemy air territory)
StrategicMapElement const& m = StrategicMap[g_refuel_site[iCounter].sector];
if (m.fEnemyControlled ||
m.fEnemyAirControlled ||
(iCounter == ESTONI_REFUELING_SITE && !CheckFact(FACT_ESTONI_REFUELLING_POSSIBLE, 0)))
{
// mark refueling site as unavailable
fRefuelingSiteAvailable[ iCounter ] = FALSE;
}
else
{
// mark refueling site as available
fRefuelingSiteAvailable[ iCounter ] = TRUE;
}
}
}
void SetUpHelicopterForPlayer( INT16 sX, INT16 sY )
{
if (!fSkyRiderSetUp)
{
iHelicopterVehicleId = AddVehicleToList( sX, sY, 0, HELICOPTER );
// set up for movement
SetUpHelicopterForMovement( );
UpdateRefuelSiteAvailability( );
fSkyRiderSetUp = TRUE;
gMercProfiles[ SKYRIDER ].fUseProfileInsertionInfo = FALSE;
}
}
void MoveAllInHelicopterToFootMovementGroup(void)
{
// take everyone out of heli and add to movement group
INT8 bNewSquad;
BOOLEAN fSuccess;
UINT8 ubInsertionCode = (UINT8)-1; // XXX HACK000E
BOOLEAN fInsertionCodeSet = FALSE;
UINT16 usInsertionData = (UINT16)-1; // XXX HACK000E
// put these guys on their own squad (we need to return their group ID, and can only return one, so they need a unique one
bNewSquad = GetFirstEmptySquad();
// go through list of everyone in helicopter
VEHICLETYPE const& v = GetHelicopter();
CFOR_EACH_PASSENGER(v, i)
{
SOLDIERTYPE* const pSoldier = *i;
Assert(InHelicopter(*pSoldier));
fSuccess = RemoveSoldierFromHelicopter( pSoldier );
Assert( fSuccess );
AddCharacterToSquad( pSoldier, bNewSquad );
// ATE: OK - the ubStrategicInsertionCode is set 'cause groupArrivesInsector has been
// called when buddy is added to a squad. However, the insertion code onlt sets set for
// the first merc, so the rest are going to use whatever they had previously....
if ( !fInsertionCodeSet )
{
ubInsertionCode = pSoldier->ubStrategicInsertionCode;
usInsertionData = pSoldier->usStrategicInsertionData;
fInsertionCodeSet = TRUE;
}
else
{
pSoldier->ubStrategicInsertionCode = ubInsertionCode;
pSoldier->usStrategicInsertionData = usInsertionData;
}
}
}
void SkyRiderTalk( UINT16 usQuoteNum )
{
// have skyrider talk to player
HeliCharacterDialogue(usQuoteNum);
fTeamPanelDirty = TRUE;
}
// Skyrider monlogue events for mapscreen
static void HandleSkyRiderMonologueEvent(SkyriderMonologueEvent const uiEventCode, UINT32 const uiSpecialCode)
{
// will handle the skyrider monologue about where the SAM sites are and what not
TurnOnAirSpaceMode();
switch( uiEventCode )
{
case( SKYRIDER_MONOLOGUE_EVENT_DRASSEN_SAM_SITE ):
SetExternMapscreenSpeechPanelXY( DEFAULT_EXTERN_PANEL_X_POS, STD_SCREEN_Y + 117 );
HandleSkyRiderMonologueAboutDrassenSAMSite( uiSpecialCode );
break;
case SKYRIDER_MONOLOGUE_EVENT_CAMBRIA_HOSPITAL:
SetExternMapscreenSpeechPanelXY( DEFAULT_EXTERN_PANEL_X_POS, STD_SCREEN_Y + 172 );
HandleSkyRiderMonologueAboutCambriaHospital( uiSpecialCode );
break;
case( SKYRIDER_MONOLOGUE_EVENT_OTHER_SAM_SITES ):
SetExternMapscreenSpeechPanelXY( STD_SCREEN_X + 335, DEFAULT_EXTERN_PANEL_Y_POS );
HandleSkyRiderMonologueAboutOtherSAMSites( uiSpecialCode );
break;
case( SKYRIDER_MONOLOGUE_EVENT_ESTONI_REFUEL ):
SetExternMapscreenSpeechPanelXY( DEFAULT_EXTERN_PANEL_X_POS, DEFAULT_EXTERN_PANEL_Y_POS );
HandleSkyRiderMonologueAboutEstoniRefuel( uiSpecialCode );
break;
}
// update time
guiTimeOfLastSkyriderMonologue = GetWorldTotalMin();
}
static void HandleSkyRiderMonologueAboutEstoniRefuel(UINT32 const uiSpecialCode)
{
// Once Estoni is free tell player about refueling
switch (uiSpecialCode)
{
case 0:
{
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_ESTONI_REFUEL, 1);
// if special event data 2 is true, then do dialogue, else this is just a trigger for an event
SkyriderDialogue(SPIEL_ABOUT_ESTONI_AIRSPACE);
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_ESTONI_REFUEL, 2);
break;
}
case 1: // Highlight Estoni
fShowEstoniRefuelHighLight = TRUE;
break;
case 2:
fShowEstoniRefuelHighLight = FALSE;
break;
}
}
static void HandleSkyRiderMonologueAboutDrassenSAMSite(UINT32 const uiSpecialCode)
{
switch (uiSpecialCode)
{
case 0:
{
// if special event data 2 is true, then do dialogue, else this is just a trigger for an event
SkyriderDialogue(MENTION_DRASSEN_SAM_SITE);
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_DRASSEN_SAM_SITE, 1);
if (StrategicMap[SECTOR_INFO_TO_STRATEGIC_INDEX(pSamList[1])].fEnemyControlled)
{
SkyriderDialogue(SECOND_HALF_OF_MENTION_DRASSEN_SAM_SITE);
}
else if (CheckFact(FACT_SKYRIDER_USED_IN_MAPSCREEN, SKYRIDER))
{ // Ian says don't use the SAM site quote unless player has tried flying already
SkyriderDialogue(SAM_SITE_TAKEN);
gfSkyriderSaidCongratsOnTakingSAM = TRUE;
}
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_DRASSEN_SAM_SITE, 2);
break;
}
case 1: // Highlight Drassen SAM site sector
fShowDrassenSAMHighLight = TRUE;
SetSAMSiteAsFound(SAM_SITE_TWO);
break;
case 2:
fShowDrassenSAMHighLight = FALSE;
break;
}
}
static void HandleSkyRiderMonologueAboutCambriaHospital(UINT32 const uiSpecialCode)
{
switch (uiSpecialCode)
{
case 0:
{
// if special event data 2 is true, then do dialogue, else this is just a trigger for an event
SkyriderDialogue(MENTION_HOSPITAL_IN_CAMBRIA);
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_CAMBRIA_HOSPITAL, 1);
// Highlight Cambria hospital sector
fShowCambriaHospitalHighLight = TRUE;
break;
}
case 1:
fShowCambriaHospitalHighLight = FALSE;
break;
}
}
static void HandleSkyRiderMonologueAboutOtherSAMSites(UINT32 const uiSpecialCode)
{
/* Handle skyrider telling player about other SAM sites on fifth hiring or
* after one near drassen is taken out */
switch (uiSpecialCode)
{
case 0:
{
// if special event data 2 is true, then do dialogue, else this is just a trigger for an event
SkyriderDialogue(SPIEL_ABOUT_OTHER_SAM_SITES);
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_OTHER_SAM_SITES, 1);
SkyriderDialogue(SECOND_HALF_OF_SPIEL_ABOUT_OTHER_SAM_SITES);
SkyriderDialogueWithSpecialEvent(SKYRIDER_MONOLOGUE_EVENT_OTHER_SAM_SITES, 2);
break;
}
case 1: // Highlight other SAMs
fShowOtherSAMHighLight = TRUE;
// Reveal other 3 SAM sites
SetSAMSiteAsFound(SAM_SITE_ONE);
SetSAMSiteAsFound(SAM_SITE_THREE);
SetSAMSiteAsFound(SAM_SITE_FOUR);
break;
case 2:
fShowOtherSAMHighLight = FALSE;
break;
}
}
void CheckAndHandleSkyriderMonologues( void )
{
// wait at least this many days between Skyrider monologues
if ( ( GetWorldTotalMin() - guiTimeOfLastSkyriderMonologue ) >= ( MIN_DAYS_BETWEEN_SKYRIDER_MONOLOGUES * 24 * 60 ) )
{
if( guiHelicopterSkyriderTalkState == 0 )
{
HandleSkyRiderMonologueEvent( SKYRIDER_MONOLOGUE_EVENT_DRASSEN_SAM_SITE, 0 );
guiHelicopterSkyriderTalkState = 1;
}
else if( guiHelicopterSkyriderTalkState == 1 )
{
// if enemy still controls the Cambria hospital sector
if( StrategicMap[ CALCULATE_STRATEGIC_INDEX( HOSPITAL_SECTOR_X, HOSPITAL_SECTOR_Y ) ].fEnemyControlled )
{
HandleSkyRiderMonologueEvent( SKYRIDER_MONOLOGUE_EVENT_CAMBRIA_HOSPITAL, 0 );
}
// advance state even if player already has Cambria's hospital sector!!!
guiHelicopterSkyriderTalkState = 2;
}
else if( guiHelicopterSkyriderTalkState == 2 )
{
// wait until player has taken over a SAM site before saying this and advancing state
if ( gfSkyriderSaidCongratsOnTakingSAM )
{
HandleSkyRiderMonologueEvent( SKYRIDER_MONOLOGUE_EVENT_OTHER_SAM_SITES, 0 );
guiHelicopterSkyriderTalkState = 3;
}
}
else if( guiHelicopterSkyriderTalkState == 3 )
{
// wait until Estoni refuelling site becomes available
if ( fRefuelingSiteAvailable[ ESTONI_REFUELING_SITE ] )
{
HandleSkyRiderMonologueEvent( SKYRIDER_MONOLOGUE_EVENT_ESTONI_REFUEL, 0 );
guiHelicopterSkyriderTalkState = 4;
}
}
}
}
static void HandleBlitOfSectorLocatorIcon(UINT8 const sector, UINT8 const locator)
{
HandleBlitOfSectorLocatorIcon(SECTORX(sector), SECTORY(sector), 0, locator);
}
void HandleAnimationOfSectors( void )
{
BOOLEAN fSkipSpeakersLocator = FALSE;
// these don't need to be saved, they merely turn off the highlights after they stop flashing
static BOOLEAN fOldShowDrassenSAMHighLight = FALSE;
static BOOLEAN fOldShowCambriaHospitalHighLight = FALSE;
static BOOLEAN fOldShowEstoniRefuelHighLight = FALSE;
static BOOLEAN fOldShowOtherSAMHighLight = FALSE;
// find out which mode we are in and animate for that mode
// Drassen SAM site
if( fShowDrassenSAMHighLight )
{
fOldShowDrassenSAMHighLight = TRUE;
// Drassen's SAM site is #2
HandleBlitOfSectorLocatorIcon(pSamList[1], LOCATOR_COLOR_RED);
fSkipSpeakersLocator = TRUE;
}
else if( fOldShowDrassenSAMHighLight )
{
fOldShowDrassenSAMHighLight = FALSE;
fMapPanelDirty = TRUE;
}
// Cambria hospital
if( fShowCambriaHospitalHighLight )
{
fOldShowCambriaHospitalHighLight = TRUE;
HandleBlitOfSectorLocatorIcon( HOSPITAL_SECTOR_X, HOSPITAL_SECTOR_Y, 0, LOCATOR_COLOR_RED );
fSkipSpeakersLocator = TRUE;
}
else if( fOldShowCambriaHospitalHighLight )
{
fOldShowCambriaHospitalHighLight = FALSE;
fMapPanelDirty = TRUE;
}
// show other SAM sites
if( fShowOtherSAMHighLight )
{
fOldShowOtherSAMHighLight = TRUE;
HandleBlitOfSectorLocatorIcon(pSamList[0], LOCATOR_COLOR_RED);
HandleBlitOfSectorLocatorIcon(pSamList[2], LOCATOR_COLOR_RED);
HandleBlitOfSectorLocatorIcon(pSamList[3], LOCATOR_COLOR_RED);
fSkipSpeakersLocator = TRUE;
}
else if( fOldShowOtherSAMHighLight )
{
fOldShowOtherSAMHighLight = FALSE;
fMapPanelDirty = TRUE;
}
// show Estoni site
if( fShowEstoniRefuelHighLight )
{
fOldShowEstoniRefuelHighLight = TRUE;
INT16 const sec = g_refuel_site[ESTONI_REFUELING_SITE].sector;
HandleBlitOfSectorLocatorIcon(GET_X_FROM_STRATEGIC_INDEX(sec), GET_Y_FROM_STRATEGIC_INDEX(sec), 0, LOCATOR_COLOR_RED);
fSkipSpeakersLocator = TRUE;
}
else if( fOldShowEstoniRefuelHighLight )
{
fOldShowEstoniRefuelHighLight = FALSE;
fMapPanelDirty = TRUE;
}
// don't show sector locator over the speaker's sector if he is talking about another sector - it's confusing
if ( !fSkipSpeakersLocator )
{
switch( gubBlitSectorLocatorCode )
{
case LOCATOR_COLOR_RED: // normal one used for mines (will now be overriden with yellow)
HandleBlitOfSectorLocatorIcon( gsSectorLocatorX, gsSectorLocatorY, 0, LOCATOR_COLOR_RED );
break;
case LOCATOR_COLOR_YELLOW: // used for all other dialogues
HandleBlitOfSectorLocatorIcon( gsSectorLocatorX, gsSectorLocatorY, 0, LOCATOR_COLOR_YELLOW );
break;
}
}
}
void HandleHelicopterOnGround(BOOLEAN handleGraphicToo)
{
// No worries if underground
if (gbWorldSectorZ != 0) return;
for (UINT8 site = 0; site != NUMBER_OF_REFUEL_SITES; ++site)
{
RefuelSite const& r = g_refuel_site[site];
// Is this refueling site sector the loaded sector?
if (CALCULATE_STRATEGIC_INDEX(gWorldSectorX, gWorldSectorY) != r.sector) continue;
// YES, so find out if the chopper is landed here
if (IsHelicopterOnGroundAtRefuelingSite(r))
{
if(handleGraphicToo)
{
AddHelicopterToMaps(true, r);
}
// ATE: Add Skyrider too
// ATE: only if hired
if (iHelicopterVehicleId != -1)
{
MERCPROFILESTRUCT& p = GetProfile(SKYRIDER);
p.sSectorX = gWorldSectorX;
p.sSectorY = gWorldSectorY;
}
}
else
{
if(handleGraphicToo)
{
AddHelicopterToMaps(false, r);
}
// ATE: Remove Skyrider
if (iHelicopterVehicleId != -1)
{
MERCPROFILESTRUCT& p = GetProfile(SKYRIDER);
p.sSectorX = 0;
p.sSectorY = 0;
// See if we can find him and remove him if so
// ATE: Don't do this if buddy is on our team!
SOLDIERTYPE* const s = FindSoldierByProfileID(SKYRIDER);
if (s && s->bTeam != OUR_TEAM) TacticalRemoveSoldier(*s);
}
}
if(handleGraphicToo)
{
InvalidateWorldRedundency();
}
break;
}
}
static bool IsHelicopterOnGroundAtRefuelingSite(RefuelSite const& r)
{
if (fHelicopterDestroyed) return false;
if (fHelicopterIsAirBorne) return false;
// if we haven't even met SkyRider
if (!fSkyRiderSetUp)
{ // Then it's always at Drassen
return &r == &g_refuel_site[DRASSEN_REFUELING_SITE];
}
// on the ground, but is it at this site or at another one?
VEHICLETYPE const& v = GetHelicopter();
return CALCULATE_STRATEGIC_INDEX(v.sSectorX, v.sSectorY) == r.sector;
}
static void HeliCrashSoundStopCallback(void* pData)
{
SkyriderDestroyed( );
}
static BOOLEAN HandleSAMSiteAttackOfHelicopterInSector(INT16 sSectorX, INT16 sSectorY)
{
UINT8 ubSamNumber = 0;
INT8 bSAMCondition;
UINT8 ubChance;
// if this sector is in friendly airspace, we're safe
if (!StrategicMap[CALCULATE_STRATEGIC_INDEX(sSectorX, sSectorY)].fEnemyAirControlled)
{
// no problem, friendly airspace
return( FALSE );
}
// which SAM controls this sector?
ubSamNumber = ubSAMControlledSectors[ sSectorX ][ sSectorY ];
// if none of them
if (ubSamNumber == 0)
{
return( FALSE);
}
// get the condition of that SAM site (NOTE: SAM #s are 1-4, but indexes are 0-3!!!)
Assert( ubSamNumber <= NUMBER_OF_SAMS );
bSAMCondition = StrategicMap[ SECTOR_INFO_TO_STRATEGIC_INDEX( pSamList[ ubSamNumber - 1 ] ) ].bSAMCondition;
// if the SAM site is too damaged to be a threat
if( bSAMCondition < MIN_CONDITION_FOR_SAM_SITE_TO_WORK )
{
// no problem, SAM site not working
return( FALSE );
}
// Hostile airspace controlled by a working SAM site, so SAM site fires a SAM at Skyrider!!!
// calc chance that chopper will be shot down
ubChance = bSAMCondition;
// there's a fair chance of a miss even if the SAM site is in perfect working order
if (ubChance > MAX_SAM_SITE_ACCURACY)
{
ubChance = MAX_SAM_SITE_ACCURACY;
}
if( PreRandom( 100 ) < ubChance)
{
// another hit!
gubHelicopterHitsTaken++;
// Took a hit! Pause time so player can reconsider
StopTimeCompression();
// first hit?
if ( gubHelicopterHitsTaken == 1 )
{
HeliCharacterDialogue(HELI_TOOK_MINOR_DAMAGE);
}
// second hit?
else if ( gubHelicopterHitsTaken == 2 )
{
// going back to base (no choice, dialogue says so)
HeliCharacterDialogue(HELI_TOOK_MAJOR_DAMAGE);
MakeHeliReturnToBase();
}
// third hit!
else
{
// Important: Skyrider must still be alive when he talks, so must do this before heli is destroyed!
HeliCharacterDialogue(HELI_GOING_DOWN);
// everyone die die die
// play sound
if (PlayJA2StreamingSampleFromFile(STSOUNDSDIR "/blah2.wav", HIGHVOLUME, 1, MIDDLEPAN, HeliCrashSoundStopCallback) == SOUND_ERROR)
{
// Destroy here if we cannot play streamed sound sample....
SkyriderDestroyed( );
}
else
{
// otherwise it's handled in the callback
// remove any arrival events for the helicopter's group
DeleteStrategicEvent(EVENT_GROUP_ARRIVAL, GetHelicopter().ubMovementGroup);
}
// special return code indicating heli was destroyed
return( TRUE );
}
}
// still flying
return( FALSE );
}
// check if helicopter can take off?
BOOLEAN CanHelicopterTakeOff( void )
{
// if it's already in the air
if (fHelicopterIsAirBorne) return TRUE;
VEHICLETYPE const& v = GetHelicopter();
// grab location
INT16 const sHelicopterSector = CALCULATE_STRATEGIC_INDEX(v.sSectorX, v.sSectorY);
// if it's not in enemy control, we can take off
if (!StrategicMap[sHelicopterSector].fEnemyControlled)
{
return( TRUE );
}
return( FALSE );
}
static void AddHeliPiece(INT16 const sGridNo, UINT16 const sOStruct)
{
if (IndexExistsInStructLayer(sGridNo, sOStruct)) return;
AddStructToTail(sGridNo, sOStruct);
}
static void AddHelicopterToMaps(bool const add, RefuelSite const& r)
{
GridNo const grid_no = r.grid_no;
INT16 const ostruct = r.heli_ostruct;
// are we adding or taking away
if (add)
{
AddHeliPiece(grid_no, ostruct );
AddHeliPiece(grid_no, ostruct + 1);
AddHeliPiece(grid_no - 800, ostruct + 2);
AddHeliPiece(grid_no, ostruct + 3);
AddHeliPiece(grid_no, ostruct + 4);
AddHeliPiece(grid_no - 800, ostruct + 5);
// ATE: If any mercs here, bump them off!
INT16 sCentreGridX;
INT16 sCentreGridY;
ConvertGridNoToXY(grid_no, &sCentreGridX, &sCentreGridY);
for (INT16 y = sCentreGridY - 5; y < sCentreGridY + 5; ++y)
{
for (INT16 x = sCentreGridX - 5; x < sCentreGridX + 5; ++x)
{
BumpAnyExistingMerc(MAPROWCOLTOPOS(y, x));
}
}
}
else
{
// remove from the world
RemoveStruct(grid_no, ostruct );
RemoveStruct(grid_no, ostruct + 1);
RemoveStruct(grid_no - 800, ostruct + 2);
RemoveStruct(grid_no, ostruct + 3);
RemoveStruct(grid_no, ostruct + 4);
RemoveStruct(grid_no - 800, ostruct + 5);
}
InvalidateWorldRedundency();
SetRenderFlags(RENDER_FLAG_FULL);
}
bool IsSkyriderFlyingInSector(INT16 const x, INT16 const y)
{
// up and about?
if (iHelicopterVehicleId == -1) return false;
if (!CanHelicopterFly()) return false;
if (!fHelicopterIsAirBorne) return false;
VEHICLETYPE const& v = GetHelicopter();
// the right sector?
return x == v.sSectorX && y == v.sSectorY;
}
bool IsGroupTheHelicopterGroup(GROUP const& g)
{
if (iHelicopterVehicleId == -1) return false;
VEHICLETYPE const& v = GetHelicopter();
return
v.ubMovementGroup != 0 &&
v.ubMovementGroup == g.ubGroupID;
}
INT16 GetNumSafeSectorsInPath()
{
if (!CanHelicopterFly()) return 0;
VEHICLETYPE const& v = GetHelicopter();
INT32 const sector = CALCULATE_STRATEGIC_INDEX(v.sSectorX, v.sSectorY);
GROUP* const g = GetGroup(v.ubMovementGroup);
UINT32 n = 0;
if (PathSt const* i = v.pMercPath)
{
/* First node: Skip it if that's the sector the chopper is currently in, AND
* we're NOT gonna be changing directions (not actually performed until
* waypoints are rebuilt AFTER plotting is done) */
if ((INT32)i->uiSectorId == sector &&
i->pNext &&
!GroupBetweenSectorsAndSectorXYIsInDifferentDirection(g, GET_X_FROM_STRATEGIC_INDEX(i->pNext->uiSectorId), GET_Y_FROM_STRATEGIC_INDEX(i->pNext->uiSectorId)))
{
i = i->pNext;
}
for (; i; i = i->pNext)
{
if (StrategicMap[i->uiSectorId].fEnemyAirControlled) continue;
++n;
}
}
if (PathSt const* i = pTempHelicopterPath)
{
/* First node: Skip it if that's the sector the chopper is currently in, AND
* we're NOT gonna be changing directions (not actually performed until
* waypoints are rebuilt AFTER plotting is done) OR if the chopper has a
* mercpath, in which case this a continuation of it that would count the
* sector twice */
if ((
(INT32)i->uiSectorId == sector &&
i->pNext &&
!GroupBetweenSectorsAndSectorXYIsInDifferentDirection(g, GET_X_FROM_STRATEGIC_INDEX(i->pNext->uiSectorId), GET_Y_FROM_STRATEGIC_INDEX(i->pNext->uiSectorId))
) ||
GetLengthOfPath(v.pMercPath) > 0)
{
i = i->pNext;
}
for (; i; i = i->pNext)
{
if (StrategicMap[i->uiSectorId].fEnemyAirControlled) continue;
++n;
}
}
return n;
}
INT16 GetNumUnSafeSectorsInPath( void )
{
// get the last sector value in the helictoper's path
UINT32 uiLocation = 0;
UINT32 uiCount = 0;
// if the heli is on the move, what is the distance it will move..the length of the merc path, less the first node
if (!CanHelicopterFly()) return 0;
VEHICLETYPE const& v = GetHelicopter();
// may need to skip the sector the chopper is currently in
INT32 const iHeliSector = CALCULATE_STRATEGIC_INDEX(v.sSectorX, v.sSectorY);
// get chopper's group ptr
GROUP* const pGroup = GetGroup(v.ubMovementGroup);
const PathSt* pNode = v.pMercPath;
// any path yet?
if( pNode != NULL )
{
// first node: skip it if that's the sector the chopper is currently in, AND
// we're NOT gonna be changing directions (not actually performed until waypoints are rebuilt AFTER plotting is done)
if ( ( ( INT32 ) pNode->uiSectorId == iHeliSector ) && ( pNode->pNext != NULL ) &&
!GroupBetweenSectorsAndSectorXYIsInDifferentDirection( pGroup, ( UINT8 ) GET_X_FROM_STRATEGIC_INDEX( pNode->pNext->uiSectorId ), ( UINT8 ) GET_Y_FROM_STRATEGIC_INDEX( pNode->pNext->uiSectorId ) ) )
{
pNode = pNode->pNext;
}
while( pNode)
{
uiLocation = pNode -> uiSectorId;
if ( StrategicMap[ uiLocation ].fEnemyAirControlled )
{
uiCount++;
}
pNode = pNode ->pNext;
}
}
pNode = pTempHelicopterPath;
// any path yet?
if( pNode != NULL )
{
// first node: skip it if that's the sector the chopper is currently in, AND
// we're NOT gonna be changing directions (not actually performed until waypoints are rebuilt AFTER plotting is done)
// OR if the chopper has a mercpath, in which case this a continuation of it that would count the sector twice
if ( ( ( ( INT32 ) pNode->uiSectorId == iHeliSector ) && ( pNode->pNext != NULL ) &&
!GroupBetweenSectorsAndSectorXYIsInDifferentDirection( pGroup, ( UINT8 ) GET_X_FROM_STRATEGIC_INDEX( pNode->pNext->uiSectorId ), ( UINT8 ) GET_Y_FROM_STRATEGIC_INDEX( pNode->pNext->uiSectorId ) ) ) ||
GetLengthOfPath(v.pMercPath) > 0)
{
pNode = pNode->pNext;
}
while( pNode)
{
uiLocation = pNode -> uiSectorId;
if ( StrategicMap[ uiLocation ].fEnemyAirControlled )
{
uiCount++;
}
pNode = pNode ->pNext;
}
}
return( (INT16)uiCount );
}
static void PaySkyriderBill(void)
{
// if we owe anything for the trip
if ( iTotalAccumulatedCostByPlayer > 0 )
{
// if player can afford to pay the Skyrider bill
if( LaptopSaveInfo.iCurrentBalance >= iTotalAccumulatedCostByPlayer )
{
// no problem, pay the man
// add the transaction
AddTransactionToPlayersBook( PAYMENT_TO_NPC, SKYRIDER, GetWorldTotalMin( ), -iTotalAccumulatedCostByPlayer );
ScreenMsg( FONT_MCOLOR_DKRED, MSG_INTERFACE, pSkyriderText[ 0 ], iTotalAccumulatedCostByPlayer );
}
else
{
// money owed
if( LaptopSaveInfo.iCurrentBalance > 0 )
{
ScreenMsg( FONT_MCOLOR_DKRED, MSG_INTERFACE, pSkyriderText[ 0 ], LaptopSaveInfo.iCurrentBalance );
gMercProfiles[ SKYRIDER ].iBalance = LaptopSaveInfo.iCurrentBalance - iTotalAccumulatedCostByPlayer;
// add the transaction
AddTransactionToPlayersBook( PAYMENT_TO_NPC, SKYRIDER, GetWorldTotalMin( ), -LaptopSaveInfo.iCurrentBalance );
}
else
{
gMercProfiles[ SKYRIDER ].iBalance = - iTotalAccumulatedCostByPlayer;
}
HeliCharacterDialogue(OWED_MONEY_TO_SKYRIDER);
ScreenMsg( FONT_MCOLOR_DKRED, MSG_INTERFACE, pSkyriderText[ 1 ], -gMercProfiles[ SKYRIDER ].iBalance );
// kick everyone out! (we know we're in a safe sector if we're paying)
MoveAllInHelicopterToFootMovementGroup( );
MakeHeliReturnToBase();
}
iTotalAccumulatedCostByPlayer = 0;
}
}
void PayOffSkyriderDebtIfAny( )
{
INT32 iAmountOwed;
INT32 iPayAmount;
iAmountOwed = - gMercProfiles[ SKYRIDER ].iBalance;
// if we owe him anything, and have any money
if ( ( iAmountOwed > 0 ) && ( LaptopSaveInfo.iCurrentBalance > 0 ) )
{
iPayAmount = MIN( iAmountOwed, LaptopSaveInfo.iCurrentBalance );
// pay the man what we can
gMercProfiles[ SKYRIDER ].iBalance += iPayAmount;
// add the transaction
AddTransactionToPlayersBook( PAYMENT_TO_NPC, SKYRIDER, GetWorldTotalMin( ), -iPayAmount );
// tell player
ScreenMsg( FONT_MCOLOR_DKRED, MSG_INTERFACE, pSkyriderText[ 0 ], iPayAmount );
// now whaddawe owe?
iAmountOwed = - gMercProfiles[ SKYRIDER ].iBalance;
// if it wasn't enough
if ( iAmountOwed > 0 )
{
ScreenMsg( FONT_MCOLOR_DKRED, MSG_INTERFACE, pSkyriderText[ 1 ], iAmountOwed );
HeliCharacterDialogue(OWED_MONEY_TO_SKYRIDER);
}
}
}
static void MakeHeliReturnToBase(void)
{
VEHICLETYPE& v = GetHelicopter();
INT16 sectorID;
sectorID = CALCULATE_STRATEGIC_INDEX(v.sSectorX, v.sSectorY);
// if already at a refueling point
if ( IsRefuelSiteInSector( sectorID ) )
{
LandHelicopter();
}
else
{
// choose destination (closest refueling sector)
RefuelSite const& refuel_site = NearestRefuelPoint(true);
ClearStrategicPathList(v.pMercPath, v.ubMovementGroup);
GROUP& g = *GetGroup(v.ubMovementGroup);
v.pMercPath = BuildAStrategicPath( sectorID, refuel_site.sector, g, FALSE);
RebuildWayPointsForGroupPath(v.pMercPath, g);
fHeliReturnStraightToBase = TRUE;
fHoveringHelicopter = FALSE;
}
// stop time compression if it's on so player can digest this
StopTimeCompression();
}
bool SoldierAboardAirborneHeli(SOLDIERTYPE const& s)
{
return InHelicopter(s) && fHelicopterIsAirBorne;
}
|
/*
Copyright (c) 2015 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include"publishkernels.h"
/************************************************************************************************************
input parameter validator.
param [in] node The handle to the node.
param [in] index The index of the parameter to validate.
*************************************************************************************************************/
static vx_status VX_CALLBACK CV_Scharr_InputValidator(vx_node node, vx_uint32 index)
{
vx_status status = VX_SUCCESS;
vx_parameter param = vxGetParameterByIndex(node, index);
if (index == 0)
{
vx_image image;
vx_df_image df_image = VX_DF_IMAGE_VIRT;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &image, sizeof(vx_image)));
STATUS_ERROR_CHECK(vxQueryImage(image, VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));
if (df_image != VX_DF_IMAGE_U8)
status = VX_ERROR_INVALID_VALUE;
vxReleaseImage(&image);
}
else if (index == 1)
{
vx_image image;
vx_df_image df_image = VX_DF_IMAGE_VIRT;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &image, sizeof(vx_image)));
STATUS_ERROR_CHECK(vxQueryImage(image, VX_IMAGE_ATTRIBUTE_FORMAT, &df_image, sizeof(df_image)));
if (df_image != VX_DF_IMAGE_U8)
status = VX_ERROR_INVALID_VALUE;
vxReleaseImage(&image);
}
else if (index == 2)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_int32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (value < -1 || type != VX_TYPE_INT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
else if (index == 3)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_int32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (value < 0 || type != VX_TYPE_INT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
else if (index == 4)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_int32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (value < 0 || type != VX_TYPE_INT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
else if (index == 5)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_float32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (value < 0 || type != VX_TYPE_FLOAT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
else if (index == 6)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_float32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (type != VX_TYPE_FLOAT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
else if (index == 7)
{
vx_scalar scalar = 0; vx_enum type = 0; vx_int32 value = 0;
STATUS_ERROR_CHECK(vxQueryParameter(param, VX_PARAMETER_ATTRIBUTE_REF, &scalar, sizeof(scalar)));
STATUS_ERROR_CHECK(vxQueryScalar(scalar, VX_SCALAR_ATTRIBUTE_TYPE, &type, sizeof(type)));
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value));
if (type != VX_TYPE_INT32)
status = VX_ERROR_INVALID_VALUE;
vxReleaseScalar(&scalar);
}
vxReleaseParameter(¶m);
return status;
}
/************************************************************************************************************
output parameter validator.
*************************************************************************************************************/
static vx_status VX_CALLBACK CV_Scharr_OutputValidator(vx_node node, vx_uint32 index, vx_meta_format meta)
{
vx_status status = VX_SUCCESS;
if (index == 1)
{
vx_parameter output_param = vxGetParameterByIndex(node, 1);
vx_image output; vx_uint32 width = 0, height = 0; vx_df_image format = VX_DF_IMAGE_VIRT;
STATUS_ERROR_CHECK(vxQueryParameter(output_param, VX_PARAMETER_ATTRIBUTE_REF, &output, sizeof(vx_image)));
STATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format)));
STATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));
STATUS_ERROR_CHECK(vxQueryImage(output, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));
if (format != VX_DF_IMAGE_U8)
status = VX_ERROR_INVALID_VALUE;
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_WIDTH, &width, sizeof(width)));
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_HEIGHT, &height, sizeof(height)));
STATUS_ERROR_CHECK(vxSetMetaFormatAttribute(meta, VX_IMAGE_ATTRIBUTE_FORMAT, &format, sizeof(format)));
vxReleaseImage(&output);
vxReleaseParameter(&output_param);
}
return status;
}
/************************************************************************************************************
Execution Kernel
*************************************************************************************************************/
static vx_status VX_CALLBACK CV_Scharr_Kernel(vx_node node, const vx_reference *parameters, vx_uint32 num)
{
vx_status status = VX_SUCCESS;
vx_image image_in = (vx_image) parameters[0];
vx_image image_out = (vx_image) parameters[1];
vx_scalar scalar = (vx_scalar) parameters[2];
vx_scalar Dx = (vx_scalar) parameters[3];
vx_scalar Dy = (vx_scalar) parameters[4];
vx_scalar Scale = (vx_scalar) parameters[5];
vx_scalar Delta = (vx_scalar) parameters[6];
vx_scalar Bordertype = (vx_scalar) parameters[7];
Mat *mat, bl;
int ddepth, dx, dy, bordertype;
double scale, delta;
vx_int32 value = 0;
vx_float32 value_1 = 0;
//Extracting Values from the Scalar into Ksize and Ddepth
STATUS_ERROR_CHECK(vxReadScalarValue(scalar, &value)); ddepth = value;
STATUS_ERROR_CHECK(vxReadScalarValue(Dx, &value)); dx = value;
STATUS_ERROR_CHECK(vxReadScalarValue(Dy, &value)); dy = value;
STATUS_ERROR_CHECK(vxReadScalarValue(Scale, &value_1)); scale = value_1;
STATUS_ERROR_CHECK(vxReadScalarValue(Delta, &value_1)); delta = value_1;
STATUS_ERROR_CHECK(vxReadScalarValue(Bordertype, &value)); bordertype = value;
//Converting VX Image to OpenCV Mat
STATUS_ERROR_CHECK(match_vx_image_parameters(image_in, image_out));
STATUS_ERROR_CHECK(VX_to_CV_Image(&mat, image_in));
//Compute using OpenCV
cv::Scharr(*mat, bl, ddepth, dx, dy, scale, delta, bordertype);
//Converting OpenCV Mat into VX Image
STATUS_ERROR_CHECK(CV_to_VX_Image(image_out, &bl));
return status;
}
/************************************************************************************************************
Function to Register the Kernel for Publish
*************************************************************************************************************/
vx_status CV_Scharr_Register(vx_context context)
{
vx_status status = VX_SUCCESS;
vx_kernel kernel = vxAddKernel(context,
"org.opencv.scharr",
VX_KERNEL_OPENCV_SCHARR,
CV_Scharr_Kernel,
8,
CV_Scharr_InputValidator,
CV_Scharr_OutputValidator,
nullptr,
nullptr);
if (kernel)
{
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 0, VX_INPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 1, VX_OUTPUT, VX_TYPE_IMAGE, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 2, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 3, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 4, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 5, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 6, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxAddParameterToKernel(kernel, 7, VX_INPUT, VX_TYPE_SCALAR, VX_PARAMETER_STATE_REQUIRED));
PARAM_ERROR_CHECK(vxFinalizeKernel(kernel));
}
if (status != VX_SUCCESS)
{
exit: vxRemoveKernel(kernel); return VX_FAILURE;
}
return status;
}
|
// (C) Copyright Gert-Jan de Vos and Jan Wilmans 2013.
// 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)
// Repository at: https://github.com/djeedjay/DebugViewPP/
#include "stdafx.h"
#include <vector>
#include "Win32Lib.h"
#include "Win32Support.h"
namespace fusion {
ComInitialization::ComInitialization(CoInit init)
{
HRESULT hr = CoInitializeEx(nullptr, init);
if (FAILED(hr))
throw Win32Error(hr, "CoInitializeEx");
}
ComInitialization::~ComInitialization()
{
CoUninitialize();
}
WINDOWPLACEMENT GetWindowPlacement(HWND hwnd)
{
WINDOWPLACEMENT placement;
placement.length = sizeof(placement);
if (!::GetWindowPlacement(hwnd, &placement))
ThrowLastError("GetWindowPlacement");
return placement;
}
POINT GetMessagePos()
{
DWORD pos = ::GetMessagePos();
POINT pt = { GET_X_LPARAM(pos), GET_Y_LPARAM(pos) };
return pt;
}
POINT GetCursorPos()
{
POINT pos;
if (!GetCursorPos(&pos))
ThrowLastError("GetCursorPos");
return pos;
}
} // namespace fusion
|
//+---------------------------------------------------------------------------
//
// Copyright (C) 1996-1997, Microsoft Corporation.
//
// File: varutil.hxx
//
// Contents: Utilities for variable replacement
//
// History: 96/Jan/3 DwightKr Created
//
//----------------------------------------------------------------------------
#pragma once
enum EIsReplaceable {
eIsSimpleString = 0,
eIsSimpleReplacement,
eIsComplexReplacement,
};
EIsReplaceable IsAReplaceableParameter( WCHAR const * wcsString );
WCHAR * ReplaceParameters( WCHAR const * wcsVariableString,
CVariableSet & variableSet,
COutputFormat & outputFormat,
ULONG & cwcOut );
ULONG ReplaceNumericParameter( WCHAR const * wcsVariableString,
CVariableSet & variableSet,
COutputFormat & outputFormat,
ULONG defaultValue,
ULONG min,
ULONG max );
BOOL IsAValidCatalog( WCHAR const * wcsCatalog, ULONG cwc );
LONG IDQ_wtol( WCHAR const *pwcBuf );
|
#include "AccelerationStructure.hpp"
#include "DeviceProcedures.hpp"
#include "RayTracingProperties.hpp"
#include "Utilities/Exception.hpp"
#include "Vulkan/Buffer.hpp"
#include "Vulkan/Device.hpp"
#undef MemoryBarrier
namespace Vulkan::RayTracing {
namespace
{
uint64_t RoundUp(uint64_t size, uint64_t granularity)
{
const auto divUp = (size + granularity - 1) / granularity;
return divUp * granularity;
}
}
AccelerationStructure::AccelerationStructure(const class DeviceProcedures& deviceProcedures, const RayTracingProperties& rayTracingProperties) :
deviceProcedures_(deviceProcedures),
flags_(VK_BUILD_ACCELERATION_STRUCTURE_PREFER_FAST_TRACE_BIT_KHR),
device_(deviceProcedures.Device()),
rayTracingProperties_(rayTracingProperties)
{
}
AccelerationStructure::AccelerationStructure(AccelerationStructure&& other) noexcept :
deviceProcedures_(other.deviceProcedures_),
flags_(other.flags_),
buildGeometryInfo_(other.buildGeometryInfo_),
buildSizesInfo_(other.buildSizesInfo_),
device_(other.device_),
rayTracingProperties_(other.rayTracingProperties_),
accelerationStructure_(other.accelerationStructure_)
{
other.accelerationStructure_ = nullptr;
}
AccelerationStructure::~AccelerationStructure()
{
if (accelerationStructure_ != nullptr)
{
deviceProcedures_.vkDestroyAccelerationStructureKHR(device_.Handle(), accelerationStructure_, nullptr);
accelerationStructure_ = nullptr;
}
}
VkAccelerationStructureBuildSizesInfoKHR AccelerationStructure::GetBuildSizes(const uint32_t* pMaxPrimitiveCounts) const
{
// Query both the size of the finished acceleration structure and the amount of scratch memory needed.
VkAccelerationStructureBuildSizesInfoKHR sizeInfo = {};
sizeInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_BUILD_SIZES_INFO_KHR;
deviceProcedures_.vkGetAccelerationStructureBuildSizesKHR(
device_.Handle(),
VK_ACCELERATION_STRUCTURE_BUILD_TYPE_DEVICE_KHR,
&buildGeometryInfo_,
pMaxPrimitiveCounts,
&sizeInfo);
// AccelerationStructure offset needs to be 256 bytes aligned (official Vulkan specs, don't ask me why).
const uint64_t AccelerationStructureAlignment = 256;
const uint64_t ScratchAlignment = rayTracingProperties_.MinAccelerationStructureScratchOffsetAlignment();
sizeInfo.accelerationStructureSize = RoundUp(sizeInfo.accelerationStructureSize, AccelerationStructureAlignment);
sizeInfo.buildScratchSize = RoundUp(sizeInfo.buildScratchSize, ScratchAlignment);
return sizeInfo;
}
void AccelerationStructure::CreateAccelerationStructure(Buffer& resultBuffer, const VkDeviceSize resultOffset)
{
VkAccelerationStructureCreateInfoKHR createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_ACCELERATION_STRUCTURE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.type = buildGeometryInfo_.type;
createInfo.size = BuildSizes().accelerationStructureSize;
createInfo.buffer = resultBuffer.Handle();
createInfo.offset = resultOffset;
Check(deviceProcedures_.vkCreateAccelerationStructureKHR(device_.Handle(), &createInfo, nullptr, &accelerationStructure_),
"create acceleration structure");
}
void AccelerationStructure::MemoryBarrier(VkCommandBuffer commandBuffer)
{
// Wait for the builder to complete by setting a barrier on the resulting buffer. This is
// particularly important as the construction of the top-level hierarchy may be called right
// afterwards, before executing the command list.
VkMemoryBarrier memoryBarrier = {};
memoryBarrier.sType = VK_STRUCTURE_TYPE_MEMORY_BARRIER;
memoryBarrier.pNext = nullptr;
memoryBarrier.srcAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
memoryBarrier.dstAccessMask = VK_ACCESS_ACCELERATION_STRUCTURE_WRITE_BIT_KHR | VK_ACCESS_ACCELERATION_STRUCTURE_READ_BIT_KHR;
vkCmdPipelineBarrier(
commandBuffer,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
VK_PIPELINE_STAGE_ACCELERATION_STRUCTURE_BUILD_BIT_KHR,
0, 1, &memoryBarrier, 0, nullptr, 0, nullptr);
}
}
|
#include "event_handler.hpp"
#include "event_handler/event_thread.hpp"
#include "event_handler/events.hpp"
#include <cstdint>
#include <cstdlib>
#include <iostream>
std::mutex EventHandler::m_QueueMutex;
std::vector<Event*> EventHandler::m_Queue;
EventThread** EventHandler::m_Threads;
size_t EventHandler::m_ThreadCount;
void EventHandler::Init()
{
// TODO:
// If above core count, use core count
m_ThreadCount = 1; // Ondergrond::CurrentPlatform::GetCoreCount();
m_Threads = new EventThread*[m_ThreadCount];
for (size_t i = 0; i < m_ThreadCount; i++)
m_Threads[i] = new EventThread();
std::atexit(EventHandler::CleanUp);
}
void EventHandler::CleanUp()
{
for (size_t i = 0; i < m_ThreadCount; i++)
delete m_Threads[i];
for (auto t_Element : m_Queue)
delete t_Element;
}
void EventHandler::Run()
{
// While jobs were added to the queue
m_QueueMutex.lock();
while (IsQueueEmpty() == false)
{
// Divide them over the threads
size_t t_CurrentEventThread = 0;
for (size_t i = 0; i < m_Queue.size(); i++)
{
if (m_Queue[i] == nullptr)
break;
auto t_CurrentThread = m_Threads[t_CurrentEventThread];
t_CurrentThread->m_Queue[i] = m_Queue[i];
t_CurrentEventThread = (t_CurrentEventThread + 1) % m_ThreadCount;
}
m_Queue.clear();
m_QueueMutex.unlock();
for (size_t i = m_ThreadCount - 1; i < m_ThreadCount; i--)
{
m_Threads[i]->m_State = EventThread::StateType::Running;
if (i == 0)
{
m_Threads[i]->Join();
break; // Should not be necessary, but here for the sanity of signedness
}
else m_Threads[i]->Detach();
}
m_QueueMutex.lock();
}
m_QueueMutex.unlock();
}
bool EventHandler::IsQueueEmpty()
{
return m_Queue.size() == 0;
}
size_t EventHandler::GetThreadCount()
{
return m_ThreadCount;
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fuchsia/io/c/fidl.h>
#include <lib/zxio/inception.h>
#include <lib/zxio/null.h>
#include <lib/zxio/ops.h>
#include <string.h>
#include <sys/stat.h>
#include <zircon/syscalls.h>
typedef struct zxio_vmo {
// The |zxio_t| control structure for this object.
zxio_t io;
// The underlying VMO that stores the data.
zx_handle_t vmo;
// The size of the VMO in bytes.
//
// This value is read from the kernel during |zxio_vmo_init|, is always a
// multiple of the page size, and is never changed.
zx_off_t size;
// The current seek offset within the file.
//
// Protected by |lock|.
zx_off_t offset;
// The lock that protects |offset|.
//
// TODO: Migrate to sync_mutex_t.
mtx_t lock;
} zxio_vmo_t;
static_assert(sizeof(zxio_vmo_t) <= sizeof(zxio_storage_t),
"zxio_vmo_t must fit inside zxio_storage_t.");
static zx_status_t zxio_vmo_close(zxio_t* io) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
zx_handle_t vmo = file->vmo;
file->vmo = ZX_HANDLE_INVALID;
zx_handle_close(vmo);
return ZX_OK;
}
static zx_status_t zxio_vmo_release(zxio_t* io, zx_handle_t* out_handle) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
zx_handle_t vmo = file->vmo;
file->vmo = ZX_HANDLE_INVALID;
*out_handle = vmo;
return ZX_OK;
}
static zx_status_t zxio_vmo_clone(zxio_t* io, zx_handle_t* out_handle) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
return zx_handle_duplicate(file->vmo, ZX_RIGHT_SAME_RIGHTS, out_handle);
}
static zx_status_t zxio_vmo_attr_get(zxio_t* io, zxio_node_attr_t* out_attr) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
memset(out_attr, 0, sizeof(*out_attr));
out_attr->mode = S_IFREG | S_IRUSR;
out_attr->content_size = file->size;
return ZX_OK;
}
static zx_status_t zxio_vmo_read(zxio_t* io, void* buffer, size_t capacity,
size_t* out_actual) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
mtx_lock(&file->lock);
if (capacity > (file->size - file->offset)) {
capacity = file->size - file->offset;
}
zx_off_t offset = file->offset;
file->offset += capacity;
mtx_unlock(&file->lock);
zx_status_t status = zx_vmo_read(file->vmo, buffer, offset, capacity);
if (status == ZX_OK) {
*out_actual = capacity;
}
return status;
}
static zx_status_t zxio_vmo_read_at(zxio_t* io, size_t offset, void* buffer,
size_t capacity, size_t* out_actual) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
if (offset > file->size) {
return ZX_ERR_INVALID_ARGS;
}
if (capacity > file->size - offset) {
capacity = file->size - offset;
}
zx_status_t status = zx_vmo_read(file->vmo, buffer, offset, capacity);
if (status == ZX_OK) {
*out_actual = capacity;
}
return status;
}
zx_status_t zxio_vmo_write(zxio_t* io, const void* buffer, size_t capacity,
size_t* out_actual) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
mtx_lock(&file->lock);
if (capacity > (file->size - file->offset)) {
capacity = file->size - file->offset;
}
zx_off_t offset = file->offset;
file->offset += capacity;
mtx_unlock(&file->lock);
zx_status_t status = zx_vmo_write(file->vmo, buffer, offset, capacity);
if (status == ZX_OK) {
*out_actual = capacity;
}
return status;
}
zx_status_t zxio_vmo_write_at(zxio_t* io, size_t offset, const void* buffer,
size_t capacity, size_t* out_actual) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
if (offset > file->size) {
return ZX_ERR_INVALID_ARGS;
}
if (capacity > file->size - offset) {
capacity = file->size - offset;
}
zx_status_t status = zx_vmo_write(file->vmo, buffer, offset, capacity);
if (status == ZX_OK) {
*out_actual = capacity;
}
return status;
}
static zx_status_t zxio_vmo_seek(zxio_t* io, size_t offset,
zxio_seek_origin_t start,
size_t* out_offset) {
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(io);
mtx_lock(&file->lock);
zx_off_t at = 0u;
switch (start) {
case fuchsia_io_SeekOrigin_START:
at = offset;
break;
case fuchsia_io_SeekOrigin_CURRENT:
at = file->offset + offset;
break;
case fuchsia_io_SeekOrigin_END:
at = file->size + offset;
break;
default:
mtx_unlock(&file->lock);
return ZX_ERR_INVALID_ARGS;
}
if (at > file->size) {
at = ZX_ERR_OUT_OF_RANGE;
} else {
file->offset = at;
}
mtx_unlock(&file->lock);
*out_offset = at;
return ZX_OK;
}
static constexpr zxio_ops_t zxio_vmo_ops = []() {
zxio_ops_t ops = zxio_default_ops;
ops.close = zxio_vmo_close;
ops.release = zxio_vmo_release;
ops.clone = zxio_vmo_clone;
ops.attr_get = zxio_vmo_attr_get;
ops.read = zxio_vmo_read;
ops.read_at = zxio_vmo_read_at;
ops.write = zxio_vmo_write;
ops.write_at = zxio_vmo_write_at;
ops.seek = zxio_vmo_seek;
return ops;
}();
zx_status_t zxio_vmo_init(zxio_storage_t* storage, zx_handle_t vmo,
zx_off_t offset) {
uint64_t size = 0u;
zx_status_t status = zx_vmo_get_size(vmo, &size);
if (status != ZX_OK) {
zx_handle_close(vmo);
return status;
}
zxio_vmo_t* file = reinterpret_cast<zxio_vmo_t*>(storage);
zxio_init(&file->io, &zxio_vmo_ops);
if (offset > size)
offset = size;
file->vmo = vmo;
file->size = size;
file->offset = offset;
mtx_init(&file->lock, mtx_plain);
return ZX_OK;
}
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_EngramEntry_Saddle_Rhino_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass EngramEntry_Saddle_Rhino.EngramEntry_Saddle_Rhino_C
// 0x0000 (0x0090 - 0x0090)
class UEngramEntry_Saddle_Rhino_C : public UPrimalEngramEntry
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass EngramEntry_Saddle_Rhino.EngramEntry_Saddle_Rhino_C");
return ptr;
}
void ExecuteUbergraph_EngramEntry_Saddle_Rhino(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
// This file is licensed under the Elastic License 2.0. Copyright 2021-present, StarRocks Limited.
#include "storage/vectorized/meta_reader.h"
#include <vector>
#include "column/datum_convert.h"
#include "common/status.h"
#include "storage/rowset/beta_rowset.h"
#include "storage/rowset/column_iterator.h"
#include "storage/rowset/column_reader.h"
#include "storage/tablet.h"
#include "storage/vectorized/chunk_helper.h"
namespace starrocks::vectorized {
std::vector<std::string> SegmentMetaCollecter::support_collect_fields = {"dict_merge", "max", "min"};
Status SegmentMetaCollecter::parse_field_and_colname(const std::string& item, std::string* field,
std::string* col_name) {
for (size_t i = 0; i < support_collect_fields.size(); i++) {
if (item.size() <= support_collect_fields[i].size()) {
continue;
}
if (item.find(support_collect_fields[i]) != std::string::npos &&
item.substr(0, support_collect_fields[i].size()) == support_collect_fields[i]) {
*field = support_collect_fields[i];
*col_name = item.substr(support_collect_fields[i].size() + 1);
return Status::OK();
}
}
return Status::InvalidArgument(item);
}
MetaReader::MetaReader() : _is_init(false), _has_more(false) {}
MetaReader::~MetaReader() {}
Status MetaReader::init(const MetaReaderParams& read_params) {
RETURN_IF_ERROR(_init_params(read_params));
RETURN_IF_ERROR(_build_collect_context(read_params));
RETURN_IF_ERROR(_init_seg_meta_collecters(read_params));
if (_collect_context.seg_collecters.size() == 0) {
_has_more = false;
return Status::OK();
}
_collect_context.cursor_idx = 0;
_is_init = true;
_has_more = true;
return Status::OK();
}
Status MetaReader::_init_params(const MetaReaderParams& read_params) {
read_params.check_validation();
_tablet = read_params.tablet;
_version = read_params.version;
_chunk_size = read_params.chunk_size;
_params = read_params;
return Status::OK();
}
Status MetaReader::_build_collect_context(const MetaReaderParams& read_params) {
_collect_context.seg_collecter_params.max_cid = 0;
for (auto it : *(read_params.id_to_names)) {
std::string col_name = "";
std::string collect_field = "";
RETURN_IF_ERROR(SegmentMetaCollecter::parse_field_and_colname(it.second, &collect_field, &col_name));
int32_t index = _tablet->field_index(col_name);
if (index < 0) {
std::stringstream ss;
ss << "invalid column name: " << it.second;
LOG(WARNING) << ss.str();
return Status::InternalError(ss.str());
}
// get column type
FieldType type = _tablet->tablet_schema().column(index).type();
_collect_context.seg_collecter_params.field_type.emplace_back(type);
// get collect field
_collect_context.seg_collecter_params.fields.emplace_back(collect_field);
// get column id
_collect_context.seg_collecter_params.cids.emplace_back(index);
_collect_context.seg_collecter_params.max_cid = std::max(_collect_context.seg_collecter_params.max_cid, index);
// get result slot id
_collect_context.result_slot_ids.emplace_back(it.first);
// only collect the field of dict need read data page
// others just depend on footer
if (collect_field == "dict_merge") {
_collect_context.seg_collecter_params.read_page.emplace_back(true);
} else {
_collect_context.seg_collecter_params.read_page.emplace_back(false);
}
}
return Status::OK();
}
Status MetaReader::_init_seg_meta_collecters(const MetaReaderParams& params) {
std::vector<SegmentSharedPtr> segments;
RETURN_IF_ERROR(_get_segments(params.tablet, params.version, &segments));
for (auto& segment : segments) {
SegmentMetaCollecter* seg_collecter = new SegmentMetaCollecter(segment);
_obj_pool.add(seg_collecter);
RETURN_IF_ERROR(seg_collecter->init(&_collect_context.seg_collecter_params));
_collect_context.seg_collecters.emplace_back(seg_collecter);
}
return Status::OK();
}
Status MetaReader::_get_segments(const TabletSharedPtr& tablet, const Version& version,
std::vector<SegmentSharedPtr>* segments) {
if (tablet->updates() != nullptr) {
LOG(INFO) << "Skipped Update tablet";
return Status::OK();
}
std::vector<RowsetSharedPtr> rowsets;
Status acquire_rowset_st;
{
std::shared_lock l(tablet->get_header_lock());
acquire_rowset_st = tablet->capture_consistent_rowsets(_version, &rowsets);
}
if (!acquire_rowset_st.ok()) {
std::stringstream ss;
ss << "fail to init reader. tablet=" << tablet->full_name() << "res=" << acquire_rowset_st;
LOG(WARNING) << ss.str();
return Status::InternalError(ss.str().c_str());
}
for (auto& rs : rowsets) {
RETURN_IF_ERROR(rs->load());
auto beta_rowset = down_cast<BetaRowset*>(rs.get());
for (auto seg : beta_rowset->segments()) {
segments->emplace_back(seg);
}
}
return Status::OK();
}
Status MetaReader::_fill_result_chunk(Chunk* chunk) {
for (size_t i = 0; i < _collect_context.result_slot_ids.size(); i++) {
auto s_id = _collect_context.result_slot_ids[i];
auto slot = _params.desc_tbl->get_slot_descriptor(s_id);
if (_collect_context.seg_collecter_params.fields[i] == "dict_merge") {
TypeDescriptor item_desc;
item_desc = slot->type();
TypeDescriptor desc;
desc.type = TYPE_ARRAY;
desc.children.emplace_back(item_desc);
vectorized::ColumnPtr column = vectorized::ColumnHelper::create_column(desc, false);
chunk->append_column(std::move(column), slot->id());
} else {
vectorized::ColumnPtr column = vectorized::ColumnHelper::create_column(slot->type(), false);
chunk->append_column(std::move(column), slot->id());
}
}
return Status::OK();
}
Status MetaReader::do_get_next(ChunkPtr* result) {
const uint32_t chunk_capacity = _chunk_size;
uint16_t chunk_start = 0;
*result = std::make_shared<vectorized::Chunk>();
if (nullptr == result->get()) {
return Status::InternalError("Failed to allocate new chunk.");
}
RETURN_IF_ERROR(_fill_result_chunk(result->get()));
while ((chunk_start < chunk_capacity) && _has_more) {
RETURN_IF_ERROR(_read((*result).get(), chunk_capacity - chunk_start));
(*result)->check_or_die();
size_t next_start = (*result)->num_rows();
chunk_start = next_start;
}
return Status::OK();
}
Status MetaReader::open() {
for (auto collector : _collect_context.seg_collecters) {
RETURN_IF_ERROR(collector->open());
}
return Status::OK();
}
Status MetaReader::_read(Chunk* chunk, size_t n) {
std::vector<vectorized::Column*> columns;
for (size_t i = 0; i < _collect_context.seg_collecter_params.fields.size(); ++i) {
const ColumnPtr& col = chunk->get_column_by_index(i);
columns.emplace_back(col.get());
}
size_t remaining = n;
while (remaining > 0) {
if (_collect_context.cursor_idx >= _collect_context.seg_collecters.size()) {
_has_more = false;
return Status::OK();
}
RETURN_IF_ERROR(_collect_context.seg_collecters[_collect_context.cursor_idx]->collect(&columns));
remaining--;
_collect_context.cursor_idx++;
}
return Status::OK();
}
bool MetaReader::has_more() {
return _has_more;
}
SegmentMetaCollecter::SegmentMetaCollecter(SegmentSharedPtr segment) : _segment(segment) {}
SegmentMetaCollecter::~SegmentMetaCollecter() {}
Status SegmentMetaCollecter::init(const SegmentMetaCollecterParams* params) {
_params = params;
return Status::OK();
}
Status SegmentMetaCollecter::open() {
RETURN_IF_ERROR(_init_return_column_iterators());
return Status::OK();
}
Status SegmentMetaCollecter::_init_return_column_iterators() {
DCHECK_EQ(_params->fields.size(), _params->cids.size());
DCHECK_EQ(_params->fields.size(), _params->read_page.size());
fs::BlockManager* block_mgr = fs::fs_util::block_manager();
RETURN_IF_ERROR(block_mgr->open_block(_segment->file_name(), &_rblock));
_column_iterators.resize(_params->max_cid + 1, nullptr);
for (int i = 0; i < _params->fields.size(); i++) {
if (_params->read_page[i]) {
auto cid = _params->cids[i];
if (_column_iterators[cid] == nullptr) {
RETURN_IF_ERROR(_segment->new_column_iterator(cid, &_column_iterators[cid]));
_obj_pool.add(_column_iterators[cid]);
ColumnIteratorOptions iter_opts;
iter_opts.check_dict_encoding = true;
iter_opts.rblock = _rblock.get();
iter_opts.stats = &_stats;
RETURN_IF_ERROR(_column_iterators[cid]->init(iter_opts));
}
}
}
return Status::OK();
}
Status SegmentMetaCollecter::collect(std::vector<vectorized::Column*>* dsts) {
DCHECK_EQ(dsts->size(), _params->fields.size());
for (size_t i = 0; i < _params->fields.size(); i++) {
RETURN_IF_ERROR(_collect(_params->fields[i], _params->cids[i], (*dsts)[i], _params->field_type[i]));
}
return Status::OK();
}
Status SegmentMetaCollecter::_collect(const std::string& name, ColumnId cid, vectorized::Column* column,
FieldType type) {
if (name == "dict_merge") {
return _collect_dict(cid, column, type);
} else if (name == "max") {
return _collect_max(cid, column, type);
} else if (name == "min") {
return _collect_min(cid, column, type);
}
return Status::NotSupported("Not Support Collect Meta: " + name);
}
// collect dict
Status SegmentMetaCollecter::_collect_dict(ColumnId cid, vectorized::Column* column, FieldType type) {
if (!_column_iterators[cid]) {
return Status::InvalidArgument("Invalid Collect Params.");
}
std::vector<Slice> words;
if (!_column_iterators[cid]->all_page_dict_encoded()) {
// if all_page_dict_encoded if false, return fake dict word which cardinality exceed low cardinality base size
// so FE will not collect again and mark this column not a low cardinality
words = FAKE_DICT_SLICE_WORDS;
} else {
RETURN_IF_ERROR(_column_iterators[cid]->fetch_all_dict_words(&words));
}
vectorized::ArrayColumn* array_column = nullptr;
array_column = down_cast<vectorized::ArrayColumn*>(column);
auto* offsets = array_column->offsets_column().get();
auto& data = offsets->get_data();
size_t end_offset = data.back();
end_offset += words.size();
offsets->append(end_offset);
// add elements
auto dst = array_column->elements_column().get();
dst->append_strings(words);
return Status::OK();
}
Status SegmentMetaCollecter::_collect_max(ColumnId cid, vectorized::Column* column, FieldType type) {
return __collect_max_or_min<true>(cid, column, type);
}
Status SegmentMetaCollecter::_collect_min(ColumnId cid, vectorized::Column* column, FieldType type) {
return __collect_max_or_min<false>(cid, column, type);
}
template <bool is_max>
Status SegmentMetaCollecter::__collect_max_or_min(ColumnId cid, vectorized::Column* column, FieldType type) {
if (cid >= _segment->num_columns()) {
return Status::NotFound("");
}
const ColumnReader* col_reader = _segment->column(cid);
if (col_reader == nullptr || col_reader->segment_zone_map() == nullptr) {
return Status::NotFound("");
}
if (col_reader->column_type() != type) {
return Status::InternalError("column type mismatch");
}
const ZoneMapPB* segment_zone_map_pb = col_reader->segment_zone_map();
TypeInfoPtr type_info = get_type_info(delegate_type(type));
if constexpr (!is_max) {
vectorized::Datum min;
if (!segment_zone_map_pb->has_null()) {
RETURN_IF_ERROR(vectorized::datum_from_string(type_info.get(), &min, segment_zone_map_pb->min(), nullptr));
column->append_datum(min);
}
} else if constexpr (is_max) {
vectorized::Datum max;
if (segment_zone_map_pb->has_not_null()) {
RETURN_IF_ERROR(vectorized::datum_from_string(type_info.get(), &max, segment_zone_map_pb->max(), nullptr));
column->append_datum(max);
}
}
return Status::OK();
}
} // namespace starrocks::vectorized
|
#include "src/glib_src.h"
#if _USER_DRIVER == _WINDOWS_DRIVER
#ifdef UNICODE
LPCWSTR WIN_cname = L"GLIB_WNDCLASS";
#else
char * WIN_cname = "GLIB_WNDCLASS";
#endif
HINSTANCE WIN_hinstance;
bool WIN_wmpaint = false;
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hprev, LPSTR str, int cmd)
{
WIN_hinstance = hInst;
WIN_Initialize();
int argc = 0;
u_int max_cnt = 0;
while (*(str + max_cnt) || *(str + max_cnt + 1))
{
max_cnt++;
if (*(str + max_cnt) == 0)
argc++;
}
u_int * argv;
if (argc != 0) {
argv = (u_int *)malloc((u_int)argc * (u_int)sizeof(u_int));
u_int ptr = 0;
u_int last = 0;
for (u_int i = 0; i <= max_cnt; i++) {
if (str[i] == 0)
{
*(argv + ptr) = (u_int)(int)(void *)&str[last];
last = i + 1;
ptr++;
}
}
}
else argv = NULL;
int res = gmain((char **)argv, argc);
exit(res);
return res;
}
int WIN_Initialize()
{
glibSetDefaultLanguage();
return WIN_RegisterClass();
}
int WIN_RegisterClass()
{
WNDCLASS c;
c.cbClsExtra = 0;
c.cbWndExtra = 0;
c.hbrBackground = (HBRUSH)COLOR_WINDOW;
c.hCursor = LoadCursor(NULL, IDC_ARROW);
c.hIcon = LoadIcon(NULL, IDI_APPLICATION);
c.hInstance = WIN_hinstance;
c.lpfnWndProc = WndProc;
c.lpszClassName = WIN_cname;
c.lpszMenuName = NULL;
c.style = CS_VREDRAW | CS_HREDRAW;
if (!RegisterClass(&c)) return -1;
return 0;
}
int WIN_Paint(EventArgs * args, Window w)
{
if (glibCheckWindowEvent(w, EVENT_DRAW)) {
glibStartWindowDraw(w);
args->msg = EVENT_DRAW;
return glibRunWindowEvent(w, args);
}
return 0;
}
#define DefWinProc DefWindowProc(wnd, msg, wp, lp)
LRESULT CALLBACK WndProc(HWND wnd, UINT msg, WPARAM wp, LPARAM lp)
{
Window w = EX_GetWindow(wnd);
if (w == NULL) return DefWinProc;
if WINDOW_FAILED(w) return DefWinProc;
EventArgs args;
if (msg == WM_DESTROY)
{
args.msg = EVENT_CLOSED;
glibRunWindowEvent(w, &args);
glibCloseWindow(w);
return 0;
}
switch (msg)
{
case WM_SHOWWINDOW:
if (glibCheckWindowEvent(w, EVENT_SHOWN)) {
args.msg = EVENT_SHOWN;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_CLOSE:
if (glibCheckWindowEvent(w, EVENT_CLOSING)) {
args.flag = EVENT_CLOSING_CLOSE;
args.msg = EVENT_CLOSING;
if (glibRunWindowEvent(w, &args)) {
if (args.flag == EVENT_CLOSING_CLOSE) glibCloseWindow(w);
return 0;
}
return 1;
}
break;
case WM_SIZE:
w->width = LITTLE_WORD(lp);
w->height = BIG_WORD(lp);
if (glibCheckWindowEvent(w, EVENT_RESIZE)) {
args.msg = EVENT_RESIZE;
if (wp == SIZE_MINIMIZED) args.flag = EVENT_RESIZE_MINIMIZED;
if (wp == SIZE_MAXIMIZED) args.flag = EVENT_RESIZE_MAXIMIZED;
else args.flag = EVENT_RESIZE_RESTORED;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_MOVE:
w->x = LITTLE_WORD(lp);
w->y = BIG_WORD(lp);
if (glibCheckWindowEvent(w, EVENT_MOVED)) {
args.msg = EVENT_MOVED;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_PAINT:
WIN_wmpaint = true;
WIN_Paint(&args, w);
WIN_wmpaint = false;
if (w->flags & SYS_REDRAW)
return DefWinProc;
return 0;
break;
case WM_LBUTTONDOWN:
if (glibCheckWindowEvent(w, EVENT_MOUSEDOWN)) {
args.msg = EVENT_MOUSEDOWN;
args.flag = MOUSE_LEFTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_MBUTTONDOWN:
if (glibCheckWindowEvent(w, EVENT_MOUSEDOWN)) {
args.msg = EVENT_MOUSEDOWN;
args.flag = MOUSE_MIDDLEBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_RBUTTONDOWN:
if (glibCheckWindowEvent(w, EVENT_MOUSEDOWN)) {
args.msg = EVENT_MOUSEDOWN;
args.flag = MOUSE_RIGHTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_XBUTTONDOWN:
if (glibCheckWindowEvent(w, EVENT_MOUSEDOWN)) {
args.msg = EVENT_MOUSEDOWN;
if ((u_int16)((wp >> 16) & 0xffff) == 1) args.flag = MOUSE_X1BUTTON;
else args.flag = MOUSE_X2BUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_LBUTTONUP:
if (glibCheckWindowEvent(w, EVENT_MOUSEUP)) {
args.msg = EVENT_MOUSEUP;
args.flag = MOUSE_LEFTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_MBUTTONUP:
if (glibCheckWindowEvent(w, EVENT_MOUSEUP)) {
args.msg = EVENT_MOUSEUP;
args.flag = MOUSE_MIDDLEBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_RBUTTONUP:
if (glibCheckWindowEvent(w, EVENT_MOUSEUP)) {
args.msg = EVENT_MOUSEUP;
args.flag = MOUSE_RIGHTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_XBUTTONUP:
if (glibCheckWindowEvent(w, EVENT_MOUSEUP)) {
args.msg = EVENT_MOUSEUP;
if ((u_int16)((wp >> 16) & 0xffff) == 1) args.flag = MOUSE_X1BUTTON;
else args.flag = MOUSE_X2BUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_LBUTTONDBLCLK:
if (glibCheckWindowEvent(w, EVENT_DOUBLECLICK)) {
args.msg = EVENT_DOUBLECLICK;
args.flag = MOUSE_LEFTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_MBUTTONDBLCLK:
if (glibCheckWindowEvent(w, EVENT_DOUBLECLICK)) {
args.msg = EVENT_DOUBLECLICK;
args.flag = MOUSE_MIDDLEBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_RBUTTONDBLCLK:
if (glibCheckWindowEvent(w, EVENT_DOUBLECLICK)) {
args.msg = EVENT_DOUBLECLICK;
args.flag = MOUSE_RIGHTBUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_XBUTTONDBLCLK:
if (glibCheckWindowEvent(w, EVENT_DOUBLECLICK)) {
args.msg = EVENT_DOUBLECLICK;
if (BIG_WORD(wp) == 1) args.flag = MOUSE_X1BUTTON;
else args.flag = MOUSE_X2BUTTON;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_MOUSEMOVE:
Mouse.x = ((int32)(int16)LITTLE_WORD(lp));
Mouse.y = ((int32)(int16)BIG_WORD(lp));
if (glibCheckWindowEvent(w, EVENT_MOUSEMOVE)) {
args.msg = EVENT_MOUSEMOVE;
return !glibRunWindowEvent(w, &args);
}
break;
case WM_KEYDOWN:
if (glibCheckWindowEvent(w, EVENT_KEYDOWN)) {
args.msg = EVENT_KEYDOWN;
args.flag = (u_int32)wp;
return !glibRunWindowEvent(w, &args);
}
break;
}
return DefWinProc;
}
void WIN_DrawWindow(Image im, Window w, Point min, Point max)
{
byte * ptr = (byte *)malloc((max.x - min.x) * (max.y - min.y) * 4);
if (ptr == NULL) return;
HDC hdc;
PAINTSTRUCT p;
if (WIN_wmpaint) hdc = BeginPaint((HWND)w->ptr, &p);
else hdc = GetDC((HWND)w->ptr);
HBITMAP hBitmap = CreateCompatibleBitmap(hdc, max.x - min.x, max.y - min.y);
u_int add = 0, iadd = (min.y * im->width + min.x) * 4;
u_int addad = (min.x - max.x + im->width) * 4;
for (long y = min.y; y < (long)max.y; y++)
{
for (long x = min.x; x < (long)max.x; x++, add += 4, iadd += 4)
{
*(ptr + add) = *(im->image + iadd + 3);
*(ptr + add + 1) = *(im->image + iadd + 2);
*(ptr + add + 2) = *(im->image + iadd + 1);
*(ptr + add + 3) = *(im->image + iadd);
}
iadd += addad;
}
SetBitmapBits(hBitmap, (max.x - min.x) * (max.y - min.y) * 4, ptr);
HDC hdcMem = CreateCompatibleDC(hdc);
HGDIOBJ oldBitmap = SelectObject(hdcMem, hBitmap);
BitBlt(hdc, 0, 0, (max.x - min.x), (max.y - min.y), hdcMem, 0, 0, SRCCOPY);
SelectObject(hdcMem, oldBitmap);
DeleteObject(oldBitmap);
DeleteObject(hBitmap);
DeleteDC(hdcMem);
if (WIN_wmpaint) EndPaint((HWND)w->ptr, &p);
ReleaseDC((HWND)w->ptr, hdc);
free(ptr);
}
int WIN_MainLoop()
{
MSG msg = { 0 };
while (msg.message != WM_QUIT)
{
if (PeekMessage(&msg, NULL, 0, -1, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{
EventArgs args;
args.msg = EVENT_BASIC;
Window w = glib_window_last;
while (w != NULL)
{
if (glibCheckWindowEvent(w, EVENT_BASIC)) glibRunWindowEvent(w, &args);
w = (Window)w->prev;
}
}
}
return (int)msg.lParam;
}
int WIN_CreateConsole()
{/*
AllocConsole();
HANDLE handle_out = GetStdHandle(STD_OUTPUT_HANDLE);
int hCrt = _open_osfhandle((long)handle_out, _O_TEXT);
FILE* hf_out = _fdopen(hCrt, "w");
setvbuf(hf_out, NULL, _IONBF, 1);
*stdout = *hf_out;
HANDLE handle_in = GetStdHandle(STD_INPUT_HANDLE);
hCrt = _open_osfhandle((long)handle_in, _O_TEXT);
FILE* hf_in = _fdopen(hCrt, "r");
setvbuf(hf_in, NULL, _IONBF, 128);
*stdin = *hf_in;
*/
return 0;
}
HBITMAP WIN_HBITMAP(HDC dc, Point pos, LPWSTR text, Image im, ARGB font, ARGB back)
{
byte * ptr = (byte *)malloc(im->width * im->height * 4);
HDC compatibleDeviceContext = CreateCompatibleDC(dc);
HBITMAP bitmapHandle = CreateCompatibleBitmap(dc, im->width, im->height);
u_int add = 0, iadd = 0;
for (long y = 0; y < (long)im->height; y++)
for (long x = 0; x < (long)im->width; x++, add += 4, iadd += 4)
{
*(ptr + add) = *(im->image + iadd + 3);
*(ptr + add + 1) = *(im->image + iadd + 2);
*(ptr + add + 2) = *(im->image + iadd + 1);
*(ptr + add + 3) = *(im->image + iadd);
}
SetBitmapBits(bitmapHandle, im->width * im->height * 4, ptr);
free(ptr);
HGDIOBJ previousSelectedHandle = SelectObject(compatibleDeviceContext, bitmapHandle);
SetTextColor(compatibleDeviceContext, RGB(font.r, font.g, font.b));
if (back.a != 0)
SetBkColor(compatibleDeviceContext, RGB(back.r, back.g, back.b));
else
SetBkMode(compatibleDeviceContext, TRANSPARENT);
TextOut(compatibleDeviceContext, pos.x, pos.y, text, strlen(text));
SelectObject(compatibleDeviceContext, previousSelectedHandle);
DeleteDC(compatibleDeviceContext);
return bitmapHandle;
}
void WIN_DrawText(Image im, Point pos, char * str, u_int32 format, ARGB font, ARGB back)
{
HDC deviceContext = GetDC(nullptr);
w_char * wstr = (w_char *)malloc((strlen(str) + 1) * sizeof(w_char));
glibConvertString(str, wstr);
HBITMAP capturedBitmap = WIN_HBITMAP(deviceContext, pos, wstr, im, font, back);
free(wstr);
BITMAPINFO bitmapInfo = { 0 };
bitmapInfo.bmiHeader.biSize = sizeof(bitmapInfo.bmiHeader);
GetDIBits(deviceContext, capturedBitmap, 0, 0, nullptr, &bitmapInfo, DIB_RGB_COLORS);
byte * pixels = new byte[bitmapInfo.bmiHeader.biSizeImage];
bitmapInfo.bmiHeader.biCompression = BI_RGB;
GetDIBits(deviceContext, capturedBitmap, 0, bitmapInfo.bmiHeader.biHeight, (LPVOID)pixels, &bitmapInfo, DIB_RGB_COLORS);
int iy = im->width * im->height * 4 - im->width * 4;
for(int y = 0; y < im->height; y++, iy -= im->width * 4)
for (int x = 0; x < im->width; x++)
{
byte * cls = (pixels + y * im->width * 4 + x * 4);
ARGB clr = ARGB{ cls[3], cls[2], cls[1], cls[0] };
*(ARGB *)(void *)(im->image + iy + x * 4) = clr;
}
DeleteObject(capturedBitmap);
ReleaseDC(nullptr, deviceContext);
delete[] pixels;
}
#endif
|
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
#include "aodv-weep-id-cache.h"
#include <algorithm>
namespace ns3 {
namespace weep {
bool
IdCache::IsDuplicate (Ipv4Address addr, uint32_t id)
{
Purge ();
for (std::vector<UniqueId>::const_iterator i = m_idCache.begin ();
i != m_idCache.end (); ++i)
{
if (i->m_context == addr && i->m_id == id)
{
return true;
}
}
struct UniqueId uniqueId =
{
addr, id, m_lifetime + Simulator::Now ()
};
m_idCache.push_back (uniqueId);
return false;
}
void
IdCache::Purge ()
{
m_idCache.erase (remove_if (m_idCache.begin (), m_idCache.end (),
IsExpired ()), m_idCache.end ());
}
uint32_t
IdCache::GetSize ()
{
Purge ();
return m_idCache.size ();
}
}
}
|
#include "nodehandle.h"
NodeHandle::NodeHandle()
{
Readyaml();
AngleLUT();
save_sub = nh.subscribe("interface/bin_save", 1000, &NodeHandle::SaveButton_setting, this);
//blackframe_pub = nh.advertise<sensor_msgs::Image>("camera/black", 1);
blackdis_pub = nh.advertise<std_msgs::Int32MultiArray>("BlackRealDis", 1);
//http://localhost:8080/stream?topic=/camera/image_monitor webfor /camera/image
}
void NodeHandle::AngleLUT()
{
double ang_PI;
for (int ang = 0; ang <= 360; ang++)
{
ang_PI = ang * PI / 180;
Angle_sin.push_back(sin(ang_PI));
Angle_cos.push_back(cos(ang_PI));
}
}
void NodeHandle::Readyaml()
{
std::string param = YAML_PATH;
const char *parampath = param.c_str();
if (ifstream(parampath))
{
std::string temp = "rosparam load " + param + " FIRA/vision";
const char *load = temp.c_str();
system(load);
cout << "Read the yaml file" << endl;
Parameter_getting();
}
else
{
ROS_ERROR("yaml file does not exist");
}
}
void NodeHandle::Parameter_getting()
{
cout << "get parameter" << endl;
//===================中心參數=========================
nh.getParam("FIRA/vision/Center/Center_X", CenterXMsg);
nh.getParam("FIRA/vision/Center/Center_Y", CenterYMsg);
nh.getParam("FIRA/vision/Center/Inner", InnerMsg);
nh.getParam("FIRA/vision/Center/Outer", OuterMsg);
nh.getParam("FIRA/vision/Center/Front", FrontMsg);
nh.getParam("FIRA/vision/Center/Camera_high", Camera_HighMsg);
//==================黑白掃描參數=======================
nh.getParam("FIRA/vision/HSV/black/gray", BlackGrayMsg);
nh.getParam("FIRA/vision/HSV/black/angle", BlackAngleMsg);
}
//======================前置處理結束========================
int NodeHandle::Frame_Area(int coordinate, int range)
{
if (coordinate < 0)
coordinate = 0;
else if (coordinate >= range)
coordinate = range - 1;
return coordinate;
}
//角度調整
//修正大於或小於360的角度
int NodeHandle::Angle_Adjustment(int angle)
{
if (angle < 0)
return angle + 360;
else if (angle >= 360)
return angle - 360;
else
return angle;
}
//========================save============================
void NodeHandle::SaveButton_setting(const vision::bin msg)
{
//cout<<"Save\n";
SaveButton = msg.bin;
Parameter_getting();
}
//========================distance========================
//========================publisher=======================
double NodeHandle::camera_f(double Omni_pixel)
{
double m = (Omni_pixel * 0.0099) / 60; // m = H1/H0 = D1/D0 D0 + D1 = 180
double D0 = 180 / (1 + m); // D1 = m *D0
double D1 = 180 / (1 + (1 / m)); // D0 = 1/m *D1
double f = 1 / (1 / D0 + 1 / D1);
//ROS_INFO("m = %f D0 = %f D1 = %f F = %f",m,D0,D1,f);
return D1;
}
double NodeHandle::Omni_distance(double pixel_dis)
{
double Z = -1 * Camera_HighMsg; //Camera_HighMsg=650mm;
//double c = D0/2;
double c = 83.125;
double b = c * 0.8722;
double f = camera_f(OuterMsg * 2 * 0.9784);
double r = atan2(f, pixel_dis * 0.0099);
double dis = Z * (pow(b, 2) - pow(c, 2)) * cos(r) / ((pow(b, 2) + pow(c, 2)) * sin(r) - 2 * b * c) * 0.1;
if (dis < 0 || dis > 999)
{
dis = 999;
}
//ROS_INFO("%f %f %f %f",Z,c,r,dis);
return dis;
}
//========================publisher=======================
void NodeHandle::Pub_blackframe(Mat frame)
{
sensor_msgs::ImagePtr blackframeMsg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", frame).toImageMsg();
blackframe_pub.publish(blackframeMsg);
}
void NodeHandle::Pub_blackdis(std_msgs::Int32MultiArray distance)
{
blackdis_pub.publish(distance);
}
|
#ifndef DEQUE_POSTINGS_H
#define DEQUE_POSTINGS_H
#include <deque>
#include <iostream>
#include "index/PostingsInterface.hpp"
namespace tsdb {
namespace index {
class DequePostings : public PostingsInterface {
private:
std::deque<uint64_t> list;
mutable int i;
public:
DequePostings() : i(-1) {}
DequePostings(std::deque<uint64_t> &&list) : list(std::move(list)), i(-1) {}
bool next() const {
// NOTICE(Alec), static_cast to int first.
if (i >= static_cast<int>(list.size()) - 1) return false;
++i;
return true;
}
bool seek(uint64_t v) const {
if (list.empty() || i >= static_cast<int>(list.size())) return false;
if (i < 0) i = 0;
if (list[i] >= v) return true;
auto it = std::lower_bound(list.begin() + i, list.end(), v);
if (it == list.end()) {
i = list.size();
return false;
}
i = it - list.begin();
return true;
}
// next() or seek() must be called first.
uint64_t at() const { return list[i]; }
void push_back(uint64_t t) { list.push_back(t); }
int size() const { return list.size(); }
void sort() { std::sort(list.begin(), list.end()); }
};
} // namespace index
} // namespace tsdb
#endif
|
#ifndef INPUT_SATURATION_H
#define INPUT_SATURATION_H
namespace cgmres {
// Stores parameters representing the saturation on the control input.
// Member variables of InputSaturation:
// index_: the index of the element of the control input that is constrained.
// min_: the minimum value of the constrained element of the control input.
// max_: the maximum value of the constrained element of the control input.
// dummy_weight_: the weight parameter on the corresponding dummy input in the
// cost function.
// quadratic_weiht_: the weight parameter on the quadratic term for the
// corresponding dummy input in the cost function.
// Each member variables can be obtained by access functions, e.g., by index(),
// min(), max(), dummy_weight(), and quadratic_weight().
class InputSaturation {
public:
// Constructs InputSaturation with setting member variables as
// index_=0, min_=0, max_=0, dummy_weight_=0, and quadratic_weight=0.
InputSaturation();
// Constructs InputSaturation with setting member variables
// index_, min_, max_, dummy_weight_, and quadratic_weight with values in
// arguments.
InputSaturation(const int index, const double min, const double max,
const double dummy_weight, const double quadratic_weight);
// Constructs InputSaturation with setting member variables
// index_, min_, max_, dummy_weight_, and with values in arguments and
// setting quadratic_weight with 0.
InputSaturation(const int index, const double min, const double max,
const double dummy_weight);
// Copy constructer of InputSaturation.
// Copy all private member variables, index_, min_, max_, dummy_weight_,
// and quadratic_weight_.
InputSaturation(const InputSaturation& other);
// Copy all private member variables, index_, min_, max_, dummy_weight_,
// and quadratic_weight_.
InputSaturation& operator=(const InputSaturation& other);
// Operator override for sort.
bool operator<(const InputSaturation& other) const;
// Sets index_, min_, max_, dummy_weight_, and quadratic_weight with values
// in arguments.
void setParameters(const int index, const double min, const double max,
const double dummy_weight, const double quadratic_weight);
// Sets index_, min_, max_, and dummy_weight_, with values in arguments and
// sets quadratic_weight with 0.
void setParameters(const int index, const double min, const double max,
const double dummy_weight);
// Returns the index of the element of the control input that is constrained.
inline int index() const {
return index_;
}
// Returns the minimum value of the constrained element of the control input.
inline double min() const {
return min_;
}
// Returns the maximum value of the constrained element of the control input.
inline double max() const {
return max_;
}
// Returns the weight parameter on the corresponding dummy input in the cost
// function.
inline double dummy_weight() const {
return dummy_weight_;
}
// Returns the weight parameter on the quadratic term for the corresponding
// dummy input in the cost function.
inline double quadratic_weight() const {
return quadratic_weight_;
}
private:
int index_;
double min_, max_, dummy_weight_, quadratic_weight_;
};
} // namespace cgmres
#endif // INPUT_SATURATION_H
|
//
// Copyright (C) 2017 Alex Smith
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
#include "CRasteriser.h"
#include "CSurface.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <SDL.h>
static const uint32_t kWindowWidth = 512;
static const uint32_t kWindowHeight = 512;
static void Draw(CSurface& inSurface,
CRasteriser& inRasteriser)
{
const SVertex vertices[3] =
{
{{-0.5f, -0.5f, 1.0f, 1.0f}, {1.0f, 0.0f, 0.0f, 1.0f}},
{{ 0.5f, -0.5f, 1.0f, 1.0f}, {0.0f, 1.0f, 0.0f, 1.0f}},
{{ 0.0f, 0.5f, 1.0f, 1.0f}, {0.0f, 0.0f, 1.0f, 1.0f}},
};
inRasteriser.DrawTriangle(inSurface, vertices);
}
int main(int argc, char** argv)
{
SDL_Init(SDL_INIT_VIDEO);
SDL_Window* window = SDL_CreateWindow("swrast",
SDL_WINDOWPOS_CENTERED,
SDL_WINDOWPOS_CENTERED,
kWindowWidth,
kWindowHeight,
0);
CSurface surface(kWindowWidth, kWindowHeight);
SDL_Surface* sourceSDLSurface = surface.CreateSDLSurface();
SDL_Surface* destSDLSurface = SDL_GetWindowSurface(window);
SDL_SetSurfaceBlendMode(destSDLSurface, SDL_BLENDMODE_NONE);
double totalDrawTime = 0.0;
double totalFrameTime = 0.0;
uint32_t numFrames = 0;
const uint64_t perfFreq = SDL_GetPerformanceFrequency();
CRasteriser rasteriser;
while (true)
{
const uint64_t frameStart = SDL_GetPerformanceCounter();
SDL_Event event;
if (SDL_PollEvent(&event))
{
if (event.type == SDL_QUIT)
break;
}
surface.Clear();
const uint64_t drawStart = SDL_GetPerformanceCounter();
Draw(surface, rasteriser);
const uint64_t drawEnd = SDL_GetPerformanceCounter();
SDL_BlitSurface(sourceSDLSurface, nullptr, destSDLSurface, nullptr);
SDL_UpdateWindowSurface(window);
const uint64_t frameEnd = SDL_GetPerformanceCounter();
totalDrawTime += static_cast<double>((drawEnd - drawStart) * 1000) / perfFreq;
totalFrameTime += static_cast<double>((frameEnd - frameStart) * 1000) / perfFreq;
numFrames++;
if (totalFrameTime >= 2000.0)
{
const double avgDrawTime = totalDrawTime / numFrames;
const double avgFrameTime = totalFrameTime / numFrames;
printf("Average: draw = %.4f ms, frame = %.4f ms\n",
avgDrawTime,
avgFrameTime);
totalDrawTime = totalFrameTime = 0.0;
numFrames = 0;
}
}
return 0;
}
|
#include <CL/cl.hpp>
#include <fstream>
#include <iostream>
#include <algorithm>
// =================================================================
// ---------------------- Secondary Functions ----------------------
// =================================================================
cl::Device getDefaultDevice(); // Return the first device found in this OpenCL platform.
void initializeDevice(); // Inicialize device and compile kernel code.
void seqMultiplyMatrices(int* a,
int* b,
int* c,
const int M,
const int N,
const int K); // Sequentially performs the operation c[M,N] = a[M,K] * b[K,N].
void parMultiplyMatrices(int* a,
int* b,
int* c,
const int M,
const int N,
const int K); // Parallelly performs the operation c[M,N] = a[M,K] * b[K,N].
bool checkEquality(int* c1,
int* c2,
const int M,
const int N); // Check if the matrices c1 and c2 are equal.
// =================================================================
// ------------------------ Global Variables ------------------------
// =================================================================
cl::Program program; // The program that will run on the device.
cl::Context context; // The context which holds the device.
cl::Device device; // The device where the kernel will run.
// =================================================================
// ------------------------- Main Function -------------------------
// =================================================================
int main(){
/**
* Create auxiliary variables.
* */
clock_t start, end;
const int EXECUTIONS = 40;
/**
* Prepare input constants related to the dimensions of the matrices.
* */
const int M = 1 << 4;
const int N = 1 << 4;
const int K = 1 << 12;
/**
* Prepare input matrices A and B.
* */
const size_t ROWS_A = M;
const size_t COLS_A = K;
std::vector<int> a(ROWS_A * COLS_A, 3);
const size_t ROWS_B = K;
const size_t COLS_B = N;
std::vector<int> b(ROWS_B * COLS_B, 5);
/**
* Prepare sequential and parallel output matrices.
* */
const size_t ROWS_C = M;
const size_t COLS_C = N;
std::vector<int> cs(ROWS_C * COLS_C);
std::vector<int> cp(ROWS_C * COLS_C);
/**
* Sequentially multiply matrices.
* */
start = clock();
for(int i = 0; i < EXECUTIONS; i++){
seqMultiplyMatrices(a.data(), b.data(), cs.data(), M, N, K);
}
end = clock();
double seqTime = ((double) 10e3 * (end - start)) / CLOCKS_PER_SEC / EXECUTIONS;
/**
* Initialize OpenCL device.
* */
initializeDevice();
/**
* Parallelly multiply matrices.
* */
start = clock();
for(int i = 0; i < EXECUTIONS; i++){
parMultiplyMatrices(a.data(), b.data(), cp.data(), M, N, K);
}
end = clock();
double parTime = ((double) 10e3 * (end - start)) / CLOCKS_PER_SEC / EXECUTIONS;
/**
* Check if outputs are equal.
* */
bool equal = checkEquality(cs.data(), cp.data(), ROWS_C, COLS_C);
/**
* Print results.
* */
std::cout << "Status: " << (equal ? "SUCCESS!" : "FAILED!") << std::endl;
std::cout << "Results: \n\tA[0] = " << a[0] << "\n\tB[0] = " << b[0] << "\n\tC[0] = " << cp[0] << std::endl;
std::cout << "Mean execution time: \n\tSequential: " << seqTime << " ms;\n\tParallel: " << parTime << " ms." << std::endl;
std::cout << "Performance gain: " << (100 * (seqTime - parTime) / parTime) << "\%\n";
return 0;
}
// =================================================================
// ---------------------- Secondary Functions ----------------------
// =================================================================
/**
* Return the first device found in this OpenCL platform.
* */
cl::Device getDefaultDevice(){
/**
* Search for all the OpenCL platforms available and check
* if there are any.
* */
std::vector<cl::Platform> platforms;
cl::Platform::get(&platforms);
if (platforms.empty()){
std::cerr << "No platforms found!" << std::endl;
exit(1);
}
/**
* Search for all the devices on the first platform and check if
* there are any available.
* */
auto platform = platforms.front();
std::vector<cl::Device> devices;
platform.getDevices(CL_DEVICE_TYPE_ALL, &devices);
if (devices.empty()){
std::cerr << "No devices found!" << std::endl;
exit(1);
}
/**
* Return the first device found.
* */
return devices.front();
}
/**
* Inicialize device and compile kernel code.
* */
void initializeDevice(){
/**
* Select the first available device.
* */
device = getDefaultDevice();
/**
* Read OpenCL kernel file as a string.
* */
std::ifstream kernel_file("matrix_multiplication.cl");
std::string src(std::istreambuf_iterator<char>(kernel_file), (std::istreambuf_iterator<char>()));
/**
* Compile kernel program which will run on the device.
* */
cl::Program::Sources sources(1, std::make_pair(src.c_str(), src.length() + 1));
context = cl::Context(device);
program = cl::Program(context, sources);
auto err = program.build();
if(err != CL_BUILD_SUCCESS){
std::cerr << "Error!\nBuild Status: " << program.getBuildInfo<CL_PROGRAM_BUILD_STATUS>(device)
<< "\nBuild Log:\t " << program.getBuildInfo<CL_PROGRAM_BUILD_LOG>(device) << std::endl;
exit(1);
}
}
/**
* Sequentially performs the operation c[M,N] = a[M,K] * b[K,N].
* */
void seqMultiplyMatrices(int* a, int* b, int* c,
const int M,
const int N,
const int K){
for(int i = 0; i < M; i++){
for(int j = 0; j < N; j++){
int sum = 0;
for(int k = 0; k < K; k++){
sum += a[i*K + k] * b[j + k*N];
}
c[i*N + j] = sum;
}
}
}
/**
* Parallelly performs the operation c[M,N] = a[M,K] * b[K,N].
* */
void parMultiplyMatrices(int* a, int* b, int* c,
const int M,
const int N,
const int K){
/**
* Create buffers and allocate memory on the device.
* */
cl::Buffer aBuf(context, CL_MEM_READ_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, M * K * sizeof(int), a);
cl::Buffer bBuf(context, CL_MEM_READ_ONLY | CL_MEM_HOST_NO_ACCESS | CL_MEM_COPY_HOST_PTR, K * N * sizeof(int), b);
cl::Buffer cBuf(context, CL_MEM_READ_WRITE | CL_MEM_HOST_READ_ONLY, M * N * sizeof(int));
/**
* Set kernel arguments.
* */
cl::Kernel kernel(program, "multiplyMatrices");
kernel.setArg(0, aBuf);
kernel.setArg(1, bBuf);
kernel.setArg(2, cBuf);
kernel.setArg(3, sizeof(unsigned int), &M);
kernel.setArg(4, sizeof(unsigned int), &N);
kernel.setArg(5, sizeof(unsigned int), &K);
/**
* Execute the kernel function and collect its result.
* */
cl::CommandQueue queue(context, device, CL_QUEUE_PROFILING_ENABLE);
queue.enqueueNDRangeKernel(kernel, cl::NullRange, cl::NDRange(N, M));
queue.enqueueReadBuffer(cBuf, CL_TRUE, 0, M * N * sizeof(int), c);
queue.finish();
}
/**
* Check if the matrices C1 and C2 are equal.
* */
bool checkEquality(int* c1, int* c2,
const int M,
const int N){
for(int i = 0; i < M*N; i++){
if(c1[i] != c2[i]){
return false;
}
}
return true;
}
|
/*
* TI Voxel Lib component.
*
* Copyright (c) 2014 Texas Instruments Inc.
*/
#ifdef WINDOWS
#define _USE_MATH_DEFINES
#include <math.h>
#endif
#include "DepthCamera.h"
#include "Logger.h"
#include "PointCloudFrameGenerator.h"
#if defined(ARM_OPT) || defined (x86_OPT)
int32_t nFrameWidth = 0, nFrameHeight = 0;
#endif
namespace Voxel
{
DepthCamera::DepthCamera(const String &name, const String &chipset, DevicePtr device): _device(device), _name(name), _chipset(chipset),
_rawFrameBuffers(MAX_FRAME_BUFFERS), _depthFrameBuffers(MAX_FRAME_BUFFERS), _pointCloudBuffers(MAX_FRAME_BUFFERS),
_parameterInit(true), _running(false), _isPaused(false),
_unprocessedFilters(_rawFrameBuffers), _processedFilters(_rawFrameBuffers), _depthFilters(_depthFrameBuffers),
_pointCloudFrameGenerator(new PointCloudFrameGenerator()),
configFile(name, "")
{
_frameGenerators[2] = std::dynamic_pointer_cast<FrameGenerator>(_pointCloudFrameGenerator);
_makeID();
configFile.read(name + ".conf"); // Read and keep the configuration ready for use. The file must be in VOXEL_CONF_PATH
}
bool DepthCamera::_init()
{
{
CalibrationInformation &calibInfo = _getCalibrationInformationStructure()[CALIB_SECT_LENS];
calibInfo.name = CALIB_SECT_LENS;
calibInfo.id = CALIB_SECT_LENS_ID;
calibInfo.definingParameters = {};
calibInfo.calibrationParameters = {"fx", "fy", "cx", "cy", "k1", "k2", "k3", "p1", "p2"};
}
String serialNumber;
if(getSerialNumber(serialNumber))
{
configFile.setHardwareID(serialNumber);
configFile.readFromHardware();
}
int currentID = -1;
if(_getCurrentProfileID(currentID) && currentID >= 0)
{
if(!setCameraProfile(currentID, true))
return setCameraProfile(configFile.getDefaultCameraProfileID());
else
return true;
}
else
return setCameraProfile(configFile.getDefaultCameraProfileID());
}
bool DepthCamera::_addParameters(const Vector<ParameterPtr> ¶ms)
{
_parameters.reserve(_parameters.size() + params.size());
for(const ParameterPtr &p: params)
{
if(_parameters.find(p->name()) == _parameters.end())
{
_parameters[p->name()] = p;
}
else
{
logger(LOG_ERROR) << "DepthCamera: Found an existing parameter in the list of parameters, with name " << p->name() << ". Not overwriting it." << std::endl;
//return _parameterInit = false;
}
}
return true;
}
bool DepthCamera::clearAllCallbacks()
{
for(auto i = 0; i < FRAME_TYPE_COUNT; i++)
_callback[i] = nullptr;
return true;
}
bool DepthCamera::clearCallback(FrameType type)
{
if(type < FRAME_TYPE_COUNT)
{
_callback[type] = nullptr;
return true;
}
return false;
}
bool DepthCamera::registerCallback(FrameType type, CallbackType f)
{
if(type < FRAME_TYPE_COUNT)
{
if(_callback[type])
logger(LOG_WARNING) << "DepthCamera: " << id() << " already has a callback for this type = " << type << ". Overwriting it now." << std::endl;
_callBackTypesRegistered |= (1 << type);
_callback[type] = f;
return true;
}
logger(LOG_ERROR) << "DepthCamera: Invalid callback type = " << type << " attempted for depth camera " << id() << std::endl;
return false;
}
bool DepthCamera::_callbackAndContinue(uint32_t &callBackTypesToBeCalled, DepthCamera::FrameType type, const Frame &frame)
{
if(!_isPaused && (callBackTypesToBeCalled | (1 << type)) && _callback[type])
{
_callback[type](*this, frame, type);
}
callBackTypesToBeCalled &= ~(1 << type);
return callBackTypesToBeCalled != 0;
}
void DepthCamera::_captureLoop()
{
uint consecutiveCaptureFails = 0;
while(_running)
{
uint32_t callBackTypesToBeCalled = _callBackTypesRegistered;
if(consecutiveCaptureFails > 100)
{
logger(LOG_ERROR) << "DepthCamera: 100 consecutive failures in capture of frame. Stopping stream for " << id() << std::endl;
_running = false;
continue;
}
if((_callBackTypesRegistered == 0 || _callBackTypesRegistered == FRAME_RAW_FRAME_UNPROCESSED) && !isSavingFrameStream()) // Only unprocessed frame types requested or none requested?
{
auto f = _rawFrameBuffers.get();
if(!_captureRawUnprocessedFrame(*f))
{
consecutiveCaptureFails++;
continue;
}
if(_callback[FRAME_RAW_FRAME_UNPROCESSED])
{
FilterSet<RawFrame>::FrameSequence _frameBuffers;
_frameBuffers.push_front(f);
if(!_unprocessedFilters.applyFilter(_frameBuffers))
{
logger(LOG_ERROR) << "DepthCamera: Failed to apply filters on raw unprocessed frame" << std::endl;
consecutiveCaptureFails++;
continue;
}
if(!_isPaused)
_callback[FRAME_RAW_FRAME_UNPROCESSED](*this, (Frame &)(**_frameBuffers.begin()), FRAME_RAW_FRAME_UNPROCESSED);
_writeToFrameStream(**_frameBuffers.begin());
}
else
{
_writeToFrameStream(*f);
}
consecutiveCaptureFails = 0;
}
else
{
auto f1 = _rawFrameBuffers.get();
if(!_captureRawUnprocessedFrame(*f1))
{
consecutiveCaptureFails++;
continue;
}
FilterSet<RawFrame>::FrameSequence _unprocessedFrameBuffers;
_unprocessedFrameBuffers.push_front(f1);
if(!_unprocessedFilters.applyFilter(_unprocessedFrameBuffers))
{
logger(LOG_ERROR) << "DepthCamera: Failed to apply filters on raw unprocessed frame" << std::endl;
consecutiveCaptureFails++;
continue;
}
if(!_callbackAndContinue(callBackTypesToBeCalled, FRAME_RAW_FRAME_UNPROCESSED, ***_unprocessedFrameBuffers.begin()) && !isSavingFrameStream())
{
consecutiveCaptureFails = 0;
continue;
}
auto f = _rawFrameBuffers.get();
if(!_processRawFrame(**_unprocessedFrameBuffers.begin(), *f))
{
consecutiveCaptureFails++;
continue;
}
FilterSet<RawFrame>::FrameSequence _processedFrameBuffers;
_processedFrameBuffers.push_front(f);
if(!_processedFilters.applyFilter(_processedFrameBuffers))
{
logger(LOG_ERROR) << "DepthCamera: Failed to apply filters on raw processed frame" << std::endl;
consecutiveCaptureFails++;
continue;
}
if(!_callbackAndContinue(callBackTypesToBeCalled, FRAME_RAW_FRAME_PROCESSED, ***_processedFrameBuffers.begin()) && !isSavingFrameStream())
{
consecutiveCaptureFails = 0;
continue;
}
auto d = _depthFrameBuffers.get();
if(!_convertToDepthFrame(**_processedFrameBuffers.begin(), *d))
{
consecutiveCaptureFails++;
continue;
}
FilterSet<DepthFrame>::FrameSequence _depthFrameBuffers;
_depthFrameBuffers.push_front(d);
if(!_depthFilters.applyFilter(_depthFrameBuffers))
{
logger(LOG_ERROR) << "DepthCamera: Failed to apply filters on depth frame" << std::endl;
consecutiveCaptureFails++;
continue;
}
if(!_callbackAndContinue(callBackTypesToBeCalled, FRAME_DEPTH_FRAME, ***_depthFrameBuffers.begin()) && !isSavingFrameStream())
{
consecutiveCaptureFails = 0;
continue;
}
auto p = _pointCloudBuffers.get();
if(!_convertToPointCloudFrame(**_depthFrameBuffers.begin(), *p))
{
consecutiveCaptureFails++;
continue;
}
_callbackAndContinue(callBackTypesToBeCalled, FRAME_XYZI_POINT_CLOUD_FRAME, **p);
consecutiveCaptureFails = 0;
_writeToFrameStream(**_unprocessedFrameBuffers.begin());
}
}
if(!_running)
{
closeFrameStream();
_stop();
}
logger(LOG_INFO) << "DepthCamera: Streaming stopped." << std::endl;
}
bool DepthCamera::_convertToPointCloudFrame(const DepthFramePtr &depthFrame, PointCloudFramePtr &pointCloudFrame)
{
if(!depthFrame)
{
logger(LOG_ERROR) << "DepthCamera: Blank depth frame." << std::endl;
return false;
}
FramePtr p1 = std::dynamic_pointer_cast<Frame>(depthFrame);
FramePtr p2 = std::dynamic_pointer_cast<Frame>(pointCloudFrame);
bool ret = _pointCloudFrameGenerator->generate(p1, p2);
if(ret)
{
pointCloudFrame = std::dynamic_pointer_cast<PointCloudFrame>(p2);
return true;
}
else
return false;
}
void DepthCamera::_captureThreadWrapper()
{
_captureLoop();
}
bool DepthCamera::start()
{
if (isRunning())
{
logger(LOG_ERROR) << "DepthCamera: Camera is already running. Please stop it before calling start() again." << std::endl;
return false;
}
wait();
if (_captureThread && _captureThread->joinable())
{
logger(LOG_ERROR) << "DepthCamera: Camera is still running. Please wait for the current capture loop to complete before calling start() again." << std::endl;
return false;
}
if(!_callBackTypesRegistered)
{
logger(LOG_ERROR) << "DepthCamera: Please register a callback to " << _id << " before starting capture" << std::endl;
return false;
}
#if defined(ARM_OPT) || defined (x86_OPT)
FrameSize s;
_getFrameSize(s);
nFrameWidth = s.width;
nFrameHeight = s.height;
#endif
resetFilters();
if(!_start())
return false;
_running = true;
_isPaused = false;
//_captureThreadWrapper();
_captureThread = ThreadPtr(new Thread(&DepthCamera::_captureThreadWrapper, this));
return true;
}
bool DepthCamera::stop()
{
if (!isRunning())
{
logger(LOG_WARNING) << "DepthCamera: Camera is not running." << std::endl;
return true;
}
_running = false;
_isPaused = false;
wait();
return true;
}
void DepthCamera::wait()
{
if(_captureThread && _captureThread->get_id() != std::this_thread::get_id() && _captureThread->joinable())
_captureThread->join();
}
bool DepthCamera::close()
{
if(isRunning())
stop();
_programmer.reset();
_streamer.reset();
_rawFrameBuffers.clear();
_depthFrameBuffers.clear();
_pointCloudBuffers.clear();
_parameters.clear();
return true;
}
bool DepthCamera::pause()
{
if(!_isPaused)
{
_isPaused = true;
Lock<Mutex> _(_frameStreamWriterMutex);
if(_frameStreamWriter)
_frameStreamWriter->pause();
return true;
}
return false;
}
bool DepthCamera::resume()
{
if(_isPaused)
{
_isPaused = false;
Lock<Mutex> _(_frameStreamWriterMutex);
if(_frameStreamWriter)
_frameStreamWriter->resume();
return true;
}
return false;
}
DepthCamera::~DepthCamera()
{
close();
}
bool DepthCamera::reset()
{
if(isRunning())
{
logger(LOG_ERROR) << "DepthCamera: Please stop the depth camera before calling reset" << std::endl;
return false;
}
if(!_reset())
{
logger(LOG_ERROR) << "DepthCamera: Failed to reset device " << id() << std::endl;
return false;
}
resetFilters();
return true;
}
int DepthCamera::addFilter(FilterPtr p, DepthCamera::FrameType frameType, int beforeFilterID)
{
if(frameType == FRAME_RAW_FRAME_UNPROCESSED)
return _unprocessedFilters.addFilter(p, beforeFilterID);
else if(frameType == FRAME_RAW_FRAME_PROCESSED)
return _processedFilters.addFilter(p, beforeFilterID);
else if(frameType == FRAME_DEPTH_FRAME)
return _depthFilters.addFilter(p, beforeFilterID);
else
{
logger(LOG_ERROR) << "DepthCamera: Filter not supported for frame type = '" << frameType << "' for camera = " << id() << std::endl;
return -1;
}
}
bool DepthCamera::removeAllFilters(FrameType frameType)
{
if(frameType == FRAME_RAW_FRAME_UNPROCESSED)
return _unprocessedFilters.removeAllFilters();
else if(frameType == FRAME_RAW_FRAME_PROCESSED)
return _processedFilters.removeAllFilters();
else if(frameType == FRAME_DEPTH_FRAME)
return _depthFilters.removeAllFilters();
else
{
logger(LOG_ERROR) << "DepthCamera: Filter not supported for frame type = '" << frameType << "' for camera = " << id() << std::endl;
return false;
}
}
FilterPtr DepthCamera::getFilter(int filterID, DepthCamera::FrameType frameType) const
{
if(frameType == FRAME_RAW_FRAME_UNPROCESSED)
return _unprocessedFilters.getFilter(filterID);
else if(frameType == FRAME_RAW_FRAME_PROCESSED)
return _processedFilters.getFilter(filterID);
else if(frameType == FRAME_DEPTH_FRAME)
return _depthFilters.getFilter(filterID);
else
{
logger(LOG_ERROR) << "DepthCamera: Filter not supported for frame type = '" << frameType << "' for camera = " << id() << std::endl;
return nullptr;
}
}
bool DepthCamera::removeFilter(int filterID, FrameType frameType)
{
if(frameType == FRAME_RAW_FRAME_UNPROCESSED)
return _unprocessedFilters.removeFilter(filterID);
else if(frameType == FRAME_RAW_FRAME_PROCESSED)
return _processedFilters.removeFilter(filterID);
else if(frameType == FRAME_DEPTH_FRAME)
return _depthFilters.removeFilter(filterID);
else
{
logger(LOG_ERROR) << "DepthCamera: Filter not supported for frame type = '" << frameType << "' for camera = " << id() << std::endl;
return false;
}
}
bool DepthCamera::refreshParams()
{
Lock<Mutex> _(_accessMutex);
bool ret = true;
for(auto &i: _parameters)
{
if(!i.second->refresh())
{
logger(LOG_ERROR) << "DepthCamera: Failed to update value for parameter '" << i.first << "'" << std::endl;
ret = false;
}
}
return ret;
}
void DepthCamera::resetFilters()
{
_unprocessedFilters.reset();
_processedFilters.reset();
_depthFilters.reset();
}
bool DepthCamera::_writeToFrameStream(RawFramePtr &rawUnprocessed)
{
Lock<Mutex> _(_frameStreamWriterMutex);
if(_frameStreamWriter && (!_frameStreamWriter->isPaused() &&
!_frameStreamWriter->write(std::dynamic_pointer_cast<Frame>(rawUnprocessed))))
{
logger(LOG_ERROR) << "DepthCamera: Failed to save frames to frame stream" << std::endl;
return false;
}
return true;
}
bool DepthCamera::saveFrameStream(const String &fileName)
{
Lock<Mutex> _(_frameStreamWriterMutex);
if(_frameStreamWriter)
{
logger(LOG_ERROR) << "DepthCamera: Frame stream is already being saved." << std::endl;
return false;
}
if(!_frameGenerators[0] || !_frameGenerators[1] || !_frameGenerators[2])
{
logger(LOG_ERROR) << "DepthCamera: Necessary generators are not yet created? Can't save stream." << std::endl;
return false;
}
FrameStreamWriterPtr w = FrameStreamWriterPtr(
new FrameStreamWriter(fileName, _frameGenerators[0]->id(), _frameGenerators[1]->id(), _frameGenerators[2]->id())
);
_frameGenerators[0]->setFrameStreamWriter(w);
_frameGenerators[1]->setFrameStreamWriter(w);
_frameGenerators[2]->setFrameStreamWriter(w);
_frameGenerators[0]->writeConfiguration();
_frameGenerators[1]->writeConfiguration();
_frameGenerators[2]->writeConfiguration();
_frameStreamWriter = w;
return _frameStreamWriter->isStreamGood();
}
bool DepthCamera::isSavingFrameStream()
{
Lock<Mutex> _(_frameStreamWriterMutex);
return _frameStreamWriter?true:false;
}
bool DepthCamera::closeFrameStream()
{
Lock<Mutex> _(_frameStreamWriterMutex);
if(_frameStreamWriter)
{
_frameGenerators[0]->removeFrameStreamWriter();
_frameGenerators[1]->removeFrameStreamWriter();
_frameGenerators[2]->removeFrameStreamWriter();
_frameStreamWriter->close();
_frameStreamWriter.reset();
return true;
}
else
{
logger(LOG_DEBUG) << "DepthCamera: Frame stream writer not present." << std::endl;
return false;
}
}
bool DepthCamera::setCameraProfile(const int id, bool softApply)
{
if(!configFile.setCurrentCameraProfile(id))
{
logger(LOG_ERROR) << "DepthCamera: Could not set the camera profile to '" << id << "'" << std::endl;
return false;
}
if(!_saveCurrentProfileID(id))
logger(LOG_WARNING) << "DepthCamera: Could not save the camera profile ID '" << id << "'" << std::endl;
/*
// Uncomment this perform soft-reset every time a profile is selected.
if(!reset())
{
logger(LOG_ERROR) << "DepthCamera: Failed to reset camera, to set new camera profile" << std::endl;
return false;
}
*/
if(!refreshParams())
return false;
if(!softApply)
{
ConfigurationFile *config;
String cameraProfileName;
if(!configFile.getCameraProfileName(id, cameraProfileName))
{
logger(LOG_ERROR) << "DepthCamera: Failed to get new camera profile name" << std::endl;
return false;
}
if(!(config = configFile.getCameraProfile(id)))
{
logger(LOG_ERROR) << "DepthCamera: Failed to get new camera profile information" << std::endl;
return false;
}
const ConfigSet *params;
if(config->getConfigSet("defining_params", params) && !_applyConfigParams(params))
{
logger(LOG_ERROR) << "DepthCamera: Could not set defining parameters to initialize profile '" << cameraProfileName << "'" << std::endl;
return false;
}
if(config->getConfigSet("params", params) && !_applyConfigParams(params))
{
logger(LOG_ERROR) << "DepthCamera: Could not set parameters to initialize profile '" << cameraProfileName << "'" << std::endl;
return false;
}
}
if(!_onReset())
return false;
return true;
}
int DepthCamera::addCameraProfile(const String &profileName, const int parentID)
{
return configFile.addCameraProfile(profileName, parentID);
}
bool DepthCamera::removeCameraProfile(const int id)
{
if(id == getCurrentCameraProfileID() && configFile.removeCameraProfile(id))
{
return setCameraProfile(getCurrentCameraProfileID());
}
else
return configFile.removeCameraProfile(id);
}
bool DepthCamera::_applyConfigParams(const ConfigSet *params)
{
for(auto i = 0; i < params->paramNames.size(); i++)
{
if(params->paramNames[i].compare(0, 2, "0x") == 0)
{
logger(LOG_INFO) << "DepthCamera: Setting register '" << params->paramNames[i] << "'" << std::endl;
char *endptr;
uint32_t reg = (uint32_t)strtol(params->paramNames[i].c_str(), &endptr, 16);
uint32_t value = (uint32_t)strtol(params->get(params->paramNames[i]).c_str(), &endptr, 0);
if(!_programmer->writeRegister(reg, value))
{
logger(LOG_ERROR) << "Failed to write to register @0x" << std::hex << reg << " = 0x" << value << std::dec << std::endl;
}
continue;
}
else if(params->paramNames[i] == "frame_rate")
{
float rate = params->getFloat(params->paramNames[i]);
FrameRate r;
r.numerator = rate*10000;
r.denominator = 10000;
uint g = gcd(r.numerator, r.denominator);
r.numerator /= g;
r.denominator /= g;
if(!setFrameRate(r))
{
logger(LOG_ERROR) << "DepthCamera: Failed to set frame rate to " << rate << "fps" << std::endl;
return false;
}
continue;
}
logger(LOG_INFO) << "DepthCamera: Setting parameter '" << params->paramNames[i] << "'" << std::endl;
const Parameter *p = getParam(params->paramNames[i]).get();
if(!p)
{
logger(LOG_ERROR) << "DepthCamera: Ignoring unknown parameter " << params->paramNames[i] << std::endl;
return false;
}
const BoolParameter *bp = dynamic_cast<const BoolParameter *>(p);
const EnumParameter *ep = dynamic_cast<const EnumParameter *>(p);
const IntegerParameter *ip = dynamic_cast<const IntegerParameter *>(p);
const UnsignedIntegerParameter *up = dynamic_cast<const UnsignedIntegerParameter *>(p);
const FloatParameter *fp = dynamic_cast<const FloatParameter *>(p);
if(bp)
{
if(!set(params->paramNames[i], params->getBoolean(params->paramNames[i])))
return false;
}
else if(ip || ep)
{
if(!set(params->paramNames[i], params->getInteger(params->paramNames[i])))
return false;
}
else if(up)
{
if(!set(params->paramNames[i], (uint)params->getInteger(params->paramNames[i])))
return false;
}
else if(fp)
{
if(!set(params->paramNames[i], params->getFloat(params->paramNames[i])))
return false;
}
else
{
logger(LOG_ERROR) << "DepthCamera: Parameter type unknown for " << params->paramNames[i] << std::endl;
return false;
}
}
return true;
}
bool DepthCamera::getSerialNumber(String &serialNumber) const
{
serialNumber = _device->serialNumber();
return true;
}
bool DepthCamera::setSerialNumber(const String &serialNumber)
{
return false;
}
}
|
///////////////////////////////////////////////
/// @file 006_reverse-linked-list.cpp
/// @author Jake Turelli (jake.turelli@gmail.com)
/// @brief https://leetcode.com/problems/reverse-linked-list/
/// @version 0.1
/// @date 2022-01-08
///
/// @copyright Copyright (c) 2022
///
///////////////////////////////////////////////
#include <cstdio>
using namespace std;
// Completed 1/8/2022
// Runtime: 8 ms, faster than 62.75% of C++ online submissions for Reverse Linked List.
// Memory Usage: 8.2 MB, less than 78.03% of C++ online submissions for Reverse Linked List.
//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 *reverseList(ListNode *head)
{
ListNode *current = head;
ListNode *next;
ListNode *previous = nullptr;
while (current != nullptr)
{
next = current->next;
current->next = previous;
previous = current;
current = next;
}
return previous;
}
};
int main(int argc, char const *argv[])
{
Solution solution;
ListNode node5(5);
ListNode node4(4, &node5);
ListNode node3(3, &node4);
ListNode node2(2, &node3);
ListNode node1(1, &node2);
ListNode *reverse_list = solution.reverseList(&node1);
ListNode *print_node = reverse_list;
while (print_node != nullptr)
{
printf("node %i\n", print_node->val);
print_node = print_node->next;
}
return 0;
}
|
//////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2015, John Haddon. 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 John Haddon nor the names of
// any other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include "Gaffer/Loop.h"
#include "Gaffer/ContextAlgo.h"
#include "Gaffer/MetadataAlgo.h"
#include "boost/bind.hpp"
namespace Gaffer
{
GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( Loop );
Loop::Loop( const std::string &name )
: ComputeNode( name ), m_inPlugIndex( 0 ), m_outPlugIndex( 0 ), m_firstPlugIndex( 0 )
{
// Connect to `childAddedSignal()` so we can set ourselves up later when the
// appropriate plugs are added manually.
/// \todo Remove this and do all the work in `setup()`.
childAddedSignal().connect( boost::bind( &Loop::childAdded, this ) );
}
Loop::~Loop()
{
}
void Loop::setup( const ValuePlug *plug )
{
if( inPlug() )
{
throw IECore::Exception( "Loop already has an \"in\" plug." );
}
if( outPlug() )
{
throw IECore::Exception( "Loop already has an \"out\" plug." );
}
PlugPtr in = plug->createCounterpart( "in", Plug::In );
MetadataAlgo::copyColors( plug , in.get() , /* overwrite = */ false );
in->setFlags( Plug::Serialisable, true );
addChild( in );
PlugPtr out = plug->createCounterpart( "out", Plug::Out );
MetadataAlgo::copyColors( plug , out.get() , /* overwrite = */ false );
addChild( out );
}
ValuePlug *Loop::inPlug()
{
return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr;
}
const ValuePlug *Loop::inPlug() const
{
return m_inPlugIndex ? getChild<ValuePlug>( m_inPlugIndex ) : nullptr;
}
ValuePlug *Loop::outPlug()
{
return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr;
}
const ValuePlug *Loop::outPlug() const
{
return m_outPlugIndex ? getChild<ValuePlug>( m_outPlugIndex ) : nullptr;
}
ValuePlug *Loop::nextPlug()
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr;
}
const ValuePlug *Loop::nextPlug() const
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex ) : nullptr;
}
ValuePlug *Loop::previousPlug()
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr;
}
const ValuePlug *Loop::previousPlug() const
{
return m_firstPlugIndex ? getChild<ValuePlug>( m_firstPlugIndex + 1 ) : nullptr;
}
IntPlug *Loop::iterationsPlug()
{
return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr;
}
const IntPlug *Loop::iterationsPlug() const
{
return m_firstPlugIndex ? getChild<IntPlug>( m_firstPlugIndex + 2 ) : nullptr;
}
StringPlug *Loop::indexVariablePlug()
{
return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr;
}
const StringPlug *Loop::indexVariablePlug() const
{
return m_firstPlugIndex ? getChild<StringPlug>( m_firstPlugIndex + 3 ) : nullptr;
}
Gaffer::BoolPlug *Loop::enabledPlug()
{
return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr;
}
const Gaffer::BoolPlug *Loop::enabledPlug() const
{
return m_firstPlugIndex ? getChild<BoolPlug>( m_firstPlugIndex + 4 ) : nullptr;
}
Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output )
{
return output == outPlug() ? inPlug() : nullptr;
}
const Gaffer::Plug *Loop::correspondingInput( const Gaffer::Plug *output ) const
{
return output == outPlug() ? inPlug() : nullptr;
}
void Loop::affects( const Plug *input, DependencyNode::AffectedPlugsContainer &outputs ) const
{
ComputeNode::affects( input, outputs );
if( input == iterationsPlug() )
{
addAffectedPlug( outPlug(), outputs );
}
else if(
input == indexVariablePlug() ||
input == enabledPlug()
)
{
addAffectedPlug( outPlug(), outputs );
addAffectedPlug( previousPlug(), outputs );
}
else if( const ValuePlug *inputValuePlug = IECore::runTimeCast<const ValuePlug>( input ) )
{
std::vector<IECore::InternedString> relativeName;
const ValuePlug *ancestor = ancestorPlug( inputValuePlug, relativeName );
if( ancestor == inPlug() || ancestor == nextPlug() )
{
outputs.push_back( descendantPlug( outPlug(), relativeName ) );
outputs.push_back( descendantPlug( previousPlug(), relativeName ) );
}
}
}
void Loop::hash( const ValuePlug *output, const Context *context, IECore::MurmurHash &h ) const
{
int index = -1;
IECore::InternedString indexVariable;
if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) )
{
Context::EditableScope tmpContext( context );
if( index >= 0 )
{
tmpContext.set<int>( indexVariable, index );
}
else
{
tmpContext.remove( indexVariable );
}
h = plug->hash();
return;
}
ComputeNode::hash( output, context, h );
}
void Loop::compute( ValuePlug *output, const Context *context ) const
{
int index = -1;
IECore::InternedString indexVariable;
if( const ValuePlug *plug = sourcePlug( output, context, index, indexVariable ) )
{
Context::EditableScope tmpContext( context );
if( index >= 0 )
{
tmpContext.set<int>( indexVariable, index );
}
else
{
tmpContext.remove( indexVariable );
}
output->setFrom( plug );
return;
}
ComputeNode::compute( output, context );
}
void Loop::childAdded()
{
setupPlugs();
}
bool Loop::setupPlugs()
{
const ValuePlug *in = getChild<ValuePlug>( "in" );
const ValuePlug *out = getChild<ValuePlug>( "out" );
if( !in || !out )
{
return false;
}
childAddedSignal().disconnect( boost::bind( &Loop::childAdded, this ) );
m_inPlugIndex = std::find( children().begin(), children().end(), in ) - children().begin();
m_outPlugIndex = std::find( children().begin(), children().end(), out ) - children().begin();
const size_t firstPlugIndex = children().size();
addChild( in->createCounterpart( "next", Plug::In ) );
addChild( out->createCounterpart( "previous", Plug::Out ) );
addChild( new IntPlug( "iterations", Gaffer::Plug::In, 10, 0 ) );
addChild( new StringPlug( "indexVariable", Gaffer::Plug::In, "loop:index" ) );
addChild( new BoolPlug( "enabled", Gaffer::Plug::In, true ) );
// Only assign after adding all plugs, because our plug accessors
// use a non-zero value to indicate that all plugs are now available.
m_firstPlugIndex = firstPlugIndex;
// The in/out plugs might be dynamic in the case of
// LoopComputeNode, but because we create the next/previous
// plugs ourselves in response, they don't need to be dynamic.
nextPlug()->setFlags( Plug::Dynamic, false );
previousPlug()->setFlags( Plug::Dynamic, false );
// Copy styling over from main plugs.
/// \todo We shouldn't really need to do this, because plug colours are
/// expected to be registered against plug type, so our plugs will get
/// the right colour automatically (and `copyColors()` will do nothing
/// because of the `overwrite = false` argument). We are keeping it for
/// now to accommodate proprietary extensions which are using custom colours
/// instead of introducing their own plug types, but some day we should
/// just remove this entirely. Note that the same applies for the Dot,
/// ContextProcessor, ArrayPlug and Switch nodes. See
/// https://github.com/GafferHQ/gaffer/pull/2953 for further discussion.
MetadataAlgo::copyColors( inPlug(), nextPlug() , /* overwrite = */ false );
MetadataAlgo::copyColors( inPlug(), previousPlug() , /* overwrite = */ false );
// Because we're a loop, our affects() implementation specifies a cycle
// between nextPlug() and previousPlug(), so we must ask nicely for leniency
// during dirty propagation. The cycles aren't an issue when it comes to
// hash()/compute() because each iteration changes the context and we bottom
// out after the specified number of iterations.
previousPlug()->setFlags( Plug::AcceptsDependencyCycles, true );
for( Gaffer::RecursivePlugIterator it( previousPlug() ); !it.done(); ++it )
{
(*it)->setFlags( Plug::AcceptsDependencyCycles, true );
}
return true;
}
void Loop::addAffectedPlug( const ValuePlug *output, DependencyNode::AffectedPlugsContainer &outputs ) const
{
if( output->children().size() )
{
for( RecursiveOutputPlugIterator it( output ); !it.done(); ++it )
{
if( !(*it)->children().size() )
{
outputs.push_back( it->get() );
}
}
}
else
{
outputs.push_back( output );
}
}
const ValuePlug *Loop::ancestorPlug( const ValuePlug *plug, std::vector<IECore::InternedString> &relativeName ) const
{
while( plug )
{
const GraphComponent *plugParent = plug->parent();
if( plugParent == this )
{
return plug;
}
else
{
relativeName.push_back( plug->getName() );
plug = static_cast<const ValuePlug *>( plugParent );
}
}
return nullptr;
}
const ValuePlug *Loop::descendantPlug( const ValuePlug *plug, const std::vector<IECore::InternedString> &relativeName ) const
{
for( std::vector<IECore::InternedString>::const_reverse_iterator it = relativeName.rbegin(), eIt = relativeName.rend(); it != eIt; ++it )
{
plug = plug->getChild<ValuePlug>( *it );
}
return plug;
}
const ValuePlug *Loop::sourcePlug( const ValuePlug *output, const Context *context, int &sourceLoopIndex, IECore::InternedString &indexVariable ) const
{
sourceLoopIndex = -1;
ContextAlgo::GlobalScope globalScope( context, inPlug() );
indexVariable = indexVariablePlug()->getValue();
std::vector<IECore::InternedString> relativeName;
const ValuePlug *ancestor = ancestorPlug( output, relativeName );
if( ancestor == previousPlug() )
{
const int index = context->get<int>( indexVariable, 0 );
if( index >= 1 && enabledPlug()->getValue() )
{
sourceLoopIndex = index - 1;
return descendantPlug( nextPlug(), relativeName );
}
else
{
return descendantPlug( inPlug(), relativeName );
}
}
else if( ancestor == outPlug() )
{
const int iterations = iterationsPlug()->getValue();
if( iterations > 0 && enabledPlug()->getValue() )
{
sourceLoopIndex = iterations - 1;
return descendantPlug( nextPlug(), relativeName );
}
else
{
return descendantPlug( inPlug(), relativeName );
}
}
return nullptr;
}
} // namespace Gaffer
|
/*
* Copyright 2014 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "GrFlushToGpuDrawTarget.h"
#include "GrContext.h"
#include "GrFontCache.h"
#include "GrGpu.h"
#include "GrBufferAllocPool.h"
GrFlushToGpuDrawTarget::GrFlushToGpuDrawTarget(GrGpu* gpu,
GrVertexBufferAllocPool* vertexPool,
GrIndexBufferAllocPool* indexPool)
: INHERITED(gpu->getContext())
, fGpu(SkRef(gpu))
, fVertexPool(vertexPool)
, fIndexPool(indexPool)
, fFlushing(false) {
fCaps.reset(SkRef(fGpu->caps()));
SkASSERT(vertexPool);
SkASSERT(indexPool);
GeometryPoolState& poolState = fGeoPoolStateStack.push_back();
poolState.fUsedPoolVertexBytes = 0;
poolState.fUsedPoolIndexBytes = 0;
#ifdef SK_DEBUG
poolState.fPoolVertexBuffer = (GrVertexBuffer*)~0;
poolState.fPoolStartVertex = ~0;
poolState.fPoolIndexBuffer = (GrIndexBuffer*)~0;
poolState.fPoolStartIndex = ~0;
#endif
}
GrFlushToGpuDrawTarget::~GrFlushToGpuDrawTarget() {
// This must be called by before the GrDrawTarget destructor
this->releaseGeometry();
}
void GrFlushToGpuDrawTarget::setDrawBuffers(DrawInfo* info, size_t vertexStride) {
GeometryPoolState& poolState = fGeoPoolStateStack.back();
if (kBuffer_GeometrySrcType == this->getGeomSrc().fVertexSrc) {
info->setVertexBuffer(this->getGeomSrc().fVertexBuffer);
} else {
// Update the bytes used since the last reserve-geom request.
size_t bytes = (info->vertexCount() + info->startVertex()) * vertexStride;
poolState.fUsedPoolVertexBytes = SkTMax(poolState.fUsedPoolVertexBytes, bytes);
info->setVertexBuffer(poolState.fPoolVertexBuffer);
info->adjustStartVertex(poolState.fPoolStartVertex);
}
if (info->isIndexed()) {
if (kBuffer_GeometrySrcType == this->getGeomSrc().fIndexSrc) {
info->setIndexBuffer(this->getGeomSrc().fIndexBuffer);
} else {
// Update the bytes used since the last reserve-geom request.
size_t bytes = (info->indexCount() + info->startIndex()) * sizeof(uint16_t);
poolState.fUsedPoolIndexBytes = SkTMax(poolState.fUsedPoolIndexBytes, bytes);
info->setIndexBuffer(poolState.fPoolIndexBuffer);
info->adjustStartIndex(poolState.fPoolStartIndex);
}
}
}
void GrFlushToGpuDrawTarget::reset() {
SkASSERT(1 == fGeoPoolStateStack.count());
this->resetVertexSource();
this->resetIndexSource();
fVertexPool->reset();
fIndexPool->reset();
this->onReset();
}
void GrFlushToGpuDrawTarget::flush() {
SkASSERT(kReserved_GeometrySrcType != this->getGeomSrc().fVertexSrc);
SkASSERT(kReserved_GeometrySrcType != this->getGeomSrc().fIndexSrc);
if (fFlushing) {
return;
}
fFlushing = true;
fGpu->getContext()->getFontCache()->updateTextures();
fVertexPool->unmap();
fIndexPool->unmap();
fGpu->saveActiveTraceMarkers();
this->onFlush();
fGpu->restoreActiveTraceMarkers();
fFlushing = false;
this->reset();
}
void GrFlushToGpuDrawTarget::willReserveVertexAndIndexSpace(int vertexCount,
size_t vertexStride,
int indexCount) {
// We use geometryHints() to know whether to flush the draw buffer. We
// can't flush if we are inside an unbalanced pushGeometrySource.
// Moreover, flushing blows away vertex and index data that was
// previously reserved. So if the vertex or index data is pulled from
// reserved space and won't be released by this request then we can't
// flush.
bool insideGeoPush = fGeoPoolStateStack.count() > 1;
bool unreleasedVertexSpace =
!vertexCount &&
kReserved_GeometrySrcType == this->getGeomSrc().fVertexSrc;
bool unreleasedIndexSpace =
!indexCount &&
kReserved_GeometrySrcType == this->getGeomSrc().fIndexSrc;
int vcount = vertexCount;
int icount = indexCount;
if (!insideGeoPush &&
!unreleasedVertexSpace &&
!unreleasedIndexSpace &&
this->geometryHints(vertexStride, &vcount, &icount)) {
this->flush();
}
}
bool GrFlushToGpuDrawTarget::geometryHints(size_t vertexStride,
int* vertexCount,
int* indexCount) const {
// we will recommend a flush if the data could fit in a single
// preallocated buffer but none are left and it can't fit
// in the current buffer (which may not be prealloced).
bool flush = false;
if (indexCount) {
int32_t currIndices = fIndexPool->currentBufferIndices();
if (*indexCount > currIndices &&
(!fIndexPool->preallocatedBuffersRemaining() &&
*indexCount <= fIndexPool->preallocatedBufferIndices())) {
flush = true;
}
*indexCount = currIndices;
}
if (vertexCount) {
int32_t currVertices = fVertexPool->currentBufferVertices(vertexStride);
if (*vertexCount > currVertices &&
(!fVertexPool->preallocatedBuffersRemaining() &&
*vertexCount <= fVertexPool->preallocatedBufferVertices(vertexStride))) {
flush = true;
}
*vertexCount = currVertices;
}
return flush;
}
bool GrFlushToGpuDrawTarget::onReserveVertexSpace(size_t vertexSize,
int vertexCount,
void** vertices) {
GeometryPoolState& poolState = fGeoPoolStateStack.back();
SkASSERT(vertexCount > 0);
SkASSERT(vertices);
SkASSERT(0 == poolState.fUsedPoolVertexBytes);
*vertices = fVertexPool->makeSpace(vertexSize,
vertexCount,
&poolState.fPoolVertexBuffer,
&poolState.fPoolStartVertex);
return SkToBool(*vertices);
}
bool GrFlushToGpuDrawTarget::onReserveIndexSpace(int indexCount, void** indices) {
GeometryPoolState& poolState = fGeoPoolStateStack.back();
SkASSERT(indexCount > 0);
SkASSERT(indices);
SkASSERT(0 == poolState.fUsedPoolIndexBytes);
*indices = fIndexPool->makeSpace(indexCount,
&poolState.fPoolIndexBuffer,
&poolState.fPoolStartIndex);
return SkToBool(*indices);
}
void GrFlushToGpuDrawTarget::releaseReservedVertexSpace() {
GeometryPoolState& poolState = fGeoPoolStateStack.back();
const GeometrySrcState& geoSrc = this->getGeomSrc();
// If we get a release vertex space call then our current source should either be reserved
// or array (which we copied into reserved space).
SkASSERT(kReserved_GeometrySrcType == geoSrc.fVertexSrc);
// When the caller reserved vertex buffer space we gave it back a pointer
// provided by the vertex buffer pool. At each draw we tracked the largest
// offset into the pool's pointer that was referenced. Now we return to the
// pool any portion at the tail of the allocation that no draw referenced.
size_t reservedVertexBytes = geoSrc.fVertexSize * geoSrc.fVertexCount;
fVertexPool->putBack(reservedVertexBytes - poolState.fUsedPoolVertexBytes);
poolState.fUsedPoolVertexBytes = 0;
poolState.fPoolVertexBuffer = NULL;
poolState.fPoolStartVertex = 0;
}
void GrFlushToGpuDrawTarget::releaseReservedIndexSpace() {
GeometryPoolState& poolState = fGeoPoolStateStack.back();
const GeometrySrcState& geoSrc = this->getGeomSrc();
// If we get a release index space call then our current source should either be reserved
// or array (which we copied into reserved space).
SkASSERT(kReserved_GeometrySrcType == geoSrc.fIndexSrc);
// Similar to releaseReservedVertexSpace we return any unused portion at
// the tail
size_t reservedIndexBytes = sizeof(uint16_t) * geoSrc.fIndexCount;
fIndexPool->putBack(reservedIndexBytes - poolState.fUsedPoolIndexBytes);
poolState.fUsedPoolIndexBytes = 0;
poolState.fPoolIndexBuffer = NULL;
poolState.fPoolStartIndex = 0;
}
void GrFlushToGpuDrawTarget::geometrySourceWillPush() {
GeometryPoolState& poolState = fGeoPoolStateStack.push_back();
poolState.fUsedPoolVertexBytes = 0;
poolState.fUsedPoolIndexBytes = 0;
#ifdef SK_DEBUG
poolState.fPoolVertexBuffer = (GrVertexBuffer*)~0;
poolState.fPoolStartVertex = ~0;
poolState.fPoolIndexBuffer = (GrIndexBuffer*)~0;
poolState.fPoolStartIndex = ~0;
#endif
}
void GrFlushToGpuDrawTarget::geometrySourceWillPop(const GeometrySrcState& restoredState) {
SkASSERT(fGeoPoolStateStack.count() > 1);
fGeoPoolStateStack.pop_back();
GeometryPoolState& poolState = fGeoPoolStateStack.back();
// we have to assume that any slack we had in our vertex/index data
// is now unreleasable because data may have been appended later in the
// pool.
if (kReserved_GeometrySrcType == restoredState.fVertexSrc) {
poolState.fUsedPoolVertexBytes = restoredState.fVertexSize * restoredState.fVertexCount;
}
if (kReserved_GeometrySrcType == restoredState.fIndexSrc) {
poolState.fUsedPoolIndexBytes = sizeof(uint16_t) * restoredState.fIndexCount;
}
}
bool GrFlushToGpuDrawTarget::onCanCopySurface(const GrSurface* dst,
const GrSurface* src,
const SkIRect& srcRect,
const SkIPoint& dstPoint) {
return getGpu()->canCopySurface(dst, src, srcRect, dstPoint);
}
bool GrFlushToGpuDrawTarget::onInitCopySurfaceDstDesc(const GrSurface* src, GrSurfaceDesc* desc) {
return getGpu()->initCopySurfaceDstDesc(src, desc);
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The Bitcoin Token developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "allocators.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
#include <QWidget>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget* parent, WalletModel* model, Context context) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(model),
context(context),
fCapsLock(false)
{
ui->setupUi(this);
this->setStyleSheet(GUIUtil::loadStyleSheet());
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
this->model = model;
switch (mode) {
case Mode::Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case Mode::UnlockAnonymize:
ui->anonymizationCheckBox->show();
case Mode::Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Mode::Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case Mode::ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet."));
break;
}
// Set checkbox "For anonymization and staking only" depending on from where we were called
if (context == Context::Unlock_Menu || context == Context::BIP_38) {
ui->anonymizationCheckBox->setChecked(true);
}
else {
ui->anonymizationCheckBox->setChecked(false);
}
// It doesn't make sense to show the checkbox for sending BTCT because you wouldn't check it anyway.
if (context == Context::Send_BTCT) {
ui->anonymizationCheckBox->hide();
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
// Attempt to overwrite text so that they do not linger around in memory
ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size()));
ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size()));
ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size()));
delete ui;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if (!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
switch (mode) {
case Mode::Encrypt: {
if (newpass1.empty() || newpass2.empty()) {
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BTCT</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (retval == QMessageBox::Yes) {
if (newpass1 == newpass2) {
if (model->setWalletEncrypted(true, newpass1)) {
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("BTCT will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your BTCTs from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
} else {
QDialog::reject(); // Cancelled
}
} break;
case Mode::UnlockAnonymize:
case Mode::Unlock:
if (!model->setWalletLocked(false, oldpass, ui->anonymizationCheckBox->isChecked())) {
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::Decrypt:
if (!model->setWalletEncrypted(false, oldpass)) {
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
} else {
QDialog::accept(); // Success
}
break;
case Mode::ChangePass:
if (newpass1 == newpass2) {
if (model->changePassphrase(oldpass, newpass1)) {
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
} else {
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch (mode) {
case Mode::Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Mode::UnlockAnonymize: // Old passphrase x1
case Mode::Unlock: // Old passphrase x1
case Mode::Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case Mode::ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent* event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject* object, QEvent* event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent* ke = static_cast<QKeyEvent*>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar* psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
|
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/android/tab_model/tab_model_observer.h"
#include "chrome/browser/android/tab_android.h"
TabModelObserver::TabModelObserver() {}
TabModelObserver::~TabModelObserver() {}
void TabModelObserver::DidSelectTab(TabAndroid* tab,
TabModel::TabSelectionType type) {}
void TabModelObserver::WillCloseTab(TabAndroid* tab, bool animate) {}
void TabModelObserver::DidCloseTab(int tab_id, bool incognito) {}
void TabModelObserver::WillAddTab(TabAndroid* tab,
TabModel::TabLaunchType type) {}
void TabModelObserver::DidAddTab(TabAndroid* tab,
TabModel::TabLaunchType type) {}
void TabModelObserver::DidMoveTab(TabAndroid* tab,
int new_index,
int old_index) {}
void TabModelObserver::TabPendingClosure(TabAndroid* tab) {}
void TabModelObserver::TabClosureUndone(TabAndroid* tab) {}
void TabModelObserver::TabClosureCommitted(TabAndroid* tab) {}
void TabModelObserver::AllTabsPendingClosure(
const std::vector<TabAndroid*>& tabs) {}
void TabModelObserver::AllTabsClosureCommitted() {}
void TabModelObserver::TabRemoved(TabAndroid* tab) {}
|
// Copyright 2020 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <grpc/support/port_platform.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "absl/strings/string_view.h"
#include "src/core/lib/security/authorization/evaluate_args.h"
#include "test/core/util/eval_args_mock_endpoint.h"
namespace grpc_core {
class EvaluateArgsTest : public ::testing::Test {
protected:
void SetUp() override {
local_address_ = "255.255.255.255";
peer_address_ = "128.128.128.128";
local_port_ = 413;
peer_port_ = 314;
endpoint_ = CreateEvalArgsMockEndpoint(local_address_.c_str(), local_port_,
peer_address_.c_str(), peer_port_);
evaluate_args_ =
absl::make_unique<EvaluateArgs>(nullptr, nullptr, endpoint_);
}
void TearDown() override { grpc_endpoint_destroy(endpoint_); }
grpc_endpoint* endpoint_;
std::unique_ptr<EvaluateArgs> evaluate_args_;
std::string local_address_;
std::string peer_address_;
int local_port_;
int peer_port_;
};
TEST_F(EvaluateArgsTest, TestEvaluateArgsLocalAddress) {
absl::string_view src_address = evaluate_args_->GetLocalAddress();
EXPECT_EQ(src_address, local_address_);
}
TEST_F(EvaluateArgsTest, TestEvaluateArgsLocalPort) {
int src_port = evaluate_args_->GetLocalPort();
EXPECT_EQ(src_port, local_port_);
}
TEST_F(EvaluateArgsTest, TestEvaluateArgsPeerAddress) {
absl::string_view dest_address = evaluate_args_->GetPeerAddress();
EXPECT_EQ(dest_address, peer_address_);
}
TEST_F(EvaluateArgsTest, TestEvaluateArgsPeerPort) {
int dest_port = evaluate_args_->GetPeerPort();
EXPECT_EQ(dest_port, peer_port_);
}
TEST(EvaluateArgsMetadataTest, HandlesNullMetadata) {
EvaluateArgs eval_args(nullptr, nullptr, nullptr);
EXPECT_EQ(eval_args.GetPath(), nullptr);
EXPECT_EQ(eval_args.GetMethod(), nullptr);
EXPECT_EQ(eval_args.GetHost(), nullptr);
EXPECT_THAT(eval_args.GetHeaders(), ::testing::ElementsAre());
}
TEST(EvaluateArgsMetadataTest, HandlesEmptyMetadata) {
grpc_metadata_batch metadata;
grpc_metadata_batch_init(&metadata);
EvaluateArgs eval_args(&metadata, nullptr, nullptr);
EXPECT_EQ(eval_args.GetPath(), nullptr);
EXPECT_EQ(eval_args.GetMethod(), nullptr);
EXPECT_EQ(eval_args.GetHost(), nullptr);
EXPECT_THAT(eval_args.GetHeaders(), ::testing::ElementsAre());
grpc_metadata_batch_destroy(&metadata);
}
TEST(EvaluateArgsMetadataTest, GetPathSuccess) {
grpc_init();
const char* kPath = "/some/path";
grpc_metadata_batch metadata;
grpc_metadata_batch_init(&metadata);
grpc_slice fake_val = grpc_slice_intern(grpc_slice_from_static_string(kPath));
grpc_mdelem fake_val_md = grpc_mdelem_from_slices(GRPC_MDSTR_PATH, fake_val);
grpc_linked_mdelem storage;
storage.md = fake_val_md;
ASSERT_EQ(grpc_metadata_batch_link_head(&metadata, &storage),
GRPC_ERROR_NONE);
EvaluateArgs eval_args(&metadata, nullptr, nullptr);
EXPECT_EQ(eval_args.GetPath(), kPath);
grpc_metadata_batch_destroy(&metadata);
grpc_shutdown();
}
TEST(EvaluateArgsMetadataTest, GetHostSuccess) {
grpc_init();
const char* kHost = "host";
grpc_metadata_batch metadata;
grpc_metadata_batch_init(&metadata);
grpc_slice fake_val = grpc_slice_intern(grpc_slice_from_static_string(kHost));
grpc_mdelem fake_val_md = grpc_mdelem_from_slices(GRPC_MDSTR_HOST, fake_val);
grpc_linked_mdelem storage;
storage.md = fake_val_md;
ASSERT_EQ(grpc_metadata_batch_link_head(&metadata, &storage),
GRPC_ERROR_NONE);
EvaluateArgs eval_args(&metadata, nullptr, nullptr);
EXPECT_EQ(eval_args.GetHost(), kHost);
grpc_metadata_batch_destroy(&metadata);
grpc_shutdown();
}
TEST(EvaluateArgsMetadataTest, GetMethodSuccess) {
grpc_init();
const char* kMethod = "GET";
grpc_metadata_batch metadata;
grpc_metadata_batch_init(&metadata);
grpc_slice fake_val =
grpc_slice_intern(grpc_slice_from_static_string(kMethod));
grpc_mdelem fake_val_md =
grpc_mdelem_from_slices(GRPC_MDSTR_METHOD, fake_val);
grpc_linked_mdelem storage;
storage.md = fake_val_md;
ASSERT_EQ(grpc_metadata_batch_link_head(&metadata, &storage),
GRPC_ERROR_NONE);
EvaluateArgs eval_args(&metadata, nullptr, nullptr);
EXPECT_EQ(eval_args.GetMethod(), kMethod);
grpc_metadata_batch_destroy(&metadata);
grpc_shutdown();
}
TEST(EvaluateArgsMetadataTest, GetHeadersSuccess) {
grpc_init();
const char* kPath = "/some/path";
const char* kHost = "host";
grpc_metadata_batch metadata;
grpc_metadata_batch_init(&metadata);
grpc_slice fake_path =
grpc_slice_intern(grpc_slice_from_static_string(kPath));
grpc_mdelem fake_path_md =
grpc_mdelem_from_slices(GRPC_MDSTR_PATH, fake_path);
grpc_linked_mdelem storage;
storage.md = fake_path_md;
ASSERT_EQ(grpc_metadata_batch_link_head(&metadata, &storage, GRPC_BATCH_PATH),
GRPC_ERROR_NONE);
grpc_slice fake_host =
grpc_slice_intern(grpc_slice_from_static_string(kHost));
grpc_mdelem fake_host_md =
grpc_mdelem_from_slices(GRPC_MDSTR_HOST, fake_host);
grpc_linked_mdelem storage2;
storage2.md = fake_host_md;
ASSERT_EQ(
grpc_metadata_batch_link_tail(&metadata, &storage2, GRPC_BATCH_HOST),
GRPC_ERROR_NONE);
EvaluateArgs eval_args(&metadata, nullptr, nullptr);
EXPECT_THAT(
eval_args.GetHeaders(),
::testing::UnorderedElementsAre(
::testing::Pair(StringViewFromSlice(GRPC_MDSTR_HOST), kHost),
::testing::Pair(StringViewFromSlice(GRPC_MDSTR_PATH), kPath)));
grpc_metadata_batch_destroy(&metadata);
grpc_shutdown();
}
TEST(EvaluateArgsAuthContextTest, HandlesNullAuthContext) {
EvaluateArgs eval_args(nullptr, nullptr, nullptr);
EXPECT_EQ(eval_args.GetSpiffeId(), nullptr);
EXPECT_EQ(eval_args.GetCertServerName(), nullptr);
}
TEST(EvaluateArgsAuthContextTest, HandlesEmptyAuthCtx) {
grpc_auth_context auth_context(nullptr);
EvaluateArgs eval_args(nullptr, &auth_context, nullptr);
EXPECT_EQ(eval_args.GetSpiffeId(), nullptr);
EXPECT_EQ(eval_args.GetCertServerName(), nullptr);
}
TEST(EvaluateArgsAuthContextTest, GetSpiffeIdSuccessOneProperty) {
grpc_auth_context auth_context(nullptr);
const char* kId = "spiffeid";
auth_context.add_cstring_property(GRPC_PEER_SPIFFE_ID_PROPERTY_NAME, kId);
EvaluateArgs eval_args(nullptr, &auth_context, nullptr);
EXPECT_EQ(eval_args.GetSpiffeId(), kId);
}
TEST(EvaluateArgsAuthContextTest, GetSpiffeIdFailDuplicateProperty) {
grpc_auth_context auth_context(nullptr);
auth_context.add_cstring_property(GRPC_PEER_SPIFFE_ID_PROPERTY_NAME, "id1");
auth_context.add_cstring_property(GRPC_PEER_SPIFFE_ID_PROPERTY_NAME, "id2");
EvaluateArgs eval_args(nullptr, &auth_context, nullptr);
EXPECT_EQ(eval_args.GetSpiffeId(), nullptr);
}
TEST(EvaluateArgsAuthContextTest, GetCertServerNameSuccessOneProperty) {
grpc_auth_context auth_context(nullptr);
const char* kServer = "server";
auth_context.add_cstring_property(GRPC_X509_CN_PROPERTY_NAME, kServer);
EvaluateArgs eval_args(nullptr, &auth_context, nullptr);
EXPECT_EQ(eval_args.GetCertServerName(), kServer);
}
TEST(EvaluateArgsAuthContextTest, GetCertServerNameFailDuplicateProperty) {
grpc_auth_context auth_context(nullptr);
auth_context.add_cstring_property(GRPC_X509_CN_PROPERTY_NAME, "server1");
auth_context.add_cstring_property(GRPC_X509_CN_PROPERTY_NAME, "server2");
EvaluateArgs eval_args(nullptr, &auth_context, nullptr);
EXPECT_EQ(eval_args.GetCertServerName(), nullptr);
}
} // namespace grpc_core
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include "camera_mipi.h"
#include <unistd.h>
#include <assert.h>
#include <string.h>
#include <signal.h>
#include <pthread.h>
#include "common/util.h"
#include "common/timing.h"
#include "common/clutil.h"
#include "common/swaglog.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wundefined-inline"
#include <opencv2/opencv.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/videoio.hpp>
#pragma clang diagnostic pop
extern volatile sig_atomic_t do_exit;
#define FRAME_WIDTH 1164
#define FRAME_HEIGHT 874
#define FRAME_WIDTH_FRONT 1152
#define FRAME_HEIGHT_FRONT 864
namespace {
void camera_open(CameraState *s, bool rear) {
}
void camera_close(CameraState *s) {
s->buf.stop();
}
void open_gl_stream_def(CameraState * s, char* camera_id, int width, int height, char ** strm_def) {
printf("OPENGLSTREAM");
// gst-launch-1.0 nvarguscamerasrc sensor_id=0 ! 'video/x-raw(memory:NVMM), width=1280, height=720, framerate=20/1, format=NV12' !
// nvvidconv flip-method=2 ! 'video/x-raw, format=(string)BGRx' ! videoconvert ! 'video/x-raw, format=(string)BGR' !
// videoscale ! video/x-raw,width=800,height=600 ! nveglglessink -e
std::string strm_template="nvarguscamerasrc sensor_id=%s ! video/x-raw(memory:NVMM), width=1280, height=720, framerate=%d/1, format=NV12 ! nvvidconv flip-method=2 ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! videoscale ! video/x-raw,width=%d,height=%d ! appsink";
* strm_def = (char*)calloc(600,1);
sprintf(*strm_def,strm_template.c_str(), camera_id, s->fps, s->ci.frame_width, s->ci.frame_height);
printf(" GL Stream :[%s]\n",*strm_def);
}
void camera_init(CameraState *s, int camera_id, unsigned int fps, cl_device_id device_id, cl_context ctx) {
assert(camera_id < ARRAYSIZE(cameras_supported));
s->ci = cameras_supported[camera_id];
assert(s->ci.frame_width != 0);
s->fps = fps;
s->buf.init(device_id, ctx, s, FRAME_BUF_COUNT, "frame");
}
static void* rear_thread(void *arg) {
int err;
set_thread_name("webcam_rear_thread");
CameraState* s = (CameraState*)arg;
char * strm_def;
printf("open_GL");
char cameraId_value = '0';
open_gl_stream_def(s, &cameraId_value, 800, 600, &strm_def);
cv::VideoCapture cap_rear(strm_def); // road
free(strm_def);
cv::Size size;
size.height = s->ci.frame_height;
size.width = s->ci.frame_width;
// transforms calculation see tools/webcam/warp_vis.py
float ts[9] = {1.50330396, 0.0, -59.40969163,
0.0, 1.50330396, 76.20704846,
0.0, 0.0, 1.0};
// if camera upside down:
// float ts[9] = {-1.50330396, 0.0, 1223.4,
// 0.0, -1.50330396, 797.8,
// 0.0, 0.0, 1.0};
const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts);
if (!cap_rear.isOpened()) {
err = 1;
}
uint32_t frame_id = 0;
TBuffer* tb = &s->buf.camera_tb;
cv::Mat transformed_mat;
while (!do_exit) {
if (cap_rear.read(transformed_mat)) {
//cv::Size tsize = transformed_mat.size();
//printf("Raw Rear, W=%d, H=%d\n", tsize.width, tsize.height);
int transformed_size = transformed_mat.total() * transformed_mat.elemSize();
const int buf_idx = tbuffer_select(tb);
s->buf.camera_bufs_metadata[buf_idx] = {
.frame_id = frame_id,
};
cl_command_queue q = s->buf.camera_bufs[buf_idx].copy_q;
cl_mem yuv_cl = s->buf.camera_bufs[buf_idx].buf_cl;
cl_event map_event;
void *yuv_buf = (void *)CL_CHECK_ERR(clEnqueueMapBuffer(q, yuv_cl, CL_TRUE,
CL_MAP_WRITE, 0, transformed_size,
0, NULL, &map_event, &err));
clWaitForEvents(1, &map_event);
clReleaseEvent(map_event);
memcpy(yuv_buf, transformed_mat.data, transformed_size);
CL_CHECK(clEnqueueUnmapMemObject(q, yuv_cl, yuv_buf, 0, NULL, &map_event));
clWaitForEvents(1, &map_event);
clReleaseEvent(map_event);
tbuffer_dispatch(tb, buf_idx);
printf("Dispatch %d, transformed_size=%d, w/h=%dx%d\n", frame_id, transformed_size, transformed_mat.cols, transformed_mat.rows);
frame_id += 1;
}
}
transformed_mat.release();
cap_rear.release();
return NULL;
}
/*
void front_thread(CameraState *s) {
int err;
cv::VideoCapture cap_front(2); // driver
cap_front.set(cv::CAP_PROP_FRAME_WIDTH, 853);
cap_front.set(cv::CAP_PROP_FRAME_HEIGHT, 480);
cap_front.set(cv::CAP_PROP_FPS, s->fps);
// cv::Rect roi_front(320, 0, 960, 720);
cv::Size size;
size.height = s->ci.frame_height;
size.width = s->ci.frame_width;
// transforms calculation see tools/webcam/warp_vis.py
float ts[9] = {1.42070485, 0.0, -30.16740088,
0.0, 1.42070485, 91.030837,
0.0, 0.0, 1.0};
// if camera upside down:
// float ts[9] = {-1.42070485, 0.0, 1182.2,
// 0.0, -1.42070485, 773.0,
// 0.0, 0.0, 1.0};
const cv::Mat transform = cv::Mat(3, 3, CV_32F, ts);
if (!cap_front.isOpened()) {
err = 1;
}
uint32_t frame_id = 0;
TBuffer* tb = &s->buf.camera_tb;
while (!do_exit) {
cv::Mat frame_mat;
cv::Mat transformed_mat;
cap_front >> frame_mat;
// int rows = frame_mat.rows;
// int cols = frame_mat.cols;
// printf("Raw Front, R=%d, C=%d\n", rows, cols);
cv::warpPerspective(frame_mat, transformed_mat, transform, size, cv::INTER_LINEAR, cv::BORDER_CONSTANT, 0);
int transformed_size = transformed_mat.total() * transformed_mat.elemSize();
const int buf_idx = tbuffer_select(tb);
s->buf.camera_bufs_metadata[buf_idx] = {
.frame_id = frame_id,
};
cl_command_queue q = s->buf.camera_bufs[buf_idx].copy_q;
cl_mem yuv_cl = s->buf.camera_bufs[buf_idx].buf_cl;
cl_event map_event;
void *yuv_buf = (void *)CL_CHECK_ERR(clEnqueueMapBuffer(q, yuv_cl, CL_TRUE,
CL_MAP_WRITE, 0, transformed_size,
0, NULL, &map_event, &err));
clWaitForEvents(1, &map_event);
clReleaseEvent(map_event);
memcpy(yuv_buf, transformed_mat.data, transformed_size);
CL_CHECK(clEnqueueUnmapMemObject(q, yuv_cl, yuv_buf, 0, NULL, &map_event));
clWaitForEvents(1, &map_event);
clReleaseEvent(map_event);
tbuffer_dispatch(tb, buf_idx);
frame_id += 1;
frame_mat.release();
transformed_mat.release();
}
cap_front.release();
return;
}
*/
} // namespace
CameraInfo cameras_supported[CAMERA_ID_MAX] = {
// road facing
[CAMERA_ID_LGC920] = {
.frame_width = FRAME_WIDTH,
.frame_height = FRAME_HEIGHT,
.frame_stride = FRAME_WIDTH*3,
.bayer = false,
.bayer_flip = false,
},
// driver facing
/*[CAMERA_ID_LGC615] = {
.frame_width = FRAME_WIDTH_FRONT,
.frame_height = FRAME_HEIGHT_FRONT,
.frame_stride = FRAME_WIDTH_FRONT*3,
.bayer = false,
.bayer_flip = false,
},*/
};
void cameras_init(MultiCameraState *s, cl_device_id device_id, cl_context ctx) {
camera_init(&s->rear, CAMERA_ID_LGC920, 20, device_id, ctx);
s->rear.transform = (mat3){{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
}};
/*camera_init(&s->front, CAMERA_ID_LGC615, 10, device_id, ctx);
s->front.transform = (mat3){{
1.0, 0.0, 0.0,
0.0, 1.0, 0.0,
0.0, 0.0, 1.0,
}};*/
s->pm = new PubMaster({"frame", "frontFrame"});
}
void camera_autoexposure(CameraState *s, float grey_frac) {}
void cameras_open(MultiCameraState *s) {
// LOG("*** open front ***");
camera_open(&s->front, false);
// LOG("*** open rear ***");
//camera_open(&s->rear, true);
}
void cameras_close(MultiCameraState *s) {
//camera_close(&s->rear);
camera_close(&s->front);
delete s->pm;
}
void camera_process_front(MultiCameraState *s, CameraState *c, int cnt) {
MessageBuilder msg;
auto framed = msg.initEvent().initFrontFrame();
framed.setFrameType(cereal::FrameData::FrameType::FRONT);
fill_frame_data(framed, c->buf.cur_frame_data, cnt);
s->pm->send("frontFrame", msg);
}
void camera_process_rear(MultiCameraState *s, CameraState *c, int cnt) {
const CameraBuf *b = &c->buf;
MessageBuilder msg;
auto framed = msg.initEvent().initFrame();
fill_frame_data(framed, b->cur_frame_data, cnt);
framed.setImage(kj::arrayPtr((const uint8_t *)b->yuv_ion[b->cur_yuv_idx].addr, b->yuv_buf_size));
framed.setTransform(b->yuv_transform.v);
s->pm->send("frame", msg);
}
void cameras_run(MultiCameraState *s) {
std::vector<std::thread> threads;
threads.push_back(start_process_thread(s, "processing", &s->rear, 51, camera_process_rear));
//threads.push_back(start_process_thread(s, "frontview", &s->front, 51, camera_process_front));
std::thread t_rear = std::thread(rear_thread, &s->rear);
set_thread_name("webcam_thread");
//front_thread(&s->front);
t_rear.join();
cameras_close(s);
for (auto &t : threads) t.join();
}
|
/*
Copyright (c) 2010-2020, Intel Corporation
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 Intel Corporation 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.
*/
/** @file decl.cpp
@brief Implementations of classes related to turning declarations into
symbol names and types.
*/
#include "decl.h"
#include "expr.h"
#include "module.h"
#include "stmt.h"
#include "sym.h"
#include "type.h"
#include "util.h"
#include <set>
#include <stdio.h>
#include <string.h>
static void lPrintTypeQualifiers(int typeQualifiers) {
if (typeQualifiers & TYPEQUAL_INLINE)
printf("inline ");
if (typeQualifiers & TYPEQUAL_CONST)
printf("const ");
if (typeQualifiers & TYPEQUAL_UNIFORM)
printf("uniform ");
if (typeQualifiers & TYPEQUAL_VARYING)
printf("varying ");
if (typeQualifiers & TYPEQUAL_TASK)
printf("task ");
if (typeQualifiers & TYPEQUAL_SIGNED)
printf("signed ");
if (typeQualifiers & TYPEQUAL_UNSIGNED)
printf("unsigned ");
if (typeQualifiers & TYPEQUAL_EXPORT)
printf("export ");
if (typeQualifiers & TYPEQUAL_UNMASKED)
printf("unmasked ");
}
/** Given a Type and a set of type qualifiers, apply the type qualifiers to
the type, returning the type that is the result.
*/
static const Type *lApplyTypeQualifiers(int typeQualifiers, const Type *type, SourcePos pos) {
if (type == NULL)
return NULL;
if ((typeQualifiers & TYPEQUAL_CONST) != 0) {
type = type->GetAsConstType();
}
if (((typeQualifiers & TYPEQUAL_UNIFORM) != 0) && ((typeQualifiers & TYPEQUAL_VARYING) != 0)) {
Error(pos, "Type \"%s\" cannot be qualified with both uniform and varying.", type->GetString().c_str());
}
if ((typeQualifiers & TYPEQUAL_UNIFORM) != 0) {
if (type->IsVoidType())
Error(pos, "\"uniform\" qualifier is illegal with \"void\" type.");
else
type = type->GetAsUniformType();
} else if ((typeQualifiers & TYPEQUAL_VARYING) != 0) {
if (type->IsVoidType())
Error(pos, "\"varying\" qualifier is illegal with \"void\" type.");
else
type = type->GetAsVaryingType();
} else {
if (type->IsVoidType() == false)
type = type->GetAsUnboundVariabilityType();
}
if ((typeQualifiers & TYPEQUAL_UNSIGNED) != 0) {
if ((typeQualifiers & TYPEQUAL_SIGNED) != 0)
Error(pos, "Illegal to apply both \"signed\" and \"unsigned\" "
"qualifiers.");
const Type *unsignedType = type->GetAsUnsignedType();
if (unsignedType != NULL)
type = unsignedType;
else {
const Type *resolvedType = type->ResolveUnboundVariability(Variability::Varying);
Error(pos, "\"unsigned\" qualifier is illegal with \"%s\" type.", resolvedType->GetString().c_str());
}
}
if ((typeQualifiers & TYPEQUAL_SIGNED) != 0 && type->IsIntType() == false) {
const Type *resolvedType = type->ResolveUnboundVariability(Variability::Varying);
Error(pos,
"\"signed\" qualifier is illegal with non-integer type "
"\"%s\".",
resolvedType->GetString().c_str());
}
return type;
}
///////////////////////////////////////////////////////////////////////////
// DeclSpecs
DeclSpecs::DeclSpecs(const Type *t, StorageClass sc, int tq) {
baseType = t;
storageClass = sc;
typeQualifiers = tq;
soaWidth = 0;
vectorSize = 0;
if (t != NULL) {
if (m->symbolTable->ContainsType(t)) {
// Typedefs might have uniform/varying qualifiers inside.
if (t->IsVaryingType()) {
typeQualifiers |= TYPEQUAL_VARYING;
} else if (t->IsUniformType()) {
typeQualifiers |= TYPEQUAL_UNIFORM;
}
}
}
}
const Type *DeclSpecs::GetBaseType(SourcePos pos) const {
const Type *retType = baseType;
if (retType == NULL) {
Warning(pos, "No type specified in declaration. Assuming int32.");
retType = AtomicType::UniformInt32->GetAsUnboundVariabilityType();
}
if (vectorSize > 0) {
const AtomicType *atomicType = CastType<AtomicType>(retType);
if (atomicType == NULL) {
Error(pos, "Only atomic types (int, float, ...) are legal for vector "
"types.");
return NULL;
}
retType = new VectorType(atomicType, vectorSize);
}
retType = lApplyTypeQualifiers(typeQualifiers, retType, pos);
if (soaWidth > 0) {
const StructType *st = CastType<StructType>(retType);
if (st == NULL) {
Error(pos,
"Illegal to provide soa<%d> qualifier with non-struct "
"type \"%s\".",
soaWidth, retType->GetString().c_str());
return NULL;
} else if (soaWidth <= 0 || (soaWidth & (soaWidth - 1)) != 0) {
Error(pos,
"soa<%d> width illegal. Value must be positive power "
"of two.",
soaWidth);
return NULL;
}
if (st->IsUniformType()) {
Error(pos,
"\"uniform\" qualifier and \"soa<%d>\" qualifier can't "
"both be used in a type declaration.",
soaWidth);
return NULL;
} else if (st->IsVaryingType()) {
Error(pos,
"\"varying\" qualifier and \"soa<%d>\" qualifier can't "
"both be used in a type declaration.",
soaWidth);
return NULL;
} else
retType = st->GetAsSOAType(soaWidth);
if (soaWidth < g->target->getVectorWidth())
PerformanceWarning(pos,
"soa<%d> width smaller than gang size %d "
"currently leads to inefficient code to access "
"soa types.",
soaWidth, g->target->getVectorWidth());
}
return retType;
}
static const char *lGetStorageClassName(StorageClass storageClass) {
switch (storageClass) {
case SC_NONE:
return "";
case SC_EXTERN:
return "extern";
case SC_EXTERN_C:
return "extern \"C\"";
case SC_STATIC:
return "static";
case SC_TYPEDEF:
return "typedef";
default:
FATAL("Unhandled storage class in lGetStorageClassName");
return "";
}
}
void DeclSpecs::Print() const {
printf("Declspecs: [%s ", lGetStorageClassName(storageClass));
if (soaWidth > 0)
printf("soa<%d> ", soaWidth);
lPrintTypeQualifiers(typeQualifiers);
printf("base type: %s", baseType->GetString().c_str());
if (vectorSize > 0)
printf("<%d>", vectorSize);
printf("]");
}
///////////////////////////////////////////////////////////////////////////
// Declarator
Declarator::Declarator(DeclaratorKind dk, SourcePos p) : pos(p), kind(dk) {
child = NULL;
typeQualifiers = 0;
storageClass = SC_NONE;
arraySize = -1;
type = NULL;
initExpr = NULL;
}
void Declarator::InitFromDeclSpecs(DeclSpecs *ds) {
const Type *baseType = ds->GetBaseType(pos);
InitFromType(baseType, ds);
if (type == NULL) {
AssertPos(pos, m->errorCount > 0);
return;
}
storageClass = ds->storageClass;
if (ds->declSpecList.size() > 0 && CastType<FunctionType>(type) == NULL) {
Error(pos,
"__declspec specifiers for non-function type \"%s\" are "
"not used.",
type->GetString().c_str());
}
}
void Declarator::Print(int indent) const {
printf("%*cdeclarator: [", indent, ' ');
pos.Print();
lPrintTypeQualifiers(typeQualifiers);
printf("%s ", lGetStorageClassName(storageClass));
if (name.size() > 0)
printf("%s", name.c_str());
else
printf("(unnamed)");
printf(", array size = %d", arraySize);
printf(", kind = ");
switch (kind) {
case DK_BASE:
printf("base");
break;
case DK_POINTER:
printf("pointer");
break;
case DK_REFERENCE:
printf("reference");
break;
case DK_ARRAY:
printf("array");
break;
case DK_FUNCTION:
printf("function");
break;
default:
FATAL("Unhandled declarator kind");
}
if (initExpr != NULL) {
printf(" = (");
initExpr->Print();
printf(")");
}
if (functionParams.size() > 0) {
for (unsigned int i = 0; i < functionParams.size(); ++i) {
printf("\n%*cfunc param %d:\n", indent, ' ', i);
functionParams[i]->Print(indent + 4);
}
}
if (child != NULL)
child->Print(indent + 4);
printf("]\n");
}
void Declarator::InitFromType(const Type *baseType, DeclSpecs *ds) {
bool hasUniformQual = ((typeQualifiers & TYPEQUAL_UNIFORM) != 0);
bool hasVaryingQual = ((typeQualifiers & TYPEQUAL_VARYING) != 0);
bool isTask = ((typeQualifiers & TYPEQUAL_TASK) != 0);
bool isExported = ((typeQualifiers & TYPEQUAL_EXPORT) != 0);
bool isConst = ((typeQualifiers & TYPEQUAL_CONST) != 0);
bool isUnmasked = ((typeQualifiers & TYPEQUAL_UNMASKED) != 0);
if (hasUniformQual && hasVaryingQual) {
Error(pos, "Can't provide both \"uniform\" and \"varying\" qualifiers.");
return;
}
if (kind != DK_FUNCTION && isTask) {
Error(pos, "\"task\" qualifier illegal in variable declaration.");
return;
}
if (kind != DK_FUNCTION && isUnmasked) {
Error(pos, "\"unmasked\" qualifier illegal in variable declaration.");
return;
}
if (kind != DK_FUNCTION && isExported) {
Error(pos, "\"export\" qualifier illegal in variable declaration.");
return;
}
Variability variability(Variability::Unbound);
if (hasUniformQual)
variability = Variability::Uniform;
else if (hasVaryingQual)
variability = Variability::Varying;
if (kind == DK_BASE) {
// All of the type qualifiers should be in the DeclSpecs for the
// base declarator
AssertPos(pos, typeQualifiers == 0);
AssertPos(pos, child == NULL);
type = baseType;
} else if (kind == DK_POINTER) {
/* For now, any pointer to an SOA type gets the slice property; if
we add the capability to declare pointers as slices or not,
we'll want to set this based on a type qualifier here. */
const Type *ptrType = new PointerType(baseType, variability, isConst, baseType->IsSOAType());
if (child != NULL) {
child->InitFromType(ptrType, ds);
type = child->type;
name = child->name;
} else
type = ptrType;
} else if (kind == DK_REFERENCE) {
if (hasUniformQual) {
Error(pos, "\"uniform\" qualifier is illegal to apply to references.");
return;
}
if (hasVaryingQual) {
Error(pos, "\"varying\" qualifier is illegal to apply to references.");
return;
}
if (isConst) {
Error(pos, "\"const\" qualifier is to illegal apply to references.");
return;
}
// The parser should disallow this already, but double check.
if (CastType<ReferenceType>(baseType) != NULL) {
Error(pos, "References to references are illegal.");
return;
}
const Type *refType = new ReferenceType(baseType);
if (child != NULL) {
child->InitFromType(refType, ds);
type = child->type;
name = child->name;
} else
type = refType;
} else if (kind == DK_ARRAY) {
if (baseType->IsVoidType()) {
Error(pos, "Arrays of \"void\" type are illegal.");
return;
}
if (CastType<ReferenceType>(baseType)) {
Error(pos, "Arrays of references (type \"%s\") are illegal.", baseType->GetString().c_str());
return;
}
const Type *arrayType = new ArrayType(baseType, arraySize);
if (child != NULL) {
child->InitFromType(arrayType, ds);
type = child->type;
name = child->name;
} else {
type = arrayType;
}
} else if (kind == DK_FUNCTION) {
llvm::SmallVector<const Type *, 8> args;
llvm::SmallVector<std::string, 8> argNames;
llvm::SmallVector<Expr *, 8> argDefaults;
llvm::SmallVector<SourcePos, 8> argPos;
// Loop over the function arguments and store the names, types,
// default values (if any), and source file positions each one in
// the corresponding vector.
for (unsigned int i = 0; i < functionParams.size(); ++i) {
Declaration *d = functionParams[i];
if (d == NULL) {
AssertPos(pos, m->errorCount > 0);
continue;
}
if (d->declarators.size() == 0) {
// function declaration like foo(float), w/o a name for the
// parameter; wire up a placeholder Declarator for it
d->declarators.push_back(new Declarator(DK_BASE, pos));
d->declarators[0]->InitFromDeclSpecs(d->declSpecs);
}
AssertPos(pos, d->declarators.size() == 1);
Declarator *decl = d->declarators[0];
if (decl == NULL || decl->type == NULL) {
AssertPos(pos, m->errorCount > 0);
continue;
}
if (decl->name == "") {
// Give a name to any anonymous parameter declarations
char buf[32];
snprintf(buf, sizeof(buf), "__anon_parameter_%d", i);
decl->name = buf;
}
decl->type = decl->type->ResolveUnboundVariability(Variability::Varying);
if (d->declSpecs->storageClass != SC_NONE)
Error(decl->pos,
"Storage class \"%s\" is illegal in "
"function parameter declaration for parameter \"%s\".",
lGetStorageClassName(d->declSpecs->storageClass), decl->name.c_str());
if (decl->type->IsVoidType()) {
Error(decl->pos, "Parameter with type \"void\" illegal in function "
"parameter list.");
decl->type = NULL;
}
const ArrayType *at = CastType<ArrayType>(decl->type);
if (at != NULL) {
// As in C, arrays are passed to functions as pointers to
// their element type. We'll just immediately make this
// change now. (One shortcoming of losing the fact that
// the it was originally an array is that any warnings or
// errors later issued that print the function type will
// report this differently than it was originally declared
// in the function, but it's not clear that this is a
// significant problem.)
const Type *targetType = at->GetElementType();
if (targetType == NULL) {
AssertPos(pos, m->errorCount > 0);
return;
}
decl->type = PointerType::GetUniform(targetType, at->IsSOAType());
// Make sure there are no unsized arrays (other than the
// first dimension) in function parameter lists.
at = CastType<ArrayType>(targetType);
while (at != NULL) {
if (at->GetElementCount() == 0)
Error(decl->pos, "Arrays with unsized dimensions in "
"dimensions after the first one are illegal in "
"function parameter lists.");
at = CastType<ArrayType>(at->GetElementType());
}
}
args.push_back(decl->type);
argNames.push_back(decl->name);
argPos.push_back(decl->pos);
Expr *init = NULL;
// Try to find an initializer expression.
while (decl != NULL) {
if (decl->initExpr != NULL) {
decl->initExpr = TypeCheck(decl->initExpr);
decl->initExpr = Optimize(decl->initExpr);
if (decl->initExpr != NULL) {
init = llvm::dyn_cast<ConstExpr>(decl->initExpr);
if (init == NULL)
init = llvm::dyn_cast<NullPointerExpr>(decl->initExpr);
if (init == NULL)
Error(decl->initExpr->pos,
"Default value for parameter "
"\"%s\" must be a compile-time constant.",
decl->name.c_str());
}
break;
} else
decl = decl->child;
}
argDefaults.push_back(init);
}
const Type *returnType = baseType;
if (returnType == NULL) {
Error(pos, "No return type provided in function declaration.");
return;
}
if (CastType<FunctionType>(returnType) != NULL) {
Error(pos, "Illegal to return function type from function.");
return;
}
returnType = returnType->ResolveUnboundVariability(Variability::Varying);
bool isExternC = ds && (ds->storageClass == SC_EXTERN_C);
bool isExported = ds && ((ds->typeQualifiers & TYPEQUAL_EXPORT) != 0);
bool isTask = ds && ((ds->typeQualifiers & TYPEQUAL_TASK) != 0);
bool isUnmasked = ds && ((ds->typeQualifiers & TYPEQUAL_UNMASKED) != 0);
if (isExported && isTask) {
Error(pos, "Function can't have both \"task\" and \"export\" "
"qualifiers");
return;
}
if (isExternC && isTask) {
Error(pos, "Function can't have both \"extern \"C\"\" and \"task\" "
"qualifiers");
return;
}
if (isExternC && isExported) {
Error(pos, "Function can't have both \"extern \"C\"\" and \"export\" "
"qualifiers");
return;
}
if (isUnmasked && isExported)
Warning(pos, "\"unmasked\" qualifier is redundant for exported "
"functions.");
if (child == NULL) {
AssertPos(pos, m->errorCount > 0);
return;
}
const FunctionType *functionType = new FunctionType(returnType, args, argNames, argDefaults, argPos, isTask,
isExported, isExternC, isUnmasked);
// handle any explicit __declspecs on the function
if (ds != NULL) {
for (int i = 0; i < (int)ds->declSpecList.size(); ++i) {
std::string str = ds->declSpecList[i].first;
SourcePos ds_spec_pos = ds->declSpecList[i].second;
if (str == "safe")
(const_cast<FunctionType *>(functionType))->isSafe = true;
else if (!strncmp(str.c_str(), "cost", 4)) {
int cost = atoi(str.c_str() + 4);
if (cost < 0)
Error(ds_spec_pos, "Negative function cost %d is illegal.", cost);
(const_cast<FunctionType *>(functionType))->costOverride = cost;
} else
Error(ds_spec_pos, "__declspec parameter \"%s\" unknown.", str.c_str());
}
}
child->InitFromType(functionType, ds);
type = child->type;
name = child->name;
}
}
///////////////////////////////////////////////////////////////////////////
// Declaration
Declaration::Declaration(DeclSpecs *ds, std::vector<Declarator *> *dlist) {
declSpecs = ds;
if (dlist != NULL)
declarators = *dlist;
for (unsigned int i = 0; i < declarators.size(); ++i)
if (declarators[i] != NULL)
declarators[i]->InitFromDeclSpecs(declSpecs);
}
Declaration::Declaration(DeclSpecs *ds, Declarator *d) {
declSpecs = ds;
if (d != NULL) {
d->InitFromDeclSpecs(ds);
declarators.push_back(d);
}
}
std::vector<VariableDeclaration> Declaration::GetVariableDeclarations() const {
Assert(declSpecs->storageClass != SC_TYPEDEF);
std::vector<VariableDeclaration> vars;
for (unsigned int i = 0; i < declarators.size(); ++i) {
Declarator *decl = declarators[i];
if (decl == NULL || decl->type == NULL) {
// Ignore earlier errors
Assert(m->errorCount > 0);
continue;
}
if (decl->type->IsVoidType())
Error(decl->pos, "\"void\" type variable illegal in declaration.");
else if (CastType<FunctionType>(decl->type) == NULL) {
decl->type = decl->type->ResolveUnboundVariability(Variability::Varying);
Symbol *sym = new Symbol(decl->name, decl->pos, decl->type, decl->storageClass);
m->symbolTable->AddVariable(sym);
vars.push_back(VariableDeclaration(sym, decl->initExpr));
}
}
return vars;
}
void Declaration::DeclareFunctions() {
Assert(declSpecs->storageClass != SC_TYPEDEF);
for (unsigned int i = 0; i < declarators.size(); ++i) {
Declarator *decl = declarators[i];
if (decl == NULL || decl->type == NULL) {
// Ignore earlier errors
Assert(m->errorCount > 0);
continue;
}
const FunctionType *ftype = CastType<FunctionType>(decl->type);
if (ftype == NULL)
continue;
bool isInline = (declSpecs->typeQualifiers & TYPEQUAL_INLINE);
bool isNoInline = (declSpecs->typeQualifiers & TYPEQUAL_NOINLINE);
m->AddFunctionDeclaration(decl->name, ftype, decl->storageClass, isInline, isNoInline, decl->pos);
}
}
void Declaration::Print(int indent) const {
printf("%*cDeclaration: specs [", indent, ' ');
declSpecs->Print();
printf("], declarators:\n");
for (unsigned int i = 0; i < declarators.size(); ++i)
declarators[i]->Print(indent + 4);
}
///////////////////////////////////////////////////////////////////////////
void GetStructTypesNamesPositions(const std::vector<StructDeclaration *> &sd,
llvm::SmallVector<const Type *, 8> *elementTypes,
llvm::SmallVector<std::string, 8> *elementNames,
llvm::SmallVector<SourcePos, 8> *elementPositions) {
std::set<std::string> seenNames;
for (unsigned int i = 0; i < sd.size(); ++i) {
const Type *type = sd[i]->type;
if (type == NULL)
continue;
// FIXME: making this fake little DeclSpecs here is really
// disgusting
DeclSpecs ds(type);
if (type->IsVoidType() == false) {
if (type->IsUniformType())
ds.typeQualifiers |= TYPEQUAL_UNIFORM;
else if (type->IsVaryingType())
ds.typeQualifiers |= TYPEQUAL_VARYING;
else if (type->GetSOAWidth() != 0)
ds.soaWidth = type->GetSOAWidth();
// FIXME: ds.vectorSize?
}
for (unsigned int j = 0; j < sd[i]->declarators->size(); ++j) {
Declarator *d = (*sd[i]->declarators)[j];
d->InitFromDeclSpecs(&ds);
if (d->type->IsVoidType())
Error(d->pos, "\"void\" type illegal for struct member.");
elementTypes->push_back(d->type);
if (seenNames.find(d->name) != seenNames.end())
Error(d->pos,
"Struct member \"%s\" has same name as a "
"previously-declared member.",
d->name.c_str());
else
seenNames.insert(d->name);
elementNames->push_back(d->name);
elementPositions->push_back(d->pos);
}
}
for (int i = 0; i < (int)elementTypes->size() - 1; ++i) {
const ArrayType *arrayType = CastType<ArrayType>((*elementTypes)[i]);
if (arrayType != NULL && arrayType->GetElementCount() == 0)
Error((*elementPositions)[i], "Unsized arrays aren't allowed except "
"for the last member in a struct definition.");
}
}
|
/* Copyright (c) 2020 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "validator/GroupByValidator.h"
#include "planner/plan/Query.h"
#include "util/AnonColGenerator.h"
#include "util/AnonVarGenerator.h"
#include "util/ExpressionUtils.h"
#include "visitor/FindVisitor.h"
namespace nebula {
namespace graph {
Status GroupByValidator::validateImpl() {
auto* groupBySentence = static_cast<GroupBySentence*>(sentence_);
NG_RETURN_IF_ERROR(validateGroup(groupBySentence->groupClause()));
NG_RETURN_IF_ERROR(validateYield(groupBySentence->yieldClause()));
NG_RETURN_IF_ERROR(groupClauseSemanticCheck());
return Status::OK();
}
Status GroupByValidator::validateYield(const YieldClause* yieldClause) {
std::vector<YieldColumn*> columns;
if (yieldClause != nullptr) {
columns = yieldClause->columns();
}
if (columns.empty()) {
return Status::SemanticError("Yield cols is Empty");
}
auto* pool = qctx_->objPool();
projCols_ = pool->add(new YieldColumns);
for (auto* col : columns) {
auto colOldName = col->name();
auto* colExpr = col->expr();
if (col->expr()->kind() != Expression::Kind::kAggregate) {
auto collectAggCol = colExpr->clone();
auto aggs =
ExpressionUtils::collectAll(collectAggCol, {Expression::Kind::kAggregate});
for (auto* agg : aggs) {
DCHECK_EQ(agg->kind(), Expression::Kind::kAggregate);
NG_RETURN_IF_ERROR(
ExpressionUtils::checkAggExpr(static_cast<const AggregateExpression*>(agg)));
aggOutputColNames_.emplace_back(agg->toString());
groupItems_.emplace_back(agg->clone());
needGenProject_ = true;
}
if (!aggs.empty()) {
auto* colRewrited = ExpressionUtils::rewriteAgg2VarProp(pool, colExpr);
projCols_->addColumn(new YieldColumn(colRewrited, colOldName));
continue;
}
}
// collect exprs for check later
if (colExpr->kind() == Expression::Kind::kAggregate) {
auto* aggExpr = static_cast<AggregateExpression*>(colExpr);
NG_RETURN_IF_ERROR(ExpressionUtils::checkAggExpr(aggExpr));
} else if (!ExpressionUtils::isEvaluableExpr(colExpr)) {
yieldCols_.emplace_back(colExpr);
}
groupItems_.emplace_back(colExpr);
aggOutputColNames_.emplace_back(colOldName);
projCols_->addColumn(
new YieldColumn(VariablePropertyExpression::make(pool, "", colOldName), colOldName));
ExpressionProps yieldProps;
NG_RETURN_IF_ERROR(deduceProps(colExpr, yieldProps));
// TODO: refactor exprProps_ related logic
exprProps_.unionProps(std::move(yieldProps));
}
return Status::OK();
}
Status GroupByValidator::validateGroup(const GroupClause* groupClause) {
if (!groupClause) return Status::OK();
std::vector<YieldColumn*> columns;
if (groupClause != nullptr) {
columns = groupClause->columns();
}
auto groupByValid = [](Expression::Kind kind) -> bool {
return std::unordered_set<Expression::Kind>{Expression::Kind::kAdd,
Expression::Kind::kMinus,
Expression::Kind::kMultiply,
Expression::Kind::kDivision,
Expression::Kind::kMod,
Expression::Kind::kTypeCasting,
Expression::Kind::kFunctionCall,
Expression::Kind::kInputProperty,
Expression::Kind::kVarProperty,
Expression::Kind::kCase}
.count(kind);
};
for (auto* col : columns) {
if (graph::ExpressionUtils::findAny(col->expr(), {Expression::Kind::kAggregate}) ||
!graph::ExpressionUtils::findAny(
col->expr(), {Expression::Kind::kInputProperty, Expression::Kind::kVarProperty})) {
return Status::SemanticError("Group `%s' invalid", col->expr()->toString().c_str());
}
if (!groupByValid(col->expr()->kind())) {
return Status::SemanticError("Group `%s' invalid", col->expr()->toString().c_str());
}
NG_RETURN_IF_ERROR(deduceExprType(col->expr()));
NG_RETURN_IF_ERROR(deduceProps(col->expr(), exprProps_));
groupKeys_.emplace_back(col->expr());
}
return Status::OK();
}
Status GroupByValidator::toPlan() {
auto* groupBy = Aggregate::make(qctx_, nullptr, std::move(groupKeys_), std::move(groupItems_));
groupBy->setColNames(aggOutputColNames_);
if (!exprProps_.varProps().empty() && !userDefinedVarNameList_.empty()) {
if (userDefinedVarNameList_.size() != 1) {
return Status::SemanticError("Multiple user defined vars not supported yet.");
}
auto userDefinedVar = *userDefinedVarNameList_.begin();
if (!userDefinedVar.empty()) {
groupBy->setInputVar(userDefinedVar);
} else {
return Status::SemanticError("Invalid anonymous user defined var.");
}
}
if (needGenProject_) {
// rewrite Expr which has inner aggExpr and push it up to Project.
root_ = Project::make(qctx_, groupBy, projCols_);
} else {
root_ = groupBy;
}
tail_ = groupBy;
return Status::OK();
}
Status GroupByValidator::groupClauseSemanticCheck() {
// deduce group items and build outputs_
DCHECK_EQ(aggOutputColNames_.size(), groupItems_.size());
for (auto i = 0u; i < groupItems_.size(); ++i) {
auto type = deduceExprType(groupItems_[i]);
NG_RETURN_IF_ERROR(type);
outputs_.emplace_back(aggOutputColNames_[i], std::move(type).value());
}
// check exprProps
if (!exprProps_.srcTagProps().empty() || !exprProps_.dstTagProps().empty()) {
return Status::SemanticError("Only support input and variable in GroupBy sentence.");
}
if (!exprProps_.inputProps().empty() && !exprProps_.varProps().empty()) {
return Status::SemanticError("Not support both input and variable in GroupBy sentence.");
}
if (!exprProps_.varProps().empty() && exprProps_.varProps().size() > 1) {
return Status::SemanticError("Only one variable allowed to use.");
}
if (groupKeys_.empty()) {
groupKeys_ = yieldCols_;
} else {
std::unordered_set<Expression*> groupSet(groupKeys_.begin(), groupKeys_.end());
auto finder = [&groupSet](const Expression* expr) -> bool {
for (auto* target : groupSet) {
if (*target == *expr) {
return true;
}
}
return false;
};
for (auto* expr : yieldCols_) {
if (evaluableExpr(expr)) {
continue;
}
FindVisitor visitor(finder);
expr->accept(&visitor);
if (!visitor.found()) {
return Status::SemanticError("Yield non-agg expression `%s' must be"
" functionally dependent on items in GROUP BY clause",
expr->toString().c_str());
}
}
}
return Status::OK();
}
} // namespace graph
} // namespace nebula
|
/*
* Copyright 2018-2019 Autoware Foundation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mpc_follower/mpc_follower_core.h"
#define DEBUG_INFO(...) { if (show_debug_info_) { ROS_INFO(__VA_ARGS__); }}
MPCFollower::MPCFollower()
: nh_(""), pnh_("~"), my_position_ok_(false), my_velocity_ok_(false), my_steering_ok_(false)
{
pnh_.param("show_debug_info", show_debug_info_, bool(false));
pnh_.param("publish_debug_values", publish_debug_values_, bool(true));
pnh_.param("ctrl_period", ctrl_period_, double(0.03));
pnh_.param("enable_path_smoothing", enable_path_smoothing_, bool(true));
pnh_.param("enable_yaw_recalculation", enable_yaw_recalculation_, bool(false));
pnh_.param("path_filter_moving_ave_num", path_filter_moving_ave_num_, int(35));
pnh_.param("path_smoothing_times", path_smoothing_times_, int(1));
pnh_.param("curvature_smoothing_num", curvature_smoothing_num_, int(35));
pnh_.param("traj_resample_dist", traj_resample_dist_, double(0.1)); // [m]
pnh_.param("admisible_position_error", admisible_position_error_, double(5.0));
pnh_.param("admisible_yaw_error_deg", admisible_yaw_error_deg_, double(90.0));
pnh_.param("output_interface", output_interface_, std::string("all"));
/* mpc parameters */
pnh_.param("mpc_prediction_horizon", mpc_param_.prediction_horizon, int(70));
pnh_.param("mpc_prediction_sampling_time", mpc_param_.prediction_sampling_time, double(0.1));
pnh_.param("mpc_weight_lat_error", mpc_param_.weight_lat_error, double(1.0));
pnh_.param("mpc_weight_heading_error", mpc_param_.weight_heading_error, double(0.0));
pnh_.param("mpc_weight_heading_error_squared_vel_coeff", mpc_param_.weight_heading_error_squared_vel_coeff, double(0.3));
pnh_.param("mpc_weight_steering_input", mpc_param_.weight_steering_input, double(1.0));
pnh_.param("mpc_weight_steering_input_squared_vel_coeff", mpc_param_.weight_steering_input_squared_vel_coeff, double(0.25));
pnh_.param("mpc_weight_lat_jerk", mpc_param_.weight_lat_jerk, double(0.0));
pnh_.param("mpc_weight_terminal_lat_error", mpc_param_.weight_terminal_lat_error, double(1.0));
pnh_.param("mpc_weight_terminal_heading_error", mpc_param_.weight_terminal_heading_error, double(0.1));
pnh_.param("mpc_zero_ff_steer_deg", mpc_param_.zero_ff_steer_deg, double(2.0));
pnh_.param("steer_lim_deg", steer_lim_deg_, double(35.0));
pnh_.param("vehicle_model_wheelbase", wheelbase_, double(2.9));
/* vehicle model setup */
pnh_.param("vehicle_model_type", vehicle_model_type_, std::string("kinematics"));
if (vehicle_model_type_ == "kinematics")
{
double steer_tau;
pnh_.param("vehicle_model_steer_tau", steer_tau, double(0.1));
vehicle_model_ptr_ = std::make_shared<KinematicsBicycleModel>(wheelbase_, amathutils::deg2rad(steer_lim_deg_), steer_tau);
ROS_INFO("[MPC] set vehicle_model = kinematics");
}
else if (vehicle_model_type_ == "kinematics_no_delay")
{
vehicle_model_ptr_ = std::make_shared<KinematicsBicycleModelNoDelay>(wheelbase_, amathutils::deg2rad(steer_lim_deg_));
ROS_INFO("[MPC] set vehicle_model = kinematics_no_delay");
}
else if (vehicle_model_type_ == "dynamics")
{
double mass_fl, mass_fr, mass_rl, mass_rr, cf, cr;
pnh_.param("mass_fl", mass_fl, double(600));
pnh_.param("mass_fr", mass_fr, double(600));
pnh_.param("mass_rl", mass_rl, double(600));
pnh_.param("mass_rr", mass_rr, double(600));
pnh_.param("cf", cf, double(155494.663));
pnh_.param("cr", cr, double(155494.663));
vehicle_model_ptr_ = std::make_shared<DynamicsBicycleModel>(wheelbase_, mass_fl, mass_fr, mass_rl, mass_rr, cf, cr);
ROS_INFO("[MPC] set vehicle_model = dynamics");
}
else
{
ROS_ERROR("[MPC] vehicle_model_type is undefined");
}
/* QP solver setup */
std::string qp_solver_type_;
pnh_.param("qp_solver_type", qp_solver_type_, std::string("unconstraint_fast"));
if (qp_solver_type_ == "unconstraint")
{
qpsolver_ptr_ = std::make_shared<QPSolverEigenLeastSquare>();
ROS_INFO("[MPC] set qp solver = unconstraint");
}
else if (qp_solver_type_ == "unconstraint_fast")
{
qpsolver_ptr_ = std::make_shared<QPSolverEigenLeastSquareLLT>();
ROS_INFO("[MPC] set qp solver = unconstraint_fast");
}
// else if (qp_solver_type_ == "qpoases_hotstart")
// {
// int max_iter = 200;
// qpsolver_ptr_ = std::make_shared<QPSolverQpoasesHotstart>(max_iter);
// ROS_INFO("[MPC] set qp solver = qpoases_hotstart");
// }
else
{
ROS_ERROR("[MPC] qp_solver_type is undefined");
}
steer_cmd_prev_ = 0.0;
lateral_error_prev_ = 0.0;
yaw_error_prev_ = 0.0;
/* initialize lowpass filter */
double steering_lpf_cutoff_hz, error_deriv_lpf_curoff_hz;
pnh_.param("steering_lpf_cutoff_hz", steering_lpf_cutoff_hz, double(3.0));
pnh_.param("error_deriv_lpf_curoff_hz", error_deriv_lpf_curoff_hz, double(5.0));
lpf_steering_cmd_.initialize(ctrl_period_, steering_lpf_cutoff_hz);
lpf_lateral_error_.initialize(ctrl_period_, error_deriv_lpf_curoff_hz);
lpf_yaw_error_.initialize(ctrl_period_, error_deriv_lpf_curoff_hz);
/* set up ros system */
timer_control_ = nh_.createTimer(ros::Duration(ctrl_period_), &MPCFollower::timerCallback, this);
std::string out_twist, out_vehicle_cmd, in_vehicle_status, in_waypoints, in_selfpose;
pnh_.param("out_twist_name", out_twist, std::string("/twist_raw"));
pnh_.param("out_vehicle_cmd_name", out_vehicle_cmd, std::string("/ctrl_cmd"));
pnh_.param("in_waypoints_name", in_waypoints, std::string("/base_waypoints"));
pnh_.param("in_selfpose_name", in_selfpose, std::string("/current_pose"));
pnh_.param("in_vehicle_status_name", in_vehicle_status, std::string("/vehicle_status"));
pub_twist_cmd_ = nh_.advertise<geometry_msgs::TwistStamped>(out_twist, 1);
pub_steer_vel_ctrl_cmd_ = nh_.advertise<autoware_msgs::ControlCommandStamped>(out_vehicle_cmd, 1);
sub_ref_path_ = nh_.subscribe(in_waypoints, 1, &MPCFollower::callbackRefPath, this);
sub_pose_ = nh_.subscribe(in_selfpose, 1, &MPCFollower::callbackPose, this);
sub_vehicle_status_ = nh_.subscribe(in_vehicle_status, 1, &MPCFollower::callbackVehicleStatus, this);
/* for debug */
pub_debug_filtered_traj_ = pnh_.advertise<visualization_msgs::Marker>("debug/filtered_traj", 1);
pub_debug_predicted_traj_ = pnh_.advertise<visualization_msgs::Marker>("debug/predicted_traj", 1);
pub_debug_mpc_calc_time_ = pnh_.advertise<std_msgs::Float32>("debug/mpc_calc_time", 1);
if (publish_debug_values_)
{
pub_debug_values_ = pnh_.advertise<std_msgs::Float64MultiArray>("debug/debug_values", 1);
sub_estimate_twist_ = nh_.subscribe("/estimate_twist", 1, &MPCFollower::callbackEstimateTwist, this);
pub_debug_steer_cmd_ = pnh_.advertise<std_msgs::Float32>("debug/steer_cmd", 1);
pub_debug_steer_cmd_ff_ = pnh_.advertise<std_msgs::Float32>("debug/steer_cmd_ff", 1);
pub_debug_steer_cmd_raw_ = pnh_.advertise<std_msgs::Float32>("debug/steer_cmd_raw", 1);
pub_debug_steer_ = pnh_.advertise<std_msgs::Float32>("debug/steer", 1);
pub_debug_laterr_ = pnh_.advertise<std_msgs::Float32>("debug/laterr", 1);
pub_debug_yawerr_ = pnh_.advertise<std_msgs::Float32>("debug/yawerr", 1);
pub_debug_current_vel_ = pnh_.advertise<std_msgs::Float32>("debug/current_vel", 1);
pub_debug_vel_cmd_ = pnh_.advertise<std_msgs::Float32>("debug/vel_cmd", 1);
pub_debug_angvel_cmd_ = pnh_.advertise<std_msgs::Float32>("debug/angvel_cmd", 1);
pub_debug_angvel_steer_ = pnh_.advertise<std_msgs::Float32>("debug/angvel_from_steer", 1);
pub_debug_angvel_cmd_ff_ = pnh_.advertise<std_msgs::Float32>("debug/angvel_cmd_ff", 1);
pub_debug_angvel_estimatetwist_ = pnh_.advertise<std_msgs::Float32>("debug/angvel_estimatetwist", 1);
}
};
void MPCFollower::timerCallback(const ros::TimerEvent &te)
{
/* guard */
if (vehicle_model_ptr_ == nullptr || qpsolver_ptr_ == nullptr)
{
DEBUG_INFO("[MPC] vehicle_model = %d, qp_solver = %d", !(vehicle_model_ptr_ == nullptr), !(qpsolver_ptr_ == nullptr));
publishControlCommands(0.0, 0.0, steer_cmd_prev_, 0.0); // publish brake
return;
}
if (ref_traj_.size() == 0 || !my_position_ok_ || !my_velocity_ok_ || !my_steering_ok_)
{
DEBUG_INFO("[MPC] MPC is not solved. ref_traj_.size() = %d, my_position_ok_ = %d, my_velocity_ok_ = %d, my_steering_ok_ = %d",
ref_traj_.size(), my_position_ok_, my_velocity_ok_, my_steering_ok_);
publishControlCommands(0.0, 0.0, steer_cmd_prev_, 0.0); // publish brake
return;
}
/* control command */
double vel_cmd = 0.0;
double acc_cmd = 0.0;
double steer_cmd = 0.0;
double steer_vel_cmd = 0.0;
/* solve MPC */
auto start = std::chrono::system_clock::now();
const bool mpc_solved = calculateMPC(vel_cmd, acc_cmd, steer_cmd, steer_vel_cmd);
double elapsed_ms = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count() * 1.0e-6;
DEBUG_INFO("[MPC] timerCallback: MPC calculating time = %f [ms]\n", elapsed_ms);
/* publish computing time */
std_msgs::Float32 mpc_calc_time_msg;
mpc_calc_time_msg.data = elapsed_ms;
pub_debug_mpc_calc_time_.publish(mpc_calc_time_msg);
if (!mpc_solved)
{
ROS_WARN("[MPC] MPC is not solved. publish 0 velocity.");
vel_cmd = 0.0;
acc_cmd = 0.0;
steer_cmd = steer_cmd_prev_;
steer_vel_cmd = 0.0;
}
publishControlCommands(vel_cmd, acc_cmd, steer_cmd, steer_vel_cmd);
};
bool MPCFollower::calculateMPC(double &vel_cmd, double &acc_cmd, double &steer_cmd, double &steer_vel_cmd)
{
const int N = mpc_param_.prediction_horizon;
const double DT = mpc_param_.prediction_sampling_time;
const int DIM_X = vehicle_model_ptr_->getDimX();
const int DIM_U = vehicle_model_ptr_->getDimU();
const int DIM_Y = vehicle_model_ptr_->getDimY();
const double current_yaw = tf2::getYaw(vehicle_status_.pose.orientation);
/* calculate nearest point on reference trajectory (used as initial state) */
unsigned int nearest_index = 0;
double yaw_err, dist_err, nearest_traj_time;
geometry_msgs::Pose nearest_pose;
if (!MPCUtils::calcNearestPoseInterp(ref_traj_, vehicle_status_.pose, nearest_pose, nearest_index, dist_err, yaw_err, nearest_traj_time))
{
ROS_WARN("[MPC] calculateMPC: error in calculating nearest pose. stop mpc.");
return false;
};
/* check if lateral error is not too large */
if (dist_err > admisible_position_error_ || std::fabs(yaw_err) > amathutils::deg2rad(admisible_yaw_error_deg_ ))
{
ROS_WARN("[MPC] error is over limit, stop mpc. (pos: error = %f[m], limit: %f[m], yaw: error = %f[deg], limit %f[deg])",
dist_err, admisible_position_error_, amathutils::rad2deg(yaw_err), admisible_yaw_error_deg_);
return false;
}
/* set mpc initial time */
const double mpc_start_time = nearest_traj_time;
/* check trajectory length */
const double mpc_end_time = mpc_start_time + (N - 1) * DT;
if (mpc_end_time > ref_traj_.relative_time.back())
{
ROS_WARN("[MPC] path is too short for prediction. path end: %f[s], mpc end time: %f[s]", ref_traj_.relative_time.back(), mpc_end_time);
return false;
}
/* convert tracking x,y error to lat error */
const double err_x = vehicle_status_.pose.position.x - nearest_pose.position.x;
const double err_y = vehicle_status_.pose.position.y - nearest_pose.position.y;
const double sp_yaw = tf2::getYaw(nearest_pose.orientation);
const double err_lat = -sin(sp_yaw) * err_x + cos(sp_yaw) * err_y;
/* get steering angle */
const double steer = vehicle_status_.tire_angle_rad;
/* define initial state for error dynamics */
Eigen::VectorXd x0 = Eigen::VectorXd::Zero(DIM_X);
if (vehicle_model_type_ == "kinematics")
{
x0 << err_lat, yaw_err, steer;
}
else if (vehicle_model_type_ == "kinematics_no_delay")
{
x0 << err_lat, yaw_err;
}
else if (vehicle_model_type_ == "dynamics")
{
double dot_err_lat = (err_lat - lateral_error_prev_) / ctrl_period_;
double dot_err_yaw = (yaw_err - yaw_error_prev_) / ctrl_period_;
DEBUG_INFO("[MPC] (before lpf) dot_err_lat = %f, dot_err_yaw = %f", dot_err_lat, dot_err_yaw);
lateral_error_prev_ = err_lat;
yaw_error_prev_ = yaw_err;
dot_err_lat = lpf_lateral_error_.filter(dot_err_lat);
dot_err_yaw = lpf_yaw_error_.filter(dot_err_yaw);
DEBUG_INFO("[MPC] (after lpf) dot_err_lat = %f, dot_err_yaw = %f", dot_err_lat, dot_err_yaw);
x0 << err_lat, dot_err_lat, yaw_err, dot_err_yaw;
}
else
{
ROS_ERROR("vehicle_model_type is undefined");
return false;
}
DEBUG_INFO("[MPC] selfpose.x = %f, y = %f, yaw = %f", vehicle_status_.pose.position.x, vehicle_status_.pose.position.y, current_yaw);
DEBUG_INFO("[MPC] nearpose.x = %f, y = %f, yaw = %f", nearest_pose.position.x, nearest_pose.position.y, tf2::getYaw(nearest_pose.orientation));
DEBUG_INFO("[MPC] nearest_index = %d, nearest_traj_time = %f", nearest_index, nearest_traj_time);
DEBUG_INFO("[MPC] lat error = %f, yaw error = %f, steer = %f, sp_yaw = %f, my_yaw = %f", err_lat, yaw_err, steer, sp_yaw, current_yaw);
/////////////// generate mpc matrix ///////////////
/*
* predict equation: Xec = Aex * x0 + Bex * Uex + Wex
* cost function: J = Xex' * Qex * Xex + (Uex - Uref)' * Rex * (Uex - Urefex)
* Qex = diag([Q,Q,...]), Rex = diag([R,R,...])
*/
Eigen::MatrixXd Aex = Eigen::MatrixXd::Zero(DIM_X * N, DIM_X);
Eigen::MatrixXd Bex = Eigen::MatrixXd::Zero(DIM_X * N, DIM_U * N);
Eigen::MatrixXd Wex = Eigen::MatrixXd::Zero(DIM_X * N, 1);
Eigen::MatrixXd Cex = Eigen::MatrixXd::Zero(DIM_Y * N, DIM_X * N);
Eigen::MatrixXd Qex = Eigen::MatrixXd::Zero(DIM_Y * N, DIM_Y * N);
Eigen::MatrixXd Rex = Eigen::MatrixXd::Zero(DIM_U * N, DIM_U * N);
Eigen::MatrixXd Urefex = Eigen::MatrixXd::Zero(DIM_U * N, 1);
/* weight matrix depends on the vehicle model */
Eigen::MatrixXd Q = Eigen::MatrixXd::Zero(DIM_Y, DIM_Y);
Eigen::MatrixXd R = Eigen::MatrixXd::Zero(DIM_U, DIM_U);
Eigen::MatrixXd Q_adaptive = Eigen::MatrixXd::Zero(DIM_Y, DIM_Y);
Eigen::MatrixXd R_adaptive = Eigen::MatrixXd::Zero(DIM_U, DIM_U);
Q(0, 0) = mpc_param_.weight_lat_error;
Q(1, 1) = mpc_param_.weight_heading_error;
R(0, 0) = mpc_param_.weight_steering_input;
Eigen::MatrixXd Ad(DIM_X, DIM_X);
Eigen::MatrixXd Bd(DIM_X, DIM_U);
Eigen::MatrixXd Wd(DIM_X, 1);
Eigen::MatrixXd Cd(DIM_Y, DIM_X);
Eigen::MatrixXd Uref(DIM_U, 1);
/* resample ref_traj with mpc sampling time */
std::vector<double> mpc_time_v;
for (int i = 0; i < N; ++i)
{
mpc_time_v.push_back(mpc_start_time + i * DT);
}
MPCTrajectory mpc_resampled_ref_traj;
if (!MPCUtils::interp1dMPCTraj(ref_traj_.relative_time, ref_traj_, mpc_time_v, mpc_resampled_ref_traj))
{
ROS_WARN("[MPC] calculateMPC: mpc resample error, stop mpc calculation. check code!");
return false;
}
/* predict dynamics for N times */
for (int i = 0; i < N; ++i)
{
const double ref_k = mpc_resampled_ref_traj.k[i];
const double ref_vx = mpc_resampled_ref_traj.vx[i];
const double ref_vx_squared = ref_vx * ref_vx;
/* get discrete state matrix A, B, C, W */
vehicle_model_ptr_->setVelocity(ref_vx);
vehicle_model_ptr_->setCurvature(ref_k);
vehicle_model_ptr_->calculateDiscreteMatrix(Ad, Bd, Cd, Wd, DT);
Q_adaptive = Q;
R_adaptive = R;
if (i == N - 1)
{
Q_adaptive(0, 0) = mpc_param_.weight_terminal_lat_error;
Q_adaptive(1, 1) = mpc_param_.weight_terminal_heading_error;
}
Q_adaptive(1, 1) += ref_vx_squared * mpc_param_.weight_heading_error_squared_vel_coeff;
R_adaptive(0, 0) += ref_vx_squared * mpc_param_.weight_steering_input_squared_vel_coeff;
/* update mpc matrix */
int idx_x_i = i * DIM_X;
int idx_x_i_prev = (i - 1) * DIM_X;
int idx_u_i = i * DIM_U;
int idx_y_i = i * DIM_Y;
if (i == 0)
{
Aex.block(0, 0, DIM_X, DIM_X) = Ad;
Bex.block(0, 0, DIM_X, DIM_U) = Bd;
Wex.block(0, 0, DIM_X, 1) = Wd;
}
else
{
Aex.block(idx_x_i, 0, DIM_X, DIM_X) = Ad * Aex.block(idx_x_i_prev, 0, DIM_X, DIM_X);
for (int j = 0; j < i; ++j)
{
int idx_u_j = j * DIM_U;
Bex.block(idx_x_i, idx_u_j, DIM_X, DIM_U) = Ad * Bex.block(idx_x_i_prev, idx_u_j, DIM_X, DIM_U);
}
Wex.block(idx_x_i, 0, DIM_X, 1) = Ad * Wex.block(idx_x_i_prev, 0, DIM_X, 1) + Wd;
}
Bex.block(idx_x_i, idx_u_i, DIM_X, DIM_U) = Bd;
Cex.block(idx_y_i, idx_x_i, DIM_Y, DIM_X) = Cd;
Qex.block(idx_y_i, idx_y_i, DIM_Y, DIM_Y) = Q_adaptive;
Rex.block(idx_u_i, idx_u_i, DIM_U, DIM_U) = R_adaptive;
/* get reference input (feed-forward) */
vehicle_model_ptr_->calculateReferenceInput(Uref);
if (std::fabs(Uref(0, 0)) < amathutils::deg2rad(mpc_param_.zero_ff_steer_deg))
{
Uref(0, 0) = 0.0; // ignore curvature noise
}
Urefex.block(i * DIM_U, 0, DIM_U, 1) = Uref;
}
/* add lateral jerk : weight for (v * {u(i) - u(i-1)} )^2 */
for (int i = 0; i < N - 1; ++i)
{
const double v = mpc_resampled_ref_traj.vx[i];
const double lateral_jerk_weight = v * v * mpc_param_.weight_lat_jerk;
Rex(i, i) += lateral_jerk_weight;
Rex(i + 1, i) -= lateral_jerk_weight;
Rex(i, i + 1) -= lateral_jerk_weight;
Rex(i + 1, i + 1) += lateral_jerk_weight;
}
if (Aex.array().isNaN().any() || Bex.array().isNaN().any() ||
Cex.array().isNaN().any() || Wex.array().isNaN().any())
{
ROS_WARN("[MPC] calculateMPC: model matrix includes NaN, stop MPC.");
return false;
}
/////////////// optimization ///////////////
/*
* solve quadratic optimization.
* cost function: 1/2 * Uex' * H * Uex + f' * Uex
*/
const Eigen::MatrixXd CB = Cex * Bex;
const Eigen::MatrixXd QCB = Qex * CB;
Eigen::MatrixXd H = Eigen::MatrixXd::Zero(DIM_U * N, DIM_U * N);
H.triangularView<Eigen::Upper>() = CB.transpose() * QCB; // NOTE: This calculation is very heavy. searching for a good way...
H.triangularView<Eigen::Upper>() += Rex;
H.triangularView<Eigen::Lower>() = H.transpose();
Eigen::MatrixXd f = (Cex * (Aex * x0 + Wex)).transpose() * QCB - Urefex.transpose() * Rex;
/* constraint matrix : lb < U < ub, lbA < A*U < ubA */
const double u_lim = amathutils::deg2rad(steer_lim_deg_);
Eigen::MatrixXd A = Eigen::MatrixXd::Zero(DIM_U * N, DIM_U * N);
Eigen::MatrixXd lbA = Eigen::MatrixXd::Zero(DIM_U * N, 1);
Eigen::MatrixXd ubA = Eigen::MatrixXd::Zero(DIM_U * N, 1);
Eigen::VectorXd lb = Eigen::VectorXd::Constant(DIM_U * N, -u_lim); // min steering angle
Eigen::VectorXd ub = Eigen::VectorXd::Constant(DIM_U * N, u_lim); // max steering angle
auto start = std::chrono::system_clock::now();
Eigen::VectorXd Uex;
if (!qpsolver_ptr_->solve(H, f.transpose(), A, lb, ub, lbA, ubA, Uex))
{
ROS_WARN("[MPC] qp solver error");
return false;
}
double elapsed = std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now() - start).count() * 1.0e-6;
DEBUG_INFO("[MPC] calculateMPC: qp solver calculation time = %f [ms]", elapsed);
if (Uex.array().isNaN().any())
{
ROS_WARN("[MPC] calculateMPC: model Uex includes NaN, stop MPC. ");
return false;
}
/* saturation */
const double u_sat = std::max(std::min(Uex(0), u_lim), -u_lim);
/* filtering */
const double u_filtered = lpf_steering_cmd_.filter(u_sat);
/* set steering command */
steer_cmd = u_filtered;
steer_vel_cmd = (Uex(1) - Uex(0)) / DT;
/* Velocity control: for simplicity, now we calculate steer and speed separately */
vel_cmd = ref_traj_.vx[0];
acc_cmd = (ref_traj_.vx[1] - ref_traj_.vx[0]) / DT;
steer_cmd_prev_ = steer_cmd;
DEBUG_INFO("[MPC] calculateMPC: mpc steer command raw = %f, filtered = %f, steer_vel_cmd = %f", Uex(0, 0), u_filtered, steer_vel_cmd);
DEBUG_INFO("[MPC] calculateMPC: mpc vel command = %f, acc_cmd = %f", vel_cmd, acc_cmd);
////////////////// DEBUG ///////////////////
/* calculate predicted trajectory */
Eigen::VectorXd Xex = Aex * x0 + Bex * Uex + Wex;
MPCTrajectory debug_mpc_predicted_traj;
for (int i = 0; i < N; ++i)
{
const double lat_error = Xex(i * DIM_X);
const double yaw_error = Xex(i * DIM_X + 1);
const double x = mpc_resampled_ref_traj.x[i] - std::sin(mpc_resampled_ref_traj.yaw[i]) * lat_error;
const double y = mpc_resampled_ref_traj.y[i] + std::cos(mpc_resampled_ref_traj.yaw[i]) * lat_error;
const double z = mpc_resampled_ref_traj.z[i];
debug_mpc_predicted_traj.push_back(x, y, z, mpc_resampled_ref_traj.yaw[i] + yaw_error, 0, 0, 0);
}
/* publish for visualization */
visualization_msgs::Marker marker;
convertTrajToMarker(debug_mpc_predicted_traj, marker, "predicted_traj", 0.99, 0.99, 0.99, 0.2);
pub_debug_predicted_traj_.publish(marker);
/* publish debug values */
if (publish_debug_values_)
{
std_msgs::Float32 steer_cmd_msg; // final steering command (MPC + LPF)
steer_cmd_msg.data = steer_cmd;
pub_debug_steer_cmd_.publish(steer_cmd_msg);
std_msgs::Float32 steer_cmd_raw_msg; // mpc calculation result
steer_cmd_raw_msg.data = u_sat;
pub_debug_steer_cmd_raw_.publish(steer_cmd_raw_msg);
std_msgs::Float32 steer_cmd_ff_msg; // feedforward steering value
steer_cmd_ff_msg.data = Urefex(0);
pub_debug_steer_cmd_ff_.publish(steer_cmd_ff_msg);
std_msgs::Float32 steer_act_msg; // current steering angle
steer_act_msg.data = steer;
pub_debug_steer_.publish(steer_act_msg);
std_msgs::Float32 err_lat_msg; // lateral error
err_lat_msg.data = err_lat;
pub_debug_laterr_.publish(err_lat_msg);
std_msgs::Float32 err_yaw_msg; // yaw error
err_yaw_msg.data = yaw_err;
pub_debug_yawerr_.publish(err_yaw_msg);
std_msgs::Float32 current_vel_msg; //current velocity
current_vel_msg.data = estimate_twist_.twist.angular.z;
pub_debug_current_vel_.publish(current_vel_msg);
std_msgs::Float32 vel_cmd_msg; // velocity command
vel_cmd_msg.data = vel_cmd;
pub_debug_vel_cmd_.publish(vel_cmd_msg);
std_msgs::Float32 angvel_converted_from_steer_cmd_msg; // angular velocity calculated by steering command with kinematics model
angvel_converted_from_steer_cmd_msg.data = vehicle_status_.twist.linear.x * tan(steer_cmd) / wheelbase_;
pub_debug_angvel_cmd_.publish(angvel_converted_from_steer_cmd_msg);
std_msgs::Float32 angvel_converted_from_steer_act_msg; // angular velocity calculated by current steering with kinematics model
angvel_converted_from_steer_act_msg.data = vehicle_status_.twist.linear.x * tan(steer) / wheelbase_;
pub_debug_angvel_steer_.publish(angvel_converted_from_steer_act_msg);
std_msgs::Float32 angvel_ff_msg; // angular velocity calculated by steering feedforward with kinematics model
const double nearest_curvature = mpc_resampled_ref_traj.k[0];
angvel_ff_msg.data = nearest_curvature * vehicle_status_.twist.linear.x;
pub_debug_angvel_cmd_ff_.publish(angvel_ff_msg);
std_msgs::Float32 angvel_estimatetwist_msg; // estimate twist angular velocity
angvel_estimatetwist_msg.data = estimate_twist_.twist.angular.z;
pub_debug_angvel_estimatetwist_.publish(angvel_estimatetwist_msg);
}
return true;
};
void MPCFollower::callbackRefPath(const autoware_msgs::Lane::ConstPtr &msg)
{
current_waypoints_ = *msg;
DEBUG_INFO("[MPC] path callback: received path size = %lu", current_waypoints_.waypoints.size());
MPCTrajectory traj;
/* calculate relative time */
std::vector<double> relative_time;
MPCUtils::calcPathRelativeTime(current_waypoints_, relative_time);
DEBUG_INFO("[MPC] path callback: relative_time.size() = %lu, front() = %f, back() = %f",
relative_time.size(), relative_time.front(), relative_time.back());
/* resampling */
MPCUtils::convertWaypointsToMPCTrajWithDistanceResample(current_waypoints_, relative_time, traj_resample_dist_, traj);
MPCUtils::convertEulerAngleToMonotonic(traj.yaw);
DEBUG_INFO("[MPC] path callback: resampled traj size() = %lu", traj.relative_time.size());
/* path smoothing */
if (enable_path_smoothing_)
{
for (int i = 0; i < path_smoothing_times_; ++i)
{
if (!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, traj.x) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, traj.y) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, traj.yaw) ||
!MoveAverageFilter::filt_vector(path_filter_moving_ave_num_, traj.vx))
{
ROS_WARN("[MPC] path callback: filtering error. stop filtering");
return;
}
}
}
/* calculate yaw angle */
if (enable_yaw_recalculation_)
{
MPCUtils::calcTrajectoryYawFromXY(traj);
MPCUtils::convertEulerAngleToMonotonic(traj.yaw);
}
/* calculate curvature */
MPCUtils::calcTrajectoryCurvature(traj, curvature_smoothing_num_);
const double max_k = *max_element(traj.k.begin(), traj.k.end());
const double min_k = *min_element(traj.k.begin(), traj.k.end());
DEBUG_INFO("[MPC] path callback: trajectory curvature : max_k = %f, min_k = %f", max_k, min_k);
/* add end point with vel=0 on traj for mpc prediction */
const double mpc_predict_time_length = (mpc_param_.prediction_horizon + 1) * mpc_param_.prediction_sampling_time;
const double end_velocity = 0.0;
traj.vx.back() = end_velocity; // also for end point
traj.push_back(traj.x.back(), traj.y.back(), traj.z.back(), traj.yaw.back(),
end_velocity, traj.k.back(), traj.relative_time.back() + mpc_predict_time_length);
if (!traj.size())
{
ROS_ERROR("[MPC] path callback: trajectory size is undesired.");
DEBUG_INFO("size: x=%lu, y=%lu, z=%lu, yaw=%lu, v=%lu,k=%lu,t=%lu", traj.x.size(), traj.y.size(),
traj.z.size(), traj.yaw.size(), traj.vx.size(), traj.k.size(), traj.relative_time.size());
return;
}
ref_traj_ = traj;
/* publish trajectory for visualize */
visualization_msgs::Marker markers;
convertTrajToMarker(ref_traj_, markers, "ref_traj", 0.0, 0.5, 1.0, 0.05);
pub_debug_filtered_traj_.publish(markers);
};
void MPCFollower::convertTrajToMarker(const MPCTrajectory &traj, visualization_msgs::Marker &marker,
std::string ns, double r, double g, double b, double z)
{
marker.points.clear();
marker.header.frame_id = current_waypoints_.header.frame_id;
marker.header.stamp = ros::Time();
marker.ns = ns;
marker.id = 0;
marker.type = visualization_msgs::Marker::LINE_STRIP;
marker.action = visualization_msgs::Marker::ADD;
marker.scale.x = 0.15;
marker.scale.y = 0.3;
marker.scale.z = 0.3;
marker.color.a = 0.9;
marker.color.r = r;
marker.color.g = g;
marker.color.b = b;
for (unsigned int i = 0; i < traj.x.size(); ++i)
{
geometry_msgs::Point p;
p.x = traj.x.at(i);
p.y = traj.y.at(i);
p.z = traj.z.at(i) + z;
marker.points.push_back(p);
}
}
void MPCFollower::callbackPose(const geometry_msgs::PoseStamped::ConstPtr &msg)
{
vehicle_status_.header = msg->header;
vehicle_status_.pose = msg->pose;
my_position_ok_ = true;
};
void MPCFollower::callbackVehicleStatus(const autoware_msgs::VehicleStatus &msg)
{
vehicle_status_.tire_angle_rad = msg.angle;
vehicle_status_.twist.linear.x = amathutils::kmph2mps(msg.speed);
my_steering_ok_ = true;
my_velocity_ok_ = true;
};
void MPCFollower::publishControlCommands(const double &vel_cmd, const double &acc_cmd,
const double &steer_cmd, const double &steer_vel_cmd)
{
const double omega_cmd = vehicle_status_.twist.linear.x * std::tan(steer_cmd) / wheelbase_;
if (output_interface_ == "twist")
{
publishTwist(vel_cmd, omega_cmd);
}
else if (output_interface_ == "ctrl_cmd")
{
publishCtrlCmd(vel_cmd, acc_cmd, steer_cmd);
}
else if (output_interface_ == "all")
{
publishTwist(vel_cmd, omega_cmd);
publishCtrlCmd(vel_cmd, acc_cmd, steer_cmd);
}
else
{
ROS_WARN("[MPC] control command interface is not appropriate");
}
}
void MPCFollower::publishTwist(const double &vel_cmd, const double &omega_cmd)
{
/* convert steering to twist */
geometry_msgs::TwistStamped twist;
twist.header.frame_id = "/base_link";
twist.header.stamp = ros::Time::now();
twist.twist.linear.x = vel_cmd;
twist.twist.linear.y = 0.0;
twist.twist.linear.z = 0.0;
twist.twist.angular.x = 0.0;
twist.twist.angular.y = 0.0;
twist.twist.angular.z = omega_cmd;
pub_twist_cmd_.publish(twist);
}
void MPCFollower::publishCtrlCmd(const double &vel_cmd, const double &acc_cmd, const double &steer_cmd)
{
autoware_msgs::ControlCommandStamped cmd;
cmd.header.frame_id = "/base_link";
cmd.header.stamp = ros::Time::now();
cmd.cmd.linear_velocity = vel_cmd;
cmd.cmd.linear_acceleration = acc_cmd;
cmd.cmd.steering_angle = steer_cmd;
pub_steer_vel_ctrl_cmd_.publish(cmd);
}
MPCFollower::~MPCFollower()
{
ROS_INFO("Publish 0 twist before I died.");
double vel_cmd = 0.0;
double acc_cmd = 0.0;
double steer_cmd = 0.0;
double steer_vel_cmd = 0.0;
if (my_steering_ok_)
steer_cmd = vehicle_status_.tire_angle_rad;
publishControlCommands(vel_cmd, acc_cmd, steer_cmd, steer_vel_cmd);
};
|
//===-- GlobalStatus.cpp - Compute status info for globals -----------------==//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/GlobalStatus.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/User.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include <algorithm>
#include <cassert>
using namespace llvm;
/// Return the stronger of the two ordering. If the two orderings are acquire
/// and release, then return AcquireRelease.
///
static AtomicOrdering strongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
if ((X == AtomicOrdering::Acquire && Y == AtomicOrdering::Release) ||
(Y == AtomicOrdering::Acquire && X == AtomicOrdering::Release))
return AtomicOrdering::AcquireRelease;
return (AtomicOrdering)std::max((unsigned)X, (unsigned)Y);
}
/// It is safe to destroy a constant iff it is only used by constants itself.
/// Note that constants cannot be cyclic, so this test is pretty easy to
/// implement recursively.
///
bool llvm::isSafeToDestroyConstant(const Constant *C) {
if (isa<GlobalValue>(C))
return false;
if (isa<ConstantData>(C))
return false;
for (const User *U : C->users())
if (const Constant *CU = dyn_cast<Constant>(U)) {
if (!isSafeToDestroyConstant(CU))
return false;
} else
return false;
return true;
}
static bool analyzeGlobalAux(const Value *V, GlobalStatus &GS,
SmallPtrSetImpl<const Value *> &VisitedUsers) {
if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
if (GV->isExternallyInitialized())
GS.StoredType = GlobalStatus::StoredOnce;
for (const Use &U : V->uses()) {
const User *UR = U.getUser();
if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(UR)) {
GS.HasNonInstructionUser = true;
// If the result of the constantexpr isn't pointer type, then we won't
// know to expect it in various places. Just reject early.
if (!isa<PointerType>(CE->getType()))
return true;
// FIXME: Do we need to add constexpr selects to VisitedUsers?
if (analyzeGlobalAux(CE, GS, VisitedUsers))
return true;
} else if (const Instruction *I = dyn_cast<Instruction>(UR)) {
if (!GS.HasMultipleAccessingFunctions) {
const Function *F = I->getParent()->getParent();
if (!GS.AccessingFunction)
GS.AccessingFunction = F;
else if (GS.AccessingFunction != F)
GS.HasMultipleAccessingFunctions = true;
}
if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
GS.IsLoaded = true;
// Don't hack on volatile loads.
if (LI->isVolatile())
return true;
GS.Ordering = strongerOrdering(GS.Ordering, LI->getOrdering());
} else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
// Don't allow a store OF the address, only stores TO the address.
if (SI->getOperand(0) == V)
return true;
// Don't hack on volatile stores.
if (SI->isVolatile())
return true;
GS.Ordering = strongerOrdering(GS.Ordering, SI->getOrdering());
// If this is a direct store to the global (i.e., the global is a scalar
// value, not an aggregate), keep more specific information about
// stores.
if (GS.StoredType != GlobalStatus::Stored) {
if (const GlobalVariable *GV =
dyn_cast<GlobalVariable>(SI->getOperand(1))) {
Value *StoredVal = SI->getOperand(0);
if (Constant *C = dyn_cast<Constant>(StoredVal)) {
if (C->isThreadDependent()) {
// The stored value changes between threads; don't track it.
return true;
}
}
if (GV->hasInitializer() && StoredVal == GV->getInitializer()) {
if (GS.StoredType < GlobalStatus::InitializerStored)
GS.StoredType = GlobalStatus::InitializerStored;
} else if (isa<LoadInst>(StoredVal) &&
cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
if (GS.StoredType < GlobalStatus::InitializerStored)
GS.StoredType = GlobalStatus::InitializerStored;
} else if (GS.StoredType < GlobalStatus::StoredOnce) {
GS.StoredType = GlobalStatus::StoredOnce;
GS.StoredOnceValue = StoredVal;
} else if (GS.StoredType == GlobalStatus::StoredOnce &&
GS.StoredOnceValue == StoredVal) {
// noop.
} else {
GS.StoredType = GlobalStatus::Stored;
}
} else {
GS.StoredType = GlobalStatus::Stored;
}
}
} else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
// Skip over bitcasts and GEPs; we don't care about the type or offset
// of the pointer.
if (analyzeGlobalAux(I, GS, VisitedUsers))
return true;
} else if (isa<SelectInst>(I) || isa<PHINode>(I)) {
// Look through selects and PHIs to find if the pointer is
// conditionally accessed. Make sure we only visit an instruction
// once; otherwise, we can get infinite recursion or exponential
// compile time.
if (VisitedUsers.insert(I).second)
if (analyzeGlobalAux(I, GS, VisitedUsers))
return true;
} else if (isa<CmpInst>(I)) {
GS.IsCompared = true;
} else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
if (MTI->isVolatile())
return true;
if (MTI->getArgOperand(0) == V)
GS.StoredType = GlobalStatus::Stored;
if (MTI->getArgOperand(1) == V)
GS.IsLoaded = true;
} else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
if (MSI->isVolatile())
return true;
GS.StoredType = GlobalStatus::Stored;
} else if (auto C = ImmutableCallSite(I)) {
if (!C.isCallee(&U))
return true;
GS.IsLoaded = true;
} else {
return true; // Any other non-load instruction might take address!
}
} else if (const Constant *C = dyn_cast<Constant>(UR)) {
GS.HasNonInstructionUser = true;
// We might have a dead and dangling constant hanging off of here.
if (!isSafeToDestroyConstant(C))
return true;
} else {
GS.HasNonInstructionUser = true;
// Otherwise must be some other user.
return true;
}
}
return false;
}
GlobalStatus::GlobalStatus() = default;
bool GlobalStatus::analyzeGlobal(const Value *V, GlobalStatus &GS) {
SmallPtrSet<const Value *, 16> VisitedUsers;
return analyzeGlobalAux(V, GS, VisitedUsers);
}
|
/*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#include <aws/codepipeline/model/PutWebhookRequest.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::CodePipeline::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
PutWebhookRequest::PutWebhookRequest() :
m_webhookHasBeenSet(false)
{
}
Aws::String PutWebhookRequest::SerializePayload() const
{
JsonValue payload;
if(m_webhookHasBeenSet)
{
payload.WithObject("webhook", m_webhook.Jsonize());
}
return payload.View().WriteReadable();
}
Aws::Http::HeaderValueCollection PutWebhookRequest::GetRequestSpecificHeaders() const
{
Aws::Http::HeaderValueCollection headers;
headers.insert(Aws::Http::HeaderValuePair("X-Amz-Target", "CodePipeline_20150709.PutWebhook"));
return headers;
}
|
// Copyright 2018-2020 Drexel University
// Author: Geoffrey Mainland <mainland@drexel.edu>
// See:
// https://pybind11.readthedocs.io/en/stable/advanced/cast/custom.html
// https://github.com/pybind/pybind11/issues/1145
// https://github.com/pybind/pybind11/issues/1389
// https://github.com/pybind/pybind11/issues/1546
//
// https://github.com/pybind/pybind11/pull/1146
namespace pybind11::detail {
template<>
struct type_caster<std::shared_ptr<T>>
{
PYBIND11_TYPE_CASTER(std::shared_ptr<T>, _(TNAME));
using BaseCaster = copyable_holder_caster<T, std::shared_ptr<T>>;
bool load(pybind11::handle src, bool b)
{
BaseCaster bc;
if (!bc.load(src, b))
return false;
auto py_obj = py::reinterpret_borrow<py::object>(src);
auto base_ptr = static_cast<std::shared_ptr<T>>(bc);
// Construct a shared_ptr to the py::object
auto py_obj_ptr = std::shared_ptr<object>{
new object{py_obj},
[](auto py_object_ptr) {
// It's possible that when the shared_ptr dies we won't have the
// gil (if the last holder is in a non-Python thread), so we
// make sure to acquire it in the deleter.
gil_scoped_acquire gil;
delete py_object_ptr;
}
};
value = std::shared_ptr<T>(py_obj_ptr, base_ptr.get());
return true;
}
static handle cast(std::shared_ptr<T> base,
return_value_policy rvp,
handle h)
{
return BaseCaster::cast(base, rvp, h);
}
};
template <>
struct is_holder_type<T, std::shared_ptr<T>> : std::true_type {};
}
|
/*5. Average of Values
To get the average of a series of values, you add the values up and then divide the sum
by the number of values. Write a program that stores the following values in five different variables:
28, 32, 37, 24, and 33. The program should first calculate the sum
of these five variables and store the result in a separate variable named sum. Then, the
program should divide the sum variable by 5 to get the average. Display the average
on the screen. */
#include<iostream>
using namespace std;
#include<conio.h>//required for VS 2015 not for latest
int main()
{
int var1 = 28, var2 = 32, var3 = 37, var4 = 24, var5 = 33;//variables for calculating the sum and average
int sum; //This will store the sum
float average; //This will store the average
sum = var1 + var2 + var3 + var4 + var5; //will store the sum of variables in the variable sum
//Now for average
average = sum / 5;//formula for average
cout << "The average of five given variables is equal to: " << average;
getchar(); //only required for vs 2015 or below not for latest
return 0;
}
|
#include <sharpen/ProcessInfo.hpp>
#ifdef SHARPEN_IS_WIN
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <sharpen/Optional.hpp>
sharpen::Uint32 sharpen::GetProcessId() noexcept
{
static sharpen::Optional<sharpen::Uint32> id;
if(!id.Exist())
{
#ifdef SHARPEN_IS_WIN
id.Construct(::GetCurrentProcessId());
#else
id.Construct(static_cast<sharpen::Uint32>(::getpid()));
#endif
}
return id.Get();
}
|
// Copyright 2016 EssaBlockChain Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#include "KeyUtils.h"
#include "crypto/StrKey.h"
namespace essa
{
size_t
KeyUtils::getKeyVersionSize(strKey::StrKeyVersionByte keyVersion)
{
switch (keyVersion)
{
case strKey::STRKEY_PUBKEY_ED25519:
case strKey::STRKEY_SEED_ED25519:
return crypto_sign_PUBLICKEYBYTES;
case strKey::STRKEY_PRE_AUTH_TX:
case strKey::STRKEY_HASH_X:
return 32U;
default:
throw std::invalid_argument("invalid key version: " +
std::to_string(keyVersion));
}
}
}
|
#ifndef PORTABLE_BINARY_ARCHIVE_HPP
#define PORTABLE_BINARY_ARCHIVE_HPP
// (C) Copyright 2002 Robert Ramey - http://www.rrsd.com .
// Use, modification and distribution is 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)
// MS compatible compilers support #pragma once
#if defined(_MSC_VER)
# pragma once
#endif
#include <boost/config.hpp>
#include <boost/cstdint.hpp>
#include <boost/static_assert.hpp>
#include <boost/archive/archive_exception.hpp>
#include <climits>
#if CHAR_BIT != 8
#error This code assumes an eight-bit byte.
#endif
#include <boost/archive/basic_archive.hpp>
//#include <boost/detail/endian.hpp>
#include <boost/archive/impl/archive_serializer_map.ipp>
namespace boost { namespace archive {
enum portable_binary_archive_flags {
endian_big = 0x4000,
endian_little = 0x8000
};
//#if ( endian_big <= boost::archive::flags_last )
//#error archive flags conflict
//#endif
inline void
reverse_bytes(signed char size, char *address){
if (size <= 0)
throw archive_exception(archive_exception::other_exception);
char * first = address;
char * last = first + size - 1;
for(;first < last;++first, --last){
char x = *last;
*last = *first;
*first = x;
}
}
} }
#endif // PORTABLE_BINARY_ARCHIVE_HPP
|
//=================================================================================================
/*!
// \file src/mathtest/dmatdmatsub/MHaMHa.cpp
// \brief Source file for the MHaMHa dense matrix/dense matrix subtraction math test
//
// Copyright (C) 2012-2020 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. 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 names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/HybridMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
#ifdef BLAZE_USE_HPX_THREADS
# include <hpx/hpx_main.hpp>
#endif
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MHaMHa'..." << std::endl;
using blazetest::mathtest::TypeA;
try
{
// Matrix type definitions
using MHa = blaze::HybridMatrix<TypeA,128UL,128UL>;
// Creator type definitions
using CMHa = blazetest::Creator<MHa>;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
for( size_t j=0UL; j<=9UL; ++j ) {
RUN_DMATDMATSUB_OPERATION_TEST( CMHa( i, j ), CMHa( i, j ) );
}
}
// Running tests with large matrices
RUN_DMATDMATSUB_OPERATION_TEST( CMHa( 67UL, 67UL ), CMHa( 67UL, 67UL ) );
RUN_DMATDMATSUB_OPERATION_TEST( CMHa( 67UL, 127UL ), CMHa( 67UL, 127UL ) );
RUN_DMATDMATSUB_OPERATION_TEST( CMHa( 128UL, 64UL ), CMHa( 128UL, 64UL ) );
RUN_DMATDMATSUB_OPERATION_TEST( CMHa( 128UL, 128UL ), CMHa( 128UL, 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
|
/*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
http://www.boost.org/
Copyright (c) 2001-2012 Hartmut Kaiser. 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)
The tests included in this file were initially taken from the mcpp V2.5
preprocessor validation suite and were modified to fit into the Boost.Wave
unit test requirements.
The original files of the mcpp preprocessor are distributed under the
license reproduced at the end of this file.
=============================================================================*/
// Tests error reporting: #ifdef, #ifndef syntax errors.
// 15.4: Excessive token sequence.
//E t_6_021.cpp(20): error: ill formed preprocessor directive: #ifdef MACRO Junk
#ifdef MACRO Junk
#endif
/*-
* Copyright (c) 1998, 2002-2005 Kiyoshi Matsui <kmatsui@t3.rim.or.jp>
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 <windows.h>
#include "PatternFinder.hpp"
#include "NamesStore.hpp"
#include "EngineClasses.hpp"
class FNameEntry
{
public:
__int32 Index;
char pad_0x0004[0x4];
FNameEntry* HashNext;
union
{
char AnsiName[1024];
wchar_t WideName[1024];
};
const char* GetName() const
{
return AnsiName;
}
};
template<typename ElementType, int32_t MaxTotalElements, int32_t ElementsPerChunk>
class TStaticIndirectArrayThreadSafeRead
{
public:
int32_t Num() const
{
return NumElements;
}
bool IsValidIndex(int32_t index) const
{
return index >= 0 && index < Num() && GetById(index) != nullptr;
}
ElementType const* const& GetById(int32_t index) const
{
return *GetItemPtr(index);
}
private:
ElementType const* const* GetItemPtr(int32_t Index) const
{
int32_t ChunkIndex = Index / ElementsPerChunk;
int32_t WithinChunkIndex = Index % ElementsPerChunk;
ElementType** Chunk = Chunks[ChunkIndex];
return Chunk + WithinChunkIndex;
}
enum
{
ChunkTableSize = (MaxTotalElements + ElementsPerChunk - 1) / ElementsPerChunk
};
ElementType** Chunks[ChunkTableSize];
__int32 NumElements;
__int32 NumChunks;
};
using TNameEntryArray = TStaticIndirectArrayThreadSafeRead<FNameEntry, 2 * 1024 * 1024, 16384>;
TNameEntryArray* GlobalNames = nullptr;
bool NamesStore::Initialize()
{
auto address = FindPattern(GetModuleHandleW(nullptr), reinterpret_cast<const unsigned char*>("\x48\x8B\x5C\x24\x00\x48\x89\x05\x00\x00\x00\x00\x48\x83\xC4\x28\xC3"), "xxxx?xxx????xxxxx");
if (address == -1)
{
return false;
}
address += 5;
auto offset = *reinterpret_cast<uint32_t*>(address + 3);
GlobalNames = reinterpret_cast<decltype(GlobalNames)>(*reinterpret_cast<uintptr_t*>(address + 7 + offset));
return true;
}
void* NamesStore::GetAddress()
{
return GlobalNames;
}
size_t NamesStore::GetNamesNum() const
{
return GlobalNames->Num();
}
bool NamesStore::IsValid(size_t id) const
{
return GlobalNames->IsValidIndex(static_cast<int32_t>(id));
}
std::string NamesStore::GetById(size_t id) const
{
return GlobalNames->GetById(static_cast<int32_t>(id))->GetName();
}
|
//
// FILE NAME: CIDMacroEng_FlowCtrlItem.hpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/08/2003
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This is the header file for the CIDMacroEng_FlowCtrlItem.cpp file, which
// implements the TMEngFlowCtrlItem class. This class is used to push items
// onto a flow control management stack. When a flow control item is seen,
// an item is made and pushed. This allows us to correctly handle nesting of
// flow control statements, insuring that they are all closed correctly, and
// that we don't have any open at the end of the method and so forth.
//
// It also stores the opcode index, since the end of some control structures
// involves a jump back to the start. And, some are forward jumps, so we can
// update the forward jump offset before we pop it off.
//
// These items are used in a strict LIFO stack mode.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
#pragma once
#pragma CIDLIB_PACK(CIDLIBPACK)
// ---------------------------------------------------------------------------
// CLASS: TMEngFlowCtrlItem
// PREFIX: mefci
// ---------------------------------------------------------------------------
class CIDMACROENGEXP TMEngFlowCtrlItem : public TObject
{
public :
// -------------------------------------------------------------------
// Constructors and Destructor
// -------------------------------------------------------------------
TMEngFlowCtrlItem();
TMEngFlowCtrlItem
(
const tCIDMacroEng::EFlowTypes eType
, const tCIDLib::TCard4 c4Offset
, const tCIDLib::TCard4 c4LineNum
);
TMEngFlowCtrlItem
(
const tCIDMacroEng::EFlowTypes eType
, const tCIDLib::TCard4 c4Offset
, const tCIDLib::TCard2 c2Id
, const tCIDLib::TCard4 c4LineNum
);
TMEngFlowCtrlItem
(
const tCIDMacroEng::EFlowTypes eType
, const tCIDLib::TCard4 c4Offset1
, const tCIDLib::TCard4 c4Offset2
, const tCIDLib::TCard4 c4LineNum
);
TMEngFlowCtrlItem
(
const TMEngFlowCtrlItem& mefciToCopy
);
~TMEngFlowCtrlItem();
// -------------------------------------------------------------------
// Public operators
// -------------------------------------------------------------------
TMEngFlowCtrlItem& operator=
(
const TMEngFlowCtrlItem& mefciToAssign
);
// -------------------------------------------------------------------
// Public, non-virtual methods
// -------------------------------------------------------------------
tCIDLib::TVoid AddBreakOffset
(
const tCIDLib::TCard4 c4Offset
);
tCIDLib::TBoolean bIsLoopedType() const;
tCIDLib::TCard2 c2Id() const;
tCIDLib::TCard4 c4BreakCount() const;
tCIDLib::TCard4 c4BreakOffsetAt
(
const tCIDLib::TCard4 c4At
) const;
tCIDLib::TCard4 c4LineNum() const;
tCIDLib::TCard4 c4Offset1() const;
tCIDLib::TCard4 c4Offset1
(
const tCIDLib::TCard4 c4ToSet
);
tCIDLib::TCard4 c4Offset2() const;
tCIDLib::TCard4 c4Offset2
(
const tCIDLib::TCard4 c4ToSet
);
tCIDMacroEng::EFlowTypes eType() const;
private :
// -------------------------------------------------------------------
// Private data members
//
// m_c2Id
// Sometimes we need to remember the id of something until we get
// to the end of the loop.
//
// m_c4LineNum
// In some cases we want to give an indication of where the
// problem was if an error in flow control occurs, so they have
// to give us the line number of where this flow control item
// was found.
//
// m_c4Offset1
// The IP of where this control structure starts, i.e. the offset
// of the first opcode of the control structure.
//
// m_c4Offset2
// An extra offset that can be used to remember another IP
// where something needs to be updated. It might not always be
// be used.
//
// m_eType
// Indicates the type of item this is, e.g. while, if, else, or
// so forth.
//
// m_fcolBreaks
// This stores a list of the indexes of any jumps that we put
// out due to Break commands. These need to be updated at the
// end of the block to jump to the end of the block.
// -------------------------------------------------------------------
tCIDLib::TCard2 m_c2Id;
tCIDLib::TCard4 m_c4LineNum;
tCIDLib::TCard4 m_c4Offset1;
tCIDLib::TCard4 m_c4Offset2;
tCIDMacroEng::EFlowTypes m_eType;
TFundVector<tCIDLib::TCard4> m_fcolBreaks;
// -------------------------------------------------------------------
// Do any needed magic macros
// -------------------------------------------------------------------
RTTIDefs(TMEngFlowCtrlItem,TObject)
};
#pragma CIDLIB_POPPACK
|
/*=========================================================================
Program: Visualization Toolkit
Module: TestGPURayCastTransfer2DYScalars.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
/**
* Test 2D transfer function support in GPUVolumeRayCastMapper for multivariate data. The transfer
* function is manually created and specified over two scalar fields in the input dataset.
*/
#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkDataObject.h"
#include "vtkExodusIIReader.h"
#include "vtkGPUVolumeRayCastMapper.h"
#include "vtkImageData.h"
#include "vtkNew.h"
#include "vtkPointData.h"
#include "vtkRegressionTestImage.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderer.h"
#include "vtkResampleToImage.h"
#include "vtkTestUtilities.h"
#include "vtkTesting.h"
#include "vtkVolume.h"
#include "vtkVolumeProperty.h"
#include "vtkXMLImageDataReader.h"
int TestGPURayCastTransfer2DYScalars(int argc, char* argv[])
{
cout << "CTEST_FULL_OUTPUT (Avoid ctest truncation of output)" << endl;
// Load data
char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/disk_out_ref.ex2");
vtkNew<vtkExodusIIReader> reader;
reader->SetFileName(fname);
reader->SetPointResultArrayStatus("Temp", 1);
reader->SetPointResultArrayStatus("Pres", 1);
vtkNew<vtkResampleToImage> resample;
resample->SetUseInputBounds(true);
resample->SetSamplingDimensions(200, 200, 200);
resample->SetInputConnection(reader->GetOutputPort());
resample->Update();
delete[] fname;
// Load the transfer function
char* tfname = vtkTestUtilities::ExpandDataFileName(
argc, argv, "Data/TestGPURayCastTransfer2DYScalarsTransferFunction.vti");
vtkNew<vtkXMLImageDataReader> tfReader;
tfReader->SetFileName(tfname);
tfReader->Update();
delete[] tfname;
// Setup rendering context
vtkNew<vtkRenderWindow> renWin;
renWin->SetSize(300, 300);
renWin->SetMultiSamples(0);
vtkNew<vtkRenderWindowInteractor> iren;
iren->SetRenderWindow(renWin);
vtkNew<vtkRenderer> ren;
renWin->AddRenderer(ren);
ren->SetBackground(0.0, 0.0, 0.0);
vtkNew<vtkVolumeProperty> property;
property->SetTransferFunction2D(tfReader->GetOutput());
property->SetTransferFunctionModeTo2D();
vtkNew<vtkGPUVolumeRayCastMapper> mapper;
mapper->SetInputConnection(resample->GetOutputPort());
mapper->SetUseJittering(1);
mapper->SetScalarModeToUsePointFieldData();
mapper->SelectScalarArray("Pres");
mapper->SetTransfer2DYAxisArray("Temp");
vtkNew<vtkVolume> volume;
volume->SetMapper(mapper);
volume->SetProperty(property);
ren->AddVolume(volume);
ren->ResetCamera();
auto cam = ren->GetActiveCamera();
cam->Azimuth(90);
cam->Dolly(1.2);
iren->Initialize();
renWin->Render();
return vtkTesting::InteractorEventLoop(argc, argv, iren);
}
|
// dear imgui, v1.84 WIP
// (main code and documentation)
// Help:
// - Read FAQ at http://dearimgui.org/faq
// - Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// - Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp. All applications in examples/ are doing that.
// Read imgui.cpp for details, links and comments.
// Resources:
// - FAQ http://dearimgui.org/faq
// - Homepage & latest https://github.com/ocornut/imgui
// - Releases & changelog https://github.com/ocornut/imgui/releases
// - Gallery https://github.com/ocornut/imgui/issues/3793 (please post your screenshots/video there!)
// - Wiki https://github.com/ocornut/imgui/wiki (lots of good stuff there)
// - Glossary https://github.com/ocornut/imgui/wiki/Glossary
// - Issues & support https://github.com/ocornut/imgui/issues
// - Discussions https://github.com/ocornut/imgui/discussions
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but needs your support to sustain development and maintenance.
// Businesses: you can support continued development via invoiced technical support, maintenance and sponsoring contracts. Please reach out to "contact AT dearimgui.com".
// Individuals: you can support continued development via donations. See docs/README or web page.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE
- READ FIRST
- HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
- GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
- HOW A SIMPLE APPLICATION MAY LOOK LIKE
- HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
- USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ)
- Read all answers online: https://www.dearimgui.org/faq, or in docs/FAQ.md (with a Markdown viewer)
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] INCLUDES
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
// [SECTION] MISC HELPERS/UTILITIES (File functions)
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] STYLING
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] ERROR CHECKING
// [SECTION] LAYOUT
// [SECTION] SCROLLING
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] DRAG AND DROP
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] VIEWPORTS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUGGER WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
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 setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption.
Designed for developers and content-creators, not the typical end-user! Some of the current 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 http://dearimgui.org/controls_sheets
PROGRAMMER GUIDE
================
READ FIRST
----------
- Remember to check the wonderful Wiki (https://github.com/ocornut/imgui/wiki)
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction or
destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, fewer bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links in Wiki.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame, your UI code will be called only once. This is in contrast to e.g. Unity's implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin is on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI
----------------------------------------------
- Overwrite all the sources files except for imconfig.h (if you have modified your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified as a top-most commit which you can regularly rebase over "master".
- You can also use '#define IMGUI_USER_CONFIG "my_config_file.h" to redirect configuration to your own file.
- 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!
- To find out usage of old API, you can add '#define IMGUI_DISABLE_OBSOLETE_FUNCTIONS' in your configuration file.
- Try to keep your copy of Dear ImGui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE
---------------------------------------------------------------
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- In the majority of cases you should be able to use unmodified backends files available in the backends/ folder.
- Add the Dear ImGui source files + selected backend source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and NOT as a shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating Dear ImGui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function 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. All rendering information is stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the backends and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE
--------------------------------------
EXHIBIT 1: USING THE EXAMPLE BACKENDS (= imgui_impl_XXX.cpp files from the backends/ folder).
The sub-folders in examples/ contain examples applications following this structure.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer backends (here we are using imgui_impl_win32.cpp and imgui_impl_dx11.cpp)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
EXHIBIT 2: IMPLEMENTING CUSTOM BACKEND / CUSTOM ENGINE
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that to your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->SetTexID((void*)texture);
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform Backends)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your main loop to be able to use Dear ImGui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any Dear ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any Dear ImGui functions as well!
// Render dear imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use Dear ImGui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
To decide whether to dispatch mouse/keyboard inputs to Dear ImGui to the rest of your application,
you should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
Please read the FAQ and example applications for details about this!
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE
---------------------------------------------
The backends in impl_impl_XXX.cpp files contain many working implementations of a rendering function.
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// 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 ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by Dear ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by Dear 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->GetTexID().
// The vast majority of draw calls will use the Dear ImGui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->GetTexID());
// We are using scissoring to clip some objects. All low-level graphics API should support it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space:
// - For a given viewport, draw_data->DisplayPos == viewport->Pos and draw_data->DisplaySize == viewport->Size
// - In a single viewport application, draw_data->DisplayPos == (0,0) and draw_data->DisplaySize == io.DisplaySize, but always use GetMainViewport()->Pos/Size instead of hardcoding those values.
// - In the interest of supporting multi-viewport applications (see 'docking' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bit, you can change them to 32-bit in imconfig.h if your engine doesn't support 16-bit indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
------------------------------------------
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use Dear ImGui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can 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.KeysDown[] + 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(ImGuiFocusedFlags_AnyWindow), 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 use 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: http://dearimgui.org/controls_sheets
- 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 backend NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the backends 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 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. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about an old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
- 2021/05/19 (1.83) - backends: obsoleted direct access to ImDrawCmd::TextureId in favor of calling ImDrawCmd::GetTexID().
- if you are using official backends from the source tree: you have nothing to do.
- if you have copied old backend code or using your own: change access to draw_cmd->TextureId to draw_cmd->GetTexID().
- 2021/03/12 (1.82) - upgraded ImDrawList::AddRect(), AddRectFilled(), PathRect() to use ImDrawFlags instead of ImDrawCornersFlags.
- ImDrawCornerFlags_TopLeft -> use ImDrawFlags_RoundCornersTopLeft
- ImDrawCornerFlags_BotRight -> use ImDrawFlags_RoundCornersBottomRight
- ImDrawCornerFlags_None -> use ImDrawFlags_RoundCornersNone etc.
flags now sanely defaults to 0 instead of 0x0F, consistent with all other flags in the API.
breaking: the default with rounding > 0.0f is now "round all corners" vs old implicit "round no corners":
- rounding == 0.0f + flags == 0 --> meant no rounding --> unchanged (common use)
- rounding > 0.0f + flags != 0 --> meant rounding --> unchanged (common use)
- rounding == 0.0f + flags != 0 --> meant no rounding --> unchanged (unlikely use)
- rounding > 0.0f + flags == 0 --> meant no rounding --> BREAKING (unlikely use): will now round all corners --> use ImDrawFlags_RoundCornersNone or rounding == 0.0f.
this ONLY matters for hard coded use of 0 + rounding > 0.0f. Use of named ImDrawFlags_RoundCornersNone (new) or ImDrawCornerFlags_None (old) are ok.
the old ImDrawCornersFlags used awkward default values of ~0 or 0xF (4 lower bits set) to signify "round all corners" and we sometimes encouraged using them as shortcuts.
legacy path still support use of hard coded ~0 or any value from 0x1 or 0xF. They will behave the same with legacy paths enabled (will assert otherwise).
- 2021/03/11 (1.82) - removed redirecting functions/enums names that were marked obsolete in 1.66 (September 2018):
- ImGui::SetScrollHere() -> use ImGui::SetScrollHereY()
- 2021/03/11 (1.82) - clarified that ImDrawList::PathArcTo(), ImDrawList::PathArcToFast() won't render with radius < 0.0f. Previously it sorts of accidentally worked but would generally lead to counter-clockwise paths and have an effect on anti-aliasing.
- 2021/03/10 (1.82) - upgraded ImDrawList::AddPolyline() and PathStroke() "bool closed" parameter to "ImDrawFlags flags". The matching ImDrawFlags_Closed value is guaranteed to always stay == 1 in the future.
- 2021/02/22 (1.82) - win32+mingw: Re-enabled IME functions by default even under MinGW. In July 2016, issue #738 had me incorrectly disable those default functions for MinGW. MinGW users should: either link with -limm32, either set their imconfig file with '#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS'.
- 2021/02/17 (1.82) - renamed rarely used style.CircleSegmentMaxError (old default = 1.60f) to style.CircleTessellationMaxError (new default = 0.30f) as the meaning of the value changed.
- 2021/02/03 (1.81) - renamed ListBoxHeader(const char* label, ImVec2 size) to BeginListBox(). Kept inline redirection function (will obsolete).
- removed ListBoxHeader(const char* label, int items_count, int height_in_items = -1) in favor of specifying size. Kept inline redirection function (will obsolete).
- renamed ListBoxFooter() to EndListBox(). Kept inline redirection function (will obsolete).
- 2021/01/26 (1.81) - removed ImGuiFreeType::BuildFontAtlas(). Kept inline redirection function. Prefer using '#define IMGUI_ENABLE_FREETYPE', but there's a runtime selection path available too. The shared extra flags parameters (very rarely used) are now stored in ImFontAtlas::FontBuilderFlags.
- renamed ImFontConfig::RasterizerFlags (used by FreeType) to ImFontConfig::FontBuilderFlags.
- renamed ImGuiFreeType::XXX flags to ImGuiFreeTypeBuilderFlags_XXX for consistency with other API.
- 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.63 (August 2018):
- ImGui::IsItemDeactivatedAfterChange() -> use ImGui::IsItemDeactivatedAfterEdit().
- ImGuiCol_ModalWindowDarkening -> use ImGuiCol_ModalWindowDimBg
- ImGuiInputTextCallback -> use ImGuiTextEditCallback
- ImGuiInputTextCallbackData -> use ImGuiTextEditCallbackData
- 2020/12/21 (1.80) - renamed ImDrawList::AddBezierCurve() to AddBezierCubic(), and PathBezierCurveTo() to PathBezierCubicCurveTo(). Kept inline redirection function (will obsolete).
- 2020/12/04 (1.80) - added imgui_tables.cpp file! Manually constructed project files will need the new file added!
- 2020/11/18 (1.80) - renamed undocumented/internals ImGuiColumnsFlags_* to ImGuiOldColumnFlags_* in prevision of incoming Tables API.
- 2020/11/03 (1.80) - renamed io.ConfigWindowsMemoryCompactTimer to io.ConfigMemoryCompactTimer as the feature will apply to other data structures
- 2020/10/14 (1.80) - backends: moved all backends files (imgui_impl_XXXX.cpp, imgui_impl_XXXX.h) from examples/ to backends/.
- 2020/10/12 (1.80) - removed redirecting functions/enums that were marked obsolete in 1.60 (April 2018):
- io.RenderDrawListsFn pointer -> use ImGui::GetDrawData() value and call the render function of your backend
- ImGui::IsAnyWindowFocused() -> use ImGui::IsWindowFocused(ImGuiFocusedFlags_AnyWindow)
- ImGui::IsAnyWindowHovered() -> use ImGui::IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
- ImGuiStyleVar_Count_ -> use ImGuiStyleVar_COUNT
- ImGuiMouseCursor_Count_ -> use ImGuiMouseCursor_COUNT
- removed redirecting functions names that were marked obsolete in 1.61 (May 2018):
- InputFloat (... int decimal_precision ...) -> use InputFloat (... const char* format ...) with format = "%.Xf" where X is your value for decimal_precision.
- same for InputFloat2()/InputFloat3()/InputFloat4() variants taking a `int decimal_precision` parameter.
- 2020/10/05 (1.79) - removed ImGuiListClipper: Renamed constructor parameters which created an ambiguous alternative to using the ImGuiListClipper::Begin() function, with misleading edge cases (note: imgui_memory_editor <0.40 from imgui_club/ used this old clipper API. Update your copy if needed).
- 2020/09/25 (1.79) - renamed ImGuiSliderFlags_ClampOnInput to ImGuiSliderFlags_AlwaysClamp. Kept redirection enum (will obsolete sooner because previous name was added recently).
- 2020/09/25 (1.79) - renamed style.TabMinWidthForUnselectedCloseButton to style.TabMinWidthForCloseButton.
- 2020/09/21 (1.79) - renamed OpenPopupContextItem() back to OpenPopupOnItemClick(), reverting the change from 1.77. For varieties of reason this is more self-explanatory.
- 2020/09/21 (1.79) - removed return value from OpenPopupOnItemClick() - returned true on mouse release on an item - because it is inconsistent with other popup APIs and makes others misleading. It's also and unnecessary: you can use IsWindowAppearing() after BeginPopup() for a similar result.
- 2020/09/17 (1.79) - removed ImFont::DisplayOffset in favor of ImFontConfig::GlyphOffset. DisplayOffset was applied after scaling and not very meaningful/useful outside of being needed by the default ProggyClean font. If you scaled this value after calling AddFontDefault(), this is now done automatically. It was also getting in the way of better font scaling, so let's get rid of it now!
- 2020/08/17 (1.78) - obsoleted use of the trailing 'float power=1.0f' parameter for DragFloat(), DragFloat2(), DragFloat3(), DragFloat4(), DragFloatRange2(), DragScalar(), DragScalarN(), SliderFloat(), SliderFloat2(), SliderFloat3(), SliderFloat4(), SliderScalar(), SliderScalarN(), VSliderFloat() and VSliderScalar().
replaced the 'float power=1.0f' argument with integer-based flags defaulting to 0 (as with all our flags).
worked out a backward-compatibility scheme so hopefully most C++ codebase should not be affected. in short, when calling those functions:
- if you omitted the 'power' parameter (likely!), you are not affected.
- if you set the 'power' parameter to 1.0f (same as previous default value): 1/ your compiler may warn on float>int conversion, 2/ everything else will work. 3/ you can replace the 1.0f value with 0 to fix the warning, and be technically correct.
- if you set the 'power' parameter to >1.0f (to enable non-linear editing): 1/ your compiler may warn on float>int conversion, 2/ code will assert at runtime, 3/ in case asserts are disabled, the code will not crash and enable the _Logarithmic flag. 4/ you can replace the >1.0f value with ImGuiSliderFlags_Logarithmic to fix the warning/assert and get a _similar_ effect as previous uses of power >1.0f.
see https://github.com/ocornut/imgui/issues/3361 for all details.
kept inline redirection functions (will obsolete) apart for: DragFloatRange2(), VSliderFloat(), VSliderScalar(). For those three the 'float power=1.0f' version was removed directly as they were most unlikely ever used.
for shared code, you can version check at compile-time with `#if IMGUI_VERSION_NUM >= 17704`.
- obsoleted use of v_min > v_max in DragInt, DragFloat, DragScalar to lock edits (introduced in 1.73, was not demoed nor documented very), will be replaced by a more generic ReadOnly feature. You may use the ImGuiSliderFlags_ReadOnly internal flag in the meantime.
- 2020/06/23 (1.77) - removed BeginPopupContextWindow(const char*, int mouse_button, bool also_over_items) in favor of BeginPopupContextWindow(const char*, ImGuiPopupFlags flags) with ImGuiPopupFlags_NoOverItems.
- 2020/06/15 (1.77) - renamed OpenPopupOnItemClick() to OpenPopupContextItem(). Kept inline redirection function (will obsolete). [NOTE: THIS WAS REVERTED IN 1.79]
- 2020/06/15 (1.77) - removed CalcItemRectClosestPoint() entry point which was made obsolete and asserting in December 2017.
- 2020/04/23 (1.77) - removed unnecessary ID (first arg) of ImFontAtlas::AddCustomRectRegular().
- 2020/01/22 (1.75) - ImDrawList::AddCircle()/AddCircleFilled() functions don't accept negative radius any more.
- 2019/12/17 (1.75) - [undid this change in 1.76] made Columns() limited to 64 columns by asserting above that limit. While the current code technically supports it, future code may not so we're putting the restriction ahead.
- 2019/12/13 (1.75) - [imgui_internal.h] changed ImRect() default constructor initializes all fields to 0.0f instead of (FLT_MAX,FLT_MAX,-FLT_MAX,-FLT_MAX). If you used ImRect::Add() to create bounding boxes by adding multiple points into it, you may need to fix your initial value.
- 2019/12/08 (1.75) - removed redirecting functions/enums that were marked obsolete in 1.53 (December 2017):
- ShowTestWindow() -> use ShowDemoWindow()
- IsRootWindowFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootWindow)
- IsRootWindowOrAnyChildFocused() -> use IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows)
- SetNextWindowContentWidth(w) -> use SetNextWindowContentSize(ImVec2(w, 0.0f)
- GetItemsLineHeightWithSpacing() -> use GetFrameHeightWithSpacing()
- ImGuiCol_ChildWindowBg -> use ImGuiCol_ChildBg
- ImGuiStyleVar_ChildWindowRounding -> use ImGuiStyleVar_ChildRounding
- ImGuiTreeNodeFlags_AllowOverlapMode -> use ImGuiTreeNodeFlags_AllowItemOverlap
- IMGUI_DISABLE_TEST_WINDOWS -> use IMGUI_DISABLE_DEMO_WINDOWS
- 2019/12/08 (1.75) - obsoleted calling ImDrawList::PrimReserve() with a negative count (which was vaguely documented and rarely if ever used). Instead, we added an explicit PrimUnreserve() API.
- 2019/12/06 (1.75) - removed implicit default parameter to IsMouseDragging(int button = 0) to be consistent with other mouse functions (none of the other functions have it).
- 2019/11/21 (1.74) - ImFontAtlas::AddCustomRectRegular() now requires an ID larger than 0x110000 (instead of 0x10000) to conform with supporting Unicode planes 1-16 in a future update. ID below 0x110000 will now assert.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS to IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS for consistency.
- 2019/11/19 (1.74) - renamed IMGUI_DISABLE_MATH_FUNCTIONS to IMGUI_DISABLE_DEFAULT_MATH_FUNCTIONS for consistency.
- 2019/10/22 (1.74) - removed redirecting functions/enums that were marked obsolete in 1.52 (October 2017):
- Begin() [old 5 args version] -> use Begin() [3 args], use SetNextWindowSize() SetNextWindowBgAlpha() if needed
- IsRootWindowOrAnyChildHovered() -> use IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows)
- AlignFirstTextHeightToWidgets() -> use AlignTextToFramePadding()
- SetNextWindowPosCenter() -> use SetNextWindowPos() with a pivot of (0.5f, 0.5f)
- ImFont::Glyph -> use ImFontGlyph
- 2019/10/14 (1.74) - inputs: Fixed a miscalculation in the keyboard/mouse "typematic" repeat delay/rate calculation, used by keys and e.g. repeating mouse buttons as well as the GetKeyPressedAmount() function.
if you were using a non-default value for io.KeyRepeatRate (previous default was 0.250), you can add +io.KeyRepeatDelay to it to compensate for the fix.
The function was triggering on: 0.0 and (delay+rate*N) where (N>=1). Fixed formula responds to (N>=0). Effectively it made io.KeyRepeatRate behave like it was set to (io.KeyRepeatRate + io.KeyRepeatDelay).
If you never altered io.KeyRepeatRate nor used GetKeyPressedAmount() this won't affect you.
- 2019/07/15 (1.72) - removed TreeAdvanceToLabelPos() which is rarely used and only does SetCursorPosX(GetCursorPosX() + GetTreeNodeToLabelSpacing()). Kept redirection function (will obsolete).
- 2019/07/12 (1.72) - renamed ImFontAtlas::CustomRect to ImFontAtlasCustomRect. Kept redirection typedef (will obsolete).
- 2019/06/14 (1.72) - removed redirecting functions/enums names that were marked obsolete in 1.51 (June 2017): ImGuiCol_Column*, ImGuiSetCond_*, IsItemHoveredRect(), IsPosHoveringAnyWindow(), IsMouseHoveringAnyWindow(), IsMouseHoveringWindow(), IMGUI_ONCE_UPON_A_FRAME. Grep this log for details and new names, or see how they were implemented until 1.71.
- 2019/06/07 (1.71) - rendering of child window outer decorations (bg color, border, scrollbars) is now performed as part of the parent window. If you have
overlapping child windows in a same parent, and relied on their relative z-order to be mapped to their submission order, this will affect your rendering.
This optimization is disabled if the parent window has no visual output, because it appears to be the most common situation leading to the creation of overlapping child windows.
Please reach out if you are affected.
- 2019/05/13 (1.71) - renamed SetNextTreeNodeOpen() to SetNextItemOpen(). Kept inline redirection function (will obsolete).
- 2019/05/11 (1.71) - changed io.AddInputCharacter(unsigned short c) signature to io.AddInputCharacter(unsigned int c).
- 2019/04/29 (1.70) - improved ImDrawList thick strokes (>1.0f) preserving correct thickness up to 90 degrees angles (e.g. rectangles). If you have custom rendering using thick lines, they will appear thicker now.
- 2019/04/29 (1.70) - removed GetContentRegionAvailWidth(), use GetContentRegionAvail().x instead. Kept inline redirection function (will obsolete).
- 2019/03/04 (1.69) - renamed GetOverlayDrawList() to GetForegroundDrawList(). Kept redirection function (will obsolete).
- 2019/02/26 (1.69) - renamed ImGuiColorEditFlags_RGB/ImGuiColorEditFlags_HSV/ImGuiColorEditFlags_HEX to ImGuiColorEditFlags_DisplayRGB/ImGuiColorEditFlags_DisplayHSV/ImGuiColorEditFlags_DisplayHex. Kept redirection enums (will obsolete).
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with an arbitrarily small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Kept redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_XXX files have been split to separate platform (Win32, GLFW, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old backends will still work as is, however prefer using the separated backends as they will be updated to support multi-viewports.
when adopting new backends follow the main.cpp code of your preferred examples/ folder to know which functions to call.
in particular, note that old backends called ImGui::NewFrame() at the end of their ImGui_ImplXXXX_NewFrame() function.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 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 backend 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. Otherwise 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.
IsItemHoveredRect() --> IsItemHovered(ImGuiHoveredFlags_RectOnly)
IsMouseHoveringAnyWindow() --> IsWindowHovered(ImGuiHoveredFlags_AnyWindow)
IsMouseHoveringWindow() --> IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup | ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) [weird, old behavior]
- 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/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Kept redirection typedef (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 backend 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 type.
- 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_Column to ImGuiCol_Separator, ImGuiCol_ColumnHovered to ImGuiCol_SeparatorHovered, ImGuiCol_ColumnActive to ImGuiCol_SeparatorActive. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_Always to ImGuiCond_Always, ImGuiSetCond_Once to ImGuiCond_Once, ImGuiSetCond_FirstUseEver to ImGuiCond_FirstUseEver, ImGuiSetCond_Appearing to ImGuiCond_Appearing. 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, otherwise if <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 ImDrawList::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_XXX.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).
parameters: '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 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.
- 2015/01/11 (1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
- old: const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); [..Upload texture to GPU..];
- new: unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); [..Upload texture to GPU..]; io.Fonts->SetTexID(YourTexIdentifier);
you now have 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.
- 2015/01/11 (1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to call io.Fonts->SetTexID()
- 2015/01/11 (1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
- 2015/01/11 (1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ)
================================
Read all answers online:
https://www.dearimgui.org/faq or https://github.com/ocornut/imgui/blob/master/docs/FAQ.md (same url)
Read all answers locally (with a text editor or ideally a Markdown viewer):
docs/FAQ.md
Some answers are copied down here to facilitate searching in code.
Q&A: Basics
===========
Q: Where is the documentation?
A: This library is poorly documented at the moment and expects the user to be acquainted with C/C++.
- Run the examples/ and explore them.
- See demo code in imgui_demo.cpp and particularly the ImGui::ShowDemoWindow() function.
- The demo covers most features of Dear ImGui, so you can read the code and see its output.
- See documentation and comments at the top of imgui.cpp + effectively imgui.h.
- Dozens of standalone example applications using e.g. OpenGL/DirectX are provided in the
examples/ folder to explain how to integrate Dear ImGui with your own engine/application.
- The Wiki (https://github.com/ocornut/imgui/wiki) has many resources and links.
- The Glossary (https://github.com/ocornut/imgui/wiki/Glossary) page also may be useful.
- Your programming IDE is your friend, find the type or function declaration to find comments
associated with it.
Q: What is this library called?
Q: Which version should I get?
>> This library is called "Dear ImGui", please don't call it "ImGui" :)
>> See https://www.dearimgui.org/faq for details.
Q&A: Integration
================
Q: How to get started?
A: Read 'PROGRAMMER GUIDE' above. Read examples/README.txt.
Q: How can I tell whether to dispatch mouse/keyboard to Dear ImGui or my application?
A: You should read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags!
>> See https://www.dearimgui.org/faq for a fully detailed answer. You really want to read this.
Q. How can I enable keyboard controls?
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
Q: I integrated Dear ImGui in my engine and little squares are showing instead of text...
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around...
Q: I integrated Dear ImGui in my engine and some elements are displaying outside their expected windows boundaries...
>> See https://www.dearimgui.org/faq
Q&A: Usage
----------
Q: Why is my widget not reacting when I click on it?
Q: How can I have widgets with an empty label?
Q: How can I have multiple widgets with the same label?
Q: How can I display an image? What is ImTextureID, how does it works?
Q: How can I use my own math types instead of ImVec2/ImVec4?
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
Q: How can I display custom shapes? (using low-level ImDrawList API)
>> See https://www.dearimgui.org/faq
Q&A: Fonts, Text
================
Q: How should I handle DPI in my application?
Q: How can I load a different font than the default?
Q: How can I easily use icons in my application?
Q: How can I load multiple fonts?
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
>> See https://www.dearimgui.org/faq and https://github.com/ocornut/imgui/edit/master/docs/FONTS.md
Q&A: Concerns
=============
Q: Who uses Dear ImGui?
Q: Can you create elaborate/serious tools with Dear ImGui?
Q: Can you reskin the look of Dear ImGui?
Q: Why using C++ (as opposed to C)?
>> See https://www.dearimgui.org/faq
Q&A: Community
==============
Q: How can I help?
A: - Businesses: please reach out to "contact AT dearimgui.com" if you work in a place using Dear ImGui!
We can discuss ways for your company to fund development via invoiced technical support, maintenance or sponsoring contacts.
This is among the most useful thing you can do for Dear ImGui. With increased funding, we can hire more people working on this project.
- Individuals: you can support continued development via PayPal donations. See README.
- If you are experienced with Dear ImGui and C++, look at the GitHub issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- 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. Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui helps 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).
*/
//-------------------------------------------------------------------------
// [SECTION] INCLUDES
//-------------------------------------------------------------------------
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DISABLE
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
// System includes
#include <ctype.h> // toupper
#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
// [Windows] OS specific includes (optional)
#if defined(_WIN32) && defined(IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) && defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#define IMGUI_DISABLE_WIN32_FUNCTIONS
#endif
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#ifndef __MINGW32__
#include <Windows.h> // _wfopen, OpenClipboard
#else
#include <windows.h>
#endif
#if defined(WINAPI_FAMILY) && (WINAPI_FAMILY == WINAPI_FAMILY_APP) // UWP doesn't have all Win32 functions
#define IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS
#define IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS
#endif
#endif
// [Apple] OS specific includes
#if defined(__APPLE__)
#include <TargetConditionals.h>
#endif
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#if defined(_MSC_VER) && _MSC_VER >= 1922 // MSVC 2019 16.2 or later
#pragma warning (disable: 5054) // operator '|': deprecated between enumerations of different types
#endif
#pragma warning (disable: 26451) // [Static Analyzer] Arithmetic overflow : Using operator 'xxx' on a 4 byte value and then casting the result to a 8 byte value. Cast the value to the wider type before calling operator 'xxx' to avoid overflow(io.2).
#pragma warning (disable: 26495) // [Static Analyzer] Variable 'XXX' is uninitialized. Always initialize a member variable (type.6).
#pragma warning (disable: 26812) // [Static Analyzer] The enum type 'xxx' is unscoped. Prefer 'enum class' over 'enum' (Enum.3).
#endif
// Clang/GCC warnings with -Weverything
#if defined(__clang__)
#if __has_warning("-Wunknown-warning-option")
#pragma clang diagnostic ignored "-Wunknown-warning-option" // warning: unknown warning group 'xxx' // not all warnings are known by all Clang versions and they tend to be rename-happy.. so ignoring warnings triggers new warnings on some configuration. Great!
#endif
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning: unknown warning group 'xxx'
#pragma clang diagnostic ignored "-Wold-style-cast" // warning: use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning: comparing floating point with == or != is unsafe // storing and comparing against same constants (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 is.
#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'
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning: zero as null pointer constant // some standard header variations use #define NULL 0
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#pragma clang diagnostic ignored "-Wimplicit-int-float-conversion" // warning: implicit conversion from 'xxx' to 'float' may lose precision
#elif defined(__GNUC__)
// We disable -Wpragmas because GCC doesn't provide an has_warning equivalent and some forks/patches may not following the warning/version association.
#pragma GCC diagnostic ignored "-Wpragmas" // warning: unknown option after '#pragma GCC diagnostic' kind
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-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 "-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
#pragma GCC diagnostic ignored "-Wclass-memaccess" // [__GNUC__ >= 8] warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_INI_SETTINGS 0 // Save additional comments in .ini file (particularly helps for Docking, but makes saving slower)
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by backend)
static const float WINDOWS_HOVER_PADDING = 4.0f; // Extend outside window for hovering/resizing (maxxed with TouchPadding) and inside windows for borders. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
static const float WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER = 2.00f; // Lock scrolled window (so it doesn't pick child windows that are scrolling through) for a certain time, unless mouse moved.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
// Settings
static void WindowSettingsHandler_ClearAll(ImGuiContext*, ImGuiSettingsHandler*);
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void WindowSettingsHandler_ApplyAll(ImGuiContext*, ImGuiSettingsHandler*);
static void WindowSettingsHandler_WriteAll(ImGuiContext*, ImGuiSettingsHandler*, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
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);
namespace ImGui
{
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingOverlay();
static void NavUpdateMoveResult();
static void NavUpdateInitResult();
static float NavUpdatePageUpPageDown();
static inline void NavUpdateAnyRequestFlag();
static void NavEndFrame();
static bool NavScoreItem(ImGuiNavItemData* result, ImRect cand);
static void NavApplyItemToResult(ImGuiNavItemData* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel);
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
static void NavRestoreLayer(ImGuiNavLayer layer);
static int FindWindowFocusIndex(ImGuiWindow* window);
// Error Checking
static void ErrorCheckNewFrameSanityChecks();
static void ErrorCheckEndFrameSanityChecks();
// Misc
static void UpdateSettings();
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static void UpdateTabFocus();
static void UpdateDebugToolItemPicker();
static bool UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect);
static void RenderWindowOuterBorders(ImGuiWindow* window);
static void RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size);
static void RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open);
// Viewports
static void UpdateViewportsNewFrame();
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// DLL users:
// - Heaps and globals are not shared across DLL boundaries!
// - You will need to call SetCurrentContext() + SetAllocatorFunctions() for each static/DLL boundary you are calling from.
// - Same applies for hot-reloading mechanisms that are reliant on reloading DLL (note that many hot-reloading mechanisms work without DLL).
// - Using Dear ImGui via a shared library is not recommended, because of function call overhead and because we don't guarantee backward nor forward ABI compatibility.
// - Confused? In a debugger: add GImGui to your watch window and notice how its value changes depending on your current location (which DLL boundary you are in).
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// - ImGui::CreateContext() will automatically set this pointer if it is NULL.
// Change to a different context by calling ImGui::SetCurrentContext().
// - Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts:
// - Change this variable to use thread local storage so each thread can refer to a different context, in your imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp files. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aims to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from a different namespace.
// - DLL users: read comments above.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// - You probably don't want to modify that mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
// - DLL users: read comments above.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static ImGuiMemAllocFunc GImAllocatorAllocFunc = MallocWrapper;
static ImGuiMemFreeFunc GImAllocatorFreeFunc = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 0.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows. Large values tend to lead to variety of artifacts and are not recommended.
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
WindowMenuButtonPosition= ImGuiDir_Left; // Position of the collapsing/docking button in the title bar (left/right). Defaults to ImGuiDir_Left.
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)
CellPadding = ImVec2(4,2); // Padding within a table cell
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. Preferably > (FramePadding.x + 1).
ScrollbarSize = 14.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.
LogSliderDeadzone = 4.0f; // The size in pixels of the dead-zone around zero on logarithmic sliders that cross zero.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
TabMinWidthForCloseButton = 0.0f; // Minimum width for close button to appears on an unselected tab when hovered. Set to 0.0f to always show when hovering, set to FLT_MAX to never show close button unless selected.
ColorButtonPosition = ImGuiDir_Right; // Side of the color button in the ColorEdit4 widget (left/right). Defaults to ImGuiDir_Right.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text. Defaults to (0.0f, 0.0f) (top-left aligned). It's generally important to keep this left-aligned if you want to lay multiple items on a same line.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // 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-aliased lines/borders. Disable if you are really tight on CPU/GPU.
AntiAliasedLinesUseTex = true; // Enable anti-aliased lines/borders using textures where possible. Require backend to render with bilinear filtering.
AntiAliasedFill = true; // Enable anti-aliased 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.
CircleTessellationMaxError = 0.30f; // Maximum error (in pixels) allowed when using AddCircle()/AddCircleFilled() or drawing rounded corner rectangles with no explicit segment count specified. Decrease for higher quality but more geometry.
// Default theme
ImGui::StyleColorsDark(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);
CellPadding = ImFloor(CellPadding * 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);
LogSliderDeadzone = ImFloor(LogSliderDeadzone * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
TabMinWidthForCloseButton = (TabMinWidthForCloseButton != FLT_MAX) ? ImFloor(TabMinWidthForCloseButton * scale_factor) : FLT_MAX;
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));
IM_ASSERT(IM_ARRAYSIZE(ImGuiIO::MouseDown) == ImGuiMouseButton_COUNT && IM_ARRAYSIZE(ImGuiIO::MouseClicked) == ImGuiMouseButton_COUNT); // Our pre-C++11 IM_STATIC_ASSERT() macros triggers warning on modern compilers so we don't use it here.
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
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.275f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
ConfigMemoryCompactTimer = 60.0f;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
ImeSetInputScreenPosFn = ImeSetInputScreenPosFn_DefaultImpl;
ImeWindowHandle = NULL;
// 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(unsigned int c)
{
if (c != 0)
InputQueueCharacters.push_back(c <= IM_UNICODE_CODEPOINT_MAX ? (ImWchar)c : IM_UNICODE_CODEPOINT_INVALID);
}
// UTF16 strings use surrogate pairs to encode codepoints >= 0x10000, so
// we should save the high surrogate.
void ImGuiIO::AddInputCharacterUTF16(ImWchar16 c)
{
if (c == 0 && InputQueueSurrogate == 0)
return;
if ((c & 0xFC00) == 0xD800) // High surrogate, must save
{
if (InputQueueSurrogate != 0)
InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
InputQueueSurrogate = c;
return;
}
ImWchar cp = c;
if (InputQueueSurrogate != 0)
{
if ((c & 0xFC00) != 0xDC00) // Invalid low surrogate
{
InputQueueCharacters.push_back(IM_UNICODE_CODEPOINT_INVALID);
}
else
{
#if IM_UNICODE_CODEPOINT_MAX == 0xFFFF
cp = IM_UNICODE_CODEPOINT_INVALID; // Codepoint will not fit in ImWchar
#else
cp = (ImWchar)(((InputQueueSurrogate - 0xD800) << 10) + (c - 0xDC00) + 0x10000);
#endif
}
InputQueueSurrogate = 0;
}
InputQueueCharacters.push_back(cp);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c != 0)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Geometry functions)
//-----------------------------------------------------------------------------
ImVec2 ImBezierCubicClosestPoint(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, int num_segments)
{
IM_ASSERT(num_segments > 0); // Use ImBezierCubicClosestPointCasteljau()
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
float t_step = 1.0f / (float)num_segments;
for (int i_step = 1; i_step <= num_segments; i_step++)
{
ImVec2 p_current = ImBezierCubicCalc(p1, p2, p3, p4, t_step * i_step);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
return p_closest;
}
// Closely mimics PathBezierToCasteljau() in imgui_draw.cpp
static void ImBezierCubicClosestPointCasteljauStep(const ImVec2& p, ImVec2& p_closest, ImVec2& p_last, float& p_closest_dist2, float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4, float tess_tol, int level)
{
float dx = x4 - x1;
float dy = y4 - y1;
float d2 = ((x2 - x4) * dy - (y2 - y4) * dx);
float d3 = ((x3 - x4) * dy - (y3 - y4) * dx);
d2 = (d2 >= 0) ? d2 : -d2;
d3 = (d3 >= 0) ? d3 : -d3;
if ((d2 + d3) * (d2 + d3) < tess_tol * (dx * dx + dy * dy))
{
ImVec2 p_current(x4, y4);
ImVec2 p_line = ImLineClosestPoint(p_last, p_current, p);
float dist2 = ImLengthSqr(p - p_line);
if (dist2 < p_closest_dist2)
{
p_closest = p_line;
p_closest_dist2 = dist2;
}
p_last = p_current;
}
else if (level < 10)
{
float x12 = (x1 + x2)*0.5f, y12 = (y1 + y2)*0.5f;
float x23 = (x2 + x3)*0.5f, y23 = (y2 + y3)*0.5f;
float x34 = (x3 + x4)*0.5f, y34 = (y3 + y4)*0.5f;
float x123 = (x12 + x23)*0.5f, y123 = (y12 + y23)*0.5f;
float x234 = (x23 + x34)*0.5f, y234 = (y23 + y34)*0.5f;
float x1234 = (x123 + x234)*0.5f, y1234 = (y123 + y234)*0.5f;
ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1, y1, x12, y12, x123, y123, x1234, y1234, tess_tol, level + 1);
ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, x1234, y1234, x234, y234, x34, y34, x4, y4, tess_tol, level + 1);
}
}
// tess_tol is generally the same value you would find in ImGui::GetStyle().CurveTessellationTol
// Because those ImXXX functions are lower-level than ImGui:: we cannot access this value automatically.
ImVec2 ImBezierCubicClosestPointCasteljau(const ImVec2& p1, const ImVec2& p2, const ImVec2& p3, const ImVec2& p4, const ImVec2& p, float tess_tol)
{
IM_ASSERT(tess_tol > 0.0f);
ImVec2 p_last = p1;
ImVec2 p_closest;
float p_closest_dist2 = FLT_MAX;
ImBezierCubicClosestPointCasteljauStep(p, p_closest, p_last, p_closest_dist2, p1.x, p1.y, p2.x, p2.y, p3.x, p3.y, p4.x, p4.y, tess_tol, 0);
return p_closest;
}
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;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (String, Format, Hash functions)
//-----------------------------------------------------------------------------
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
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;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = IM_ALLOC(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
IM_FREE(dst);
dst = (char*)IM_ALLOC(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bit
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
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;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
const char* ImStrSkipBlank(const char* str)
{
while (str[0] == ' ' || str[0] == '\t')
str++;
return str;
}
// 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_DEFAULT_FORMAT_FUNCTIONS
// We support stb_sprintf which is much faster (see: https://github.com/nothings/stb/blob/master/stb_sprintf.h)
// You may set IMGUI_USE_STB_SPRINTF to use our default wrapper, or set IMGUI_DISABLE_DEFAULT_FORMAT_FUNCTIONS
// and setup the wrapper yourself. (FIXME-OPT: Some of our high-level operations such as ImGuiTextBuffer::appendfv() are
// designed using two-passes worst case, which probably could be improved using the stbsp_vsprintfcb() function.)
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "stb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
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)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
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_DEFAULT_FORMAT_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImGuiID ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// 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/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImGuiID ImHashStr(const char* data_p, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *data++;
if (c == '#' && data_size >= 2 && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *data++)
{
if (c == '#' && data[0] == '#' && data[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (File functions)
//-----------------------------------------------------------------------------
// Default file functions
#ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
ImFileHandle ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames.
// Previously we used ImTextCountCharsFromUtf8/ImTextStrFromUtf8 here but we now need to support ImWchar16 and ImWchar32!
const int filename_wsize = ::MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
const int mode_wsize = ::MultiByteToWideChar(CP_UTF8, 0, mode, -1, NULL, 0);
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
::MultiByteToWideChar(CP_UTF8, 0, filename, -1, (wchar_t*)&buf[0], filename_wsize);
::MultiByteToWideChar(CP_UTF8, 0, mode, -1, (wchar_t*)&buf[filename_wsize], mode_wsize);
return ::_wfopen((const wchar_t*)&buf[0], (const wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// We should in theory be using fseeko()/ftello() with off_t and _fseeki64()/_ftelli64() with __int64, waiting for the PR that does that in a very portable pre-C++11 zero-warnings way.
bool ImFileClose(ImFileHandle f) { return fclose(f) == 0; }
ImU64 ImFileGetSize(ImFileHandle f) { long off = 0, sz = 0; return ((off = ftell(f)) != -1 && !fseek(f, 0, SEEK_END) && (sz = ftell(f)) != -1 && !fseek(f, off, SEEK_SET)) ? (ImU64)sz : (ImU64)-1; }
ImU64 ImFileRead(void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fread(data, (size_t)sz, (size_t)count, f); }
ImU64 ImFileWrite(const void* data, ImU64 sz, ImU64 count, ImFileHandle f) { return fwrite(data, (size_t)sz, (size_t)count, f); }
#endif // #ifndef IMGUI_DISABLE_DEFAULT_FILE_FUNCTIONS
// Helper: Load file content into memory
// Memory allocated with IM_ALLOC(), must be freed by user using IM_FREE() == ImGui::MemFree()
// This can't really be used with "rt" because fseek size won't match read size.
void* ImFileLoadToMemory(const char* filename, const char* mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && mode);
if (out_file_size)
*out_file_size = 0;
ImFileHandle f;
if ((f = ImFileOpen(filename, mode)) == NULL)
return NULL;
size_t file_size = (size_t)ImFileGetSize(f);
if (file_size == (size_t)-1)
{
ImFileClose(f);
return NULL;
}
void* file_data = IM_ALLOC(file_size + padding_bytes);
if (file_data == NULL)
{
ImFileClose(f);
return NULL;
}
if (ImFileRead(file_data, 1, file_size, f) != file_size)
{
ImFileClose(f);
IM_FREE(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
ImFileClose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bit character, process single character input.
// A nearly-branchless UTF-8 decoder, based on work of Christopher Wellons (https://github.com/skeeto/branchless-utf8).
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
static const char lengths[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0 };
static const int masks[] = { 0x00, 0x7f, 0x1f, 0x0f, 0x07 };
static const uint32_t mins[] = { 0x400000, 0, 0x80, 0x800, 0x10000 };
static const int shiftc[] = { 0, 18, 12, 6, 0 };
static const int shifte[] = { 0, 6, 4, 2, 0 };
int len = lengths[*(const unsigned char*)in_text >> 3];
int wanted = len + !len;
if (in_text_end == NULL)
in_text_end = in_text + wanted; // Max length, nulls will be taken into account.
// Copy at most 'len' bytes, stop copying at 0 or past in_text_end. Branch predictor does a good job here,
// so it is fast even with excessive branching.
unsigned char s[4];
s[0] = in_text + 0 < in_text_end ? in_text[0] : 0;
s[1] = in_text + 1 < in_text_end ? in_text[1] : 0;
s[2] = in_text + 2 < in_text_end ? in_text[2] : 0;
s[3] = in_text + 3 < in_text_end ? in_text[3] : 0;
// Assume a four-byte character and load four bytes. Unused bits are shifted out.
*out_char = (uint32_t)(s[0] & masks[len]) << 18;
*out_char |= (uint32_t)(s[1] & 0x3f) << 12;
*out_char |= (uint32_t)(s[2] & 0x3f) << 6;
*out_char |= (uint32_t)(s[3] & 0x3f) << 0;
*out_char >>= shiftc[len];
// Accumulate the various error conditions.
int e = 0;
e = (*out_char < mins[len]) << 6; // non-canonical encoding
e |= ((*out_char >> 11) == 0x1b) << 7; // surrogate half?
e |= (*out_char > IM_UNICODE_CODEPOINT_MAX) << 8; // out of range?
e |= (s[1] & 0xc0) >> 2;
e |= (s[2] & 0xc0) >> 4;
e |= (s[3] ) >> 6;
e ^= 0x2a; // top two bits of each tail byte correct?
e >>= shifte[len];
if (e)
{
// No bytes are consumed when *in_text == 0 || in_text == in_text_end.
// One byte is consumed in case of invalid first byte of in_text.
// All available bytes (at most `len` bytes) are consumed on incomplete/invalid second to last bytes.
// Invalid or incomplete input may consume less bytes than wanted, therefore every byte has to be inspected in s.
wanted = ImMin(wanted, !!s[0] + !!s[1] + !!s[2] + !!s[3]);
*out_char = IM_UNICODE_CODEPOINT_INVALID;
}
return wanted;
}
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;
*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;
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8_inline(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 < 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;
}
if (c <= 0x10FFFF)
{
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;
}
// Invalid code point, the max unicode is 0x10FFFF
return 0;
}
const char* ImTextCharToUtf8(char out_buf[5], unsigned int c)
{
int count = ImTextCharToUtf8_inline(out_buf, 5, c);
out_buf[count] = 0;
return out_buf;
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int unused = 0;
return ImTextCharFromUtf8(&unused, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c < 0x10000) return 3;
if (c <= 0x10FFFF) return 4;
return 3;
}
int ImTextStrToUtf8(char* out_buf, int out_buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_p = out_buf;
const char* buf_end = out_buf + out_buf_size;
while (buf_p < buf_end - 1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_p++ = (char)c;
else
buf_p += ImTextCharToUtf8_inline(buf_p, (int)(buf_end - buf_p - 1), c);
}
*buf_p = 0;
return (int)(buf_p - 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;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
IMGUI_API ImU32 ImAlphaBlendColors(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);
}
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;
}
// 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 = ImFabs(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 = ImFmod(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;
}
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::ImGuiStoragePair* LowerBound(ImVector<ImGuiStorage::ImGuiStoragePair>& data, ImGuiID key)
{
ImGuiStorage::ImGuiStoragePair* first = data.Data;
ImGuiStorage::ImGuiStoragePair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::ImGuiStoragePair* 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 ImGuiStoragePair*)lhs)->key > ((const ImGuiStoragePair*)rhs)->key) return +1;
if (((const ImGuiStoragePair*)lhs)->key < ((const ImGuiStoragePair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(ImGuiStoragePair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(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
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStoragePair* it = LowerBound(const_cast<ImVector<ImGuiStoragePair>&>(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)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(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)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, ImGuiStoragePair(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)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(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)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStoragePair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, ImGuiStoragePair(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;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_TEXT_INPUTS
// 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::SetNextItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::ImGuiTextRange::split(char separator, ImVector<ImGuiTextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(ImGuiTextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(ImGuiTextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
ImGuiTextRange input_range(InputBuf, InputBuf + strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
ImGuiTextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
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 ImGuiTextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.b + 1, f.e) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.b, f.e) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
#endif
//-----------------------------------------------------------------------------
// [SECTION] 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
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// 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)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be and really confusing/spaghetti, mostly because we changed
// the API mid-way through development and support two ways to using the clipper, needs some rework (see TODO)
//-----------------------------------------------------------------------------
// FIXME-TABLE: This prevents us from using ImGuiListClipper _inside_ a table cell.
// The problem we have is that without a Begin/End scheme for rows using the clipper is ambiguous.
static bool GetSkipItemForListClipping()
{
ImGuiContext& g = *GImGui;
return (g.CurrentTable ? g.CurrentTable->HostSkipItems : g.CurrentWindow->SkipItems);
}
// 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 (GetSkipItemForListClipping())
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRect);
if (g.NavJustMovedToId && window->NavLastIds[0] == g.NavJustMovedToId)
unclipped_rect.Add(ImRect(window->Pos + window->NavRectRel[0].Min, window->Pos + window->NavRectRel[0].Max));
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == 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;
}
static void SetCursorPosYAndSetupForPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() 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.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float off_y = pos_y - window->DC.CursorPos.y;
window->DC.CursorPos.y = pos_y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, pos_y);
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - g.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 (ImGuiOldColumns* columns = window->DC.CurrentColumns)
columns->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
if (ImGuiTable* table = g.CurrentTable)
{
if (table->IsInsideRow)
ImGui::TableEndRow(table);
table->RowPosY2 = window->DC.CursorPos.y;
const int row_increase = (int)((off_y / line_height) + 0.5f);
//table->CurrentRow += row_increase; // Can't do without fixing TableEndRow()
table->RowBgColorCounter += row_increase;
}
}
ImGuiListClipper::ImGuiListClipper()
{
memset(this, 0, sizeof(*this));
ItemsCount = -1;
}
ImGuiListClipper::~ImGuiListClipper()
{
IM_ASSERT(ItemsCount == -1 && "Forgot to call End(), or to Step() until false?");
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Step() 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 items_count, float items_height)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (ImGuiTable* table = g.CurrentTable)
if (table->IsInsideRow)
ImGui::TableEndRow(table);
StartPosY = window->DC.CursorPos.y;
ItemsHeight = items_height;
ItemsCount = items_count;
ItemsFrozen = 0;
StepNo = 0;
DisplayStart = -1;
DisplayEnd = 0;
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0) // Already ended
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 && DisplayStart >= 0)
SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight);
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiTable* table = g.CurrentTable;
if (table && table->IsInsideRow)
ImGui::TableEndRow(table);
// No items
if (ItemsCount == 0 || GetSkipItemForListClipping())
{
End();
return false;
}
// Step 0: Let you process the first element (regardless of it being visible or not, so we can measure the element height)
if (StepNo == 0)
{
// While we are in frozen row state, keep displaying items one by one, unclipped
// FIXME: Could be stored as a table-agnostic state.
if (table != NULL && !table->IsUnfrozenRows)
{
DisplayStart = ItemsFrozen;
DisplayEnd = ItemsFrozen + 1;
ItemsFrozen++;
return true;
}
StartPosY = window->DC.CursorPos.y;
if (ItemsHeight <= 0.0f)
{
// Submit the first item so we can measure its height (generally it is 0..1)
DisplayStart = ItemsFrozen;
DisplayEnd = ItemsFrozen + 1;
StepNo = 1;
return true;
}
// Already has item height (given by user in Begin): skip to calculating step
DisplayStart = DisplayEnd;
StepNo = 2;
}
// Step 1: the clipper infer height from first element
if (StepNo == 1)
{
IM_ASSERT(ItemsHeight <= 0.0f);
if (table)
{
const float pos_y1 = table->RowPosY1; // Using this instead of StartPosY to handle clipper straddling the frozen row
const float pos_y2 = table->RowPosY2; // Using this instead of CursorPos.y to take account of tallest cell.
ItemsHeight = pos_y2 - pos_y1;
window->DC.CursorPos.y = pos_y2;
}
else
{
ItemsHeight = window->DC.CursorPos.y - StartPosY;
}
IM_ASSERT(ItemsHeight > 0.0f && "Unable to calculate item height! First item hasn't moved the cursor vertically!");
StepNo = 2;
}
// Reached end of list
if (DisplayEnd >= ItemsCount)
{
End();
return false;
}
// Step 2: calculate the actual range of elements to display, and position the cursor before the first element
if (StepNo == 2)
{
IM_ASSERT(ItemsHeight > 0.0f);
int already_submitted = DisplayEnd;
ImGui::CalcListClipping(ItemsCount - already_submitted, ItemsHeight, &DisplayStart, &DisplayEnd);
DisplayStart += already_submitted;
DisplayEnd += already_submitted;
// Seek cursor
if (DisplayStart > already_submitted)
SetCursorPosYAndSetupForPrevLine(StartPosY + (DisplayStart - ItemsFrozen) * ItemsHeight, ItemsHeight);
StepNo = 3;
return true;
}
// 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.
if (StepNo == 3)
{
// Seek cursor
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupForPrevLine(StartPosY + (ItemsCount - ItemsFrozen) * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
return false;
}
IM_ASSERT(0);
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] STYLING
//-----------------------------------------------------------------------------
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->Style;
}
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)
{
ImGuiStyle& style = GImGui->Style;
if (style.Alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(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);
}
// 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;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorStack.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorStack.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorStack.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorStack.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, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, CellPadding) }, // ImGuiStyleVar_CellPadding
{ 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, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
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.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() float variant but 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.StyleVarStack.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0 && "Called PushStyleVar() ImVec2 variant but 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.StyleVarStack.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.StyleVarStack.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_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TableHeaderBg: return "TableHeaderBg";
case ImGuiCol_TableBorderStrong: return "TableBorderStrong";
case ImGuiCol_TableBorderLight: return "TableBorderLight";
case ImGuiCol_TableRowBg: return "TableRowBg";
case ImGuiCol_TableRowBgAlt: return "TableRowBgAlt";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Some of those (internal) functions are currently quite a legacy mess - their signature and behavior will change,
// we need a nicer separation between low-level functions and high-level functions relying on the ImGui context.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: context.
//-----------------------------------------------------------------------------
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;
}
// 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;
}
if (text != text_display_end)
{
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
if (text != text_end)
{
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::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// 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);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
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;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Another overly complex function until we reorganize everything into a nice all-in-one helper.
// This is made more complex because we have dissociated the layout rectangle (pos_min..pos_max) which define _where_ the ellipsis is, from actual clipping of text and limit of the ellipsis display.
// This is because in the context of tabs we selectively hide part of the text when the Close Button appears, but we don't want the ellipsis to move.
void ImGui::RenderTextEllipsis(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, float clip_max_x, float ellipsis_max_x, const char* text, const char* text_end_full, const ImVec2* text_size_if_known)
{
ImGuiContext& g = *GImGui;
if (text_end_full == NULL)
text_end_full = FindRenderedTextEnd(text);
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_end_full, false, 0.0f);
//draw_list->AddLine(ImVec2(pos_max.x, pos_min.y - 4), ImVec2(pos_max.x, pos_max.y + 4), IM_COL32(0, 0, 255, 255));
//draw_list->AddLine(ImVec2(ellipsis_max_x, pos_min.y-2), ImVec2(ellipsis_max_x, pos_max.y+2), IM_COL32(0, 255, 0, 255));
//draw_list->AddLine(ImVec2(clip_max_x, pos_min.y), ImVec2(clip_max_x, pos_max.y), IM_COL32(255, 0, 0, 255));
// FIXME: We could technically remove (last_glyph->AdvanceX - last_glyph->X1) from text_size.x here and save a few pixels.
if (text_size.x > pos_max.x - pos_min.x)
{
// Hello wo...
// | | |
// min max ellipsis_max
// <-> this is generally some padding value
const ImFont* font = draw_list->_Data->Font;
const float font_size = draw_list->_Data->FontSize;
const char* text_end_ellipsis = NULL;
ImWchar ellipsis_char = font->EllipsisChar;
int ellipsis_char_count = 1;
if (ellipsis_char == (ImWchar)-1)
{
ellipsis_char = (ImWchar)'.';
ellipsis_char_count = 3;
}
const ImFontGlyph* glyph = font->FindGlyph(ellipsis_char);
float ellipsis_glyph_width = glyph->X1; // Width of the glyph with no padding on either side
float ellipsis_total_width = ellipsis_glyph_width; // Full width of entire ellipsis
if (ellipsis_char_count > 1)
{
// Full ellipsis size without free spacing after it.
const float spacing_between_dots = 1.0f * (draw_list->_Data->FontSize / font->FontSize);
ellipsis_glyph_width = glyph->X1 - glyph->X0 + spacing_between_dots;
ellipsis_total_width = ellipsis_glyph_width * (float)ellipsis_char_count - spacing_between_dots;
}
// We can now claim the space between pos_max.x and ellipsis_max.x
const float text_avail_width = ImMax((ImMax(pos_max.x, ellipsis_max_x) - ellipsis_total_width) - pos_min.x, 1.0f);
float text_size_clipped_x = font->CalcTextSizeA(font_size, text_avail_width, 0.0f, text, text_end_full, &text_end_ellipsis).x;
if (text == text_end_ellipsis && text_end_ellipsis < text_end_full)
{
// Always display at least 1 character if there's no room for character + ellipsis
text_end_ellipsis = text + ImTextCountUtf8BytesFromChar(text, text_end_full);
text_size_clipped_x = font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text, text_end_ellipsis).x;
}
while (text_end_ellipsis > text && ImCharIsBlankA(text_end_ellipsis[-1]))
{
// Trim trailing space before ellipsis (FIXME: Supporting non-ascii blanks would be nice, for this we need a function to backtrack in UTF-8 text)
text_end_ellipsis--;
text_size_clipped_x -= font->CalcTextSizeA(font_size, FLT_MAX, 0.0f, text_end_ellipsis, text_end_ellipsis + 1).x; // Ascii blanks are always 1 byte
}
// Render text, render ellipsis
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_ellipsis, &text_size, ImVec2(0.0f, 0.0f));
float ellipsis_x = pos_min.x + text_size_clipped_x;
if (ellipsis_x + ellipsis_total_width <= ellipsis_max_x)
for (int i = 0; i < ellipsis_char_count; i++)
{
font->RenderChar(draw_list, font_size, ImVec2(ellipsis_x, pos_min.y), GetColorU32(ImGuiCol_Text), ellipsis_char);
ellipsis_x += ellipsis_glyph_width;
}
}
else
{
RenderTextClippedEx(draw_list, pos_min, ImVec2(clip_max_x, pos_max.y), text, text_end_full, &text_size, ImVec2(0.0f, 0.0f));
}
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_end_full);
}
// 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, 0, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, 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, 0, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
}
}
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 = g.CurrentWindow;
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, 0, 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);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name) : DrawListInst(NULL)
{
memset(this, 0, sizeof(*this));
Name = ImStrdup(name);
NameBufLen = (int)strlen(name) + 1;
ID = ImHashStr(name);
IDStack.push_back(ID);
MoveId = GetID("#MOVE");
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
AutoFitFramesX = AutoFitFramesY = -1;
AutoPosLastDirection = ImGuiDir_None;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
LastTimeActive = -1.0f;
FontWindowScale = 1.0f;
SettingsOffset = -1;
DrawList = &DrawListInst;
DrawList->_Data = &context->DrawListSharedData;
DrawList->_OwnerName = Name;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiOldColumns();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
#endif
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
#endif
return id;
}
ImGuiID ImGuiWindow::GetID(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_Pointer, ptr);
#endif
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(int n)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&n, sizeof(n), seed);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO(id, ImGuiDataType_S32, (intptr_t)n);
#endif
return id;
}
// 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 = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
g.CurrentTable = window && window->DC.CurrentTableIdx != -1 ? g.Tables.GetByIndex(window->DC.CurrentTableIdx) : NULL;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::GcCompactTransientMiscBuffers()
{
ImGuiContext& g = *GImGui;
g.ItemFlagsStack.clear();
g.GroupStack.clear();
TableGcCompactSettings();
}
// Free up/compact internal window buffers, we can use this when a window becomes unused.
// Not freed:
// - ImGuiWindow, ImGuiWindowSettings, Name, StateStorage, ColumnsStorage (may hold useful data)
// This should have no noticeable visual effect. When the window reappear however, expect new allocation/buffer growth/copy cost.
void ImGui::GcCompactTransientWindowBuffers(ImGuiWindow* window)
{
window->MemoryCompacted = true;
window->MemoryDrawListIdxCapacity = window->DrawList->IdxBuffer.Capacity;
window->MemoryDrawListVtxCapacity = window->DrawList->VtxBuffer.Capacity;
window->IDStack.clear();
window->DrawList->_ClearFreeMemory();
window->DC.ChildWindows.clear();
window->DC.ItemWidthStack.clear();
window->DC.TextWrapPosStack.clear();
}
void ImGui::GcAwakeTransientWindowBuffers(ImGuiWindow* window)
{
// We stored capacity of the ImDrawList buffer to reduce growth-caused allocation/copy when awakening.
// The other buffers tends to amortize much faster.
window->MemoryCompacted = false;
window->DrawList->IdxBuffer.reserve(window->MemoryDrawListIdxCapacity);
window->DrawList->VtxBuffer.reserve(window->MemoryDrawListVtxCapacity);
window->MemoryDrawListIdxCapacity = window->MemoryDrawListVtxCapacity = 0;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressedBefore = false;
g.ActiveIdHasBeenEditedBefore = false;
g.ActiveIdMouseButton = -1;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowOverlap = false;
g.ActiveIdNoClearOnFocusLoss = false;
g.ActiveIdWindow = window;
g.ActiveIdHasBeenEditedThisFrame = false;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
// Clear declaration of inputs claimed by the widget
// (Please note that this is WIP and not all keys/inputs are thoroughly declared by all widgets yet)
g.ActiveIdUsingMouseWheel = false;
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL); // g.ActiveId = 0;
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
g.HoveredIdUsingMouseWheel = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 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 = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEditedThisFrame = true;
g.ActiveIdHasBeenEditedBefore = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
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;
}
// 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()
ImGuiItemStatusFlags status_flags = window->DC.LastItemStatusFlags;
if (!(status_flags & 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)
// [2021/03/02] Reworked / reverted the revert, finally. Note we want e.g. BeginGroup/ItemAdd/EndGroup to work as well. (#3851)
// [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 && (status_flags & ImGuiItemStatusFlags_HoveredWindow) == 0)
if ((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0)
return false;
// Test if another item is active (e.g. being dragged)
if ((flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem) == 0)
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.
// The ImGuiHoveredFlags_AllowWhenBlockedByPopup flag will be tested here.
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((g.CurrentItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for calling after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the 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)
return false;
if (!IsWindowContentHoverable(window, ImGuiHoveredFlags_None) || (g.CurrentItemFlags & ImGuiItemFlags_Disabled))
{
g.HoveredIdDisabled = true;
return false;
}
// We exceptionally allow this function to be called with id==0 to allow using it for easy high-level
// hover test in widgets code. We could also decide to split this function is two.
if (id != 0)
{
SetHoveredID(id);
// [DEBUG] Item Picker tool!
// We perform the check here because SetHoveredID() is not frequently called (1~ time a frame), making
// the cost of this tool near-zero. We can get slightly better call-stack and support picking non-hovered
// items if we perform the test in ItemAdd(), but that would incur a small runtime cost.
// #define IMGUI_DEBUG_TOOL_ITEM_PICKER_EX in imconfig.h if you want this check to also be performed in ItemAdd().
if (g.DebugItemPickerActive && g.HoveredIdPreviousFrame == id)
GetForegroundDrawList()->AddRect(bb.Min, bb.Max, IM_COL32(255, 255, 0, 255));
if (g.DebugItemPickerBreakId == id)
IM_DEBUG_BREAK();
}
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 && id != g.NavId))
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
// This is also inlined in ItemAdd()
// Note: if ImGuiItemStatusFlags_HasDisplayRect is set, user needs to set window->DC.LastItemDisplayRect!
void ImGui::SetLastItemData(ImGuiWindow* window, ImGuiID item_id, ImGuiItemStatusFlags item_flags, const ImRect& item_rect)
{
window->DC.LastItemId = item_id;
window->DC.LastItemStatusFlags = item_flags;
window->DC.LastItemRect = item_rect;
}
// Process TAB/Shift+TAB. Be mindful that this function may _clear_ the ActiveID when tabbing out.
void ImGui::ItemFocusable(ImGuiWindow* window, ImGuiID id)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0 && id == window->DC.LastItemId);
// Increment counters
// FIXME: ImGuiItemFlags_Disabled should disable more.
const bool is_tab_stop = (g.CurrentItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->DC.FocusCounterRegular++;
if (is_tab_stop)
{
window->DC.FocusCounterTabStop++;
if (g.NavId == id)
g.NavIdTabCounter = window->DC.FocusCounterTabStop;
}
// Process 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 (g.ActiveId == id && g.TabFocusPressed && !IsActiveIdUsingKey(ImGuiKey_Tab) && g.TabFocusRequestNextWindow == NULL)
{
g.TabFocusRequestNextWindow = window;
g.TabFocusRequestNextCounterTabStop = window->DC.FocusCounterTabStop + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
}
// Handle focus requests
if (g.TabFocusRequestCurrWindow == window)
{
if (window->DC.FocusCounterRegular == g.TabFocusRequestCurrCounterRegular)
{
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_FocusedByCode;
return;
}
if (is_tab_stop && window->DC.FocusCounterTabStop == g.TabFocusRequestCurrCounterTabStop)
{
g.NavJustTabbedId = id;
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_FocusedByTabbing;
return;
}
// If another item is about to be focused, we clear our own active id
if (g.ActiveId == id)
ClearActiveID();
}
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (wrap_pos_x == 0.0f)
{
// We could decide to setup a default wrapping max point for auto-resizing windows,
// or have auto-wrap (with unspecified wrapping pos) behave as a ContentSize extending function?
//if (window->Hidden && (window->Flags & ImGuiWindowFlags_AlwaysAutoResize))
// wrap_pos_x = ImMax(window->WorkRect.Min.x + g.FontSize * 10.0f, window->WorkRect.Max.x);
//else
wrap_pos_x = window->WorkRect.Max.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);
}
// IM_ALLOC() == ImGui::MemAlloc()
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return (*GImAllocatorAllocFunc)(size, GImAllocatorUserData);
}
// IM_FREE() == ImGui::MemFree()
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return (*GImAllocatorFreeFunc)(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
ImGuiContext& g = *GImGui;
return g.IO.GetClipboardTextFn ? g.IO.GetClipboardTextFn(g.IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
ImGuiContext& g = *GImGui;
if (g.IO.SetClipboardTextFn)
g.IO.SetClipboardTextFn(g.IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share Dear 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(ImGuiMemAllocFunc alloc_func, ImGuiMemFreeFunc free_func, void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
// This is provided to facilitate copying allocators from one static/DLL boundary to another (e.g. retrieve default allocator of your executable address space)
void ImGui::GetAllocatorFunctions(ImGuiMemAllocFunc* p_alloc_func, ImGuiMemFreeFunc* p_free_func, void** p_user_data)
{
*p_alloc_func = GImAllocatorAllocFunc;
*p_free_func = GImAllocatorFreeFunc;
*p_user_data = GImAllocatorUserData;
}
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);
}
// No specific ordering/dependency support, will see as needed
ImGuiID ImGui::AddContextHook(ImGuiContext* ctx, const ImGuiContextHook* hook)
{
ImGuiContext& g = *ctx;
IM_ASSERT(hook->Callback != NULL && hook->HookId == 0 && hook->Type != ImGuiContextHookType_PendingRemoval_);
g.Hooks.push_back(*hook);
g.Hooks.back().HookId = ++g.HookIdNext;
return g.HookIdNext;
}
// Deferred removal, avoiding issue with changing vector while iterating it
void ImGui::RemoveContextHook(ImGuiContext* ctx, ImGuiID hook_id)
{
ImGuiContext& g = *ctx;
IM_ASSERT(hook_id != 0);
for (int n = 0; n < g.Hooks.Size; n++)
if (g.Hooks[n].HookId == hook_id)
g.Hooks[n].Type = ImGuiContextHookType_PendingRemoval_;
}
// Call context hooks (used by e.g. test engine)
// We assume a small number of hooks so all stored in same array
void ImGui::CallContextHooks(ImGuiContext* ctx, ImGuiContextHookType hook_type)
{
ImGuiContext& g = *ctx;
for (int n = 0; n < g.Hooks.Size; n++)
if (g.Hooks[n].Type == hook_type)
g.Hooks[n].Callback(&g, &g.Hooks[n]);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
return GImGui->IO;
}
// Pass this to your backend rendering function! Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
ImGuiViewportP* viewport = g.Viewports[0];
return viewport->DrawDataP.Valid ? &viewport->DrawDataP : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
static ImDrawList* GetViewportDrawList(ImGuiViewportP* viewport, size_t drawlist_no, const char* drawlist_name)
{
// Create the draw list on demand, because they are not frequently used for all viewports
ImGuiContext& g = *GImGui;
IM_ASSERT(drawlist_no < IM_ARRAYSIZE(viewport->DrawLists));
ImDrawList* draw_list = viewport->DrawLists[drawlist_no];
if (draw_list == NULL)
{
draw_list = IM_NEW(ImDrawList)(&g.DrawListSharedData);
draw_list->_OwnerName = drawlist_name;
viewport->DrawLists[drawlist_no] = draw_list;
}
// Our ImDrawList system requires that there is always a command
if (viewport->DrawListsLastFrame[drawlist_no] != g.FrameCount)
{
draw_list->_ResetForNewFrame();
draw_list->PushTextureID(g.IO.Fonts->TexID);
draw_list->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
viewport->DrawListsLastFrame[drawlist_no] = g.FrameCount;
}
return draw_list;
}
ImDrawList* ImGui::GetBackgroundDrawList(ImGuiViewport* viewport)
{
return GetViewportDrawList((ImGuiViewportP*)viewport, 0, "##Background");
}
ImDrawList* ImGui::GetBackgroundDrawList()
{
ImGuiContext& g = *GImGui;
return GetBackgroundDrawList(g.Viewports[0]);
}
ImDrawList* ImGui::GetForegroundDrawList(ImGuiViewport* viewport)
{
return GetViewportDrawList((ImGuiViewportP*)viewport, 1, "##Foreground");
}
ImDrawList* ImGui::GetForegroundDrawList()
{
ImGuiContext& g = *GImGui;
return GetForegroundDrawList(g.Viewports[0]);
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdNoClearOnFocusLoss = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
// FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
// This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
// but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other.
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// 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 generally 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] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
}
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();
}
}
}
// Initiate moving window when clicking on empty space or title bar.
// Handle left-click and right-click focus.
void ImGui::UpdateMouseMovingWindowEndFrame()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click on empty space to focus window and start moving
// (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
// Handle the edge case of a popup being closed while clicking in its empty space.
// If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
ImGuiWindow* root_window = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
const bool is_closed_popup = root_window && (root_window->Flags & ImGuiWindowFlags_Popup) && !IsPopupOpen(root_window->PopupId, ImGuiPopupFlags_AnyPopupLevel);
if (root_window != NULL && !is_closed_popup)
{
StartMouseMovingWindow(g.HoveredWindow); //-V595
// Cancel moving if clicked outside of title bar
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(root_window->Flags & ImGuiWindowFlags_NoTitleBar))
if (!root_window->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
// Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
if (g.HoveredIdDisabled)
g.MovingWindow = NULL;
}
else if (root_window == NULL && g.NavWindow != NULL && GetTopMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus based on where the mouse is aimed
// Instead, focus will be restored to the window under the bottom-most closed popup.
// (The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetTopMostPopupModal();
bool hovered_window_above_modal = g.HoveredWindow && IsWindowAbove(g.HoveredWindow, modal);
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal, true);
}
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) 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 ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -g.IO.MouseDoubleClickTime * 2.0f; // Mark as "old enough" 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.MouseDownWasDoubleClick[i] = g.IO.MouseDoubleClicked[i];
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (!g.IO.MouseDown[i] && !g.IO.MouseReleased[i])
g.IO.MouseDownWasDoubleClick[i] = false;
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
static void StartLockWheelingWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WheelingWindow == window)
return;
g.WheelingWindow = window;
g.WheelingWindowRefMousePos = g.IO.MousePos;
g.WheelingWindowTimer = WINDOWS_MOUSE_WHEEL_SCROLL_LOCK_TIMER;
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
// Reset the locked window if we move the mouse or after the timer elapses
if (g.WheelingWindow != NULL)
{
g.WheelingWindowTimer -= g.IO.DeltaTime;
if (IsMousePosValid() && ImLengthSqr(g.IO.MousePos - g.WheelingWindowRefMousePos) > g.IO.MouseDragThreshold * g.IO.MouseDragThreshold)
g.WheelingWindowTimer = 0.0f;
if (g.WheelingWindowTimer <= 0.0f)
{
g.WheelingWindow = NULL;
g.WheelingWindowTimer = 0.0f;
}
}
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
if ((g.ActiveId != 0 && g.ActiveIdUsingMouseWheel) || (g.HoveredIdPreviousFrame != 0 && g.HoveredIdPreviousFrameUsingMouseWheel))
return;
ImGuiWindow* window = g.WheelingWindow ? g.WheelingWindow : g.HoveredWindow;
if (!window || window->Collapsed)
return;
// Zoom / Scale window
// FIXME-OBSOLETE: This is an old feature, it still works but pretty much nobody is using it and may be best redesigned.
if (g.IO.MouseWheel != 0.0f && g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
StartLockWheelingWindow(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;
if (window == window->RootWindow)
{
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
SetWindowPos(window, window->Pos + offset, 0);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
}
return;
}
// Mouse wheel scrolling
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent
if (g.IO.KeyCtrl)
return;
// As a standard behavior holding SHIFT while using Vertical Mouse Wheel triggers Horizontal scroll instead
// (we avoid doing it on OSX as it the OS input layer handles this already)
const bool swap_axis = g.IO.KeyShift && !g.IO.ConfigMacOSXBehaviors;
const float wheel_y = swap_axis ? 0.0f : g.IO.MouseWheel;
const float wheel_x = swap_axis ? g.IO.MouseWheel : g.IO.MouseWheelH;
// Vertical Mouse Wheel scrolling
if (wheel_y != 0.0f)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.y == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetHeight() * 0.67f;
float scroll_step = ImFloor(ImMin(5 * window->CalcFontSize(), max_step));
SetScrollY(window, window->Scroll.y - wheel_y * scroll_step);
}
}
// Horizontal Mouse Wheel scrolling, or Vertical Mouse Wheel w/ Shift held
if (wheel_x != 0.0f)
{
StartLockWheelingWindow(window);
while ((window->Flags & ImGuiWindowFlags_ChildWindow) && ((window->ScrollMax.x == 0.0f) || ((window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))))
window = window->ParentWindow;
if (!(window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(window->Flags & ImGuiWindowFlags_NoMouseInputs))
{
float max_step = window->InnerRect.GetWidth() * 0.67f;
float scroll_step = ImFloor(ImMin(2 * window->CalcFontSize(), max_step));
SetScrollX(window, window->Scroll.x - wheel_x * scroll_step);
}
}
}
void ImGui::UpdateTabFocus()
{
ImGuiContext& g = *GImGui;
// Pressing TAB activate widget focus
g.TabFocusPressed = (g.NavWindow && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab));
if (g.ActiveId == 0 && g.TabFocusPressed)
{
// - This path is only taken when no widget are active/tabbed-into yet.
// Subsequent tabbing will be processed by FocusableItemRegister()
// - Note that SetKeyboardFocusHere() sets the Next fields mid-frame. To be consistent we also
// manipulate the Next fields here even though they will be turned into Curr fields below.
g.TabFocusRequestNextWindow = g.NavWindow;
g.TabFocusRequestNextCounterRegular = INT_MAX;
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.TabFocusRequestNextCounterTabStop = g.NavIdTabCounter + (g.IO.KeyShift ? -1 : 0);
else
g.TabFocusRequestNextCounterTabStop = g.IO.KeyShift ? -1 : 0;
}
// Turn queued focus request into current one
g.TabFocusRequestCurrWindow = NULL;
g.TabFocusRequestCurrCounterRegular = g.TabFocusRequestCurrCounterTabStop = INT_MAX;
if (g.TabFocusRequestNextWindow != NULL)
{
ImGuiWindow* window = g.TabFocusRequestNextWindow;
g.TabFocusRequestCurrWindow = window;
if (g.TabFocusRequestNextCounterRegular != INT_MAX && window->DC.FocusCounterRegular != -1)
g.TabFocusRequestCurrCounterRegular = ImModPositive(g.TabFocusRequestNextCounterRegular, window->DC.FocusCounterRegular + 1);
if (g.TabFocusRequestNextCounterTabStop != INT_MAX && window->DC.FocusCounterTabStop != -1)
g.TabFocusRequestCurrCounterTabStop = ImModPositive(g.TabFocusRequestNextCounterTabStop, window->DC.FocusCounterTabStop + 1);
g.TabFocusRequestNextWindow = NULL;
g.TabFocusRequestNextCounterRegular = g.TabFocusRequestNextCounterTabStop = INT_MAX;
}
g.NavIdTabCounter = INT_MAX;
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
g.WindowsHoverPadding = ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_HOVER_PADDING, WINDOWS_HOVER_PADDING));
// Find the window hovered by mouse:
// - 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 of the frame.
// - 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.
bool clear_hovered_windows = false;
FindHoveredWindow();
// Modal windows prevents mouse from hovering behind them.
ImGuiWindow* modal_window = GetTopMostPopupModal();
if (modal_window && g.HoveredWindow && !IsWindowChildOf(g.HoveredWindow->RootWindow, modal_window))
clear_hovered_windows = true;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
clear_hovered_windows = true;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
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.Size > 0);
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;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// 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)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
clear_hovered_windows = true;
if (clear_hovered_windows)
g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to Dear ImGui + app)
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.Size > 0);
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to Dear ImGui + app)
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;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
ImGuiKeyModFlags ImGui::GetMergedKeyModFlags()
{
ImGuiContext& g = *GImGui;
ImGuiKeyModFlags key_mod_flags = ImGuiKeyModFlags_None;
if (g.IO.KeyCtrl) { key_mod_flags |= ImGuiKeyModFlags_Ctrl; }
if (g.IO.KeyShift) { key_mod_flags |= ImGuiKeyModFlags_Shift; }
if (g.IO.KeyAlt) { key_mod_flags |= ImGuiKeyModFlags_Alt; }
if (g.IO.KeySuper) { key_mod_flags |= ImGuiKeyModFlags_Super; }
return key_mod_flags;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() and ImGui::SetCurrentContext() ?");
ImGuiContext& g = *GImGui;
// Remove pending delete hooks before frame start.
// This deferred removal avoid issues of removal while iterating the hook vector
for (int n = g.Hooks.Size - 1; n >= 0; n--)
if (g.Hooks[n].Type == ImGuiContextHookType_PendingRemoval_)
g.Hooks.erase(&g.Hooks[n]);
CallContextHooks(&g, ImGuiContextHookType_NewFramePre);
// Check and assert for various common IO and Configuration mistakes
ErrorCheckNewFrameSanityChecks();
// Load settings on first frame, save settings when modified (after a delay)
UpdateSettings();
g.Time += g.IO.DeltaTime;
g.WithinFrameScope = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
g.MenusIdSubmittedThisFrame.resize(0);
// 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.FramerateSecPerFrameCount = ImMin(g.FramerateSecPerFrameCount + 1, IM_ARRAYSIZE(g.FramerateSecPerFrame));
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)g.FramerateSecPerFrameCount)) : FLT_MAX;
UpdateViewportsNewFrame();
// Setup current font and draw list shared data
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
ImRect virtual_space(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
for (int n = 0; n < g.Viewports.Size; n++)
virtual_space.Add(g.Viewports[n]->GetMainRect());
g.DrawListSharedData.ClipRectFullscreen = virtual_space.ToVec4();
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
g.DrawListSharedData.SetCircleTessellationMaxError(g.Style.CircleTessellationMaxError);
g.DrawListSharedData.InitialFlags = ImDrawListFlags_None;
if (g.Style.AntiAliasedLines)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLines;
if (g.Style.AntiAliasedLinesUseTex && !(g.Font->ContainerAtlas->Flags & ImFontAtlasFlags_NoBakedLines))
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedLinesUseTex;
if (g.Style.AntiAliasedFill)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AntiAliasedFill;
if (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasVtxOffset)
g.DrawListSharedData.InitialFlags |= ImDrawListFlags_AllowVtxOffset;
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
viewport->DrawDataP.Clear();
}
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Update HoveredId data
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredIdPreviousFrameUsingMouseWheel = g.HoveredIdUsingMouseWheel;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
g.HoveredIdUsingMouseWheel = false;
g.HoveredIdDisabled = false;
// Update ActiveId data (clear reference to active widget if the widget isn't alive anymore)
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEditedBefore = g.ActiveIdHasBeenEditedBefore;
g.ActiveIdIsAlive = 0;
g.ActiveIdHasBeenEditedThisFrame = false;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.TempInputId != 0 && g.ActiveId != g.TempInputId)
g.TempInputId = 0;
if (g.ActiveId == 0)
{
g.ActiveIdUsingNavDirMask = 0x00;
g.ActiveIdUsingNavInputMask = 0x00;
g.ActiveIdUsingKeyInputMask = 0x00;
}
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSource = false;
g.DragDropWithinTarget = false;
g.DragDropHoldJustPressedId = 0;
// Update keyboard input state
// Synchronize io.KeyMods with individual modifiers io.KeyXXX bools
g.IO.KeyMods = GetMergedKeyModFlags();
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 navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetTopMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Update legacy TAB focus
UpdateTabFocus();
// Mark all windows as not visible and compact unused memory.
IM_ASSERT(g.WindowsFocusOrder.Size <= g.Windows.Size);
const float memory_compact_start_time = (g.GcCompactAll || g.IO.ConfigMemoryCompactTimer < 0.0f) ? FLT_MAX : (float)g.Time - g.IO.ConfigMemoryCompactTimer;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
// Garbage collect transient buffers of recently unused windows
if (!window->WasActive && !window->MemoryCompacted && window->LastTimeActive < memory_compact_start_time)
GcCompactTransientWindowBuffers(window);
}
// Garbage collect transient buffers of recently unused tables
for (int i = 0; i < g.TablesLastTimeActive.Size; i++)
if (g.TablesLastTimeActive[i] >= 0.0f && g.TablesLastTimeActive[i] < memory_compact_start_time)
TableGcCompactTransientBuffers(g.Tables.GetByIndex(i));
for (int i = 0; i < g.TablesTempDataStack.Size; i++)
if (g.TablesTempDataStack[i].LastTimeActive >= 0.0f && g.TablesTempDataStack[i].LastTimeActive < memory_compact_start_time)
TableGcCompactTransientBuffers(&g.TablesTempDataStack[i]);
if (g.GcCompactAll)
GcCompactTransientMiscBuffers();
g.GcCompactAll = false;
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusTopMostWindowUnderOne(NULL, 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.BeginPopupStack.resize(0);
g.ItemFlagsStack.resize(0);
g.ItemFlagsStack.push_back(ImGuiItemFlags_None);
g.GroupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow, false);
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
UpdateDebugToolItemPicker();
// Create implicit/fallback window - which 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.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
g.WithinFrameScopeWithImplicitWindow = true;
SetNextWindowSize(ImVec2(400, 400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
IM_ASSERT(g.CurrentWindow->IsFallbackWindow == true);
CallContextHooks(&g, ImGuiContextHookType_NewFramePost);
}
// [DEBUG] Item picker tool - start with DebugStartItemPicker() - useful to visually select an item and break into its call-stack.
void ImGui::UpdateDebugToolItemPicker()
{
ImGuiContext& g = *GImGui;
g.DebugItemPickerBreakId = 0;
if (g.DebugItemPickerActive)
{
const ImGuiID hovered_id = g.HoveredIdPreviousFrame;
SetMouseCursor(ImGuiMouseCursor_Hand);
if (IsKeyPressedMap(ImGuiKey_Escape))
g.DebugItemPickerActive = false;
if (IsMouseClicked(0) && hovered_id)
{
g.DebugItemPickerBreakId = hovered_id;
g.DebugItemPickerActive = false;
}
SetNextWindowBgAlpha(0.60f);
BeginTooltip();
Text("HoveredId: 0x%08X", hovered_id);
Text("Press ESC to abort picking.");
TextColored(GetStyleColorVec4(hovered_id ? ImGuiCol_Text : ImGuiCol_TextDisabled), "Click to break in debugger!");
EndTooltip();
}
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
{
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window");
ini_handler.ClearAllFn = WindowSettingsHandler_ClearAll;
ini_handler.ReadOpenFn = WindowSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = WindowSettingsHandler_ReadLine;
ini_handler.ApplyAllFn = WindowSettingsHandler_ApplyAll;
ini_handler.WriteAllFn = WindowSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
// Add .ini handle for ImGuiTable type
TableSettingsInstallHandler(context);
// Create default viewport
ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
g.Viewports.push_back(viewport);
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* 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)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized Dear ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(&g);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
CallContextHooks(&g, ImGuiContextHookType_Shutdown);
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsTempSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredWindowUnderMovingWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorStack.clear();
g.StyleVarStack.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
for (int i = 0; i < g.Viewports.Size; i++)
IM_DELETE(g.Viewports[i]);
g.Viewports.clear();
g.TabBars.Clear();
g.CurrentTabBarStack.clear();
g.ShrinkWidthBuffer.clear();
g.Tables.Clear();
for (int i = 0; i < g.TablesTempDataStack.Size; i++)
g.TablesTempDataStack[i].~ImGuiTableTempData();
g.TablesTempDataStack.clear();
g.DrawChannelsTempMergeBuffer.clear();
g.ClipboardHandlerData.clear();
g.MenusIdSubmittedThisFrame.clear();
g.InputTextState.ClearFreeMemory();
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile)
{
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
if (g.LogFile != stdout)
#endif
ImFileClose(g.LogFile);
g.LogFile = NULL;
}
g.LogBuffer.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)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 AddWindowToSortBuffer(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)
ImQsort(window->DC.ChildWindows.Data, (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
// Remove trailing command if unused.
// Technically we could return directly instead of popping, but this make things looks neat in Metrics/Debugger window as well.
draw_list->_PopUnusedDrawCmd();
if (draw_list->CmdBuffer.Size == 0)
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);
if (!(draw_list->Flags & ImDrawListFlags_AllowVtxOffset))
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:
// - First, make sure you are coarse clipping yourself and not trying to draw many things outside visible bounds.
// Be mindful that the ImDrawList API doesn't filter vertices. Use the Metrics/Debugger window to inspect draw list contents.
// - If you want large meshes with more than 64K vertices, you can either:
// (A) Handle the ImDrawCmd::VtxOffset value in your renderer backend, and set 'io.BackendFlags |= ImGuiBackendFlags_RendererHasVtxOffset'.
// Most example backends already support this from 1.71. Pre-1.71 backends won't.
// Some graphics API such as GL ES 1/2 don't have a way to offset the starting vertex so it is not supported for them.
// (B) Or handle 32-bit indices in your renderer backend, and uncomment '#define ImDrawIdx unsigned int' line in imconfig.h.
// Most example backends already support this. For example, the OpenGL example code detect index size at compile-time:
// 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 graphics API.
// - If for some reason neither of those solutions works for you, 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_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
{
ImGuiContext& g = *GImGui;
ImGuiViewportP* viewport = g.Viewports[0];
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[layer], window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
AddWindowToDrawData(child, layer);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
AddWindowToDrawData(window, layer);
}
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 SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
{
ImGuiIO& io = ImGui::GetIO();
ImDrawData* draw_data = &viewport->DrawDataP;
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = viewport->Pos;
draw_data->DisplaySize = viewport->Size;
draw_data->FramebufferScale = io.DisplayFramebufferScale;
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// Push a clipping rectangle for both ImGui logic (hit-testing etc.) and low-level ImDrawList rendering.
// - When using this function it is sane to ensure that float are perfectly rounded to integer values,
// so that e.g. (int)(max.x-min.x) in user's render produce correct result.
// - If the code here changes, may need to update code of functions like NextColumn() and PushColumnClipRect():
// some frequently called functions which to modify both channels and clipping simultaneously tend to use the
// more specialized SetWindowClipRectBeforeSetChannel() to avoid extraneous updates of underlying ImDrawCmds.
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);
// Don't process EndFrame() multiple times.
if (g.FrameCountEnded == g.FrameCount)
return;
IM_ASSERT(g.WithinFrameScope && "Forgot to call ImGui::NewFrame()?");
CallContextHooks(&g, ImGuiContextHookType_EndFramePre);
ErrorCheckEndFrameSanityChecks();
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.IO.ImeSetInputScreenPosFn && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImeLastPos - g.PlatformImePos) > 0.0001f))
{
g.IO.ImeSetInputScreenPosFn((int)g.PlatformImePos.x, (int)g.PlatformImePos.y);
g.PlatformImeLastPos = g.PlatformImePos;
}
// Hide implicit/fallback "Debug" window if it hasn't been used
g.WithinFrameScopeWithImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Update navigation: CTRL+Tab, wrap-around requests
NavEndFrame();
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount && !(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
g.DragDropWithinSource = true;
SetTooltip("...");
g.DragDropWithinSource = false;
}
// End frame
g.WithinFrameScope = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because children may not exist yet
g.WindowsTempSortBuffer.resize(0);
g.WindowsTempSortBuffer.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;
AddWindowToSortBuffer(&g.WindowsTempSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsTempSortBuffer.Size);
g.Windows.swap(g.WindowsTempSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
CallContextHooks(&g, ImGuiContextHookType_EndFramePost);
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
g.IO.MetricsRenderWindows = 0;
CallContextHooks(&g, ImGuiContextHookType_RenderPre);
// Add background ImDrawList (for each active viewport)
for (int n = 0; n != g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
viewport->DrawDataBuilder.Clear();
if (viewport->DrawLists[0] != NULL)
AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetBackgroundDrawList(viewport));
}
// Add ImDrawList to render
ImGuiWindow* windows_to_render_top_most[2];
windows_to_render_top_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_top_most[1] = (g.NavWindowingTarget ? g.NavWindowingListWindow : NULL);
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
IM_MSVC_WARNING_SUPPRESS(6011); // Static Analysis false positive "warning C6011: Dereferencing NULL pointer 'window'"
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_top_most[0] && window != windows_to_render_top_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_top_most); n++)
if (windows_to_render_top_most[n] && IsWindowActiveAndVisible(windows_to_render_top_most[n])) // NavWindowingTarget is always temporarily displayed as the top-most window
AddRootWindowToDrawData(windows_to_render_top_most[n]);
// Setup ImDrawData structures for end-user
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
viewport->DrawDataBuilder.FlattenIntoSingleLayer();
// Draw software mouse cursor if requested by io.MouseDrawCursor flag
if (g.IO.MouseDrawCursor)
RenderMouseCursor(GetForegroundDrawList(viewport), g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor, IM_COL32_WHITE, IM_COL32_BLACK, IM_COL32(0, 0, 0, 48));
// Add foreground ImDrawList (for each active viewport)
if (viewport->DrawLists[1] != NULL)
AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetForegroundDrawList(viewport));
SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
ImDrawData* draw_data = &viewport->DrawDataP;
g.IO.MetricsRenderVertices += draw_data->TotalVtxCount;
g.IO.MetricsRenderIndices += draw_data->TotalIdxCount;
}
CallContextHooks(&g, ImGuiContextHookType_RenderPost);
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, g.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);
// Round
// FIXME: This has been here since Dec 2015 (7b0bf230) but down the line we want this out.
// FIXME: Investigate using ceilf or e.g.
// - https://git.musl-libc.org/cgit/musl/tree/src/math/ceilf.c
// - https://embarkstudios.github.io/rust-gpu/api/src/libm/math/ceilf.rs.html
text_size.x = IM_FLOOR(text_size.x + 0.99999f);
return text_size;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programmatically
// with 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 isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* hovered_window = NULL;
ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize = g.IO.ConfigWindowsResizeFromEdges ? g.WindowsHoverPadding : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if (window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_AlwaysAutoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize);
if (!bb.Contains(g.IO.MousePos))
continue;
// Support for one rectangular hole in any given window
// FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
if (window->HitTestHoleSize.x != 0)
{
ImVec2 hole_pos(window->Pos.x + (float)window->HitTestHoleOffset.x, window->Pos.y + (float)window->HitTestHoleOffset.y);
ImVec2 hole_size((float)window->HitTestHoleSize.x, (float)window->HitTestHoleSize.y);
if (ImRect(hole_pos, hole_pos + hole_size).Contains(g.IO.MousePos))
continue;
}
if (hovered_window == NULL)
hovered_window = window;
IM_MSVC_WARNING_SUPPRESS(28182); // [Static Analyzer] Dereferencing NULL pointer.
if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
hovered_window_ignoring_moving_window = window;
if (hovered_window && hovered_window_ignoring_moving_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
}
// 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;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
ImGuiContext& g = *GImGui;
return g.IO.KeyMap[imgui_key];
}
// Note that dear imgui doesn't know the semantic of each entry of io.KeysDown[]!
// Use your own indices/enums according to how your backend/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0)
return false;
ImGuiContext& g = *GImGui;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDown[user_key_index];
}
// t0 = previous time (e.g.: g.Time - g.IO.DeltaTime)
// t1 = current time (e.g.: g.Time)
// An event is triggered at:
// t = 0.0f t = repeat_delay, t = repeat_delay + repeat_rate*N
int ImGui::CalcTypematicRepeatAmount(float t0, float t1, float repeat_delay, float repeat_rate)
{
if (t1 == 0.0f)
return 1;
if (t0 >= t1)
return 0;
if (repeat_rate <= 0.0f)
return (t0 < repeat_delay) && (t1 >= repeat_delay);
const int count_t0 = (t0 < repeat_delay) ? -1 : (int)((t0 - repeat_delay) / repeat_rate);
const int count_t1 = (t1 < repeat_delay) ? -1 : (int)((t1 - repeat_delay) / repeat_rate);
const int count = count_t1 - count_t0;
return count;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, 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(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsMouseClicked(ImGuiMouseButton 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)
{
// FIXME: 2019/05/03: Our old repeat code was wrong here and led to doubling the repeat rate, which made it an ok rate for repeat on mouse hold.
int amount = CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate * 0.50f);
if (amount > 0)
return true;
}
return false;
}
bool ImGui::IsMouseReleased(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(ImGuiMouseButton button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
// Return if a mouse click/drag went past the given threshold. Valid to call during the MouseReleased frame.
// [Internal] This doesn't test if the button is pressed
bool ImGui::IsMouseDragPastThreshold(ImGuiMouseButton 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;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
bool ImGui::IsMouseDragging(ImGuiMouseButton button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
return IsMouseDragPastThreshold(button, lock_threshold);
}
ImVec2 ImGui::GetMousePos()
{
ImGuiContext& g = *GImGui;
return g.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.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.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)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
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;
}
// Return the delta from the initial clicking position while the mouse button is clicked or was just released.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). backends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(ImGuiMouseButton 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] || g.IO.MouseReleased[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MouseClickedPos[button]))
return g.IO.MousePos - g.IO.MouseClickedPos[button];
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(ImGuiMouseButton 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::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDeactivated)
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Deactivated) != 0;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEditedBefore || (g.ActiveId == 0 && g.ActiveIdHasBeenEditedBefore));
}
// == GetItemID() == GetFocusID()
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId != window->DC.LastItemId || g.NavId == 0)
return false;
return true;
}
// Important: this can be useful but it is NOT equivalent to the behavior of e.g.Button()!
// Most widgets have specific reactions based on mouse-up/down state, mouse position etc.
bool ImGui::IsItemClicked(ImGuiMouseButton mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsItemToggledOpen()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledOpen) ? true : false;
}
bool ImGui::IsItemToggledSelection()
{
ImGuiContext& g = *GImGui;
return (g.CurrentWindow->DC.LastItemStatusFlags & ImGuiItemStatusFlags_ToggledSelection) ? true : false;
}
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);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
// FIXME: Although this is exposed, its interaction and ideal idiom with using ImGuiButtonFlags_AllowItemOverlap flag are extremely confusing, need rework.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
ImGuiID id = g.CurrentWindow->DC.LastItemId;
if (g.HoveredId == id)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == id)
g.ActiveIdAllowOverlap = true;
}
void ImGui::SetItemUsingMouseWheel()
{
ImGuiContext& g = *GImGui;
ImGuiID id = g.CurrentWindow->DC.LastItemId;
if (g.HoveredId == id)
g.HoveredIdUsingMouseWheel = true;
if (g.ActiveId == id)
g.ActiveIdUsingMouseWheel = 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();
}
bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_ChildWindow;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = 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);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
if (name)
ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(g.TempBuffer, IM_ARRAYSIZE(g.TempBuffer), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(g.TempBuffer, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = (ImS8)auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayersActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id + 1, child_window); // Steal ActiveId with another arbitrary 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(g.WithinEndChild == false);
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() calls
g.WithinEndChild = true;
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
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.NavLayersActiveMask != 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.NavLayersActiveMask == 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);
}
if (g.HoveredWindow == window)
parent_window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
}
g.WithinEndChild = false;
g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
}
// 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);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
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::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name);
return FindWindowByID(id);
}
static void ApplyWindowSettings(ImGuiWindow* window, ImGuiWindowSettings* settings)
{
window->Pos = ImFloor(ImVec2(settings->Pos.x, settings->Pos.y));
if (settings->Size.x > 0 && settings->Size.y > 0)
window->Size = window->SizeFull = ImFloor(ImVec2(settings->Size.x, settings->Size.y));
window->Collapsed = settings->Collapsed;
}
static ImGuiWindow* CreateNewWindow(const char* name, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
//IMGUI_DEBUG_LOG("CreateNewWindow '%s', flags = 0x%08X\n", name, flags);
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
const ImGuiViewport* main_viewport = ImGui::GetMainViewport();
window->Pos = main_viewport->Pos + ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
ApplyWindowSettings(window, settings);
}
window->DC.CursorStartPos = window->DC.CursorMaxPos = window->Pos; // So first call to CalcContentSize() doesn't return crazy values
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_ChildWindow))
{
g.WindowsFocusOrder.push_back(window);
window->FocusOrder = (short)(g.WindowsFocusOrder.Size - 1);
}
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImVec2 CalcWindowSizeAfterConstraint(ImGuiWindow* window, const ImVec2& size_desired)
{
ImGuiContext& g = *GImGui;
ImVec2 new_size = size_desired;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSizeConstraint)
{
// 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;
}
new_size.x = IM_FLOOR(new_size.x);
new_size.y = IM_FLOOR(new_size.y);
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
ImGuiWindow* window_for_height = window;
const float decoration_up_height = window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight();
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, decoration_up_height + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static void CalcWindowContentSizes(ImGuiWindow* window, ImVec2* content_size_current, ImVec2* content_size_ideal)
{
bool preserve_old_content_sizes = false;
if (window->Collapsed && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
preserve_old_content_sizes = true;
else if (window->Hidden && window->HiddenFramesCannotSkipItems == 0 && window->HiddenFramesCanSkipItems > 0)
preserve_old_content_sizes = true;
if (preserve_old_content_sizes)
{
*content_size_current = window->ContentSize;
*content_size_ideal = window->ContentSizeIdeal;
return;
}
content_size_current->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(window->DC.CursorMaxPos.x - window->DC.CursorStartPos.x);
content_size_current->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(window->DC.CursorMaxPos.y - window->DC.CursorStartPos.y);
content_size_ideal->x = (window->ContentSizeExplicit.x != 0.0f) ? window->ContentSizeExplicit.x : IM_FLOOR(ImMax(window->DC.CursorMaxPos.x, window->DC.IdealMaxPos.x) - window->DC.CursorStartPos.x);
content_size_ideal->y = (window->ContentSizeExplicit.y != 0.0f) ? window->ContentSizeExplicit.y : IM_FLOOR(ImMax(window->DC.CursorMaxPos.y, window->DC.IdealMaxPos.y) - window->DC.CursorStartPos.y);
}
static ImVec2 CalcWindowAutoFitSize(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
ImVec2 size_pad = window->WindowPadding * 2.0f;
ImVec2 size_desired = size_contents + size_pad + ImVec2(0.0f, decoration_up_height);
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_desired;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
// FIXME-VIEWPORT-WORKAREA: May want to use GetWorkSize() instead of Size depending on the type of windows?
ImVec2 avail_size = ImGui::GetMainViewport()->Size;
ImVec2 size_auto_fit = ImClamp(size_desired, size_min, ImMax(size_min, avail_size - style.DisplaySafeAreaPadding * 2.0f));
// 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 ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcWindowSizeAfterConstraint(window, size_auto_fit);
bool will_have_scrollbar_x = (size_auto_fit_after_constraint.x - size_pad.x - 0.0f < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar);
bool will_have_scrollbar_y = (size_auto_fit_after_constraint.y - size_pad.y - decoration_up_height < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar)) || (window->Flags & ImGuiWindowFlags_AlwaysVerticalScrollbar);
if (will_have_scrollbar_x)
size_auto_fit.y += style.ScrollbarSize;
if (will_have_scrollbar_y)
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowNextAutoFitSize(ImGuiWindow* window)
{
ImVec2 size_contents_current;
ImVec2 size_contents_ideal;
CalcWindowContentSizes(window, &size_contents_current, &size_contents_ideal);
ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, size_contents_ideal);
ImVec2 size_final = CalcWindowSizeAfterConstraint(window, size_auto_fit);
return size_final;
}
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 = CalcWindowSizeAfterConstraint(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;
}
// Data for resizing from corner
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static 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 (Unused)
{ ImVec2(1, 0), ImVec2(-1, +1), 9, 12 } // Upper-right (Unused)
};
// Data for resizing from borders
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 SegmentN1, SegmentN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(+1, 0), ImVec2(0, 1), ImVec2(0, 0), IM_PI * 1.00f }, // Left
{ ImVec2(-1, 0), ImVec2(1, 0), ImVec2(1, 1), IM_PI * 0.00f }, // Right
{ ImVec2(0, +1), ImVec2(0, 0), ImVec2(1, 0), IM_PI * 1.50f }, // Up
{ ImVec2(0, -1), ImVec2(1, 1), ImVec2(0, 1), IM_PI * 0.50f } // Down
};
static ImRect GetResizeBorderRect(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 == ImGuiDir_Left) { return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); }
if (border_n == ImGuiDir_Right) { return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); }
if (border_n == ImGuiDir_Up) { return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); }
if (border_n == ImGuiDir_Down) { return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); }
IM_ASSERT(0);
return ImRect();
}
// 0..3: corners (Lower-right, Lower-left, Unused, Unused)
ImGuiID ImGui::GetWindowResizeCornerID(ImGuiWindow* window, int n)
{
IM_ASSERT(n >= 0 && n < 4);
ImGuiID id = window->ID;
id = ImHashStr("#RESIZE", 0, id);
id = ImHashData(&n, sizeof(int), id);
return id;
}
// Borders (Left, Right, Up, Down)
ImGuiID ImGui::GetWindowResizeBorderID(ImGuiWindow* window, ImGuiDir dir)
{
IM_ASSERT(dir >= 0 && dir < 4);
int n = (int)dir + 4;
ImGuiID id = window->ID;
id = ImHashStr("#RESIZE", 0, id);
id = ImHashData(&n, sizeof(int), id);
return id;
}
// Handle resize for: Resize Grips, Borders, Gamepad
// Return true when using auto-fit (double click on resize grip)
static bool ImGui::UpdateWindowManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4], const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return false;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return false;
bool ret_auto_fit = false;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
const float grip_hover_inner_size = IM_FLOOR(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_HOVER_PADDING : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Resize grips and borders are on layer 1
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& def = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, def.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
bool hovered, held;
ImRect resize_rect(corner - def.InnerDir * grip_hover_outer_size, corner + def.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
ImGuiID resize_grip_id = window->GetID(resize_grip_n); // == GetWindowResizeCornerID()
ButtonBehavior(resize_rect, resize_grip_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetForegroundDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcWindowSizeAfterConstraint(window, size_auto_fit);
ret_auto_fit = true;
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 clamp_min = ImVec2(def.CornerPosN.x == 1.0f ? visibility_rect.Min.x : -FLT_MAX, def.CornerPosN.y == 1.0f ? visibility_rect.Min.y : -FLT_MAX);
ImVec2 clamp_max = ImVec2(def.CornerPosN.x == 0.0f ? visibility_rect.Max.x : +FLT_MAX, def.CornerPosN.y == 0.0f ? visibility_rect.Max.y : +FLT_MAX);
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(def.InnerDir * grip_hover_outer_size, def.InnerDir * -grip_hover_inner_size, def.CornerPosN); // Corner of the window corresponding to our corner grip
corner_target = ImClamp(corner_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, corner_target, def.CornerPosN, &pos_target, &size_target);
}
// Only lower-left grip is visible before hovering/activating
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 ImGuiResizeBorderDef& def = resize_border_def[border_n];
const ImGuiAxis axis = (border_n == ImGuiDir_Left || border_n == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_HOVER_PADDING);
ImGuiID border_id = window->GetID(border_n + 4); // == GetWindowResizeBorderID()
ButtonBehavior(border_rect, border_id, &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetForegroundDrawLists(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (axis == ImGuiAxis_X) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 clamp_min(border_n == ImGuiDir_Right ? visibility_rect.Min.x : -FLT_MAX, border_n == ImGuiDir_Down ? visibility_rect.Min.y : -FLT_MAX);
ImVec2 clamp_max(border_n == ImGuiDir_Left ? visibility_rect.Max.x : +FLT_MAX, border_n == ImGuiDir_Up ? visibility_rect.Max.y : +FLT_MAX);
ImVec2 border_target = window->Pos;
border_target[axis] = g.IO.MousePos[axis] - g.ActiveIdClickOffset[axis] + WINDOWS_HOVER_PADDING;
border_target = ImClamp(border_target, clamp_min, clamp_max);
CalcResizePosSizeFromAnyCorner(window, border_target, ImMin(def.SegmentN1, def.SegmentN2), &pos_target, &size_target);
}
}
PopID();
// Restore nav layer
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_Keyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_Gamepad)
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));
nav_resize_delta = ImMax(nav_resize_delta, visibility_rect.Min - window->Pos - window->Size);
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 = CalcWindowSizeAfterConstraint(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 = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
return ret_auto_fit;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& visibility_rect)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = window->Size;
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
size_for_clamping.y = window->TitleBarHeight();
window->Pos = ImClamp(window->Pos, visibility_rect.Min - size_for_clamping, visibility_rect.Max);
}
static void ImGui::RenderWindowOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, 0, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI * 0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.SegmentN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI * 0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), 0, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar))
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
// Draw background and borders
// Draw and handle scrollbars
void ImGui::RenderWindowDecorations(ImGuiWindow* window, const ImRect& title_bar_rect, bool title_bar_is_highlight, int resize_grip_count, const ImU32 resize_grip_col[4], float resize_grip_draw_size)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
// Ensure that ScrollBar doesn't read last frame's SkipItems
IM_ASSERT(window->BeginCount == 0);
window->SkipItems = false;
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
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
if (!(flags & ImGuiWindowFlags_NoBackground))
{
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
bool override_alpha = false;
float alpha = 1.0f;
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasBgAlpha)
{
alpha = g.NextWindowData.BgAlphaVal;
override_alpha = true;
}
if (override_alpha)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? 0 : ImDrawFlags_RoundCornersBottom);
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawFlags_RoundCornersTop);
}
// 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 + ImVec2(window_border_size, 0), menu_bar_rect.Max - ImVec2(window_border_size, 0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawFlags_RoundCornersTop);
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(ImGuiAxis_X);
if (window->ScrollbarY)
Scrollbar(ImGuiAxis_Y);
// 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.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, resize_grip_draw_size) : ImVec2(resize_grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(resize_grip_draw_size, window_border_size) : ImVec2(window_border_size, resize_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
RenderWindowOuterBorders(window);
}
}
// Render title text, collapse button, close button
void ImGui::RenderWindowTitleBarContents(ImGuiWindow* window, const ImRect& title_bar_rect, const char* name, bool* p_open)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
ImGuiWindowFlags flags = window->Flags;
const bool has_close_button = (p_open != NULL);
const bool has_collapse_button = !(flags & ImGuiWindowFlags_NoCollapse) && (style.WindowMenuButtonPosition != ImGuiDir_None);
// Close & Collapse button are on the Menu NavLayer and don't default focus (unless there's nothing else on that layer)
const ImGuiItemFlags item_flags_backup = g.CurrentItemFlags;
g.CurrentItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
// Layout buttons
// FIXME: Would be nice to generalize the subtleties expressed here into reusable code.
float pad_l = style.FramePadding.x;
float pad_r = style.FramePadding.x;
float button_sz = g.FontSize;
ImVec2 close_button_pos;
ImVec2 collapse_button_pos;
if (has_close_button)
{
pad_r += button_sz;
close_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Right)
{
pad_r += button_sz;
collapse_button_pos = ImVec2(title_bar_rect.Max.x - pad_r - style.FramePadding.x, title_bar_rect.Min.y);
}
if (has_collapse_button && style.WindowMenuButtonPosition == ImGuiDir_Left)
{
collapse_button_pos = ImVec2(title_bar_rect.Min.x + pad_l - style.FramePadding.x, title_bar_rect.Min.y);
pad_l += button_sz;
}
// Collapse button (submitting first so it gets priority when choosing a navigation init fallback)
if (has_collapse_button)
if (CollapseButton(window->GetID("#COLLAPSE"), collapse_button_pos))
window->WantCollapseToggle = true; // Defer actual collapsing to next frame as we are too far in the Begin() function
// Close button
if (has_close_button)
if (CloseButton(window->GetID("#CLOSE"), close_button_pos))
*p_open = false;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
g.CurrentItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is WAY too much messy code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
const float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
const ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
// As a nice touch we try to ensure that centered title text doesn't get affected by visibility of Close/Collapse button,
// while uncentered title text will still reach edges correctly.
if (pad_l > style.FramePadding.x)
pad_l += g.Style.ItemInnerSpacing.x;
if (pad_r > style.FramePadding.x)
pad_r += g.Style.ItemInnerSpacing.x;
if (style.WindowTitleAlign.x > 0.0f && style.WindowTitleAlign.x < 1.0f)
{
float centerness = ImSaturate(1.0f - ImFabs(style.WindowTitleAlign.x - 0.5f) * 2.0f); // 0.0f on either edges, 1.0f on center
float pad_extend = ImMin(ImMax(pad_l, pad_r), title_bar_rect.GetWidth() - pad_l - pad_r - text_size.x);
pad_l = ImMax(pad_l, pad_extend * centerness);
pad_r = ImMax(pad_r, pad_extend * centerness);
}
ImRect layout_r(title_bar_rect.Min.x + pad_l, title_bar_rect.Min.y, title_bar_rect.Max.x - pad_r, title_bar_rect.Max.y);
ImRect clip_r(layout_r.Min.x, layout_r.Min.y, ImMin(layout_r.Max.x + g.Style.ItemInnerSpacing.x, title_bar_rect.Max.x), layout_r.Max.y);
//if (g.IO.KeyShift) window->DrawList->AddRect(layout_r.Min, layout_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
//if (g.IO.KeyCtrl) window->DrawList->AddRect(clip_r.Min, clip_r.Max, IM_COL32(255, 128, 0, 255)); // [DEBUG]
RenderTextClipped(layout_r.Min, layout_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_r);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(layout_r.Min.x, layout_r.Min.x + (layout_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, layout_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, IM_FLOOR(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, layout_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_r);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
window->RootWindow = parent_window->RootWindow;
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new Dear 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 && name[0] != '\0'); // Window name required
IM_ASSERT(g.WithinFrameScope); // 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);
const bool window_just_created = (window == NULL);
if (window_just_created)
window = CreateNewWindow(name, flags);
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == 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);
window->IsFallbackWindow = (g.CurrentWindowStack.Size == 0 && g.WithinFrameScopeWithImplicitWindow);
// 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
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.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;
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->LastTimeActive = (float)g.Time;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// 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));
// We allow window memory to be compacted so recreate the base stack when needed.
if (window->IDStack.Size == 0)
window->IDStack.push_back(window->ID);
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = window;
window->DC.StackSizesOnBegin.SetToCurrentState();
g.CurrentWindow = NULL;
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupData& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
// Update ->RootWindow and others pointers (before any possible call to FocusWindow)
if (first_begin_of_the_frame)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
// Process SetNextWindow***() calls
// (FIXME: Consider splitting the HasXXX flags into X/Y components
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.Flags & ImGuiNextWindowDataFlags_HasPos)
{
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);
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasSize)
{
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);
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasScroll)
{
if (g.NextWindowData.ScrollVal.x >= 0.0f)
{
window->ScrollTarget.x = g.NextWindowData.ScrollVal.x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
if (g.NextWindowData.ScrollVal.y >= 0.0f)
{
window->ScrollTarget.y = g.NextWindowData.ScrollVal.y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
}
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasContentSize)
window->ContentSizeExplicit = g.NextWindowData.ContentSizeVal;
else if (first_begin_of_the_frame)
window->ContentSizeExplicit = ImVec2(0.0f, 0.0f);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasCollapsed)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasFocus)
FocusWindow(window);
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)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX, -FLT_MAX, +FLT_MAX, +FLT_MAX);
window->IDStack.resize(1);
window->DrawList->_ResetForNewFrame();
window->DC.CurrentTableIdx = -1;
// Restore buffer capacity when woken from a compacted state, to avoid
if (window->MemoryCompacted)
GcAwakeTransientWindowBuffers(window);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if (g.NavWindowingListWindow != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesCannotSkipItems > 0);
CalcWindowContentSizes(window, &window->ContentSize, &window->ContentSizeIdeal);
if (window->HiddenFramesCanSkipItems > 0)
window->HiddenFramesCanSkipItems--;
if (window->HiddenFramesCannotSkipItems > 0)
window->HiddenFramesCannotSkipItems--;
if (window->HiddenFramesForRenderOnly > 0)
window->HiddenFramesForRenderOnly--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesCannotSkipItems = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/ContentSize for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesCannotSkipItems = 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->ContentSize = window->ContentSizeIdeal = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
// FIXME-VIEWPORT: In the docking/viewport branch, this is the point where we select the current viewport (which may affect the style)
SetCurrentWindow(window);
// LOCK BORDER SIZE AND PADDING FOR THE FRAME (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(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);
// Lock menu offset so size calculation can use it as menu-bar windows need a minimum size.
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// 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))
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcWindowAutoFitSize(window, window->ContentSizeIdeal);
bool use_current_size_for_scrollbar_x = window_just_created;
bool use_current_size_for_scrollbar_y = window_just_created;
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_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api)
{
window->SizeFull.y = size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window 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 = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
use_current_size_for_scrollbar_x = true;
}
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
{
window->SizeFull.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
use_current_size_for_scrollbar_y = true;
}
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcWindowSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// Decoration size
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight();
// 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 && !(flags & ImGuiWindowFlags_Modal) && !window_pos_set_by_api) // FIXME: BeginPopup() could use SetNextWindowPos()
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)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 = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesCannotSkipItems == 0);
if (window_pos_with_pivot)
SetWindowPos(window, window->SetWindowPosVal - window->Size * window->SetWindowPosPivot, 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Calculate the range of allowed position for that window (to be movable and visible past safe area padding)
// When clamping to stay visible, we will enforce that window->Pos stays inside of visibility_rect.
ImGuiViewportP* viewport = (ImGuiViewportP*)(void*)GetMainViewport();
ImRect viewport_rect(viewport->GetMainRect());
ImRect viewport_work_rect(viewport->GetWorkRect());
ImVec2 visibility_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
ImRect visibility_rect(viewport_work_rect.Min + visibility_padding, viewport_work_rect.Max - visibility_padding);
// Clamp position/size so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (viewport_rect.GetWidth() > 0.0f && viewport_rect.GetHeight() > 0.0f)
ClampWindowRect(window, visibility_rect);
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
// Large values tend to lead to variety of artifacts and are not recommended.
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
// For windows with title bar or menu bar, we clamp to FrameHeight(FontSize + FramePadding.y * 2.0f) to completely hide artifacts.
//if ((window->Flags & ImGuiWindowFlags_MenuBar) || !(window->Flags & ImGuiWindowFlags_NoTitleBar))
// window->WindowRounding = ImMin(window->WindowRounding, g.FontSize + style.FramePadding.y * 2.0f);
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Tooltip)) == 0)
want_focus = true;
}
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = {};
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // Allow resize from lower-left if we have the mouse cursor feedback for it.
const float resize_grip_draw_size = IM_FLOOR(ImMax(g.FontSize * 1.10f, window->WindowRounding + 1.0f + g.FontSize * 0.2f));
if (!window->Collapsed)
if (UpdateWindowManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0], visibility_rect))
use_current_size_for_scrollbar_x = use_current_size_for_scrollbar_y = true;
window->ResizeBorderHeld = (signed char)border_held;
// SCROLLBAR VISIBILITY
// Update scrollbar visibility (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.
// When we use InnerRect here we are intentionally reading last frame size, same for ScrollbarSizes values before we set them again.
ImVec2 avail_size_from_current_frame = ImVec2(window->SizeFull.x, window->SizeFull.y - decoration_up_height);
ImVec2 avail_size_from_last_frame = window->InnerRect.GetSize() + window->ScrollbarSizes;
ImVec2 needed_size_from_last_frame = window_just_created ? ImVec2(0, 0) : window->ContentSize + window->WindowPadding * 2.0f;
float size_x_for_scrollbars = use_current_size_for_scrollbar_x ? avail_size_from_current_frame.x : avail_size_from_last_frame.x;
float size_y_for_scrollbars = use_current_size_for_scrollbar_y ? avail_size_from_current_frame.y : avail_size_from_last_frame.y;
//bool scrollbar_y_from_last_frame = window->ScrollbarY; // FIXME: May want to use that in the ScrollbarX expression? How many pros vs cons?
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((needed_size_from_last_frame.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (needed_size_from_last_frame.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// UPDATE RECTANGLES (1- THOSE NOT AFFECTED BY SCROLLING)
// Update various regions. Variables they depends on should be set above in this function.
// We set this up after processing the resize grip so that our rectangles doesn't lag by a frame.
// Outer rectangle
// Not affected by window border size. Used by:
// - FindHoveredWindow() (w/ extra padding when border resize is enabled)
// - Begin() initial clipping rect for drawing window background and borders.
// - Begin() clipping whole child
const ImRect host_rect = ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip) ? parent_window->ClipRect : viewport_rect;
const ImRect outer_rect = window->Rect();
const ImRect title_bar_rect = window->TitleBarRect();
window->OuterRectClipped = outer_rect;
window->OuterRectClipped.ClipWith(host_rect);
// Inner rectangle
// Not affected by window border size. Used by:
// - InnerClipRect
// - ScrollToBringRectIntoView()
// - NavUpdatePageUpPageDown()
// - Scrollbar()
window->InnerRect.Min.x = window->Pos.x;
window->InnerRect.Min.y = window->Pos.y + decoration_up_height;
window->InnerRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x;
window->InnerRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y;
// Inner clipping rectangle.
// Will extend a little bit outside the normal work region.
// This is to allow e.g. Selectable or CollapsingHeader or some separators to cover that space.
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
// Affected by window/frame border size. Used by:
// - Begin() initial clip rect
float top_border_size = (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerRect.Min.x + ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerRect.Min.y + top_border_size);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerRect.Max.x - ImMax(ImFloor(window->WindowPadding.x * 0.5f), window->WindowBorderSize));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerRect.Max.y - window->WindowBorderSize);
window->InnerClipRect.ClipWithFull(host_rect);
// 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 = ImFloor(window->Size.x * 0.65f);
else
window->ItemWidthDefault = ImFloor(g.FontSize * 16.0f);
// SCROLLING
// Lock down maximum scrolling
// The value of ScrollMax are ahead from ScrollbarX/ScrollbarY which is intentionally using InnerRect from previous rect in order to accommodate
// for right/bottom aligned items without creating a scrollbar.
window->ScrollMax.x = ImMax(0.0f, window->ContentSize.x + window->WindowPadding.x * 2.0f - window->InnerRect.GetWidth());
window->ScrollMax.y = ImMax(0.0f, window->ContentSize.y + window->WindowPadding.y * 2.0f - window->InnerRect.GetHeight());
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// DRAWING
// Setup draw list and outer clipping rectangle
IM_ASSERT(window->DrawList->CmdBuffer.Size == 1 && window->DrawList->CmdBuffer[0].ElemCount == 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
PushClipRect(host_rect.Min, host_rect.Max, false);
// Draw modal window background (darkens what is behind them, all viewports)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetTopMostPopupModal() && window->HiddenFramesCannotSkipItems <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && (window == g.NavWindowingTargetAnim->RootWindow);
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
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);
}
// Since 1.71, child window can render their decoration (bg color, border, scrollbars, etc.) within their parent to save a draw call.
// When using overlapping child windows, this will break the assumption that child z-order is mapped to submission order.
// We disable this when the parent window has zero vertices, which is a common pattern leading to laying out multiple overlapping child.
// We also disabled this when we have dimming overlay behind this specific one child.
// FIXME: More code may rely on explicit sorting of overlapping child window and would need to disable this somehow. Please get in contact if you are affected.
{
bool render_decorations_in_parent = false;
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
if (window->DrawList->CmdBuffer.back().ElemCount == 0 && parent_window->DrawList->VtxBuffer.Size > 0)
render_decorations_in_parent = true;
if (render_decorations_in_parent)
window->DrawList = parent_window->DrawList;
// Handle title bar, scrollbar, resize grips and resize borders
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight);
RenderWindowDecorations(window, title_bar_rect, title_bar_is_highlight, resize_grip_count, resize_grip_col, resize_grip_draw_size);
if (render_decorations_in_parent)
window->DrawList = &window->DrawListInst;
}
// Draw navigation selection/windowing rectangle border
if (g.NavWindowingTargetAnim == 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);
}
// UPDATE RECTANGLES (2- THOSE AFFECTED BY SCROLLING)
// Work rectangle.
// Affected by window padding and border size. Used by:
// - Columns() for right-most edge
// - TreeNode(), CollapsingHeader() for right-most edge
// - BeginTabBar() for right-most edge
const bool allow_scrollbar_x = !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar);
const bool allow_scrollbar_y = !(flags & ImGuiWindowFlags_NoScrollbar);
const float work_rect_size_x = (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : ImMax(allow_scrollbar_x ? window->ContentSize.x : 0.0f, window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
const float work_rect_size_y = (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : ImMax(allow_scrollbar_y ? window->ContentSize.y : 0.0f, window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - window->ScrollbarSizes.y));
window->WorkRect.Min.x = ImFloor(window->InnerRect.Min.x - window->Scroll.x + ImMax(window->WindowPadding.x, window->WindowBorderSize));
window->WorkRect.Min.y = ImFloor(window->InnerRect.Min.y - window->Scroll.y + ImMax(window->WindowPadding.y, window->WindowBorderSize));
window->WorkRect.Max.x = window->WorkRect.Min.x + work_rect_size_x;
window->WorkRect.Max.y = window->WorkRect.Min.y + work_rect_size_y;
window->ParentWorkRect = window->WorkRect;
// [LEGACY] Content Region
// FIXME-OBSOLETE: window->ContentRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
// Used by:
// - Mouse wheel scrolling + many other things
window->ContentRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + decoration_up_height;
window->ContentRegionRect.Max.x = window->ContentRegionRect.Min.x + (window->ContentSizeExplicit.x != 0.0f ? window->ContentSizeExplicit.x : (window->Size.x - window->WindowPadding.x * 2.0f - window->ScrollbarSizes.x));
window->ContentRegionRect.Max.y = window->ContentRegionRect.Min.y + (window->ContentSizeExplicit.y != 0.0f ? window->ContentSizeExplicit.y : (window->Size.y - window->WindowPadding.y * 2.0f - decoration_up_height - 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.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, decoration_up_height + 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.IdealMaxPos = window->DC.CursorStartPos;
window->DC.CurrLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayersActiveMask = window->DC.NavLayersActiveMaskNext;
window->DC.NavLayersActiveMaskNext = 0x00;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (window->ScrollMax.y > 0.0f);
window->DC.MenuBarAppending = false;
window->DC.MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
window->DC.TreeDepth = 0;
window->DC.TreeJumpToParentOnPopMask = 0x00;
window->DC.ChildWindows.resize(0);
window->DC.StateStorage = &window->StateStorage;
window->DC.CurrentColumns = NULL;
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.FocusCounterRegular = window->DC.FocusCounterTabStop = -1;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
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); // <-- this is in the way for us to be able to defer and sort reappearing FocusWindow() calls
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar))
RenderWindowTitleBarContents(window, ImRect(title_bar_rect.Min.x + window->WindowBorderSize, title_bar_rect.Min.y, title_bar_rect.Max.x - window->WindowBorderSize, title_bar_rect.Max.y), name, p_open);
// Clear hit test shape every frame
window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
// 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.NavWindow == window && g.ActiveId == 0)
if (g.ActiveId == window->MoveId)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// We fill last item data based on Title Bar/Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
SetLastItemData(window, window->MoveId, IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0, title_bar_rect);
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (!(window->Flags & ImGuiWindowFlags_NoTitleBar))
IMGUI_TEST_ENGINE_ITEM_ADD(window->DC.LastItemRect, window->DC.LastItemId);
#endif
}
else
{
// Append
SetCurrentWindow(window);
}
// Pull/inherit current state
g.CurrentItemFlags = g.ItemFlagsStack.back(); // Inherit from shared stack
window->DC.NavFocusScopeIdCurrent = (flags & ImGuiWindowFlags_ChildWindow) ? parent_window->DC.NavFocusScopeIdCurrent : 0; // Inherit from parent only // -V595
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)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.ClearFlags();
// Update visibility
if (first_begin_of_the_frame)
{
if (flags & ImGuiWindowFlags_ChildWindow)
{
// 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 them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0);
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0) // FIXME: Doesn't make sense for ChildWindow??
if (!g.LogEnabled)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesCanSkipItems = 1;
// Hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCanSkipItems > 0))
window->HiddenFramesCanSkipItems = 1;
if (parent_window && (parent_window->Collapsed || parent_window->HiddenFramesCannotSkipItems > 0))
window->HiddenFramesCannotSkipItems = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesCanSkipItems = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesCanSkipItems > 0) || (window->HiddenFramesCannotSkipItems > 0) || (window->HiddenFramesForRenderOnly > 0);
// Disable inputs for requested number of frames
if (window->DisableInputsFrames > 0)
{
window->DisableInputsFrames--;
window->Flags |= ImGuiWindowFlags_NoInputs;
}
// Update the SkipItems flag, used to early out of all items functions (no layout required)
bool skip_items = false;
if (window->Collapsed || !window->Active || window->Hidden)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesCannotSkipItems <= 0)
skip_items = true;
window->SkipItems = skip_items;
}
return !window->SkipItems;
}
void ImGui::End()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Error checking: verify that user hasn't called End() too many times!
if (g.CurrentWindowStack.Size <= 1 && g.WithinFrameScopeWithImplicitWindow)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size > 1, "Calling End() too many times!");
return;
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
// Error checking: verify that user doesn't directly call End() on a child window.
if (window->Flags & ImGuiWindowFlags_ChildWindow)
IM_ASSERT_USER_ERROR(g.WithinEndChild, "Must call EndChild() and not End()!");
// Close anything that is open
if (window->DC.CurrentColumns)
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.BeginPopupStack.pop_back();
window->DC.StackSizesOnBegin.CompareWithCurrentState();
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == window->RootWindow);
const int cur_order = window->FocusOrder;
IM_ASSERT(g.WindowsFocusOrder[cur_order] == window);
if (g.WindowsFocusOrder.back() == window)
return;
const int new_order = g.WindowsFocusOrder.Size - 1;
for (int n = cur_order; n < new_order; n++)
{
g.WindowsFocusOrder[n] = g.WindowsFocusOrder[n + 1];
g.WindowsFocusOrder[n]->FocusOrder--;
IM_ASSERT(g.WindowsFocusOrder[n]->FocusOrder == n);
}
g.WindowsFocusOrder[new_order] = window;
window->FocusOrder = (short)new_order;
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window) // Cheap early out (could be better)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the top-most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(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.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavFocusScopeId = 0;
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
g.NavInitRequest = g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Close popups if any
ClosePopupsOverWindow(window, false);
// Move the root window to the top of the pile
IM_ASSERT(window == NULL || window->RootWindow != NULL);
ImGuiWindow* focus_front_window = window ? window->RootWindow : NULL; // NB: In docking branch this is window->RootWindowDockStop
ImGuiWindow* display_front_window = window ? window->RootWindow : NULL;
// Steal active widgets. Some of the cases it triggers includes:
// - Focus a window while an InputText in another window is active, if focus happens before the old InputText can run.
// - When using Nav to activate menu items (due to timing of activating on press->new window appears->losing ActiveId)
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != focus_front_window)
if (!g.ActiveIdNoClearOnFocusLoss)
ClearActiveID();
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Bring to front
BringWindowToFocusFront(focus_front_window);
if (((window->Flags | display_front_window->Flags) & ImGuiWindowFlags_NoBringToFrontOnFocus) == 0)
BringWindowToDisplayFront(display_front_window);
}
void ImGui::FocusTopMostWindowUnderOne(ImGuiWindow* under_this_window, ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
const int start_idx = ((under_this_window != NULL) ? FindWindowFocusIndex(under_this_window) : g.WindowsFocusOrder.Size) - 1;
for (int i = start_idx; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
IM_ASSERT(window == window->RootWindow);
if (window != ignore_window && window->WasActive)
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
FocusWindow(NULL);
}
// Important: this alone doesn't alter current ImDrawList state. This is called by PushFont/PopFont only.
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 = ImMax(1.0f, 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.TexUvLines = atlas->TexUvLines;
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)
{
ImGuiContext& g = *GImGui;
ImGuiItemFlags item_flags = g.CurrentItemFlags;
IM_ASSERT(item_flags == g.ItemFlagsStack.back());
if (enabled)
item_flags |= option;
else
item_flags &= ~option;
g.CurrentItemFlags = item_flags;
g.ItemFlagsStack.push_back(item_flags);
}
void ImGui::PopItemFlag()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ItemFlagsStack.Size > 1); // Too many calls to PopItemFlag() - we always leave a 0 at the bottom of the stack.
g.ItemFlagsStack.pop_back();
g.CurrentItemFlags = g.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !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.TextWrapPosStack.push_back(window->DC.TextWrapPos);
window->DC.TextWrapPos = wrap_pos_x;
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.back();
window->DC.TextWrapPosStack.pop_back();
}
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::IsWindowAbove(ImGuiWindow* potential_above, ImGuiWindow* potential_below)
{
ImGuiContext& g = *GImGui;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* candidate_window = g.Windows[i];
if (candidate_window == potential_above)
return true;
if (candidate_window == potential_below)
return false;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (g.HoveredWindow == NULL)
return false;
if ((flags & ImGuiHoveredFlags_AnyWindow) == 0)
{
ImGuiWindow* window = g.CurrentWindow;
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow->RootWindow != window->RootWindow)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != window->RootWindow)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (!IsWindowChildOf(g.HoveredWindow, window))
return false;
break;
default:
if (g.HoveredWindow != window)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredWindow, 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;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
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)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmatically.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->WasActive && window == window->RootWindow && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
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;
}
void ImGui::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;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
ImVec2 offset = window->Pos - old_pos;
window->DC.CursorPos += offset; // 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 += offset; // And more importantly we need to offset CursorMaxPos/CursorStartPos this so ContentSize calculation doesn't get affected.
window->DC.IdealMaxPos += offset;
window->DC.CursorStartPos += offset;
}
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;
}
void ImGui::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;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = IM_FLOOR(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = IM_FLOOR(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);
}
void ImGui::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::SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
{
IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
window->HitTestHoleSize = ImVec2ih(size);
window->HitTestHoleOffset = ImVec2ih(pos - window->Pos);
}
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;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasPos;
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;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasSize;
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.Flags |= ImGuiNextWindowDataFlags_HasSizeConstraint;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
// Content size = inner scrollable rectangle, padded with WindowPadding.
// SetNextWindowContentSize(ImVec2(100,100) + ImGuiWindowFlags_AlwaysAutoResize will always allow submitting a 100x100 item.
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasContentSize;
g.NextWindowData.ContentSizeVal = ImFloor(size);
}
void ImGui::SetNextWindowScroll(const ImVec2& scroll)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasScroll;
g.NextWindowData.ScrollVal = scroll;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasCollapsed;
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasFocus;
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.Flags |= ImGuiNextWindowDataFlags_HasBgAlpha;
g.NextWindowData.BgAlphaVal = alpha;
}
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)
{
IM_ASSERT(scale > 0.0f);
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::PushFocusScope(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.FocusScopeStack.push_back(window->DC.NavFocusScopeIdCurrent);
window->DC.NavFocusScopeIdCurrent = id;
}
void ImGui::PopFocusScope()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.FocusScopeStack.Size > 0); // Too many PopFocusScope() ?
window->DC.NavFocusScopeIdCurrent = g.FocusScopeStack.back();
g.FocusScopeStack.pop_back();
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.TabFocusRequestNextWindow = window;
g.TabFocusRequestNextCounterRegular = window->DC.FocusCounterRegular + 1 + offset;
g.TabFocusRequestNextCounterTabStop = 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 == window->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = window->DC.LastItemId;
g.NavInitResultRectRel = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(str_id);
window->IDStack.push_back(id);
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(str_id_begin, str_id_end);
window->IDStack.push_back(id);
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(ptr_id);
window->IDStack.push_back(id);
}
void ImGui::PushID(int int_id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiID id = window->GetIDNoKeepAlive(int_id);
window->IDStack.push_back(id);
}
// Push a given id value ignoring the ID stack as a seed.
void ImGui::PushOverrideID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->IDStack.push_back(id);
}
// Helper to avoid a common series of PushOverrideID -> GetID() -> PopID() call
// (note that when using this pattern, TestEngine's "Stack Tool" will tend to not display the intermediate stack level.
// for that to work we would need to do PushOverrideID() -> ItemAdd() -> PopID() which would alter widget code a little more)
ImGuiID ImGui::GetIDWithSeed(const char* str, const char* str_end, ImGuiID seed)
{
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiContext& g = *GImGui;
IMGUI_TEST_ENGINE_ID_INFO2(id, ImGuiDataType_String, str, str_end);
#endif
return id;
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
IM_ASSERT(window->IDStack.Size > 1); // Too many PopID(), or could be popping in a wrong/different window?
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;
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 = GImGui->CurrentWindow;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
//-----------------------------------------------------------------------------
// [SECTION] ERROR CHECKING
//-----------------------------------------------------------------------------
// Helper function to verify ABI compatibility between caller code and compiled version of Dear ImGui.
// Verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. your user code
// may see different structures than what imgui.cpp sees, which is problematic.
// We usually require settings to be in imconfig.h to make sure that they are accessible to all compilation units involved with Dear ImGui.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert, size_t sz_idx)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION) != 0) { error = true; IM_ASSERT(strcmp(version, IMGUI_VERSION) == 0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
if (sz_idx != sizeof(ImDrawIdx)) { error = true; IM_ASSERT(sz_idx == sizeof(ImDrawIdx) && "Mismatched struct layout!"); }
return !error;
}
static void ImGui::ErrorCheckNewFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Check user IM_ASSERT macro
// (IF YOU GET A WARNING OR COMPILE ERROR HERE: it means your assert macro is incorrectly defined!
// If your macro uses multiple statements, it NEEDS to be surrounded by a 'do { ... } while (0)' block.
// This is a common C/C++ idiom to allow multiple statements macros to be used in control flow blocks.)
// #define IM_ASSERT(EXPR) if (SomeCode(EXPR)) SomeMoreCode(); // Wrong!
// #define IM_ASSERT(EXPR) do { if (SomeCode(EXPR)) SomeMoreCode(); } while (0) // Correct!
if (true) IM_ASSERT(1); else IM_ASSERT(0);
// Check user data
// (We pass an error message in the assert expression to make 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 || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
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.CircleTessellationMaxError > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting!"); // Allows us to avoid a few clamps in color computations
IM_ASSERT(g.Style.WindowMinSize.x >= 1.0f && g.Style.WindowMinSize.y >= 1.0f && "Invalid style setting.");
IM_ASSERT(g.Style.WindowMenuButtonPosition == ImGuiDir_None || g.Style.WindowMenuButtonPosition == ImGuiDir_Left || g.Style.WindowMenuButtonPosition == ImGuiDir_Right);
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)");
// Check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only 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.");
// Check: the io.ConfigWindowsResizeFromEdges option requires backend to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
}
static void ImGui::ErrorCheckEndFrameSanityChecks()
{
ImGuiContext& g = *GImGui;
// Verify that io.KeyXXX fields haven't been tampered with. Key mods should not be modified between NewFrame() and EndFrame()
// One possible reason leading to this assert is that your backends update inputs _AFTER_ NewFrame().
// It is known that when some modal native windows called mid-frame takes focus away, some backends such as GLFW will
// send key release events mid-frame. This would normally trigger this assertion and lead to sheared inputs.
// We silently accommodate for this case by ignoring/ the case where all io.KeyXXX modifiers were released (aka key_mod_flags == 0),
// while still correctly asserting on mid-frame key press events.
const ImGuiKeyModFlags key_mod_flags = GetMergedKeyModFlags();
IM_ASSERT((key_mod_flags == 0 || g.IO.KeyMods == key_mod_flags) && "Mismatching io.KeyCtrl/io.KeyShift/io.KeyAlt/io.KeySuper vs io.KeyMods");
IM_UNUSED(key_mod_flags);
// Recover from errors
//ErrorCheckEndFrameRecover();
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1)
End();
}
else
{
IM_ASSERT_USER_ERROR(g.CurrentWindowStack.Size == 1, "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
IM_ASSERT_USER_ERROR(g.GroupStack.Size == 0, "Missing EndGroup call!");
}
// Experimental recovery from incorrect usage of BeginXXX/EndXXX/PushXXX/PopXXX calls.
// Must be called during or before EndFrame().
// This is generally flawed as we are not necessarily End/Popping things in the right order.
// FIXME: Can't recover from inside BeginTabItem/EndTabItem yet.
// FIXME: Can't recover from interleaved BeginTabBar/Begin
void ImGui::ErrorCheckEndFrameRecover(ImGuiErrorLogCallback log_callback, void* user_data)
{
// PVS-Studio V1044 is "Loop break conditions do not depend on the number of iterations"
ImGuiContext& g = *GImGui;
while (g.CurrentWindowStack.Size > 0)
{
while (g.CurrentTable && (g.CurrentTable->OuterWindow == g.CurrentWindow || g.CurrentTable->InnerWindow == g.CurrentWindow))
{
if (log_callback) log_callback(user_data, "Recovered from missing EndTable() in '%s'", g.CurrentTable->OuterWindow->Name);
EndTable();
}
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window != NULL);
while (g.CurrentTabBar != NULL) //-V1044
{
if (log_callback) log_callback(user_data, "Recovered from missing EndTabBar() in '%s'", window->Name);
EndTabBar();
}
while (window->DC.TreeDepth > 0)
{
if (log_callback) log_callback(user_data, "Recovered from missing TreePop() in '%s'", window->Name);
TreePop();
}
while (g.GroupStack.Size > window->DC.StackSizesOnBegin.SizeOfGroupStack)
{
if (log_callback) log_callback(user_data, "Recovered from missing EndGroup() in '%s'", window->Name);
EndGroup();
}
while (window->IDStack.Size > 1)
{
if (log_callback) log_callback(user_data, "Recovered from missing PopID() in '%s'", window->Name);
PopID();
}
while (g.ColorStack.Size > window->DC.StackSizesOnBegin.SizeOfColorStack)
{
if (log_callback) log_callback(user_data, "Recovered from missing PopStyleColor() in '%s' for ImGuiCol_%s", window->Name, GetStyleColorName(g.ColorStack.back().Col));
PopStyleColor();
}
while (g.StyleVarStack.Size > window->DC.StackSizesOnBegin.SizeOfStyleVarStack)
{
if (log_callback) log_callback(user_data, "Recovered from missing PopStyleVar() in '%s'", window->Name);
PopStyleVar();
}
while (g.FocusScopeStack.Size > window->DC.StackSizesOnBegin.SizeOfFocusScopeStack)
{
if (log_callback) log_callback(user_data, "Recovered from missing PopFocusScope() in '%s'", window->Name);
PopFocusScope();
}
if (g.CurrentWindowStack.Size == 1)
{
IM_ASSERT(g.CurrentWindow->IsFallbackWindow);
break;
}
IM_ASSERT(window == g.CurrentWindow);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
{
if (log_callback) log_callback(user_data, "Recovered from missing EndChild() for '%s'", window->Name);
EndChild();
}
else
{
if (log_callback) log_callback(user_data, "Recovered from missing End() for '%s'", window->Name);
End();
}
}
}
// Save current stack sizes for later compare
void ImGuiStackSizes::SetToCurrentState()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
SizeOfIDStack = (short)window->IDStack.Size;
SizeOfColorStack = (short)g.ColorStack.Size;
SizeOfStyleVarStack = (short)g.StyleVarStack.Size;
SizeOfFontStack = (short)g.FontStack.Size;
SizeOfFocusScopeStack = (short)g.FocusScopeStack.Size;
SizeOfGroupStack = (short)g.GroupStack.Size;
SizeOfBeginPopupStack = (short)g.BeginPopupStack.Size;
}
// Compare to detect usage errors
void ImGuiStackSizes::CompareWithCurrentState()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_UNUSED(window);
// Window stacks
// NOT checking: DC.ItemWidth, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
IM_ASSERT(SizeOfIDStack == window->IDStack.Size && "PushID/PopID or TreeNode/TreePop Mismatch!");
// Global stacks
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
IM_ASSERT(SizeOfGroupStack == g.GroupStack.Size && "BeginGroup/EndGroup Mismatch!");
IM_ASSERT(SizeOfBeginPopupStack == g.BeginPopupStack.Size && "BeginPopup/EndPopup or BeginMenu/EndMenu Mismatch!");
IM_ASSERT(SizeOfColorStack >= g.ColorStack.Size && "PushStyleColor/PopStyleColor Mismatch!");
IM_ASSERT(SizeOfStyleVarStack >= g.StyleVarStack.Size && "PushStyleVar/PopStyleVar Mismatch!");
IM_ASSERT(SizeOfFontStack >= g.FontStack.Size && "PushFont/PopFont Mismatch!");
IM_ASSERT(SizeOfFocusScopeStack == g.FocusScopeStack.Size && "PushFocusScope/PopFocusScope Mismatch!");
}
//-----------------------------------------------------------------------------
// [SECTION] LAYOUT
//-----------------------------------------------------------------------------
// - ItemSize()
// - ItemAdd()
// - SameLine()
// - GetCursorScreenPos()
// - SetCursorScreenPos()
// - GetCursorPos(), GetCursorPosX(), GetCursorPosY()
// - SetCursorPos(), SetCursorPosX(), SetCursorPosY()
// - GetCursorStartPos()
// - Indent()
// - Unindent()
// - SetNextItemWidth()
// - PushItemWidth()
// - PushMultiItemsWidths()
// - PopItemWidth()
// - CalcItemWidth()
// - CalcItemSize()
// - GetTextLineHeight()
// - GetTextLineHeightWithSpacing()
// - GetFrameHeight()
// - GetFrameHeightWithSpacing()
// - GetContentRegionMax()
// - GetContentRegionMaxAbs() [Internal]
// - GetContentRegionAvail(),
// - GetWindowContentRegionMin(), GetWindowContentRegionMax()
// - GetWindowContentRegionWidth()
// - BeginGroup()
// - EndGroup()
// Also see in imgui_widgets: tab bars, columns.
//-----------------------------------------------------------------------------
// Advance cursor given item size for layout.
// Register minimum needed size so it can extend the bounding box used for auto-fit calculation.
// See comments in ItemAdd() about how/why the size provided to ItemSize() vs ItemAdd() may often different.
void ImGui::ItemSize(const ImVec2& size, float text_baseline_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// We increase the height in this function to accommodate for baseline offset.
// In theory we should be offsetting the starting position (window->DC.CursorPos), that will be the topic of a larger refactor,
// but since ItemSize() is not yet an API that moves the cursor (to handle e.g. wrapping) enlarging the height has the same effect.
const float offset_to_match_baseline_y = (text_baseline_y >= 0) ? ImMax(0.0f, window->DC.CurrLineTextBaseOffset - text_baseline_y) : 0.0f;
const float line_height = ImMax(window->DC.CurrLineSize.y, size.y + offset_to_match_baseline_y);
// Always align ourselves on pixel boundaries
//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.x = window->DC.CursorPos.x + size.x;
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y;
window->DC.CursorPos.x = IM_FLOOR(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x); // Next line
window->DC.CursorPos.y = IM_FLOOR(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y); // Next line
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.PrevLineSize.y = line_height;
window->DC.CurrLineSize.y = 0.0f;
window->DC.PrevLineTextBaseOffset = ImMax(window->DC.CurrLineTextBaseOffset, text_baseline_y);
window->DC.CurrLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_baseline_y)
{
ItemSize(bb.GetSize(), text_baseline_y);
}
// 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 provide a larger region to ItemAdd() which is used drawing/interaction.
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg, ImGuiItemAddFlags flags)
{
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).
// We intentionally don't check if g.NavWindow != NULL because g.NavAnyRequest should only be set when it is non null.
// If we crash on a NULL g.NavWindow we need to fix the bug elsewhere.
window->DC.NavLayersActiveMaskNext |= (1 << window->DC.NavLayerCurrent);
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);
// [DEBUG] Item Picker tool, when enabling the "extended" version we perform the check in ItemAdd()
#ifdef IMGUI_DEBUG_TOOL_ITEM_PICKER_EX
if (id == g.DebugItemPickerBreakId)
{
IM_DEBUG_BREAK();
g.DebugItemPickerBreakId = 0;
}
#endif
}
// Equivalent to calling SetLastItemData()
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
g.NextItemData.Flags = ImGuiNextItemDataFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
IMGUI_TEST_ENGINE_ITEM_ADD(nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// 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]
// Tab stop handling (previously was using internal ItemFocusable() api)
// FIXME-NAV: We would now want to move this above the clipping test, but this would require being able to scroll and currently this would mean an extra frame. (#4079, #343)
if (flags & ImGuiItemAddFlags_Focusable)
ItemFocusable(window, id);
// 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;
}
// Gets back to previous line and continue with horizontal layout
// offset_from_start_x == 0 : follow right after previous item
// offset_from_start_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 offset_from_start_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (offset_from_start_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + offset_from_start_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
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.CurrLineSize = window->DC.PrevLineSize;
window->DC.CurrLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
// 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;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
// Affect large frame+labels widgets only.
void ImGui::SetNextItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
g.NextItemData.Flags |= ImGuiNextItemDataFlags_HasWidth;
g.NextItemData.Width = item_width;
}
// FIXME: Remove the == 0.0f behavior?
void ImGui::PushItemWidth(float item_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiStyle& style = g.Style;
const float w_item_one = ImMax(1.0f, IM_FLOOR((w_full - (style.ItemInnerSpacing.x) * (components - 1)) / (float)components));
const float w_item_last = ImMax(1.0f, IM_FLOOR(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components - 1)));
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth); // Backup current width
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components - 2; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = (components == 1) ? w_item_last : w_item_one;
g.NextItemData.Flags &= ~ImGuiNextItemDataFlags_HasWidth;
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
window->DC.ItemWidthStack.pop_back();
}
// Calculate default item width given value passed to PushItemWidth() or SetNextItemWidth().
// The SetNextItemWidth() data is generally cleared/consumed by ItemAdd() or NextItemData.ClearFlags()
float ImGui::CalcItemWidth()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float w;
if (g.NextItemData.Flags & ImGuiNextItemDataFlags_HasWidth)
w = g.NextItemData.Width;
else
w = window->DC.ItemWidth;
if (w < 0.0f)
{
float region_max_x = GetContentRegionMaxAbs().x;
w = ImMax(1.0f, region_max_x - window->DC.CursorPos.x + w);
}
w = IM_FLOOR(w);
return w;
}
// [Internal] Calculate full item size given user provided 'size' parameter and default width/height. Default width is often == CalcItemWidth().
// Those two functions CalcItemWidth vs CalcItemSize are awkwardly named because they are not fully symmetrical.
// Note that only CalcItemWidth() is publicly exposed.
// The 4.0f here may be changed to match CalcItemWidth() and/or BeginChild() (right now we have a mismatch which is harmless but undesirable)
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_w, float default_h)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImVec2 region_max;
if (size.x < 0.0f || size.y < 0.0f)
region_max = GetContentRegionMaxAbs();
if (size.x == 0.0f)
size.x = default_w;
else if (size.x < 0.0f)
size.x = ImMax(4.0f, region_max.x - window->DC.CursorPos.x + size.x);
if (size.y == 0.0f)
size.y = default_h;
else if (size.y < 0.0f)
size.y = ImMax(4.0f, region_max.y - window->DC.CursorPos.y + size.y);
return size;
}
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;
}
// FIXME: All the Contents Region function are messy or misleading. WE WILL AIM TO OBSOLETE ALL OF THEM WITH A NEW "WORK RECT" API. Thanks for your patience!
// FIXME: This is in window space (not screen space!).
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max - window->Pos;
if (window->DC.CurrentColumns || g.CurrentTable)
mx.x = window->WorkRect.Max.x - window->Pos.x;
return mx;
}
// [Internal] Absolute coordinate. Saner. This is not exposed until we finishing refactoring work rect features.
ImVec2 ImGui::GetContentRegionMaxAbs()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 mx = window->ContentRegionRect.Max;
if (window->DC.CurrentColumns || g.CurrentTable)
mx.x = window->WorkRect.Max.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetContentRegionMaxAbs() - window->DC.CursorPos;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ContentRegionRect.GetWidth();
}
// 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.)
// Groups are currently a mishmash of functionalities which should perhaps be clarified and separated.
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
g.GroupStack.resize(g.GroupStack.Size + 1);
ImGuiGroupData& group_data = g.GroupStack.back();
group_data.WindowID = window->ID;
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrLineSize = window->DC.CurrLineSize;
group_data.BackupCurrLineTextBaseOffset = window->DC.CurrLineTextBaseOffset;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupHoveredIdIsAlive = g.HoveredId != 0;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.EmitItem = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrLineSize = ImVec2(0.0f, 0.0f);
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.GroupStack.Size > 0); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = g.GroupStack.back();
IM_ASSERT(group_data.WindowID == window->ID); // EndGroup() in wrong window?
ImRect group_bb(group_data.BackupCursorPos, ImMax(window->DC.CursorMaxPos, group_data.BackupCursorPos));
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrLineSize = group_data.BackupCurrLineSize;
window->DC.CurrLineTextBaseOffset = group_data.BackupCurrLineTextBaseOffset;
if (g.LogEnabled)
g.LogLinePosY = -FLT_MAX; // To enforce a carriage return
if (!group_data.EmitItem)
{
g.GroupStack.pop_back();
return;
}
window->DC.CurrLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrLineTextBaseOffset); // 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());
ItemAdd(group_bb, 0);
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// Also if you grep for LastItemId you'll notice it is only used in that context.
// (The two tests not the same because ActiveIdIsAlive is an ID itself, in order to be able to handle ActiveId being overwritten during the frame.)
const bool group_contains_curr_active_id = (group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId;
const bool group_contains_prev_active_id = (group_data.BackupActiveIdPreviousFrameIsAlive == false) && (g.ActiveIdPreviousFrameIsAlive == true);
if (group_contains_curr_active_id)
window->DC.LastItemId = g.ActiveId;
else if (group_contains_prev_active_id)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
// Forward Hovered flag
const bool group_contains_curr_hovered_id = (group_data.BackupHoveredIdIsAlive == false) && g.HoveredId != 0;
if (group_contains_curr_hovered_id)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredWindow;
// Forward Edited flag
if (group_contains_curr_active_id && g.ActiveIdHasBeenEditedThisFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
// Forward Deactivated flag
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HasDeactivated;
if (group_contains_prev_active_id && g.ActiveId != g.ActiveIdPreviousFrame)
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Deactivated;
g.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
//-----------------------------------------------------------------------------
// [SECTION] SCROLLING
//-----------------------------------------------------------------------------
// Helper to snap on edges when aiming at an item very close to the edge,
// So the difference between WindowPadding and ItemSpacing will be in the visible area after scrolling.
// When we refactor the scrolling API this may be configurable with a flag?
// Note that the effect for this won't be visible on X axis with default Style settings as WindowPadding.x == ItemSpacing.x by default.
static float CalcScrollEdgeSnap(float target, float snap_min, float snap_max, float snap_threshold, float center_ratio)
{
if (target <= snap_min + snap_threshold)
return ImLerp(snap_min, target, center_ratio);
if (target >= snap_max - snap_threshold)
return ImLerp(target, snap_max, center_ratio);
return target;
}
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window)
{
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float decoration_total_width = window->ScrollbarSizes.x;
float center_x_ratio = window->ScrollTargetCenterRatio.x;
float scroll_target_x = window->ScrollTarget.x;
if (window->ScrollTargetEdgeSnapDist.x > 0.0f)
{
float snap_x_min = 0.0f;
float snap_x_max = window->ScrollMax.x + window->SizeFull.x - decoration_total_width;
scroll_target_x = CalcScrollEdgeSnap(scroll_target_x, snap_x_min, snap_x_max, window->ScrollTargetEdgeSnapDist.x, center_x_ratio);
}
scroll.x = scroll_target_x - center_x_ratio * (window->SizeFull.x - decoration_total_width);
}
if (window->ScrollTarget.y < FLT_MAX)
{
float decoration_total_height = window->TitleBarHeight() + window->MenuBarHeight() + window->ScrollbarSizes.y;
float center_y_ratio = window->ScrollTargetCenterRatio.y;
float scroll_target_y = window->ScrollTarget.y;
if (window->ScrollTargetEdgeSnapDist.y > 0.0f)
{
float snap_y_min = 0.0f;
float snap_y_max = window->ScrollMax.y + window->SizeFull.y - decoration_total_height;
scroll_target_y = CalcScrollEdgeSnap(scroll_target_y, snap_y_min, snap_y_max, window->ScrollTargetEdgeSnapDist.y, center_y_ratio);
}
scroll.y = scroll_target_y - center_y_ratio * (window->SizeFull.y - decoration_total_height);
}
scroll.x = IM_FLOOR(ImMax(scroll.x, 0.0f));
scroll.y = IM_FLOOR(ImMax(scroll.y, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, window->ScrollMax.x);
scroll.y = ImMin(scroll.y, window->ScrollMax.y);
}
return scroll;
}
// Scroll to keep newly navigated item fully into view
ImVec2 ImGui::ScrollToBringRectIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImGuiContext& g = *GImGui;
ImRect window_rect(window->InnerRect.Min - ImVec2(1, 1), window->InnerRect.Max + ImVec2(1, 1));
//GetForegroundDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
ImVec2 delta_scroll;
if (!window_rect.Contains(item_rect))
{
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
SetScrollFromPosX(window, item_rect.Min.x - window->Pos.x - g.Style.ItemSpacing.x, 0.0f);
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
SetScrollFromPosX(window, item_rect.Max.x - window->Pos.x + g.Style.ItemSpacing.x, 1.0f);
if (item_rect.Min.y < window_rect.Min.y)
SetScrollFromPosY(window, item_rect.Min.y - window->Pos.y - g.Style.ItemSpacing.y, 0.0f);
else if (item_rect.Max.y >= window_rect.Max.y)
SetScrollFromPosY(window, item_rect.Max.y - window->Pos.y + g.Style.ItemSpacing.y, 1.0f);
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(window);
delta_scroll = next_scroll - window->Scroll;
}
// Also scroll parent window to keep us into view if necessary
if (window->Flags & ImGuiWindowFlags_ChildWindow)
delta_scroll += ScrollToBringRectIntoView(window->ParentWindow, ImRect(item_rect.Min - delta_scroll, item_rect.Max - delta_scroll));
return delta_scroll;
}
float ImGui::GetScrollX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.x;
}
float ImGui::GetScrollY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.x;
}
float ImGui::GetScrollMaxY()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->ScrollMax.y;
}
void ImGui::SetScrollX(ImGuiWindow* window, float scroll_x)
{
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
window->ScrollTargetEdgeSnapDist.x = 0.0f;
}
void ImGui::SetScrollY(ImGuiWindow* window, float scroll_y)
{
window->ScrollTarget.y = scroll_y;
window->ScrollTargetCenterRatio.y = 0.0f;
window->ScrollTargetEdgeSnapDist.y = 0.0f;
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiContext& g = *GImGui;
SetScrollX(g.CurrentWindow, scroll_x);
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiContext& g = *GImGui;
SetScrollY(g.CurrentWindow, scroll_y);
}
// Note that a local position will vary depending on initial scroll value,
// This is a little bit confusing so bear with us:
// - local_pos = (absolution_pos - window->Pos)
// - So local_x/local_y are 0.0f for a position at the upper-left corner of a window,
// and generally local_x/local_y are >(padding+decoration) && <(size-padding-decoration) when in the visible area.
// - They mostly exists because of legacy API.
// Following the rules above, when trying to work with scrolling code, consider that:
// - SetScrollFromPosY(0.0f) == SetScrollY(0.0f + scroll.y) == has no effect!
// - SetScrollFromPosY(-scroll.y) == SetScrollY(-scroll.y + scroll.y) == SetScrollY(0.0f) == reset scroll. Of course writing SetScrollY(0.0f) directly then makes more sense
// We store a target position so centering and clamping can occur on the next frame when we are guaranteed to have a known window size
void ImGui::SetScrollFromPosX(ImGuiWindow* window, float local_x, float center_x_ratio)
{
IM_ASSERT(center_x_ratio >= 0.0f && center_x_ratio <= 1.0f);
window->ScrollTarget.x = IM_FLOOR(local_x + window->Scroll.x); // Convert local position to scroll offset
window->ScrollTargetCenterRatio.x = center_x_ratio;
window->ScrollTargetEdgeSnapDist.x = 0.0f;
}
void ImGui::SetScrollFromPosY(ImGuiWindow* window, float local_y, float center_y_ratio)
{
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
const float decoration_up_height = window->TitleBarHeight() + window->MenuBarHeight(); // FIXME: Would be nice to have a more standardized access to our scrollable/client rect;
local_y -= decoration_up_height;
window->ScrollTarget.y = IM_FLOOR(local_y + window->Scroll.y); // Convert local position to scroll offset
window->ScrollTargetCenterRatio.y = center_y_ratio;
window->ScrollTargetEdgeSnapDist.y = 0.0f;
}
void ImGui::SetScrollFromPosX(float local_x, float center_x_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosX(g.CurrentWindow, local_x, center_x_ratio);
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
ImGuiContext& g = *GImGui;
SetScrollFromPosY(g.CurrentWindow, local_y, center_y_ratio);
}
// center_x_ratio: 0.0f left of last item, 0.5f horizontal center of last item, 1.0f right of last item.
void ImGui::SetScrollHereX(float center_x_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float spacing_x = ImMax(window->WindowPadding.x, g.Style.ItemSpacing.x);
float target_pos_x = ImLerp(window->DC.LastItemRect.Min.x - spacing_x, window->DC.LastItemRect.Max.x + spacing_x, center_x_ratio);
SetScrollFromPosX(window, target_pos_x - window->Pos.x, center_x_ratio); // Convert from absolute to local pos
// Tweak: snap on edges when aiming at an item very close to the edge
window->ScrollTargetEdgeSnapDist.x = ImMax(0.0f, window->WindowPadding.x - spacing_x);
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float spacing_y = ImMax(window->WindowPadding.y, g.Style.ItemSpacing.y);
float target_pos_y = ImLerp(window->DC.CursorPosPrevLine.y - spacing_y, window->DC.CursorPosPrevLine.y + window->DC.PrevLineSize.y + spacing_y, center_y_ratio);
SetScrollFromPosY(window, target_pos_y - window->Pos.y, center_y_ratio); // Convert from absolute to local pos
// Tweak: snap on edges when aiming at an item very close to the edge
window->ScrollTargetEdgeSnapDist.y = ImMax(0.0f, window->WindowPadding.y - spacing_y);
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
BeginTooltipEx(ImGuiWindowFlags_None, ImGuiTooltipFlags_None);
}
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, ImGuiTooltipFlags tooltip_flags)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSource || g.DragDropWithinTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
tooltip_flags |= ImGuiTooltipFlags_OverridePreviousTooltip;
}
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (tooltip_flags & ImGuiTooltipFlags_OverridePreviousTooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesCanSkipItems = 1; // FIXME: This may not be necessary?
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;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
BeginTooltipEx(0, ImGuiTooltipFlags_OverridePreviousTooltip);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
// Supported flags: ImGuiPopupFlags_AnyPopupId, ImGuiPopupFlags_AnyPopupLevel
bool ImGui::IsPopupOpen(ImGuiID id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
if (popup_flags & ImGuiPopupFlags_AnyPopupId)
{
// Return true if any popup is open at the current BeginPopup() level of the popup stack
// This may be used to e.g. test for another popups already opened to handle popups priorities at the same level.
IM_ASSERT(id == 0);
if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
return g.OpenPopupStack.Size > 0;
else
return g.OpenPopupStack.Size > g.BeginPopupStack.Size;
}
else
{
if (popup_flags & ImGuiPopupFlags_AnyPopupLevel)
{
// Return true if the popup is open anywhere in the popup stack
for (int n = 0; n < g.OpenPopupStack.Size; n++)
if (g.OpenPopupStack[n].PopupId == id)
return true;
return false;
}
else
{
// Return true if the popup is open at the current BeginPopup() level of the popup stack (this is the most-common query)
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
}
}
bool ImGui::IsPopupOpen(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
ImGuiID id = (popup_flags & ImGuiPopupFlags_AnyPopupId) ? 0 : g.CurrentWindow->GetID(str_id);
if ((popup_flags & ImGuiPopupFlags_AnyPopupLevel) && id != 0)
IM_ASSERT(0 && "Cannot use IsPopupOpen() with a string id and ImGuiPopupFlags_AnyPopupLevel."); // But non-string version is legal and used internally
return IsPopupOpen(id, popup_flags);
}
ImGuiWindow* ImGui::GetTopMostPopupModal()
{
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;
}
void ImGui::OpenPopup(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id), popup_flags);
}
void ImGui::OpenPopup(ImGuiID id, ImGuiPopupFlags popup_flags)
{
OpenPopupEx(id, popup_flags);
}
// 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, ImGuiPopupFlags popup_flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
const int current_stack_size = g.BeginPopupStack.Size;
if (popup_flags & ImGuiPopupFlags_NoOpenOverExistingPopup)
if (IsPopupOpen(0u, ImGuiPopupFlags_AnyPopupId))
return;
ImGuiPopupData 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.SourceWindow = g.NavWindow;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
IMGUI_DEBUG_LOG_POPUP("OpenPopupEx(0x%08X)\n", id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// 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
{
// Close child popups if any, then flag popup for open/reopen
ClosePopupToLevel(current_stack_size, false);
g.OpenPopupStack.push_back(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);
}
}
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// This function closes any popups that are over 'ref_window'.
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size == 0)
return;
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupData& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack unless the popup is a direct parent of the reference window (the reference window is often the NavWindow)
// - With this stack of window, clicking/focusing Popup1 will close Popup2 and Popup3:
// Window -> Popup1 -> Popup2 -> Popup3
// - Each popups may contain child windows, which is why we compare ->RootWindow!
// Window -> Popup1 -> Popup1_Child -> Popup2 -> Popup2_Child
bool ref_window_is_descendent_of_popup = false;
for (int n = popup_count_to_keep; n < g.OpenPopupStack.Size; n++)
if (ImGuiWindow* popup_window = g.OpenPopupStack[n].Window)
if (popup_window->RootWindow == ref_window->RootWindow)
{
ref_window_is_descendent_of_popup = true;
break;
}
if (!ref_window_is_descendent_of_popup)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
IMGUI_DEBUG_LOG_POPUP("ClosePopupsOverWindow(\"%s\") -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, restore_focus_to_window_under_popup);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool restore_focus_to_window_under_popup)
{
ImGuiContext& g = *GImGui;
IMGUI_DEBUG_LOG_POPUP("ClosePopupToLevel(%d), restore_focus_to_window_under_popup=%d\n", remaining, restore_focus_to_window_under_popup);
IM_ASSERT(remaining >= 0 && remaining < g.OpenPopupStack.Size);
// Trim open popup stack
ImGuiWindow* focus_window = g.OpenPopupStack[remaining].SourceWindow;
ImGuiWindow* popup_window = g.OpenPopupStack[remaining].Window;
g.OpenPopupStack.resize(remaining);
if (restore_focus_to_window_under_popup)
{
if (focus_window && !focus_window->WasActive && popup_window)
{
// Fallback
FocusTopMostWindowUnderOne(popup_window, NULL);
}
else
{
if (g.NavLayer == ImGuiNavLayer_Main && focus_window)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
IMGUI_DEBUG_LOG_POPUP("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
// Attention! BeginPopup() adds default flags which BeginPopupEx()!
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.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
flags |= ImGuiWindowFlags_Popup;
bool is_open = Begin(name, NULL, flags);
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.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by Dear ImGui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
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, ImGuiPopupFlags_None))
{
g.NextWindowData.ClearFlags(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default for increased visibility
// (this won't really last as settings will kick in, and is mostly for backward compatibility. user may do the same themselves)
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if ((g.NextWindowData.Flags & ImGuiNextWindowDataFlags_HasPos) == 0)
{
const ImGuiViewport* viewport = GetMainViewport();
SetNextWindowPos(viewport->GetCenter(), ImGuiCond_FirstUseEver, ImVec2(0.5f, 0.5f));
}
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse;
const bool is_open = Begin(name, p_open, flags);
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)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
if (g.NavWindow == window)
NavMoveRequestTryWrapping(window, ImGuiNavMoveFlags_LoopY);
// Child-popups don't need to be laid out
IM_ASSERT(g.WithinEndChild == false);
if (window->Flags & ImGuiWindowFlags_ChildWindow)
g.WithinEndChild = true;
End();
g.WithinEndChild = false;
}
// Helper to open a popup if mouse button is released over the item
// - This is essentially the same as BeginPopupContextItem() but without the trailing BeginPopup()
void ImGui::OpenPopupOnItemClick(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
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); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id, popup_flags);
}
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// - To create a popup associated to the last item, you generally want to pass a NULL value to str_id.
// - To create a popup with a specific identifier, pass it in str_id.
// - This is useful when using using BeginPopupContextItem() on an item which doesn't have an identifier, e.g. a Text() call.
// - This is useful when multiple code locations may want to manipulate/open the same popup, given an explicit id.
// - You may want to handle the whole on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// This is essentially the same as:
// id = str_id ? GetID(str_id) : GetItemID();
// OpenPopupOnItemClick(str_id);
// return BeginPopup(id);
// Which is essentially the same as:
// id = str_id ? GetID(str_id) : GetItemID();
// if (IsItemHovered() && IsMouseReleased(ImGuiMouseButton_Right))
// OpenPopup(id);
// return BeginPopup(id);
// The main difference being that this is tweaked to avoid computing the ID twice.
bool ImGui::BeginPopupContextItem(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (window->SkipItems)
return false;
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); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "window_context";
ImGuiID id = window->GetID(str_id);
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (!(popup_flags & ImGuiPopupFlags_NoOpenOverItems) || !IsAnyItemHovered())
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, ImGuiPopupFlags popup_flags)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (!str_id)
str_id = "void_context";
ImGuiID id = window->GetID(str_id);
int mouse_button = (popup_flags & ImGuiPopupFlags_MouseButtonMask_);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
if (GetTopMostPopupModal() == NULL)
OpenPopupEx(id, popup_flags);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings);
}
// 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.
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
// this allows us to have tooltips/popups displayed out of the parent viewport.)
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GetForegroundDrawList()->AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GetForegroundDrawList()->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;
}
}
// Tooltip and Default popup policy
// (Always first try the direction we used on the last frame, if any)
if (policy == ImGuiPopupPositionPolicy_Tooltip || policy == ImGuiPopupPositionPolicy_Default)
{
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;
const 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);
const 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 there not enough room on one axis, there's no point in positioning on a side on this axis (e.g. when not enough width, use a top/bottom position to maximize available width)
if (avail_w < size.x && (dir == ImGuiDir_Left || dir == ImGuiDir_Right))
continue;
if (avail_h < size.y && (dir == ImGuiDir_Up || dir == ImGuiDir_Down))
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;
// Clamp top-left corner of popup
pos.x = ImMax(pos.x, r_outer.Min.x);
pos.y = ImMax(pos.y, r_outer.Min.y);
*last_dir = dir;
return pos;
}
}
// Fallback when not enough room:
*last_dir = ImGuiDir_None;
// For tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
if (policy == ImGuiPopupPositionPolicy_Tooltip)
return ref_pos + ImVec2(2, 2);
// Otherwise try to keep within display
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;
}
// Note that this is used for popups, which can overlap the non work-area of individual viewports.
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_UNUSED(window);
ImRect r_screen = ((ImGuiViewportP*)(void*)GetMainViewport())->GetMainRect();
ImVec2 padding = g.Style.DisplaySafeAreaPadding;
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_outer = GetWindowAllowedExtentRect(window);
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we 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(g.CurrentWindow == window);
ImGuiWindow* parent_window = g.CurrentWindowStack[g.CurrentWindowStack.Size - 2];
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->ClipRect.Min.y, FLT_MAX, parent_window->ClipRect.Max.y); // Avoid parent menu-bar. If we wanted multi-line menu-bar, we may instead want to have the calling window setup e.g. a NextWindowData.PosConstraintAvoidRect field
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Default);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_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.
return FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid, ImGuiPopupPositionPolicy_Tooltip);
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
// FIXME-NAV: The existence of SetNavID vs SetFocusID properly needs to be clarified/reworked.
void ImGui::SetNavID(ImGuiID id, ImGuiNavLayer nav_layer, ImGuiID focus_scope_id, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow != NULL);
IM_ASSERT(nav_layer == ImGuiNavLayer_Main || nav_layer == ImGuiNavLayer_Menu);
g.NavId = id;
g.NavLayer = nav_layer;
g.NavFocusScopeId = focus_scope_id;
g.NavWindow->NavLastIds[nav_layer] = id;
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
//g.NavDisableHighlight = false;
//g.NavDisableMouseHover = g.NavMousePosDirty = true;
}
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its window->DC.NavLayerCurrent and window->DC.NavFocusScopeIdCurrent are valid.
// Note that window may be != g.CurrentWindow (e.g. SetFocusID call in InputTextEx for multi-line text)
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavWindow = window;
g.NavId = id;
g.NavLayer = nav_layer;
g.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
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;
}
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for gamepad/keyboard directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool ImGui::NavScoreItem(ImGuiNavItemData* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRect; // 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++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Overlaps(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// 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 = ImFabs(dbx) + ImFabs(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 = ImFabs(dcx) + ImFabs(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 = ImGetDirQuadrantFromDelta(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 = ImGetDirQuadrantFromDelta(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 (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]);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max - ImVec2(4, 4), cand.Max + CalcTextSize(buf) + ImVec2(4, 4), IM_COL32(40,0,0,150));
draw_list->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);
ImDrawList* draw_list = GetForegroundDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->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 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 == ImGuiNavLayer_Menu && !(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 ImGui::NavApplyItemToResult(ImGuiNavItemData* result, ImGuiWindow* window, ImGuiID id, const ImRect& nav_bb_rel)
{
result->Window = window;
result->ID = id;
result->FocusScopeId = window->DC.NavFocusScopeIdCurrent;
result->RectRel = nav_bb_rel;
}
// 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 = g.CurrentItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
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();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & (ImGuiItemFlags_Disabled | ImGuiItemFlags_NoNav)))
{
ImGuiNavItemData* 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)
NavApplyItemToResult(result, window, id, nav_bb_rel);
// Features like PageUp/PageDown need to maintain a separate score for the visible set of items.
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
NavApplyItemToResult(&g.NavMoveResultLocalVisibleSet, window, id, 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.NavFocusScopeId = window->DC.NavFocusScopeIdCurrent;
g.NavIdIsAlive = true;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::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();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
// Navigation wrap-around logic is delayed to the end of the frame because this operation is only valid after entire
// popup is assembled and in case of appended popups it is not clear which EndPopup() call is final.
g.NavWrapRequestWindow = window;
g.NavWrapRequestFlags = move_flags;
}
// FIXME: This could be replaced by updating a frame number in each window when (window == NavWindow) and (NavLayer == 0).
// This way we could find the last focused window among our children. It would be much less confusing this way?
static void ImGui::NavSaveLastChildNavWindowIntoParent(ImGuiWindow* nav_window)
{
ImGuiWindow* parent = nav_window;
while (parent && parent->RootWindow != parent && (parent->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent = parent->ParentWindow;
if (parent && parent != nav_window)
parent->NavLastChildNavWindow = nav_window;
}
// Restore the last focused child.
// Call when we are expected to land on the Main Layer (0) after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
if (window->NavLastChildNavWindow && window->NavLastChildNavWindow->WasActive)
return window->NavLastChildNavWindow;
return window;
}
void ImGui::NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
if (layer == ImGuiNavLayer_Main)
g.NavWindow = NavRestoreLastChildNavWindow(g.NavWindow);
ImGuiWindow* window = g.NavWindow;
if (window->NavLastIds[layer] != 0)
{
SetNavID(window->NavLastIds[layer], layer, 0, window->NavRectRel[layer]);
g.NavDisableHighlight = false;
g.NavDisableMouseHover = g.NavMousePosDirty = true;
}
else
{
g.NavLayer = layer;
NavInitWindow(window, true);
}
}
static inline void ImGui::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);
}
// 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);
if (window->Flags & ImGuiWindowFlags_NoNavInputs)
{
g.NavId = g.NavFocusScopeId = 0;
return;
}
bool init_for_nav = false;
if (window == window->RootWindow || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from NavInitWindow(), init_for_nav=%d, window=\"%s\", layer=%d\n", init_for_nav, window->Name, g.NavLayer);
if (init_for_nav)
{
SetNavID(0, g.NavLayer, 0, ImRect());
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
g.NavFocusScopeId = 0;
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->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()));
ImGuiViewport* viewport = GetMainViewport();
return ImFloor(ImClamp(pos, viewport->Pos, viewport->Pos + viewport->Size)); // ImFloor() is important because non-integer mouse position application in backend might be lossy and result in undesirable non-zero delta.
}
}
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)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 1.25f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicRepeatAmount(t - g.IO.DeltaTime, t, g.IO.KeyRepeatDelay * 0.72f, g.IO.KeyRepeatRate * 0.30f);
return 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 ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
io.WantSetMousePos = false;
g.NavWrapRequestWindow = NULL;
g.NavWrapRequestFlags = ImGuiNavMoveFlags_None;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("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
// Set input source as Gamepad when buttons are pressed (as some features differs when used with Gamepad vs Keyboard)
// (do it before we map Keyboard input!)
bool nav_keyboard_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (io.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (io.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active && g.NavInputSource != ImGuiInputSource_Gamepad)
{
if (io.NavInputs[ImGuiNavInput_Activate] > 0.0f || io.NavInputs[ImGuiNavInput_Input] > 0.0f || io.NavInputs[ImGuiNavInput_Cancel] > 0.0f || io.NavInputs[ImGuiNavInput_Menu] > 0.0f
|| io.NavInputs[ImGuiNavInput_DpadLeft] > 0.0f || io.NavInputs[ImGuiNavInput_DpadRight] > 0.0f || io.NavInputs[ImGuiNavInput_DpadUp] > 0.0f || io.NavInputs[ImGuiNavInput_DpadDown] > 0.0f)
g.NavInputSource = ImGuiInputSource_Gamepad;
}
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) do { if (IsKeyDown(io.KeyMap[_KEY])) { io.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_Keyboard; } } while (0)
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 (io.KeyCtrl)
io.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (io.KeyShift)
io.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
// AltGR is normally Alt+Ctrl but we can't reliably detect it (not all backends/systems/layout emit it as Alt+Ctrl)
// But also even on keyboards without AltGR we don't want Alt+Ctrl to open menu anyway.
if (io.KeyAlt && !io.KeyCtrl)
io.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
// We automatically cancel toggling nav layer when any text has been typed while holding Alt. (See #370)
if (io.KeyAlt && !io.KeyCtrl && g.NavWindowingToggleLayer && io.InputQueueCharacters.Size > 0)
g.NavWindowingToggleLayer = false;
#undef NAV_MAP_KEY
}
memcpy(io.NavInputsDownDurationPrev, io.NavInputsDownDuration, sizeof(io.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(io.NavInputs); i++)
io.NavInputsDownDuration[i] = (io.NavInputs[i] > 0.0f) ? (io.NavInputsDownDuration[i] < 0.0f ? 0.0f : io.NavInputsDownDuration[i] + io.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
if (g.NavInitResultId != 0)
NavUpdateInitResult();
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// 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 navigated item position from last frame
if ((io.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (io.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
io.MousePos = io.MousePosPrev = NavCalcPreferredRefPos();
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)
NavSaveLastChildNavWindowIntoParent(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == ImGuiNavLayer_Main)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
io.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
io.NavVisible = (io.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputTest(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
IMGUI_DEBUG_LOG_NAV("[nav] ImGuiNavInput_Cancel\n");
if (g.ActiveId != 0)
{
if (!IsActiveIdUsingNavInput(ImGuiNavInput_Cancel))
ClearActiveID();
}
else if (g.NavLayer != ImGuiNavLayer_Main)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else if (g.NavWindow && g.NavWindow != g.NavWindow->RootWindow && !(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);
ImRect child_rect = child_window->Rect();
FocusWindow(parent_window);
SetNavID(child_window->ChildId, ImGuiNavLayer_Main, 0, ImRect(child_rect.Min - parent_window->Pos, child_rect.Max - parent_window->Pos));
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
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 = g.NavFocusScopeId = 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 && IsNavInputTest(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) && IsNavInputTest(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
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
const ImGuiInputReadMode read_mode = ImGuiInputReadMode_Repeat;
if (!IsActiveIdUsingNavDir(ImGuiDir_Left) && (IsNavInputTest(ImGuiNavInput_DpadLeft, read_mode) || IsNavInputTest(ImGuiNavInput_KeyLeft_, read_mode))) { g.NavMoveDir = ImGuiDir_Left; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Right) && (IsNavInputTest(ImGuiNavInput_DpadRight, read_mode) || IsNavInputTest(ImGuiNavInput_KeyRight_, read_mode))) { g.NavMoveDir = ImGuiDir_Right; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Up) && (IsNavInputTest(ImGuiNavInput_DpadUp, read_mode) || IsNavInputTest(ImGuiNavInput_KeyUp_, read_mode))) { g.NavMoveDir = ImGuiDir_Up; }
if (!IsActiveIdUsingNavDir(ImGuiDir_Down) && (IsNavInputTest(ImGuiNavInput_DpadDown, read_mode) || IsNavInputTest(ImGuiNavInput_KeyDown_, read_mode))) { g.NavMoveDir = ImGuiDir_Down; }
}
g.NavMoveClipDir = g.NavMoveDir;
}
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)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequestForward %d\n", g.NavMoveDir);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown/Home/End scroll
// FIXME-NAV: Consider enabling those keys even without the master ImGuiConfigFlags_NavEnableKeyboard flag?
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown();
// 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.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveRequestKeyMods = io.KeyMods;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: from move, window \"%s\", layer=%d\n", g.NavWindow->Name, g.NavLayer);
g.NavInitRequest = g.NavInitRequestFromMove = true;
// Reassigning with same value, we're being explicit here.
g.NavInitResultId = 0; // -V1048
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = IM_ROUND(window->CalcFontSize() * 100 * io.DeltaTime); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetScrollY(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)
SetScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
if (scroll_dir.y != 0.0f)
SetScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When using gamepad, we project the reference nav bounding box into window visible area.
// This is to allow resuming navigation inside the visible area after doing a large amount of scrolling, since with gamepad every movements are relative
// (can't focus a visible object like we can with the mouse).
if (g.NavMoveRequest && g.NavInputSource == ImGuiInputSource_Gamepad && g.NavLayer == ImGuiNavLayer_Main)
{
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]))
{
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: clamp NavRectRel\n");
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].ClipWithFull(window_rect_rel);
g.NavId = g.NavFocusScopeId = 0;
}
}
// 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.NavScoringRect = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : ImRect(0, 0, 0, 0);
g.NavScoringRect.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRect.Min.x = ImMin(g.NavScoringRect.Min.x + 1.0f, g.NavScoringRect.Max.x);
g.NavScoringRect.Max.x = g.NavScoringRect.Min.x;
IM_ASSERT(!g.NavScoringRect.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//GetForegroundDrawList()->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)
{
ImDrawList* draw_list = GetForegroundDrawList(g.NavWindow);
if (1) { for (int layer = 0; layer < 2; layer++) draw_list->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 (1) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); draw_list->AddCircleFilled(p, 3.0f, col); draw_list->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
}
#endif
}
static void ImGui::NavUpdateInitResult()
{
// In very rare cases g.NavWindow may be null (e.g. clearing focus after requesting an init request, which does happen when releasing Alt while clicking on void)
ImGuiContext& g = *GImGui;
if (!g.NavWindow)
return;
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
// FIXME-NAV: On _NavFlattened windows, g.NavWindow will only be updated during subsequent frame. Not a problem currently.
IMGUI_DEBUG_LOG_NAV("[nav] NavInitRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", g.NavInitResultId, g.NavLayer, g.NavWindow->Name);
SetNavID(g.NavInitResultId, g.NavLayer, 0, g.NavInitResultRectRel);
if (g.NavInitRequestFromMove)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = g.NavMousePosDirty = true;
}
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavItemData* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == ImGuiNavLayer_Main)
{
ImVec2 delta_scroll;
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_ScrollToEdge)
{
float scroll_target = (g.NavMoveDir == ImGuiDir_Up) ? result->Window->ScrollMax.y : 0.0f;
delta_scroll.y = result->Window->Scroll.y - scroll_target;
SetScrollY(result->Window, scroll_target);
}
else
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
delta_scroll = ScrollToBringRectIntoView(result->Window, rect_abs);
}
// Offset our result position so mouse position can be applied immediately after in NavUpdate()
result->RectRel.TranslateX(-delta_scroll.x);
result->RectRel.TranslateY(-delta_scroll.y);
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToFocusScopeId = result->FocusScopeId;
g.NavJustMovedToKeyMods = g.NavMoveRequestKeyMods;
}
IMGUI_DEBUG_LOG_NAV("[nav] NavMoveRequest: result NavID 0x%08X in Layer %d Window \"%s\"\n", result->ID, g.NavLayer, g.NavWindow->Name);
SetNavID(result->ID, g.NavLayer, result->FocusScopeId, result->RectRel);
g.NavDisableHighlight = false;
g.NavDisableMouseHover = g.NavMousePosDirty = true;
}
// Handle PageUp/PageDown/Home/End keys
static float ImGui::NavUpdatePageUpPageDown()
{
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
if (g.NavMoveDir != ImGuiDir_None || g.NavWindow == NULL)
return 0.0f;
if ((g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) || g.NavWindowingTarget != NULL || g.NavLayer != ImGuiNavLayer_Main)
return 0.0f;
ImGuiWindow* window = g.NavWindow;
const bool page_up_held = IsKeyDown(io.KeyMap[ImGuiKey_PageUp]) && !IsActiveIdUsingKey(ImGuiKey_PageUp);
const bool page_down_held = IsKeyDown(io.KeyMap[ImGuiKey_PageDown]) && !IsActiveIdUsingKey(ImGuiKey_PageDown);
const bool home_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_Home]) && !IsActiveIdUsingKey(ImGuiKey_Home);
const bool end_pressed = IsKeyPressed(io.KeyMap[ImGuiKey_End]) && !IsActiveIdUsingKey(ImGuiKey_End);
if (page_up_held != page_down_held || home_pressed != end_pressed) // If either (not both) are pressed
{
if (window->DC.NavLayersActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
SetScrollY(window, window->Scroll.y - window->InnerRect.GetHeight());
else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
SetScrollY(window, window->Scroll.y + window->InnerRect.GetHeight());
else if (home_pressed)
SetScrollY(window, 0.0f);
else if (end_pressed)
SetScrollY(window, window->ScrollMax.y);
}
else
{
ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(io.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset up, we request the down direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(io.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset down, we request the up direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (home_pressed)
{
// FIXME-NAV: handling of Home/End is assuming that the top/bottom most item will be visible with Scroll.y == 0/ScrollMax.y
// Scrolling will be handled via the ImGuiNavMoveFlags_ScrollToEdge flag, we don't scroll immediately to avoid scrolling happening before nav result.
// Preserve current horizontal position if we have any.
nav_rect_rel.Min.y = nav_rect_rel.Max.y = -window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
else if (end_pressed)
{
nav_rect_rel.Min.y = nav_rect_rel.Max.y = window->ScrollMax.y + window->SizeFull.y - window->Scroll.y;
if (nav_rect_rel.IsInverted())
nav_rect_rel.Min.x = nav_rect_rel.Max.x = 0.0f;
g.NavMoveDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_ScrollToEdge;
}
return nav_scoring_rect_offset_y;
}
}
return 0.0f;
}
static void ImGui::NavEndFrame()
{
ImGuiContext& g = *GImGui;
// Show CTRL+TAB list window
if (g.NavWindowingTarget != NULL)
NavUpdateWindowingOverlay();
// Perform wrap-around in menus
ImGuiWindow* window = g.NavWrapRequestWindow;
ImGuiNavMoveFlags move_flags = g.NavWrapRequestFlags;
if (window != NULL && g.NavWindow == window && NavMoveRequestButNoResultYet() && g.NavMoveRequestForward == ImGuiNavForward_None && g.NavLayer == ImGuiNavLayer_Main)
{
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x =
ImMax(window->SizeFull.x, window->ContentSize.x + window->WindowPadding.x * 2.0f) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX)
{
bb_rel.TranslateY(-bb_rel.GetHeight());
clip_dir = ImGuiDir_Up;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX)
{
bb_rel.TranslateY(+bb_rel.GetHeight());
clip_dir = ImGuiDir_Down;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y =
ImMax(window->SizeFull.y, window->ContentSize.y + window->WindowPadding.y * 2.0f) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY)
{
bb_rel.TranslateX(-bb_rel.GetWidth());
clip_dir = ImGuiDir_Left;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY)
{
bb_rel.TranslateX(+bb_rel.GetWidth());
clip_dir = ImGuiDir_Right;
}
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
}
static int ImGui::FindWindowFocusIndex(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_UNUSED(g);
int order = window->FocusOrder;
IM_ASSERT(g.WindowsFocusOrder[order] == window);
return order;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
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 = ImGui::FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Windowing management mode
// Keyboard: CTRL+Tab (change focus/move/resize), Alt (toggle menu layer)
// Gamepad: Hold Menu/Square (change focus/move/resize), Tap Menu/Square (toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetTopMostPopupModal();
bool allow_windowing = (modal_window == NULL);
if (!allow_windowing)
g.NavWindowingTarget = NULL;
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = allow_windowing && !g.NavWindowingTarget && IsNavInputTest(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = allow_windowing && !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 : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window->RootWindow; // FIXME-DOCK: Will need to use RootWindowDockStop
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_Keyboard : ImGuiInputSource_Gamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_Gamepad)
{
// 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.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputTest(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputTest(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 top-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_Keyboard)
{
// 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.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 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 backend clearing releases all keys on ALT-TAB
if (IsNavInputTest(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputTest(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_Keyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_Gamepad)
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)); // FIXME: Doesn't handle variable framerate very well
ImGuiWindow* moving_window = g.NavWindowingTarget->RootWindow;
SetWindowPos(moving_window, moving_window->Pos + move_delta * move_speed, ImGuiCond_Always);
MarkIniSettingsDirty(moving_window);
g.NavDisableMouseHover = true;
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindow))
{
ClearActiveID();
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window, false);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window has ONLY a menu layer (no main layer), select it directly
// Use NavLayersActiveMaskNext since windows didn't have a chance to be Begin()-ed on this frame,
// so CTRL+Tab where the keys are only held for 1 frame will be able to use correct layers mask since
// the target window as already been previewed once.
// FIXME-NAV: This should be done in NavInit.. or in FocusWindow... However in both of those cases,
// we won't have a guarantee that windows has been visible before and therefore NavLayersActiveMask*
// won't be valid.
if (apply_focus_window->DC.NavLayersActiveMaskNext == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
ClearActiveID();
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) == 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;
// Reinitialize navigation when entering menu bar with the Alt key.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayersActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
if (new_nav_layer == ImGuiNavLayer_Menu)
g.NavWindow->NavLastIds[new_nav_layer] = 0;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingOverlay()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingListWindow == NULL)
g.NavWindowingListWindow = FindWindowByName("###NavWindowingList");
const ImGuiViewport* viewport = GetMainViewport();
SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(viewport->GetCenter(), ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
IM_ASSERT(window != NULL); // Fix static analyzers
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
// If the item has an identifier:
// - This assume/require the item to be activated (typically via ButtonBehavior).
// - Therefore if you want to use this with a mouse button other than left mouse button, it is up to the item itself to activate with another button.
// - We then pull and use the mouse button that was used to activate the item and use it to carry on the drag.
// If the item has no identifier:
// - Currently always assume left mouse button.
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// FIXME-DRAGDROP: While in the common-most "drag from non-zero active id" case we can tell the mouse button,
// in both SourceExtern and id==0 cases we may requires something else (explicit flags or some heuristic).
ImGuiMouseButton mouse_button = ImGuiMouseButton_Left;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0)
{
// Common path: items with ID
if (g.ActiveId != source_id)
return false;
if (g.ActiveIdMouseButton != -1)
mouse_button = g.ActiveIdMouseButton;
if (g.IO.MouseDown[mouse_button] == false)
return false;
g.ActiveIdAllowOverlap = false;
}
else
{
// Uncommon path: items without ID
if (g.IO.MouseDown[mouse_button] == false)
return false;
// 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;
}
// Early out
if ((window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) == 0 && (g.ActiveId == 0 || g.ActiveIdWindow != window))
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.
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
bool is_hovered = ItemHoverable(window->DC.LastItemRect, 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);
// Disable navigation and key inputs while dragging
g.ActiveIdUsingNavDirMask = ~(ImU32)0;
g.ActiveIdUsingNavInputMask = ~(ImU32)0;
g.ActiveIdUsingKeyInputMask = ~(ImU64)0;
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern");
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 (payload.SourceId == g.ActiveId)
g.ActiveIdNoClearOnFocusLoss = true;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSource = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesCanSkipItems = 1;
}
}
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);
IM_ASSERT(g.DragDropWithinSource && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSource = false;
}
// 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 32 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(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(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;
ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
if (hovered_window == NULL || window->RootWindow != hovered_window->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
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;
ImGuiWindow* hovered_window = g.HoveredWindowUnderMovingWindow;
if (hovered_window == NULL || window->RootWindow != hovered_window->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;
IM_ASSERT(g.DragDropWithinTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinTarget = true;
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.DragDropAcceptFlags = flags;
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-DRAGDROP: 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->PushClipRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1));
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;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// 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;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinTarget);
g.DragDropWithinTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
static inline void LogTextV(ImGuiContext& g, const char* fmt, va_list args)
{
if (g.LogFile)
{
g.LogBuffer.Buf.resize(0);
g.LogBuffer.appendfv(fmt, args);
ImFileWrite(g.LogBuffer.c_str(), sizeof(char), (ImU64)g.LogBuffer.size(), g.LogFile);
}
else
{
g.LogBuffer.appendfv(fmt, args);
}
}
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
LogTextV(g, fmt, args);
va_end(args);
}
void ImGui::LogTextV(const char* fmt, va_list args)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogTextV(g, fmt, 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
// FIXME: This code is a little complicated perhaps, considering simplifying the whole system.
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const char* prefix = g.LogNextPrefix;
const char* suffix = g.LogNextSuffix;
g.LogNextPrefix = g.LogNextSuffix = NULL;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > g.LogLinePosY + g.Style.FramePadding.y + 1);
if (ref_pos)
g.LogLinePosY = ref_pos->y;
if (log_new_line)
{
LogText(IM_NEWLINE);
g.LogLineFirstItem = true;
}
if (prefix)
LogRenderedText(ref_pos, prefix, prefix + strlen(prefix)); // Calculate end ourself to ensure "##" are included here.
// Re-adjust padding if we have popped out of our starting depth
if (g.LogDepthRef > window->DC.TreeDepth)
g.LogDepthRef = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogDepthRef);
const char* text_remaining = text;
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by indentation corresponding to the current depth of our log entry.
// We don't add a trailing \n yet to allow a subsequent item on the same line to be captured.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_last_line = (line_end == text_end);
if (line_start != line_end || !is_last_line)
{
const int line_length = (int)(line_end - line_start);
const int indentation = g.LogLineFirstItem ? tree_depth * 4 : 1;
LogText("%*s%.*s", indentation, "", line_length, line_start);
g.LogLineFirstItem = false;
if (*line_end == '\n')
{
LogText(IM_NEWLINE);
g.LogLineFirstItem = true;
}
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
if (suffix)
LogRenderedText(ref_pos, suffix, suffix + strlen(suffix));
}
// Start logging/capturing text output
void ImGui::LogBegin(ImGuiLogType type, int auto_open_depth)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogEnabled == false);
IM_ASSERT(g.LogFile == NULL);
IM_ASSERT(g.LogBuffer.empty());
g.LogEnabled = true;
g.LogType = type;
g.LogNextPrefix = g.LogNextSuffix = NULL;
g.LogDepthRef = window->DC.TreeDepth;
g.LogDepthToExpand = ((auto_open_depth >= 0) ? auto_open_depth : g.LogDepthToExpandDefault);
g.LogLinePosY = FLT_MAX;
g.LogLineFirstItem = true;
}
// Important: doesn't copy underlying data, use carefully (prefix/suffix must be in scope at the time of the next LogRenderedText)
void ImGui::LogSetNextTextDecoration(const char* prefix, const char* suffix)
{
ImGuiContext& g = *GImGui;
g.LogNextPrefix = prefix;
g.LogNextSuffix = suffix;
}
void ImGui::LogToTTY(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
IM_UNUSED(auto_open_depth);
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
LogBegin(ImGuiLogType_TTY, auto_open_depth);
g.LogFile = stdout;
#endif
}
// Start logging/capturing text output to given file
void ImGui::LogToFile(int auto_open_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
// FIXME: We could probably open the file in text mode "at", however note that clipboard/buffer logging will still
// be subject to outputting OS-incompatible carriage return if within strings the user doesn't use IM_NEWLINE.
// By opening the file in binary mode "ab" we have consistent output everywhere.
if (!filename)
filename = g.IO.LogFilename;
if (!filename || !filename[0])
return;
ImFileHandle f = ImFileOpen(filename, "ab");
if (!f)
{
IM_ASSERT(0);
return;
}
LogBegin(ImGuiLogType_File, auto_open_depth);
g.LogFile = f;
}
// Start logging/capturing text output to clipboard
void ImGui::LogToClipboard(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Clipboard, auto_open_depth);
}
void ImGui::LogToBuffer(int auto_open_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
LogBegin(ImGuiLogType_Buffer, auto_open_depth);
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
switch (g.LogType)
{
case ImGuiLogType_TTY:
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
fflush(g.LogFile);
#endif
break;
case ImGuiLogType_File:
ImFileClose(g.LogFile);
break;
case ImGuiLogType_Buffer:
break;
case ImGuiLogType_Clipboard:
if (!g.LogBuffer.empty())
SetClipboardText(g.LogBuffer.begin());
break;
case ImGuiLogType_None:
IM_ASSERT(0);
break;
}
g.LogEnabled = false;
g.LogType = ImGuiLogType_None;
g.LogFile = NULL;
g.LogBuffer.clear();
}
// Helper to display logging buttons
// FIXME-OBSOLETE: We should probably obsolete this and let the user have their own helper (this is one of the oldest function alive!)
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
#ifndef IMGUI_DISABLE_TTY_FUNCTIONS
const bool log_to_tty = Button("Log To TTY"); SameLine();
#else
const bool log_to_tty = false;
#endif
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushAllowKeyboardFocus(false);
SetNextItemWidth(80.0f);
SliderInt("Default Depth", &g.LogDepthToExpandDefault, 0, 9, NULL);
PopAllowKeyboardFocus();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY();
if (log_to_file)
LogToFile();
if (log_to_clipboard)
LogToClipboard();
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
// - UpdateSettings() [Internal]
// - MarkIniSettingsDirty() [Internal]
// - CreateNewWindowSettings() [Internal]
// - FindWindowSettings() [Internal]
// - FindOrCreateWindowSettings() [Internal]
// - FindSettingsHandler() [Internal]
// - ClearIniSettings() [Internal]
// - LoadIniSettingsFromDisk()
// - LoadIniSettingsFromMemory()
// - SaveIniSettingsToDisk()
// - SaveIniSettingsToMemory()
// - WindowSettingsHandler_***() [Internal]
//-----------------------------------------------------------------------------
// Called by NewFrame()
void ImGui::UpdateSettings()
{
// Load settings on first frame (if not explicitly loaded manually before)
ImGuiContext& g = *GImGui;
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
}
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
#if !IMGUI_DEBUG_INI_SETTINGS
// Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
// Preserve the full string when IMGUI_DEBUG_INI_SETTINGS is set to make .ini inspection easier.
if (const char* p = strstr(name, "###"))
name = p;
#endif
const size_t name_len = strlen(name);
// Allocate chunk
const size_t chunk_size = sizeof(ImGuiWindowSettings) + name_len + 1;
ImGuiWindowSettings* settings = g.SettingsWindows.alloc_chunk(chunk_size);
IM_PLACEMENT_NEW(settings) ImGuiWindowSettings();
settings->ID = ImHashStr(name, name_len);
memcpy(settings->GetName(), name, name_len + 1); // Store with zero terminator
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->ID == id)
return settings;
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name)))
return settings;
return CreateNewWindowSettings(name);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name);
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;
}
void ImGui::ClearIniSettings()
{
ImGuiContext& g = *GImGui;
g.SettingsIniData.clear();
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ClearAllFn)
g.SettingsHandlers[handler_n].ClearAllFn(&g, &g.SettingsHandlers[handler_n]);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
IM_FREE(file_data);
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
//IM_ASSERT(!g.WithinFrameScope && "Cannot be called between NewFrame() and EndFrame()");
//IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
g.SettingsIniData.Buf.resize((int)ini_size + 1);
char* const buf = g.SettingsIniData.Buf.Data;
char* const buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf_end[0] = 0;
// Call pre-read handlers
// Some types will clear their data (e.g. dock information) some types will allow merge/override (window)
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ReadInitFn)
g.SettingsHandlers[handler_n].ReadInitFn(&g, &g.SettingsHandlers[handler_n]);
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] == ';')
continue;
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 = (char*)(void*)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
continue;
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
entry_handler = 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);
}
}
g.SettingsLoaded = true;
// [DEBUG] Restore untouched copy so it can be browsed in Metrics (not strictly necessary)
memcpy(buf, ini_data, ini_size);
// Call post-read handlers
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].ApplyAllFn)
g.SettingsHandlers[handler_n].ApplyAllFn(&g, &g.SettingsHandlers[handler_n]);
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
ImFileHandle f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
ImFileWrite(ini_data, sizeof(char), ini_data_size, f);
ImFileClose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void WindowSettingsHandler_ClearAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
g.Windows[i]->SettingsOffset = -1;
g.SettingsWindows.clear();
}
static void* WindowSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindOrCreateWindowSettings(name);
ImGuiID id = settings->ID;
*settings = ImGuiWindowSettings(); // Clear existing if recycling previous entry
settings->ID = id;
settings->WantApply = true;
return (void*)settings;
}
static void WindowSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
int x, y;
int i;
if (sscanf(line, "Pos=%i,%i", &x, &y) == 2) { settings->Pos = ImVec2ih((short)x, (short)y); }
else if (sscanf(line, "Size=%i,%i", &x, &y) == 2) { settings->Size = ImVec2ih((short)x, (short)y); }
else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
}
// Apply to existing windows (if any)
static void WindowSettingsHandler_ApplyAll(ImGuiContext* ctx, ImGuiSettingsHandler*)
{
ImGuiContext& g = *ctx;
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
if (settings->WantApply)
{
if (ImGuiWindow* window = ImGui::FindWindowByID(settings->ID))
ApplyWindowSettings(window, settings);
settings->WantApply = false;
}
}
static void WindowSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsOffset != -1) ? g.SettingsWindows.ptr_from_offset(window->SettingsOffset) : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsOffset = g.SettingsWindows.offset_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = ImVec2ih((short)window->Pos.x, (short)window->Pos.y);
settings->Size = ImVec2ih((short)window->SizeFull.x, (short)window->SizeFull.y);
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.size() * 6); // ballpark reserve
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
{
const char* settings_name = settings->GetName();
buf->appendf("[%s][%s]\n", handler->TypeName, settings_name);
buf->appendf("Pos=%d,%d\n", settings->Pos.x, settings->Pos.y);
buf->appendf("Size=%d,%d\n", settings->Size.x, settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
buf->append("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
// - GetMainViewport()
// - UpdateViewportsNewFrame() [Internal]
// (this section is more complete in the 'docking' branch)
//-----------------------------------------------------------------------------
ImGuiViewport* ImGui::GetMainViewport()
{
ImGuiContext& g = *GImGui;
return g.Viewports[0];
}
// Update viewports and monitor infos
static void ImGui::UpdateViewportsNewFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Viewports.Size == 1);
// Update main viewport with current platform position.
// FIXME-VIEWPORT: Size is driven by backend/user code for backward-compatibility but we should aim to make this more consistent.
ImGuiViewportP* main_viewport = g.Viewports[0];
main_viewport->Flags = ImGuiViewportFlags_IsPlatformWindow | ImGuiViewportFlags_OwnedByApp;
main_viewport->Pos = ImVec2(0.0f, 0.0f);
main_viewport->Size = g.IO.DisplaySize;
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
// Lock down space taken by menu bars and status bars, reset the offset for fucntions like BeginMainMenuBar() to alter them again.
viewport->WorkOffsetMin = viewport->BuildWorkOffsetMin;
viewport->WorkOffsetMax = viewport->BuildWorkOffsetMax;
viewport->BuildWorkOffsetMin = viewport->BuildWorkOffsetMax = ImVec2(0.0f, 0.0f);
viewport->UpdateWorkRect();
}
}
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// (this section is filled in the 'docking' branch)
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#pragma comment(lib, "kernel32")
#endif
// Win32 clipboard implementation
// We use g.ClipboardHandlerData for temporary storage to ensure it is freed on Shutdown()
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (const WCHAR* wbuf_global = (const WCHAR*)::GlobalLock(wbuf_handle))
{
int buf_len = ::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, NULL, 0, NULL, NULL);
g.ClipboardHandlerData.resize(buf_len);
::WideCharToMultiByte(CP_UTF8, 0, wbuf_global, -1, g.ClipboardHandlerData.Data, buf_len, NULL, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return g.ClipboardHandlerData.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ::MultiByteToWideChar(CP_UTF8, 0, text, -1, NULL, 0);
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(WCHAR));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
WCHAR* wbuf_global = (WCHAR*)::GlobalLock(wbuf_handle);
::MultiByteToWideChar(CP_UTF8, 0, text, -1, wbuf_global, wbuf_length);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#elif defined(__APPLE__) && TARGET_OS_OSX && defined(IMGUI_ENABLE_OSX_DEFAULT_CLIPBOARD_FUNCTIONS)
#include <Carbon/Carbon.h> // Use old API to avoid need for separate .mm file
static PasteboardRef main_clipboard = 0;
// OSX clipboard implementation
// If you enable this you will need to add '-framework ApplicationServices' to your linker command-line!
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardClear(main_clipboard);
CFDataRef cf_data = CFDataCreate(kCFAllocatorDefault, (const UInt8*)text, strlen(text));
if (cf_data)
{
PasteboardPutItemFlavor(main_clipboard, (PasteboardItemID)1, CFSTR("public.utf8-plain-text"), cf_data, 0);
CFRelease(cf_data);
}
}
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
if (!main_clipboard)
PasteboardCreate(kPasteboardClipboard, &main_clipboard);
PasteboardSynchronize(main_clipboard);
ItemCount item_count = 0;
PasteboardGetItemCount(main_clipboard, &item_count);
for (ItemCount i = 0; i < item_count; i++)
{
PasteboardItemID item_id = 0;
PasteboardGetItemIdentifier(main_clipboard, i + 1, &item_id);
CFArrayRef flavor_type_array = 0;
PasteboardCopyItemFlavors(main_clipboard, item_id, &flavor_type_array);
for (CFIndex j = 0, nj = CFArrayGetCount(flavor_type_array); j < nj; j++)
{
CFDataRef cf_data;
if (PasteboardCopyItemFlavorData(main_clipboard, item_id, CFSTR("public.utf8-plain-text"), &cf_data) == noErr)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
int length = (int)CFDataGetLength(cf_data);
g.ClipboardHandlerData.resize(length + 1);
CFDataGetBytes(cf_data, CFRangeMake(0, length), (UInt8*)g.ClipboardHandlerData.Data);
g.ClipboardHandlerData[length] = 0;
CFRelease(cf_data);
return g.ClipboardHandlerData.Data;
}
}
}
return NULL;
}
#else
// Local Dear ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers.
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.ClipboardHandlerData.empty() ? NULL : g.ClipboardHandlerData.begin();
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.ClipboardHandlerData.clear();
const char* text_end = text + strlen(text);
g.ClipboardHandlerData.resize((int)(text_end - text) + 1);
memcpy(&g.ClipboardHandlerData[0], text, (size_t)(text_end - text));
g.ClipboardHandlerData[(int)(text_end - text)] = 0;
}
#endif
// Win32 API IME support (for Asian languages, etc.)
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !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
ImGuiIO& io = ImGui::GetIO();
if (HWND hwnd = (HWND)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);
::ImmReleaseContext(hwnd, himc);
}
}
#else
static void ImeSetInputScreenPosFn_DefaultImpl(int, int) {}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUGGER WINDOW
//-----------------------------------------------------------------------------
// - RenderViewportThumbnail() [Internal]
// - RenderViewportsThumbnails() [Internal]
// - MetricsHelpMarker() [Internal]
// - ShowMetricsWindow()
// - DebugNodeColumns() [Internal]
// - DebugNodeDrawList() [Internal]
// - DebugNodeDrawCmdShowMeshAndBoundingBox() [Internal]
// - DebugNodeStorage() [Internal]
// - DebugNodeTabBar() [Internal]
// - DebugNodeViewport() [Internal]
// - DebugNodeWindow() [Internal]
// - DebugNodeWindowSettings() [Internal]
// - DebugNodeWindowsList() [Internal]
//-----------------------------------------------------------------------------
#ifndef IMGUI_DISABLE_METRICS_WINDOW
void ImGui::DebugRenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 scale = bb.GetSize() / viewport->Size;
ImVec2 off = bb.Min - viewport->Pos * scale;
float alpha_mul = 1.0f;
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* thumb_window = g.Windows[i];
if (!thumb_window->WasActive || (thumb_window->Flags & ImGuiWindowFlags_ChildWindow))
continue;
ImRect thumb_r = thumb_window->Rect();
ImRect title_r = thumb_window->TitleBarRect();
thumb_r = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
title_r = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
thumb_r.ClipWithFull(bb);
title_r.ClipWithFull(bb);
const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
window->DrawList->AddRectFilled(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_WindowBg, alpha_mul));
window->DrawList->AddRectFilled(title_r.Min, title_r.Max, GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
window->DrawList->AddRect(thumb_r.Min, thumb_r.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r.Min, GetColorU32(ImGuiCol_Text, alpha_mul), thumb_window->Name, FindRenderedTextEnd(thumb_window->Name));
}
draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_Border, alpha_mul));
}
static void RenderViewportsThumbnails()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
float SCALE = 1.0f / 8.0f;
ImRect bb_full(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
for (int n = 0; n < g.Viewports.Size; n++)
bb_full.Add(g.Viewports[n]->GetMainRect());
ImVec2 p = window->DC.CursorPos;
ImVec2 off = p - bb_full.Min * SCALE;
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
ImGui::DebugRenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
}
ImGui::Dummy(bb_full.GetSize() * SCALE);
}
// Avoid naming collision with imgui_demo.cpp's HelpMarker() for unity builds.
static void MetricsHelpMarker(const char* desc)
{
ImGui::TextDisabled("(?)");
if (ImGui::IsItemHovered())
{
ImGui::BeginTooltip();
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(desc);
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
}
#ifndef IMGUI_DISABLE_DEMO_WINDOWS
namespace ImGui { void ShowFontAtlas(ImFontAtlas* atlas); }
#endif
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!Begin("Dear ImGui Metrics/Debugger", p_open))
{
End();
return;
}
ImGuiContext& g = *GImGui;
ImGuiIO& io = g.IO;
ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
// Basic info
Text("Dear ImGui %s", GetVersion());
Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
Text("%d active allocations", io.MetricsActiveAllocations);
//SameLine(); if (SmallButton("GC")) { g.GcCompactAll = true; }
Separator();
// Debugging enums
enum { WRT_OuterRect, WRT_OuterRectClipped, WRT_InnerRect, WRT_InnerClipRect, WRT_WorkRect, WRT_Content, WRT_ContentIdeal, WRT_ContentRegionRect, WRT_Count }; // Windows Rect Type
const char* wrt_rects_names[WRT_Count] = { "OuterRect", "OuterRectClipped", "InnerRect", "InnerClipRect", "WorkRect", "Content", "ContentIdeal", "ContentRegionRect" };
enum { TRT_OuterRect, TRT_InnerRect, TRT_WorkRect, TRT_HostClipRect, TRT_InnerClipRect, TRT_BackgroundClipRect, TRT_ColumnsRect, TRT_ColumnsWorkRect, TRT_ColumnsClipRect, TRT_ColumnsContentHeadersUsed, TRT_ColumnsContentHeadersIdeal, TRT_ColumnsContentFrozen, TRT_ColumnsContentUnfrozen, TRT_Count }; // Tables Rect Type
const char* trt_rects_names[TRT_Count] = { "OuterRect", "InnerRect", "WorkRect", "HostClipRect", "InnerClipRect", "BackgroundClipRect", "ColumnsRect", "ColumnsWorkRect", "ColumnsClipRect", "ColumnsContentHeadersUsed", "ColumnsContentHeadersIdeal", "ColumnsContentFrozen", "ColumnsContentUnfrozen" };
if (cfg->ShowWindowsRectsType < 0)
cfg->ShowWindowsRectsType = WRT_WorkRect;
if (cfg->ShowTablesRectsType < 0)
cfg->ShowTablesRectsType = TRT_WorkRect;
struct Funcs
{
static ImRect GetTableRect(ImGuiTable* table, int rect_type, int n)
{
if (rect_type == TRT_OuterRect) { return table->OuterRect; }
else if (rect_type == TRT_InnerRect) { return table->InnerRect; }
else if (rect_type == TRT_WorkRect) { return table->WorkRect; }
else if (rect_type == TRT_HostClipRect) { return table->HostClipRect; }
else if (rect_type == TRT_InnerClipRect) { return table->InnerClipRect; }
else if (rect_type == TRT_BackgroundClipRect) { return table->BgClipRect; }
else if (rect_type == TRT_ColumnsRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->MinX, table->InnerClipRect.Min.y, c->MaxX, table->InnerClipRect.Min.y + table->LastOuterHeight); }
else if (rect_type == TRT_ColumnsWorkRect) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->WorkRect.Min.y, c->WorkMaxX, table->WorkRect.Max.y); }
else if (rect_type == TRT_ColumnsClipRect) { ImGuiTableColumn* c = &table->Columns[n]; return c->ClipRect; }
else if (rect_type == TRT_ColumnsContentHeadersUsed){ ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersUsed, table->InnerClipRect.Min.y + table->LastFirstRowHeight); } // Note: y1/y2 not always accurate
else if (rect_type == TRT_ColumnsContentHeadersIdeal){ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXHeadersIdeal, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
else if (rect_type == TRT_ColumnsContentFrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y, c->ContentMaxXFrozen, table->InnerClipRect.Min.y + table->LastFirstRowHeight); }
else if (rect_type == TRT_ColumnsContentUnfrozen) { ImGuiTableColumn* c = &table->Columns[n]; return ImRect(c->WorkMinX, table->InnerClipRect.Min.y + table->LastFirstRowHeight, c->ContentMaxXUnfrozen, table->InnerClipRect.Max.y); }
IM_ASSERT(0);
return ImRect();
}
static ImRect GetWindowRect(ImGuiWindow* window, int rect_type)
{
if (rect_type == WRT_OuterRect) { return window->Rect(); }
else if (rect_type == WRT_OuterRectClipped) { return window->OuterRectClipped; }
else if (rect_type == WRT_InnerRect) { return window->InnerRect; }
else if (rect_type == WRT_InnerClipRect) { return window->InnerClipRect; }
else if (rect_type == WRT_WorkRect) { return window->WorkRect; }
else if (rect_type == WRT_Content) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSize); }
else if (rect_type == WRT_ContentIdeal) { ImVec2 min = window->InnerRect.Min - window->Scroll + window->WindowPadding; return ImRect(min, min + window->ContentSizeIdeal); }
else if (rect_type == WRT_ContentRegionRect) { return window->ContentRegionRect; }
IM_ASSERT(0);
return ImRect();
}
};
// Tools
if (TreeNode("Tools"))
{
// The Item Picker tool is super useful to visually select an item and break into the call-stack of where it was submitted.
if (Button("Item Picker.."))
DebugStartItemPicker();
SameLine();
MetricsHelpMarker("Will call the IM_DEBUG_BREAK() macro to break in debugger.\nWarning: If you don't have a debugger attached, this will probably crash.");
Checkbox("Show windows begin order", &cfg->ShowWindowsBeginOrder);
Checkbox("Show windows rectangles", &cfg->ShowWindowsRects);
SameLine();
SetNextItemWidth(GetFontSize() * 12);
cfg->ShowWindowsRects |= Combo("##show_windows_rect_type", &cfg->ShowWindowsRectsType, wrt_rects_names, WRT_Count, WRT_Count);
if (cfg->ShowWindowsRects && g.NavWindow != NULL)
{
BulletText("'%s':", g.NavWindow->Name);
Indent();
for (int rect_n = 0; rect_n < WRT_Count; rect_n++)
{
ImRect r = Funcs::GetWindowRect(g.NavWindow, rect_n);
Text("(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), wrt_rects_names[rect_n]);
}
Unindent();
}
Checkbox("Show ImDrawCmd mesh when hovering", &cfg->ShowDrawCmdMesh);
Checkbox("Show ImDrawCmd bounding boxes when hovering", &cfg->ShowDrawCmdBoundingBoxes);
Checkbox("Show tables rectangles", &cfg->ShowTablesRects);
SameLine();
SetNextItemWidth(GetFontSize() * 12);
cfg->ShowTablesRects |= Combo("##show_table_rects_type", &cfg->ShowTablesRectsType, trt_rects_names, TRT_Count, TRT_Count);
if (cfg->ShowTablesRects && g.NavWindow != NULL)
{
for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
{
ImGuiTable* table = g.Tables.GetByIndex(table_n);
if (table->LastFrameActive < g.FrameCount - 1 || (table->OuterWindow != g.NavWindow && table->InnerWindow != g.NavWindow))
continue;
BulletText("Table 0x%08X (%d columns, in '%s')", table->ID, table->ColumnsCount, table->OuterWindow->Name);
if (IsItemHovered())
GetForegroundDrawList()->AddRect(table->OuterRect.Min - ImVec2(1, 1), table->OuterRect.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
Indent();
char buf[128];
for (int rect_n = 0; rect_n < TRT_Count; rect_n++)
{
if (rect_n >= TRT_ColumnsRect)
{
if (rect_n != TRT_ColumnsRect && rect_n != TRT_ColumnsClipRect)
continue;
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImRect r = Funcs::GetTableRect(table, rect_n, column_n);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) Col %d %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), column_n, trt_rects_names[rect_n]);
Selectable(buf);
if (IsItemHovered())
GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
}
}
else
{
ImRect r = Funcs::GetTableRect(table, rect_n, -1);
ImFormatString(buf, IM_ARRAYSIZE(buf), "(%6.1f,%6.1f) (%6.1f,%6.1f) Size (%6.1f,%6.1f) %s", r.Min.x, r.Min.y, r.Max.x, r.Max.y, r.GetWidth(), r.GetHeight(), trt_rects_names[rect_n]);
Selectable(buf);
if (IsItemHovered())
GetForegroundDrawList()->AddRect(r.Min - ImVec2(1, 1), r.Max + ImVec2(1, 1), IM_COL32(255, 255, 0, 255), 0.0f, 0, 2.0f);
}
}
Unindent();
}
}
TreePop();
}
// Windows
DebugNodeWindowsList(&g.Windows, "Windows");
//DebugNodeWindowsList(&g.WindowsFocusOrder, "WindowsFocusOrder");
// DrawLists
int drawlist_count = 0;
for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
drawlist_count += g.Viewports[viewport_i]->DrawDataBuilder.GetDrawListCount();
if (TreeNode("DrawLists", "DrawLists (%d)", drawlist_count))
{
for (int viewport_i = 0; viewport_i < g.Viewports.Size; viewport_i++)
{
ImGuiViewportP* viewport = g.Viewports[viewport_i];
for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
}
TreePop();
}
// Viewports
if (TreeNode("Viewports", "Viewports (%d)", g.Viewports.Size))
{
Indent(GetTreeNodeToLabelSpacing());
RenderViewportsThumbnails();
Unindent(GetTreeNodeToLabelSpacing());
for (int i = 0; i < g.Viewports.Size; i++)
DebugNodeViewport(g.Viewports[i]);
TreePop();
}
// Details for Popups
if (TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
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" : "");
}
TreePop();
}
// Details for TabBars
if (TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.GetSize()))
{
for (int n = 0; n < g.TabBars.GetSize(); n++)
DebugNodeTabBar(g.TabBars.GetByIndex(n), "TabBar");
TreePop();
}
// Details for Tables
if (TreeNode("Tables", "Tables (%d)", g.Tables.GetSize()))
{
for (int n = 0; n < g.Tables.GetSize(); n++)
DebugNodeTable(g.Tables.GetByIndex(n));
TreePop();
}
// Details for Fonts
#ifndef IMGUI_DISABLE_DEMO_WINDOWS
ImFontAtlas* atlas = g.IO.Fonts;
if (TreeNode("Fonts", "Fonts (%d)", atlas->Fonts.Size))
{
ShowFontAtlas(atlas);
TreePop();
}
#endif
// Details for Docking
#ifdef IMGUI_HAS_DOCK
if (TreeNode("Docking"))
{
TreePop();
}
#endif // #ifdef IMGUI_HAS_DOCK
// Settings
if (TreeNode("Settings"))
{
if (SmallButton("Clear"))
ClearIniSettings();
SameLine();
if (SmallButton("Save to memory"))
SaveIniSettingsToMemory();
SameLine();
if (SmallButton("Save to disk"))
SaveIniSettingsToDisk(g.IO.IniFilename);
SameLine();
if (g.IO.IniFilename)
Text("\"%s\"", g.IO.IniFilename);
else
TextUnformatted("<NULL>");
Text("SettingsDirtyTimer %.2f", g.SettingsDirtyTimer);
if (TreeNode("SettingsHandlers", "Settings handlers: (%d)", g.SettingsHandlers.Size))
{
for (int n = 0; n < g.SettingsHandlers.Size; n++)
BulletText("%s", g.SettingsHandlers[n].TypeName);
TreePop();
}
if (TreeNode("SettingsWindows", "Settings packed data: Windows: %d bytes", g.SettingsWindows.size()))
{
for (ImGuiWindowSettings* settings = g.SettingsWindows.begin(); settings != NULL; settings = g.SettingsWindows.next_chunk(settings))
DebugNodeWindowSettings(settings);
TreePop();
}
if (TreeNode("SettingsTables", "Settings packed data: Tables: %d bytes", g.SettingsTables.size()))
{
for (ImGuiTableSettings* settings = g.SettingsTables.begin(); settings != NULL; settings = g.SettingsTables.next_chunk(settings))
DebugNodeTableSettings(settings);
TreePop();
}
#ifdef IMGUI_HAS_DOCK
#endif // #ifdef IMGUI_HAS_DOCK
#ifndef IMGUI_DISABLE_TEXT_INPUTS
if (TreeNode("SettingsIniData", "Settings unpacked data (.ini): %d bytes", g.SettingsIniData.size()))
{
InputTextMultiline("##Ini", (char*)(void*)g.SettingsIniData.c_str(), g.SettingsIniData.Buf.Size, ImVec2(-FLT_MIN, GetTextLineHeight() * 20), ImGuiInputTextFlags_ReadOnly);
TreePop();
}
#endif
TreePop();
}
// Misc Details
if (TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Keyboard", "Gamepad", "Nav", "Clipboard" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
Text("WINDOWING");
Indent();
Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
Text("HoveredWindow->Root: '%s'", g.HoveredWindow ? g.HoveredWindow->RootWindow->Name : "NULL");
Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
Unindent();
Text("ITEMS");
Indent();
Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
Unindent();
Text("NAV,FOCUS");
Indent();
Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
Text("NavFocusScopeId = 0x%08X", g.NavFocusScopeId);
Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
Unindent();
TreePop();
}
// Overlay: Display windows Rectangles and Begin Order
if (cfg->ShowWindowsRects || cfg->ShowWindowsBeginOrder)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive)
continue;
ImDrawList* draw_list = GetForegroundDrawList(window);
if (cfg->ShowWindowsRects)
{
ImRect r = Funcs::GetWindowRect(window, cfg->ShowWindowsRectsType);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
if (cfg->ShowWindowsBeginOrder && !(window->Flags & ImGuiWindowFlags_ChildWindow))
{
char buf[32];
ImFormatString(buf, IM_ARRAYSIZE(buf), "%d", window->BeginOrderWithinContext);
float font_size = GetFontSize();
draw_list->AddRectFilled(window->Pos, window->Pos + ImVec2(font_size, font_size), IM_COL32(200, 100, 100, 255));
draw_list->AddText(window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
// Overlay: Display Tables Rectangles
if (cfg->ShowTablesRects)
{
for (int table_n = 0; table_n < g.Tables.GetSize(); table_n++)
{
ImGuiTable* table = g.Tables.GetByIndex(table_n);
if (table->LastFrameActive < g.FrameCount - 1)
continue;
ImDrawList* draw_list = GetForegroundDrawList(table->OuterWindow);
if (cfg->ShowTablesRectsType >= TRT_ColumnsRect)
{
for (int column_n = 0; column_n < table->ColumnsCount; column_n++)
{
ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, column_n);
ImU32 col = (table->HoveredColumnBody == column_n) ? IM_COL32(255, 255, 128, 255) : IM_COL32(255, 0, 128, 255);
float thickness = (table->HoveredColumnBody == column_n) ? 3.0f : 1.0f;
draw_list->AddRect(r.Min, r.Max, col, 0.0f, 0, thickness);
}
}
else
{
ImRect r = Funcs::GetTableRect(table, cfg->ShowTablesRectsType, -1);
draw_list->AddRect(r.Min, r.Max, IM_COL32(255, 0, 128, 255));
}
}
}
#ifdef IMGUI_HAS_DOCK
// Overlay: Display Docking info
if (show_docking_nodes && g.IO.KeyCtrl)
{
}
#endif // #ifdef IMGUI_HAS_DOCK
End();
}
// [DEBUG] List fonts in a font atlas and display its texture
void ImGui::ShowFontAtlas(ImFontAtlas* atlas)
{
for (int i = 0; i < atlas->Fonts.Size; i++)
{
ImFont* font = atlas->Fonts[i];
PushID(font);
DebugNodeFont(font);
PopID();
}
if (TreeNode("Atlas texture", "Atlas texture (%dx%d pixels)", atlas->TexWidth, atlas->TexHeight))
{
ImVec4 tint_col = ImVec4(1.0f, 1.0f, 1.0f, 1.0f);
ImVec4 border_col = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
Image(atlas->TexID, ImVec2((float)atlas->TexWidth, (float)atlas->TexHeight), ImVec2(0.0f, 0.0f), ImVec2(1.0f, 1.0f), tint_col, border_col);
TreePop();
}
}
// [DEBUG] Display contents of Columns
void ImGui::DebugNodeColumns(ImGuiOldColumns* columns)
{
if (!TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
return;
BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->OffMaxX - columns->OffMinX, columns->OffMinX, columns->OffMaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, GetColumnOffsetFromNorm(columns, columns->Columns[column_n].OffsetNorm));
TreePop();
}
// [DEBUG] Display contents of ImDrawList
void ImGui::DebugNodeDrawList(ImGuiWindow* window, const ImDrawList* draw_list, const char* label)
{
ImGuiContext& g = *GImGui;
ImGuiMetricsConfig* cfg = &g.DebugMetricsConfig;
int cmd_count = draw_list->CmdBuffer.Size;
if (cmd_count > 0 && draw_list->CmdBuffer.back().ElemCount == 0 && draw_list->CmdBuffer.back().UserCallback == NULL)
cmd_count--;
bool node_open = 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, cmd_count);
if (draw_list == GetWindowDrawList())
{
SameLine();
TextColored(ImVec4(1.0f, 0.4f, 0.4f, 1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open)
TreePop();
return;
}
ImDrawList* fg_draw_list = GetForegroundDrawList(window); // Render additional visuals into the top-most draw list
if (window && IsItemHovered())
fg_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
if (window && !window->WasActive)
TextDisabled("Warning: owning Window is inactive. This DrawList is not being rendered!");
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.Data; pcmd < draw_list->CmdBuffer.Data + cmd_count; pcmd++)
{
if (pcmd->UserCallback)
{
BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
char buf[300];
ImFormatString(buf, IM_ARRAYSIZE(buf), "DrawCmd:%5d tris, Tex 0x%p, ClipRect (%4.0f,%4.0f)-(%4.0f,%4.0f)",
pcmd->ElemCount / 3, (void*)(intptr_t)pcmd->TextureId,
pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
bool pcmd_node_open = TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "%s", buf);
if (IsItemHovered() && (cfg->ShowDrawCmdMesh || cfg->ShowDrawCmdBoundingBoxes) && fg_draw_list)
DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, cfg->ShowDrawCmdMesh, cfg->ShowDrawCmdBoundingBoxes);
if (!pcmd_node_open)
continue;
// Calculate approximate coverage area (touched pixel count)
// This will be in pixels squared as long there's no post-scaling happening to the renderer output.
const ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
const ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + pcmd->VtxOffset;
float total_area = 0.0f;
for (unsigned int idx_n = pcmd->IdxOffset; idx_n < pcmd->IdxOffset + pcmd->ElemCount; )
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_n++)
triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos;
total_area += ImTriangleArea(triangle[0], triangle[1], triangle[2]);
}
// Display vertex information summary. Hover to get all triangles drawn in wire-frame
ImFormatString(buf, IM_ARRAYSIZE(buf), "Mesh: ElemCount: %d, VtxOffset: +%d, IdxOffset: +%d, Area: ~%0.f px", pcmd->ElemCount, pcmd->VtxOffset, pcmd->IdxOffset, total_area);
Selectable(buf);
if (IsItemHovered() && fg_draw_list)
DebugNodeDrawCmdShowMeshAndBoundingBox(fg_draw_list, draw_list, pcmd, true, false);
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper;
clipper.Begin(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, idx_i = pcmd->IdxOffset + clipper.DisplayStart * 3; prim < clipper.DisplayEnd; prim++)
{
char* buf_p = buf, * buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_i++)
{
const ImDrawVert& v = vtx_buffer[idx_buffer ? idx_buffer[idx_i] : idx_i];
triangle[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "Vert:" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
Selectable(buf, false);
if (fg_draw_list && IsItemHovered())
{
ImDrawListFlags backup_flags = fg_draw_list->Flags;
fg_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
fg_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f);
fg_draw_list->Flags = backup_flags;
}
}
TreePop();
}
TreePop();
}
// [DEBUG] Display mesh/aabb of a ImDrawCmd
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList* out_draw_list, const ImDrawList* draw_list, const ImDrawCmd* draw_cmd, bool show_mesh, bool show_aabb)
{
IM_ASSERT(show_mesh || show_aabb);
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
ImDrawVert* vtx_buffer = draw_list->VtxBuffer.Data + draw_cmd->VtxOffset;
// Draw wire-frame version of all triangles
ImRect clip_rect = draw_cmd->ClipRect;
ImRect vtxs_rect(FLT_MAX, FLT_MAX, -FLT_MAX, -FLT_MAX);
ImDrawListFlags backup_flags = out_draw_list->Flags;
out_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines is more readable for very large and thin triangles.
for (unsigned int idx_n = draw_cmd->IdxOffset; idx_n < draw_cmd->IdxOffset + draw_cmd->ElemCount; )
{
ImVec2 triangle[3];
for (int n = 0; n < 3; n++, idx_n++)
vtxs_rect.Add((triangle[n] = vtx_buffer[idx_buffer ? idx_buffer[idx_n] : idx_n].pos));
if (show_mesh)
out_draw_list->AddPolyline(triangle, 3, IM_COL32(255, 255, 0, 255), ImDrawFlags_Closed, 1.0f); // In yellow: mesh triangles
}
// Draw bounding boxes
if (show_aabb)
{
out_draw_list->AddRect(ImFloor(clip_rect.Min), ImFloor(clip_rect.Max), IM_COL32(255, 0, 255, 255)); // In pink: clipping rectangle submitted to GPU
out_draw_list->AddRect(ImFloor(vtxs_rect.Min), ImFloor(vtxs_rect.Max), IM_COL32(0, 255, 255, 255)); // In cyan: bounding box of triangles
}
out_draw_list->Flags = backup_flags;
}
// [DEBUG] Display details for a single font, called by ShowStyleEditor().
void ImGui::DebugNodeFont(ImFont* font)
{
bool opened = TreeNode(font, "Font: \"%s\"\n%.2f px, %d glyphs, %d file(s)",
font->ConfigData ? font->ConfigData[0].Name : "", font->FontSize, font->Glyphs.Size, font->ConfigDataCount);
SameLine();
if (SmallButton("Set as default"))
GetIO().FontDefault = font;
if (!opened)
return;
// Display preview text
PushFont(font);
Text("The quick brown fox jumps over the lazy dog");
PopFont();
// Display details
SetNextItemWidth(GetFontSize() * 8);
DragFloat("Font scale", &font->Scale, 0.005f, 0.3f, 2.0f, "%.1f");
SameLine(); MetricsHelpMarker(
"Note than the default embedded font is NOT meant to be scaled.\n\n"
"Font are currently rendered into bitmaps at a given size at the time of building the atlas. "
"You may oversample them to get some flexibility with scaling. "
"You can also render at multiple sizes and select which one to use at runtime.\n\n"
"(Glimmer of hope: the atlas system will be rewritten in the future to make scaling more flexible.)");
Text("Ascent: %f, Descent: %f, Height: %f", font->Ascent, font->Descent, font->Ascent - font->Descent);
char c_str[5];
Text("Fallback character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->FallbackChar), font->FallbackChar);
Text("Ellipsis character: '%s' (U+%04X)", ImTextCharToUtf8(c_str, font->EllipsisChar), font->EllipsisChar);
const int surface_sqrt = (int)ImSqrt((float)font->MetricsTotalSurface);
Text("Texture Area: about %d px ~%dx%d px", font->MetricsTotalSurface, surface_sqrt, surface_sqrt);
for (int config_i = 0; config_i < font->ConfigDataCount; config_i++)
if (font->ConfigData)
if (const ImFontConfig* cfg = &font->ConfigData[config_i])
BulletText("Input %d: \'%s\', Oversample: (%d,%d), PixelSnapH: %d, Offset: (%.1f,%.1f)",
config_i, cfg->Name, cfg->OversampleH, cfg->OversampleV, cfg->PixelSnapH, cfg->GlyphOffset.x, cfg->GlyphOffset.y);
// Display all glyphs of the fonts in separate pages of 256 characters
if (TreeNode("Glyphs", "Glyphs (%d)", font->Glyphs.Size))
{
ImDrawList* draw_list = GetWindowDrawList();
const ImU32 glyph_col = GetColorU32(ImGuiCol_Text);
const float cell_size = font->FontSize * 1;
const float cell_spacing = GetStyle().ItemSpacing.y;
for (unsigned int base = 0; base <= IM_UNICODE_CODEPOINT_MAX; base += 256)
{
// Skip ahead if a large bunch of glyphs are not present in the font (test in chunks of 4k)
// This is only a small optimization to reduce the number of iterations when IM_UNICODE_MAX_CODEPOINT
// is large // (if ImWchar==ImWchar32 we will do at least about 272 queries here)
if (!(base & 4095) && font->IsGlyphRangeUnused(base, base + 4095))
{
base += 4096 - 256;
continue;
}
int count = 0;
for (unsigned int n = 0; n < 256; n++)
if (font->FindGlyphNoFallback((ImWchar)(base + n)))
count++;
if (count <= 0)
continue;
if (!TreeNode((void*)(intptr_t)base, "U+%04X..U+%04X (%d %s)", base, base + 255, count, count > 1 ? "glyphs" : "glyph"))
continue;
// Draw a 16x16 grid of glyphs
ImVec2 base_pos = GetCursorScreenPos();
for (unsigned int n = 0; n < 256; n++)
{
// We use ImFont::RenderChar as a shortcut because we don't have UTF-8 conversion functions
// available here and thus cannot easily generate a zero-terminated UTF-8 encoded string.
ImVec2 cell_p1(base_pos.x + (n % 16) * (cell_size + cell_spacing), base_pos.y + (n / 16) * (cell_size + cell_spacing));
ImVec2 cell_p2(cell_p1.x + cell_size, cell_p1.y + cell_size);
const ImFontGlyph* glyph = font->FindGlyphNoFallback((ImWchar)(base + n));
draw_list->AddRect(cell_p1, cell_p2, glyph ? IM_COL32(255, 255, 255, 100) : IM_COL32(255, 255, 255, 50));
if (glyph)
font->RenderChar(draw_list, cell_size, cell_p1, glyph_col, (ImWchar)(base + n));
if (glyph && IsMouseHoveringRect(cell_p1, cell_p2))
{
BeginTooltip();
Text("Codepoint: U+%04X", base + n);
Separator();
Text("Visible: %d", glyph->Visible);
Text("AdvanceX: %.1f", glyph->AdvanceX);
Text("Pos: (%.2f,%.2f)->(%.2f,%.2f)", glyph->X0, glyph->Y0, glyph->X1, glyph->Y1);
Text("UV: (%.3f,%.3f)->(%.3f,%.3f)", glyph->U0, glyph->V0, glyph->U1, glyph->V1);
EndTooltip();
}
}
Dummy(ImVec2((cell_size + cell_spacing) * 16, (cell_size + cell_spacing) * 16));
TreePop();
}
TreePop();
}
TreePop();
}
// [DEBUG] Display contents of ImGuiStorage
void ImGui::DebugNodeStorage(ImGuiStorage* storage, const char* label)
{
if (!TreeNode(label, "%s: %d entries, %d bytes", label, storage->Data.Size, storage->Data.size_in_bytes()))
return;
for (int n = 0; n < storage->Data.Size; n++)
{
const ImGuiStorage::ImGuiStoragePair& p = storage->Data[n];
BulletText("Key 0x%08X Value { i: %d }", p.key, p.val_i); // Important: we currently don't store a type, real value may not be integer.
}
TreePop();
}
// [DEBUG] Display contents of ImGuiTabBar
void ImGui::DebugNodeTabBar(ImGuiTabBar* tab_bar, const char* label)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
const bool is_active = (tab_bar->PrevFrameVisible >= GetFrameCount() - 2);
p += ImFormatString(p, buf_end - p, "%s 0x%08X (%d tabs)%s", label, tab_bar->ID, tab_bar->Tabs.Size, is_active ? "" : " *Inactive*");
IM_UNUSED(p);
if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
bool open = TreeNode(tab_bar, "%s", buf);
if (!is_active) { PopStyleColor(); }
if (is_active && IsItemHovered())
{
ImDrawList* draw_list = GetForegroundDrawList();
draw_list->AddRect(tab_bar->BarRect.Min, tab_bar->BarRect.Max, IM_COL32(255, 255, 0, 255));
draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMinX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
draw_list->AddLine(ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Min.y), ImVec2(tab_bar->ScrollingRectMaxX, tab_bar->BarRect.Max.y), IM_COL32(0, 255, 0, 255));
}
if (open)
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
PushID(tab);
if (SmallButton("<")) { TabBarQueueReorder(tab_bar, tab, -1); } SameLine(0, 2);
if (SmallButton(">")) { TabBarQueueReorder(tab_bar, tab, +1); } SameLine();
Text("%02d%c Tab 0x%08X '%s' Offset: %.1f, Width: %.1f/%.1f",
tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, (tab->NameOffset != -1) ? tab_bar->GetTabName(tab) : "", tab->Offset, tab->Width, tab->ContentWidth);
PopID();
}
TreePop();
}
}
void ImGui::DebugNodeViewport(ImGuiViewportP* viewport)
{
SetNextItemOpen(true, ImGuiCond_Once);
if (TreeNode("viewport0", "Viewport #%d", 0))
{
ImGuiWindowFlags flags = viewport->Flags;
BulletText("Main Pos: (%.0f,%.0f), Size: (%.0f,%.0f)\nWorkArea Offset Left: %.0f Top: %.0f, Right: %.0f, Bottom: %.0f",
viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y,
viewport->WorkOffsetMin.x, viewport->WorkOffsetMin.y, viewport->WorkOffsetMax.x, viewport->WorkOffsetMax.y);
BulletText("Flags: 0x%04X =%s%s%s", viewport->Flags,
(flags & ImGuiViewportFlags_IsPlatformWindow) ? " IsPlatformWindow" : "",
(flags & ImGuiViewportFlags_IsPlatformMonitor) ? " IsPlatformMonitor" : "",
(flags & ImGuiViewportFlags_OwnedByApp) ? " OwnedByApp" : "");
for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
DebugNodeDrawList(NULL, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
TreePop();
}
}
void ImGui::DebugNodeWindow(ImGuiWindow* window, const char* label)
{
if (window == NULL)
{
BulletText("%s: NULL", label);
return;
}
ImGuiContext& g = *GImGui;
const bool is_active = window->WasActive;
ImGuiTreeNodeFlags tree_node_flags = (window == g.NavWindow) ? ImGuiTreeNodeFlags_Selected : ImGuiTreeNodeFlags_None;
if (!is_active) { PushStyleColor(ImGuiCol_Text, GetStyleColorVec4(ImGuiCol_TextDisabled)); }
const bool open = TreeNodeEx(label, tree_node_flags, "%s '%s'%s", label, window->Name, is_active ? "" : " *Inactive*");
if (!is_active) { PopStyleColor(); }
if (IsItemHovered() && is_active)
GetForegroundDrawList(window)->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!open)
return;
if (window->MemoryCompacted)
TextDisabled("Note: some memory buffers have been compacted/freed.");
ImGuiWindowFlags flags = window->Flags;
DebugNodeDrawList(window, window->DrawList, "DrawList");
BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), ContentSize (%.1f,%.1f) Ideal (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->ContentSize.x, window->ContentSize.y, window->ContentSizeIdeal.x, window->ContentSizeIdeal.y);
BulletText("Flags: 0x%08X (%s%s%s%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 " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f) Scrollbar:%s%s", window->Scroll.x, window->ScrollMax.x, window->Scroll.y, window->ScrollMax.y, window->ScrollbarX ? "X" : "", window->ScrollbarY ? "Y" : "");
BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
BulletText("Appearing: %d, Hidden: %d (CanSkip %d Cannot %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesCanSkipItems, window->HiddenFramesCannotSkipItems, window->SkipItems);
for (int layer = 0; layer < ImGuiNavLayer_COUNT; layer++)
{
ImRect r = window->NavRectRel[layer];
if (r.Min.x >= r.Max.y && r.Min.y >= r.Max.y)
{
BulletText("NavLastIds[%d]: 0x%08X", layer, window->NavLastIds[layer]);
continue;
}
BulletText("NavLastIds[%d]: 0x%08X at +(%.1f,%.1f)(%.1f,%.1f)", layer, window->NavLastIds[layer], r.Min.x, r.Min.y, r.Max.x, r.Max.y);
if (IsItemHovered())
GetForegroundDrawList(window)->AddRect(r.Min + window->Pos, r.Max + window->Pos, IM_COL32(255, 255, 0, 255));
}
BulletText("NavLayersActiveMask: %X, NavLastChildNavWindow: %s", window->DC.NavLayersActiveMask, window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (window->RootWindow != window) { DebugNodeWindow(window->RootWindow, "RootWindow"); }
if (window->ParentWindow != NULL) { DebugNodeWindow(window->ParentWindow, "ParentWindow"); }
if (window->DC.ChildWindows.Size > 0) { DebugNodeWindowsList(&window->DC.ChildWindows, "ChildWindows"); }
if (window->ColumnsStorage.Size > 0 && TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
DebugNodeColumns(&window->ColumnsStorage[n]);
TreePop();
}
DebugNodeStorage(&window->StateStorage, "Storage");
TreePop();
}
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings* settings)
{
Text("0x%08X \"%s\" Pos (%d,%d) Size (%d,%d) Collapsed=%d",
settings->ID, settings->GetName(), settings->Pos.x, settings->Pos.y, settings->Size.x, settings->Size.y, settings->Collapsed);
}
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>* windows, const char* label)
{
if (!TreeNode(label, "%s (%d)", label, windows->Size))
return;
Text("(In front-to-back order:)");
for (int i = windows->Size - 1; i >= 0; i--) // Iterate front to back
{
PushID((*windows)[i]);
DebugNodeWindow((*windows)[i], "Window");
PopID();
}
TreePop();
}
#else
void ImGui::ShowMetricsWindow(bool*) {}
void ImGui::ShowFontAtlas(ImFontAtlas*) {}
void ImGui::DebugNodeColumns(ImGuiOldColumns*) {}
void ImGui::DebugNodeDrawList(ImGuiWindow*, const ImDrawList*, const char*) {}
void ImGui::DebugNodeDrawCmdShowMeshAndBoundingBox(ImDrawList*, const ImDrawList*, const ImDrawCmd*, bool, bool) {}
void ImGui::DebugNodeFont(ImFont*) {}
void ImGui::DebugNodeStorage(ImGuiStorage*, const char*) {}
void ImGui::DebugNodeTabBar(ImGuiTabBar*, const char*) {}
void ImGui::DebugNodeWindow(ImGuiWindow*, const char*) {}
void ImGui::DebugNodeWindowSettings(ImGuiWindowSettings*) {}
void ImGui::DebugNodeWindowsList(ImVector<ImGuiWindow*>*, const char*) {}
void ImGui::DebugNodeViewport(ImGuiViewportP*) {}
#endif
//-----------------------------------------------------------------------------
// 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
//-----------------------------------------------------------------------------
#endif // #ifndef IMGUI_DISABLE
|
// Copyright 2019 Nikita Fediuchin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <string>
using namespace std;
typedef GLFWwindow* GlfwWindow;
// Injector engine name
const string EngineName = "Injector Engine";
// Injector engine version
const uint32_t EngineVersion = VK_MAKE_VERSION(0, 1, 0);
// Vulkan API version
const uint32_t VulkanVersion = VK_API_VERSION_1_1;
|
// Copyright (c) 2011-2013 The Bitcoin Core developers
// Copyright (c) 2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#define BOOST_TEST_MODULE Macrocoin Test Suite
#include "main.h"
#include "random.h"
#include "txdb.h"
#include "ui_interface.h"
#include "util.h"
#ifdef ENABLE_WALLET
#include "db.h"
#include "wallet.h"
#endif
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/thread.hpp>
CClientUIInterface uiInterface;
CWallet* pwalletMain;
extern bool fPrintToConsole;
extern void noui_connect();
struct TestingSetup {
CCoinsViewDB *pcoinsdbview;
boost::filesystem::path pathTemp;
boost::thread_group threadGroup;
ECCVerifyHandle globalVerifyHandle;
TestingSetup() {
ECC_Start();
SetupEnvironment();
fPrintToDebugLog = false; // don't want to write to debug.log file
fCheckBlockIndex = true;
SelectParams(CBaseChainParams::UNITTEST);
noui_connect();
#ifdef ENABLE_WALLET
bitdb.MakeMock();
#endif
pathTemp = GetTempPath() / strprintf("test_macrocoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex();
#ifdef ENABLE_WALLET
bool fFirstRun;
pwalletMain = new CWallet("wallet.dat");
pwalletMain->LoadWallet(fFirstRun);
RegisterValidationInterface(pwalletMain);
#endif
nScriptCheckThreads = 3;
for (int i=0; i < nScriptCheckThreads-1; i++)
threadGroup.create_thread(&ThreadScriptCheck);
RegisterNodeSignals(GetNodeSignals());
}
~TestingSetup()
{
threadGroup.interrupt_all();
threadGroup.join_all();
UnregisterNodeSignals(GetNodeSignals());
#ifdef ENABLE_WALLET
delete pwalletMain;
pwalletMain = NULL;
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
#ifdef ENABLE_WALLET
bitdb.Flush(true);
#endif
boost::filesystem::remove_all(pathTemp);
ECC_Stop();
}
};
BOOST_GLOBAL_FIXTURE(TestingSetup);
void Shutdown(void* parg)
{
exit(0);
}
void StartShutdown()
{
exit(0);
}
bool ShutdownRequested()
{
return false;
}
|
/*
* Copyright 2014 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "util.hpp"
#include "mixedutil.hpp"
#include "columntypeutil.hpp"
using namespace tightdb;
jclass GetClassMixed(JNIEnv* env)
{
static jclass jMixedClass = GetClass(env, "io/realm/internal/Mixed");
return jMixedClass;
}
jmethodID GetMixedMethodID(JNIEnv* env, const char* methodStr, const char* typeStr)
{
jclass myClass = GetClassMixed(env);
if (myClass == NULL)
return NULL;
jmethodID myMethod = env->GetMethodID(myClass, methodStr, typeStr);
if (myMethod == NULL) {
ThrowException(env, NoSuchMethod, "mixed", methodStr);
return NULL;
}
return myMethod;
}
DataType GetMixedObjectType(JNIEnv* env, jobject jMixed)
{
// Call Java "Mixed.getType"
static jmethodID jGetTypeMethodId = GetMixedMethodID(env, "getType", "()Lio/realm/internal/ColumnType;");
if (jGetTypeMethodId == NULL)
return DataType(0);
// ???TODO optimize
jobject jColumnType = env->CallObjectMethod(jMixed, jGetTypeMethodId);
return static_cast<DataType>(GetColumnTypeFromJColumnType(env, jColumnType));
}
jobject CreateJMixedFromMixed(JNIEnv* env, Mixed& mixed)
{
jclass jMixedClass = GetClassMixed(env);
if (jMixedClass == NULL)
return NULL;
TR((env, "CreateJMixedFromMixed(type %d)\n", mixed.get_type()));
switch (mixed.get_type()) {
case type_Int:
{
jmethodID consId = GetMixedMethodID(env, "<init>", "(J)V");
if (consId)
return env->NewObject(jMixedClass, consId, mixed.get_int());
}
case type_Float:
{
jmethodID consId = GetMixedMethodID(env, "<init>", "(F)V");
if (consId)
return env->NewObject(jMixedClass, consId, mixed.get_float());
}
case type_Double:
{
jmethodID consId = GetMixedMethodID(env, "<init>", "(D)V");
if (consId)
return env->NewObject(jMixedClass, consId, mixed.get_double());
}
case type_String:
{
jmethodID consId = GetMixedMethodID(env, "<init>", "(Ljava/lang/String;)V");
if (consId)
return env->NewObject(jMixedClass, consId, to_jstring(env, mixed.get_string()));
}
case type_Bool:
{
jmethodID consId = GetMixedMethodID(env, "<init>", "(Z)V");
if (consId)
return env->NewObject(jMixedClass, consId, mixed.get_bool());
}
case type_DateTime:
{
time_t timeValue = mixed.get_datetime().get_datetime();
jclass jDateClass = env->FindClass("java/util/Date");
if (jDateClass == NULL) {
ThrowException(env, ClassNotFound, "Date");
return NULL;
}
jmethodID jDateConsId = env->GetMethodID(jDateClass, "<init>", "(J)V");
if (jDateConsId == NULL) {
ThrowException(env, NoSuchMethod, "Date", "<init>");
return NULL;
}
jobject jDate = env->NewObject(jDateClass, jDateConsId, static_cast<jlong>(timeValue));
jmethodID consId = GetMixedMethodID(env, "<init>", "(Ljava/util/Date;)V");
if (consId)
return env->NewObject(jMixedClass, consId, jDate);
}
case type_Binary:
{
BinaryData binaryData = mixed.get_binary();
jmethodID consId = GetMixedMethodID(env, "<init>", "(Ljava/nio/ByteBuffer;)V");
if (consId) {
jobject jByteBuffer = env->NewDirectByteBuffer(const_cast<char*>(binaryData.data()), binaryData.size());
return env->NewObject(jMixedClass, consId, jByteBuffer);
}
}
case type_Table:
{
// param input: Table* t.
TR((env, " --Mixed(type_Table)\n"));
jmethodID consId = GetMixedMethodID(env, "<init>", "(Lio/realm/internal/ColumnType;)V");
jobject jColumnType = NULL; // GetJColumnTypeFromColumnType(env, type_Table);
if (consId)
return env->NewObject(jMixedClass, consId, jColumnType);
}
case type_Mixed:
break;
case type_Link:
break;
case type_LinkList:
break;
}
return NULL;
}
jlong GetMixedIntValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetLongValueMethodId = GetMixedMethodID(env, "getLongValue", "()J");
if (jGetLongValueMethodId)
return env->CallLongMethod(jMixed, jGetLongValueMethodId);
return 0;
}
jfloat GetMixedFloatValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetFloatValueMethodId = GetMixedMethodID(env, "getFloatValue", "()F");
if (jGetFloatValueMethodId)
return env->CallFloatMethod(jMixed, jGetFloatValueMethodId);
return 0;
}
jdouble GetMixedDoubleValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetDoubleValueMethodId = GetMixedMethodID(env, "getDoubleValue", "()D");
if (jGetDoubleValueMethodId)
return env->CallDoubleMethod(jMixed, jGetDoubleValueMethodId);
return 0;
}
jstring GetMixedStringValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetStringValueMethodId = GetMixedMethodID(env, "getStringValue", "()Ljava/lang/String;");;
if (jGetStringValueMethodId)
return (jstring)(env->CallObjectMethod(jMixed, jGetStringValueMethodId));
return 0;
}
jboolean GetMixedBooleanValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetBoolValueMethodId = GetMixedMethodID(env, "getBooleanValue", "()Z");
if (jGetBoolValueMethodId)
return env->CallBooleanMethod(jMixed, jGetBoolValueMethodId);
return 0;
}
jbyteArray GetMixedByteArrayValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetBinaryDataMethodId = GetMixedMethodID(env, "getBinaryByteArray", "()[B");
if (jGetBinaryDataMethodId)
return reinterpret_cast<jbyteArray>(env->CallObjectMethod(jMixed, jGetBinaryDataMethodId));
return 0;
}
jlong GetMixedDateTimeValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetDateTimeMethodId = GetMixedMethodID(env, "getDateTimeValue", "()J");
if (jGetDateTimeMethodId)
return env->CallLongMethod(jMixed, jGetDateTimeMethodId);
return 0;
}
jobject GetMixedByteBufferValue(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetBinaryValueMethodId = GetMixedMethodID(env, "getBinaryValue", "()Ljava/nio/ByteBuffer;");
if (jGetBinaryValueMethodId)
return env->CallObjectMethod(jMixed, jGetBinaryValueMethodId);
return 0;
}
jint GetMixedBinaryType(JNIEnv* env, jobject jMixed)
{
static jmethodID jGetBinaryTypeMethodId = GetMixedMethodID(env, "getBinaryType", "()I");
if (jGetBinaryTypeMethodId)
return env->CallIntMethod(jMixed, jGetBinaryTypeMethodId);
return 0;
}
|
/*
-- MAGMA (version 2.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date
@author Adrien REMY
@generated from src/zgetrs_nopiv_gpu.cpp, normal z -> s, Sat Mar 27 20:30:34 2021
*/
#include "magma_internal.h"
/***************************************************************************//**
Purpose
-------
SGETRS solves a system of linear equations
A * X = B,
A**T * X = B, or
A**H * X = B
with a general N-by-N matrix A using the LU factorization computed by SGETRF_NOPIV_GPU.
Arguments
---------
@param[in]
trans magma_trans_t
Specifies the form of the system of equations:
- = MagmaNoTrans: A * X = B (No transpose)
- = MagmaTrans: A**T * X = B (Transpose)
- = MagmaConjTrans: A**H * X = B (Conjugate transpose)
@param[in]
n INTEGER
The order of the matrix A. N >= 0.
@param[in]
nrhs INTEGER
The number of right hand sides, i.e., the number of columns
of the matrix B. NRHS >= 0.
@param[in]
dA REAL array on the GPU, dimension (LDDA,N)
The factors L and U from the factorization A = P*L*U as computed
by SGETRF_GPU.
@param[in]
ldda INTEGER
The leading dimension of the array A. LDDA >= max(1,N).
@param[in,out]
dB REAL array on the GPU, dimension (LDDB,NRHS)
On entry, the right hand side matrix B.
On exit, the solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array B. LDDB >= max(1,N).
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_getrs_nopiv
*******************************************************************************/
extern "C" magma_int_t
magma_sgetrs_nopiv_gpu(
magma_trans_t trans, magma_int_t n, magma_int_t nrhs,
magmaFloat_ptr dA, magma_int_t ldda,
magmaFloat_ptr dB, magma_int_t lddb,
magma_int_t *info)
{
// Constants
const float c_one = MAGMA_S_ONE;
// Local variables
bool notran = (trans == MagmaNoTrans);
*info = 0;
if ( (! notran) &&
(trans != MagmaTrans) &&
(trans != MagmaConjTrans) ) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (nrhs < 0) {
*info = -3;
} else if (ldda < max(1,n)) {
*info = -5;
} else if (lddb < max(1,n)) {
*info = -7;
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
/* Quick return if possible */
if (n == 0 || nrhs == 0) {
return *info;
}
magma_queue_t queue = NULL;
magma_device_t cdev;
magma_getdevice( &cdev );
magma_queue_create( cdev, &queue );
if (notran) {
/* Solve A * X = B. */
if ( nrhs == 1) {
magma_strsv( MagmaLower, MagmaNoTrans, MagmaUnit, n, dA, ldda, dB, 1, queue );
magma_strsv( MagmaUpper, MagmaNoTrans, MagmaNonUnit, n, dA, ldda, dB, 1, queue );
} else {
magma_strsm( MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, n, nrhs, c_one, dA, ldda, dB, lddb, queue );
magma_strsm( MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, n, nrhs, c_one, dA, ldda, dB, lddb, queue );
}
} else {
/* Solve A**T * X = B or A**H * X = B. */
if ( nrhs == 1) {
magma_strsv( MagmaUpper, trans, MagmaNonUnit, n, dA, ldda, dB, 1, queue );
magma_strsv( MagmaLower, trans, MagmaUnit, n, dA, ldda, dB, 1, queue );
} else {
magma_strsm( MagmaLeft, MagmaUpper, trans, MagmaNonUnit, n, nrhs, c_one, dA, ldda, dB, lddb, queue );
magma_strsm( MagmaLeft, MagmaLower, trans, MagmaUnit, n, nrhs, c_one, dA, ldda, dB, lddb, queue );
}
}
magma_queue_destroy( queue );
return *info;
}
|
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2015, Daichi Yoshikawa
* 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 Daichi Yoshikawa nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author: Daichi Yoshikawa
*
*********************************************************************/
#ifndef __AHL_ROBOT_LINK_HPP
#define __AHL_ROBOT_LINK_HPP
#include <iostream>
#include <memory>
#include <Eigen/Dense>
#include "ahl_robot/robot/transformation.hpp"
namespace ahl_robot
{
class Link;
using LinkPtr = std::shared_ptr<Link>;
class Link
{
public:
explicit Link ()
{
T_org = Eigen::Matrix4d::Identity();
C = Eigen::Vector3d::Zero();
I = Eigen::Matrix3d::Zero();
}
void print()
{
std::cout << "name : " << name << std::endl
<< "joint_type : " << joint_type << std::endl
<< "parent : " << parent << std::endl
<< "child : " << child << std::endl
<< "ep : " << ep << std::endl
<< "T_org : " << std::endl << T_org << std::endl
<< "C : " << std::endl << C << std::endl
<< "m : " << m << std::endl
<< "I : " << std::endl << I << std::endl
<< "q_min : " << q_min << std::endl
<< "q_max : " << q_max << std::endl
<< "dq_max : " << dq_max << std::endl
<< "tau : " << tau << std::endl
<< "tau_max : " << tau_max << std::endl;
}
std::string name = "";
std::string joint_type = "";
std::string parent = "";
std::string child = "";
bool ep = false;
TransformationPtr tf = nullptr;
Eigen::Matrix4d T_org;
Eigen::Vector3d C;
double m = 0.0;
Eigen::Matrix3d I;
double q_min = 0.0;
double q_max = 0.0;
double dq_max = 0.0;
double tau = 0.0;
double tau_max = 0.0;
};
} // namespace ahl_robot
#endif // __AHL_ROBOT_LINK_HPP
|
#ifdef COMPILATION// -*-indent-tabs-mode:t;c-basic-offset:4;tab-width:4-*-
$CXX $0 -o $0x -lcudart -lboost_unit_test_framework -lboost_timer&&$0x&&rm $0x;exit
#endif
// © Alfredo A. Correa 2019-2020
#ifndef MULTI_ADAPTORS_CUDA_HPP
#define MULTI_ADAPTORS_CUDA_HPP
#include "../memory/adaptors/cuda/allocator.hpp"
#include "../memory/adaptors/cuda/managed/allocator.hpp"
#include "../adaptors/cuda/algorithms/copy.hpp"
#include "../array.hpp"
namespace boost{
namespace multi{
namespace cuda{
template<class T>
using allocator = multi::memory::cuda::allocator<T>;
template<class T> using ptr = multi::memory::cuda::ptr<T>;
template<class T, multi::dimensionality_type D>
using array = multi::array<T, D, cuda::allocator<T>>;
template<class T, multi::dimensionality_type D>
using array_ref = multi::array_ref<T, D, cuda::ptr<T>>;
template<class T, multi::dimensionality_type D>
using static_array = multi::static_array<T, D, cuda::allocator<T>>;
template<class A> auto raw_array_cast(A&& a)
->decltype(static_array_cast<typename A::element_type, decltype(raw_pointer_cast(base(std::forward<A>(a))))>(std::forward<A>(a))){
return static_array_cast<typename A::element_type, decltype(raw_pointer_cast(base(std::forward<A>(a))))>(std::forward<A>(a));}
namespace managed{
template<class T>
using allocator = multi::memory::cuda::managed::allocator<T>;
template<class T> using ptr = multi::memory::cuda::managed::ptr<T>;
template<class T, multi::dimensionality_type D>
using array = multi::array<T, D, cuda::managed::allocator<T>>;
template<class T, multi::dimensionality_type D>
using array_ref = multi::array<T, D, multi::memory::cuda::managed::ptr<T>>;
template<class T, multi::dimensionality_type D>
using static_array = multi::array<T, D, multi::memory::cuda::managed::ptr<T>>;
}
}
/*
auto copy(const double* first, const double* last, boost::multi::array_iterator<double, 1, boost::multi::memory::cuda::managed::ptr<double, double*>, double&> d_first){
return copy(
boost::multi::array_iterator<double, 1, double const*, double const&>(first),
boost::multi::array_iterator<double, 1, double const*, double const&>(last),
d_first
);
}*/
}}
#if not __INCLUDE_LEVEL__
#define BOOST_TEST_MODULE "C++ Unit Tests for Multi CUDA adaptor"
#define BOOST_TEST_DYN_LINK
#include<boost/test/unit_test.hpp>
#include<boost/timer/timer.hpp>
#include<chrono>
#include<numeric>
template <class T>
__attribute__((always_inline)) inline void DoNotOptimize(const T &value) {
asm volatile("" : "+m"(const_cast<T &>(value)));
}
struct watch : private std::chrono::high_resolution_clock{
std::string label_; time_point start_;
watch(std::string label ="") : label_{label}, start_{now()}{}
~watch(){
std::cerr<< label_<<": "<< std::chrono::duration<double>(now() - start_).count() <<" sec"<<std::endl;
}
};
namespace multi = boost::multi;
namespace cuda = multi::cuda;
namespace utf = boost::unit_test::framework;
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_construct_1d){
multi::array<double, 1> A(4, 99.);
cuda::array<double, 1> Agpu{A};
BOOST_REQUIRE( extensions(A) == extensions(Agpu) );
BOOST_REQUIRE( Agpu == A );
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_copy_1d){
multi::array<double, 1> A(4, 99.);
cuda::array<double, 1> Agpu(4);
BOOST_REQUIRE( extensions(A) == extensions(Agpu) );
Agpu({0, 4}) = A({0, 4});
BOOST_REQUIRE( Agpu == A );
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_construct_2d){
multi::array<double, 2> A({4, 6}, 99.);
cuda::array<double, 2> Agpu{A};
BOOST_REQUIRE( extensions(A) == extensions(Agpu) );
BOOST_REQUIRE( Agpu == A );
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_copy_2d){
multi::array<double, 2> A({4, 6}); std::iota(A.data_elements(), A.data_elements() + A.num_elements(), 1.);
cuda::array<double, 2> Agpu({4, 6}, 99.);
BOOST_REQUIRE( extensions(A) == extensions(Agpu) );
Agpu({0, 4}, {1, 6}) = A({0, 4}, {1, 6});
BOOST_REQUIRE( Agpu != A );
Agpu = A;
BOOST_REQUIRE( Agpu == A );
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_copy_vs_move){
cuda::array<double, 4> Agpu({30, 100, 100, 100}, 99.);
[&, _ = watch{utf::current_test_case().full_name()+" COPY"}]{
cuda::array<double, 4> Agpu_cpy = Agpu;
BOOST_REQUIRE( &Agpu_cpy[1][2][3][4] != &Agpu[1][2][3][4] );
BOOST_REQUIRE( Agpu_cpy[1][2][3][4] == Agpu[1][2][3][4] );
}();
[&, _ = watch{utf::current_test_case().full_name()+" MOVE"}]{
cuda::array<double, 4> Agpu_mov = std::move(Agpu);
BOOST_REQUIRE( Agpu.empty() );
BOOST_REQUIRE( Agpu_mov.size() == 30 );
}();
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_copy_vs_move_complex){
using complex = std::complex<double>;
cuda::array<complex, 4> Agpu({30, 100, 100, 100}, 99.);
[&, _ = watch{utf::current_test_case().full_name()+" COPY"}]{
cuda::array<complex, 4> Agpu_cpy = Agpu;
BOOST_REQUIRE( &Agpu_cpy[1][2][3][4] != &Agpu[1][2][3][4] );
BOOST_REQUIRE( Agpu_cpy[1][2][3][4] == Agpu[1][2][3][4] );
}();
[&, _ = watch{utf::current_test_case().full_name()+" MOVE"}]{
cuda::array<complex, 4> Agpu_mov = std::move(Agpu);
BOOST_REQUIRE( Agpu.empty() );
BOOST_REQUIRE( Agpu_mov.size() == 30 );
}();
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_managed_double){
cuda::managed::array<double, 4> A({2,3,4,5});
cuda::managed::array<double, 4> B({2,3,4,5}, 0.);
cuda::managed::array<double, 4> C({2,3,4,5}, 5.);
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_managed_ai3){
using ai3 = std::array<int, 3>;
cuda::managed::array<ai3, 4> A({2,3,4,5}); // default initialize elements
cuda::managed::array<ai3, 4> B({2,3,4,5}, ai3{} ); // value initialize elements
cuda::managed::array<ai3, 4> C({2,3,4,5}, ai3{11, 22, 33} ); // value initialize elements
}
#if 0
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda_copy){
multi::array<double, 2> A({4, 5}, 99.);
cuda::array<double, 2> Agpu = A;
}
BOOST_AUTO_TEST_CASE(multi_adaptors_cuda){
multi::array<double, 2> A({4, 5}, 99.);
cuda::array<double, 2> Agpu = A;
assert( Agpu == A );
cuda::managed::array<double, 2> Amng = A;
assert( Amng == Agpu );
cuda::array_ref<double, 2> Rgpu(data_elements(Agpu), extensions(Agpu));
{std::allocator<double> a = get_allocator(A);}
{
cuda::ptr<double> p;
using multi::get_allocator;
cuda::allocator<double> a = get_allocator(p); (void)a;
}
{
cuda::managed::ptr<double> p;
using multi::get_allocator;
cuda::managed::allocator<double> a = get_allocator(p); (void)a;
}
{
double* p = nullptr;
using multi::get_allocator;
std::allocator<double> a = get_allocator(p); (void)a;
}
{
multi::array<double, 2> arr;
std::allocator<double> a = get_allocator(arr);
}
{
cuda::array<double, 2> arr;
cuda::allocator<double> a = get_allocator(arr); (void)a;
}
{
// cuda::array<double, 0> arr = 45.;
// BOOST_REQUIRE( arr() == 45. );
}
{
// cuda::managed::array<double, 0> arr = 45.;
// BOOST_REQUIRE( arr() == 45. );
}
{
cuda::managed::array<double, 1> arr = {1.2, 3.4, 4.5};
}
{
using complex = std::complex<double>;
cuda::managed::array<complex, 2> a({1000, 1000}, 99.);
BOOST_REQUIRE( size(a) == 1000 );
cuda::managed::array<complex, 2> b;
b = std::move(a);
BOOST_REQUIRE( size(b) == 1000 );
BOOST_REQUIRE( size(a) == 0 );
}
}
#endif
#endif
#endif
|
// (C) Copyright Edward Diener 2011,2012,2013
// 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).
#if !defined(BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP)
#define BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP
#include <boost/mpl/bool.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/tti/detail/dnullptr.hpp>
#include <boost/tti/detail/dmacro_sunfix.hpp>
#include <boost/tti/detail/dtfunction.hpp>
#include <boost/tti/detail/denclosing_type.hpp>
#include <boost/tti/detail/dstatic_function_tags.hpp>
#include <boost/tti/detail/dstatic_function_type.hpp>
#include <boost/tti/gen/namespace_gen.hpp>
#include <boost/type_traits/detail/yes_no_type.hpp>
#define BOOST_TTI_DETAIL_TRAIT_IMPL_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_TYPE> \
struct BOOST_PP_CAT(trait,_detail_ihsmf) \
{ \
template<BOOST_TTI_DETAIL_TP_TYPE *> \
struct helper BOOST_TTI_DETAIL_MACRO_SUNFIX ; \
\
template<class BOOST_TTI_DETAIL_TP_U> \
static ::boost::type_traits::yes_type chkt(helper<&BOOST_TTI_DETAIL_TP_U::name> *); \
\
template<class BOOST_TTI_DETAIL_TP_U> \
static ::boost::type_traits::no_type chkt(...); \
\
typedef boost::mpl::bool_<sizeof(chkt<BOOST_TTI_DETAIL_TP_T>(BOOST_TTI_DETAIL_NULLPTR))==sizeof(::boost::type_traits::yes_type)> type; \
}; \
/**/
#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_TEST_FUNC_CALL(trait,name) \
template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
struct BOOST_PP_CAT(trait,_detail_hsmf_ttc) : \
BOOST_PP_CAT(trait,_detail_ihsmf) \
< \
BOOST_TTI_DETAIL_TP_T, \
typename BOOST_TTI_NAMESPACE::detail::tfunction_seq<BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG>::type \
> \
{ \
}; \
/**/
#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_TEST_FUNC(trait,name) \
BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_TEST_FUNC_CALL(trait,name) \
template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
struct BOOST_PP_CAT(trait,_detail_hsmf_tt) : \
boost::mpl::eval_if \
< \
BOOST_TTI_NAMESPACE::detail::static_function_tag<BOOST_TTI_DETAIL_TP_TAG>, \
BOOST_PP_CAT(trait,_detail_hsmf_ttc)<BOOST_TTI_DETAIL_TP_T,BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG>, \
boost::mpl::false_ \
> \
{ \
}; \
/**/
#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_OP(trait,name) \
BOOST_TTI_DETAIL_TRAIT_IMPL_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_TEST_FUNC(trait,name) \
template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
struct BOOST_PP_CAT(trait,_detail_hsmf_op) : \
boost::mpl::eval_if \
< \
BOOST_TTI_NAMESPACE::detail::static_function_type<BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG>, \
BOOST_PP_CAT(trait,_detail_ihsmf)<BOOST_TTI_DETAIL_TP_T,BOOST_TTI_DETAIL_TP_R>, \
BOOST_PP_CAT(trait,_detail_hsmf_tt)<BOOST_TTI_DETAIL_TP_T,BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG> \
> \
{ \
}; \
/**/
#define BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION(trait,name) \
BOOST_TTI_DETAIL_TRAIT_HAS_STATIC_MEMBER_FUNCTION_OP(trait,name) \
template<class BOOST_TTI_DETAIL_TP_T,class BOOST_TTI_DETAIL_TP_R,class BOOST_TTI_DETAIL_TP_FS,class BOOST_TTI_DETAIL_TP_TAG> \
struct BOOST_PP_CAT(trait,_detail_hsmf) : \
boost::mpl::eval_if \
< \
BOOST_TTI_NAMESPACE::detail::enclosing_type<BOOST_TTI_DETAIL_TP_T>, \
BOOST_PP_CAT(trait,_detail_hsmf_op)<BOOST_TTI_DETAIL_TP_T,BOOST_TTI_DETAIL_TP_R,BOOST_TTI_DETAIL_TP_FS,BOOST_TTI_DETAIL_TP_TAG>, \
boost::mpl::false_ \
> \
{ \
}; \
/**/
#endif // BOOST_TTI_DETAIL_STATIC_MEM_FUN_HPP
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "usb-cdc-acm.h"
#include <assert.h>
#include <fuchsia/hardware/serial/c/fidl.h>
#include <zircon/hw/usb.h>
#include <zircon/hw/usb/cdc.h>
#include <ddk/binding.h>
#include <ddk/debug.h>
#include <ddk/driver.h>
#include <fbl/alloc_checker.h>
#include <usb/request-cpp.h>
#include <usb/usb-request.h>
#include <usb/usb.h>
namespace usb_cdc_acm_serial {
namespace {
constexpr int32_t kReadRequestCount = 8;
constexpr int32_t kWriteRequestCount = 8;
constexpr uint32_t kDefaultBaudRate = 115200;
constexpr uint32_t kDefaultConfig = SERIAL_DATA_BITS_8 | SERIAL_STOP_BITS_1 | SERIAL_PARITY_NONE;
constexpr uint32_t kUsbBufferSize = 2048;
constexpr uint32_t kUsbCdcAcmSetLineCoding = 0x20;
constexpr uint32_t kUsbCdcAcmGetLineCoding = 0x21;
} // namespace
struct usb_cdc_acm_line_coding_t {
uint32_t dwDTERate;
uint8_t bCharFormat;
uint8_t bParityType;
uint8_t bDataBits;
} __PACKED;
void UsbCdcAcmDevice::NotifyCallback() {
if (need_to_notify_cb_ == true) {
need_to_notify_cb_ = false;
if (notify_cb_.callback) {
notify_cb_.callback(notify_cb_.ctx, state_);
}
}
}
void UsbCdcAcmDevice::CheckStateLocked() {
uint32_t state = 0;
state |= free_write_queue_.is_empty() ? 0 : SERIAL_STATE_WRITABLE;
state |= completed_reads_queue_.is_empty() ? 0 : SERIAL_STATE_READABLE;
if (state != state_) {
state_ = state;
need_to_notify_cb_ = true;
}
}
zx_status_t UsbCdcAcmDevice::DdkRead(void* data, size_t len, zx_off_t /*off*/, size_t* actual) {
size_t bytes_copied = 0;
size_t offset = read_offset_;
auto* buffer = static_cast<uint8_t*>(data);
fbl::AutoLock lock(&lock_);
while (bytes_copied < len) {
std::optional<usb::Request<>> req = completed_reads_queue_.pop();
if (!req) {
break;
}
// Skip invalid or empty responses.
if (req->request()->response.status == ZX_OK && req->request()->response.actual > 0) {
// |offset| will always be zero if a response is being read for the first time. It can only be
// non-zero if |req| was re-queued below, which should guarantee that |offset| is within the
// response length.
assert(offset < req->request()->response.actual);
// Copy as many bytes as available or as needed from the first request.
size_t to_copy = req->request()->response.actual - offset;
if ((to_copy + bytes_copied) > len) {
to_copy = len - bytes_copied;
}
req->CopyFrom(&buffer[bytes_copied], to_copy, offset);
bytes_copied += to_copy;
// If we aren't reading the whole request, put it back on the front of the completed queue and
// mark the offset into it for the next read.
if ((to_copy + offset) < req->request()->response.actual) {
offset = offset + to_copy;
completed_reads_queue_.push_next(*std::move(req));
break;
}
}
usb_client_.RequestQueue(req->take(), &read_request_complete_);
offset = 0;
}
CheckStateLocked();
// Store the offset into the current request for the next read.
read_offset_ = offset;
*actual = bytes_copied;
lock.release();
NotifyCallback();
return ZX_OK;
}
zx_status_t UsbCdcAcmDevice::DdkWrite(const void* buf, size_t length, zx_off_t /*off*/,
size_t* actual) {
fbl::AutoLock lock(&lock_);
std::optional<usb::Request<>> req = free_write_queue_.pop();
if (!req) {
*actual = 0;
return ZX_ERR_SHOULD_WAIT;
}
*actual = req->CopyTo(buf, length, 0);
req->request()->header.length = length;
usb_client_.RequestQueue(req->take(), &write_request_complete_);
CheckStateLocked();
lock.release();
NotifyCallback();
return ZX_OK;
}
void UsbCdcAcmDevice::DdkUnbindNew(ddk::UnbindTxn txn) {
cancel_thread_ = std::thread([this, unbind_txn = std::move(txn)]() mutable {
usb_client_.CancelAll(bulk_in_addr_);
usb_client_.CancelAll(bulk_out_addr_);
unbind_txn.Reply();
});
}
void UsbCdcAcmDevice::DdkRelease() {
cancel_thread_.join();
delete this;
}
zx_status_t UsbCdcAcmDevice::SerialImplGetInfo(serial_port_info_t* info) {
memcpy(info, &serial_port_info_, sizeof(*info));
return ZX_OK;
}
zx_status_t UsbCdcAcmDevice::SerialImplConfig(uint32_t baud_rate, uint32_t flags) {
if (baud_rate_ != baud_rate || flags != config_flags_) {
return ConfigureDevice(baud_rate, flags);
}
return ZX_OK;
}
zx_status_t UsbCdcAcmDevice::SerialImplEnable(bool enable) {
enabled_ = enable;
return ZX_OK;
}
zx_status_t UsbCdcAcmDevice::SerialImplRead(void* data, size_t len, size_t* actual) {
zx_status_t status = DdkRead(data, len, 0, actual);
if (status == ZX_OK && actual == nullptr) {
return ZX_ERR_SHOULD_WAIT;
}
return status;
}
zx_status_t UsbCdcAcmDevice::SerialImplWrite(const void* buf, size_t length, size_t* actual) {
return DdkWrite(buf, length, 0, actual);
}
zx_status_t UsbCdcAcmDevice::SerialImplSetNotifyCallback(const serial_notify_t* cb) {
if (enabled_) {
return ZX_ERR_BAD_STATE;
}
notify_cb_ = *cb;
fbl::AutoLock lock(&lock_);
CheckStateLocked();
lock.release();
NotifyCallback();
return ZX_OK;
}
void UsbCdcAcmDevice::ReadComplete(usb_request_t* request) {
usb::Request<> req(request, parent_req_size_);
if (req.request()->response.status == ZX_ERR_IO_NOT_PRESENT) {
zxlogf(INFO, "usb-cdc-acm: remote closed");
return;
}
fbl::AutoLock lock(&lock_);
if (req.request()->response.status == ZX_OK) {
completed_reads_queue_.push(std::move(req));
CheckStateLocked();
} else {
usb_client_.RequestQueue(req.take(), &read_request_complete_);
}
lock.release();
NotifyCallback();
}
void UsbCdcAcmDevice::WriteComplete(usb_request_t* request) {
usb::Request<> req(request, parent_req_size_);
if (req.request()->response.status == ZX_ERR_IO_NOT_PRESENT) {
zxlogf(INFO, "usb-cdc-acm: remote closed");
return;
}
fbl::AutoLock lock(&lock_);
free_write_queue_.push(std::move(req));
CheckStateLocked();
lock.release();
NotifyCallback();
}
zx_status_t UsbCdcAcmDevice::ConfigureDevice(uint32_t baud_rate, uint32_t flags) {
if (!usb_client_.is_valid()) {
return ZX_ERR_INVALID_ARGS;
}
zx_status_t status = ZX_OK;
usb_cdc_acm_line_coding_t coding;
const bool baud_rate_only = flags & SERIAL_SET_BAUD_RATE_ONLY;
if (baud_rate_only) {
size_t coding_length;
status = usb_client_.ControlIn(USB_DIR_IN | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
kUsbCdcAcmGetLineCoding, 0, 0, ZX_TIME_INFINITE, &coding,
sizeof(coding), &coding_length);
if (coding_length != sizeof(coding)) {
zxlogf(TRACE, "usb-cdc-acm: failed to fetch line coding");
}
if (status != ZX_OK) {
return status;
}
} else {
switch (flags & SERIAL_STOP_BITS_MASK) {
case SERIAL_STOP_BITS_1:
coding.bCharFormat = 0;
break;
case SERIAL_STOP_BITS_2:
coding.bCharFormat = 2;
break;
default:
return ZX_ERR_INVALID_ARGS;
}
switch (flags & SERIAL_PARITY_MASK) {
case SERIAL_PARITY_NONE:
coding.bParityType = 0;
break;
case SERIAL_PARITY_EVEN:
coding.bParityType = 2;
break;
case SERIAL_PARITY_ODD:
coding.bParityType = 1;
break;
default:
return ZX_ERR_INVALID_ARGS;
}
switch (flags & SERIAL_DATA_BITS_MASK) {
case SERIAL_DATA_BITS_5:
coding.bDataBits = 5;
break;
case SERIAL_DATA_BITS_6:
coding.bDataBits = 6;
break;
case SERIAL_DATA_BITS_7:
coding.bDataBits = 7;
break;
case SERIAL_DATA_BITS_8:
coding.bDataBits = 8;
break;
default:
return ZX_ERR_INVALID_ARGS;
}
}
coding.dwDTERate = baud_rate;
status = usb_client_.ControlOut(USB_DIR_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE,
kUsbCdcAcmSetLineCoding, 0, 0, ZX_TIME_INFINITE, &coding,
sizeof(coding));
if (status == ZX_OK) {
baud_rate_ = baud_rate;
if (!baud_rate_only) {
config_flags_ = flags;
}
}
return status;
}
zx_status_t UsbCdcAcmDevice::Bind() {
zx_status_t status = ZX_OK;
if (!usb_client_.is_valid()) {
return ZX_ERR_PROTOCOL_NOT_SUPPORTED;
}
// Enumerate available interfaces and find bulk-in and bulk-out endpoints.
std::optional<usb::InterfaceList> usb_interface_list;
status = usb::InterfaceList::Create(usb_client_, true, &usb_interface_list);
if (status != ZX_OK) {
return status;
}
fbl::AutoLock lock(&lock_);
uint8_t bulk_in_address = 0;
uint8_t bulk_out_address = 0;
for (auto interface : *usb_interface_list) {
if (interface.descriptor()->bNumEndpoints > 1) {
for (auto& endpoint : interface.GetEndpointList()) {
if (usb_ep_type(&endpoint.descriptor) == USB_ENDPOINT_BULK) {
if (usb_ep_direction(&endpoint.descriptor) == USB_ENDPOINT_IN) {
bulk_in_address = endpoint.descriptor.bEndpointAddress;
} else if (usb_ep_direction(&endpoint.descriptor) == USB_ENDPOINT_OUT) {
bulk_out_address = endpoint.descriptor.bEndpointAddress;
}
}
}
}
}
if (!bulk_in_address || !bulk_out_address) {
zxlogf(ERROR, "usb-cdc-acm: Bind() could not find bulk-in and bulk-out endpoints");
return ZX_ERR_NOT_SUPPORTED;
}
bulk_in_addr_ = bulk_in_address;
bulk_out_addr_ = bulk_out_address;
parent_req_size_ = usb_client_.GetRequestSize();
status = ConfigureDevice(kDefaultBaudRate, kDefaultConfig);
if (status != ZX_OK) {
zxlogf(ERROR, "usb-cdc-acm: failed to set default baud rate: %d", status);
return status;
}
serial_port_info_.serial_class = fuchsia_hardware_serial_Class_GENERIC;
status = DdkAdd("usb-cdc-acm");
if (status != ZX_OK) {
zxlogf(ERROR, "usb-cdc-acm: failed to create device: %d", status);
return status;
}
// Create and immediately queue read requests after successfully adding the device.
for (int i = 0; i < kReadRequestCount; i++) {
std::optional<usb::Request<>> request;
status = usb::Request<>::Alloc(&request, kUsbBufferSize, bulk_in_addr_, parent_req_size_);
if (status != ZX_OK) {
zxlogf(ERROR, "usb-cdc-acm: allocating reads failed %d", status);
return status;
}
usb_client_.RequestQueue(request->take(), &read_request_complete_);
}
for (int i = 0; i < kWriteRequestCount; i++) {
std::optional<usb::Request<>> request;
status = usb::Request<>::Alloc(&request, kUsbBufferSize, bulk_out_addr_, parent_req_size_);
if (status != ZX_OK) {
zxlogf(ERROR, "usb-cdc-acm: allocating writes failed %d", status);
return status;
}
free_write_queue_.push(*std::move(request));
}
return ZX_OK;
}
} // namespace usb_cdc_acm_serial
namespace {
zx_status_t cdc_acm_bind(void* /*ctx*/, zx_device_t* device) {
fbl::AllocChecker ac;
auto dev = fbl::make_unique_checked<usb_cdc_acm_serial::UsbCdcAcmDevice>(&ac, device);
if (!ac.check()) {
return ZX_ERR_NO_MEMORY;
}
auto status = dev->Bind();
if (status != ZX_OK) {
zxlogf(INFO, "usb-cdc-acm: failed to add serial driver %d", status);
}
// Devmgr is now in charge of the memory for dev.
__UNUSED auto ptr = dev.release();
return status;
}
constexpr zx_driver_ops_t cdc_acm_driver_ops = []() {
zx_driver_ops_t ops = {};
ops.version = DRIVER_OPS_VERSION;
ops.bind = cdc_acm_bind;
return ops;
}();
} // namespace
// clang-format off
ZIRCON_DRIVER_BEGIN(cdc_acm, cdc_acm_driver_ops, "zircon", "0.1", 3)
BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_USB),
BI_ABORT_IF(NE, BIND_USB_CLASS, USB_CLASS_COMM),
BI_MATCH_IF(EQ, BIND_USB_SUBCLASS, USB_CDC_SUBCLASS_ABSTRACT),
ZIRCON_DRIVER_END(cdc_acm)
// clang-form at on
|
#include <hook_manager.hpp>
#include "qfx_runtime.hpp"
#include "render/qfx_renderer.hpp"
#define IS_3D_PROJECTION_MATRIX(x) (x[2*4+3] < 0)
#define MATRIXMODE RENDERER->GetLastMatrixMode()
#define RENDERER QfxRenderer::GetInstance()
using namespace reshade;
using namespace QuakeFX;
HOOK_EXPORT void WINAPI qfx_glMatrixMode(GLenum mode)
{
if (RENDERER->GetIsInitialized())
{
RENDERER->OnMatrixModeChanged(mode);
}
auto trampoline = hooks::call(qfx_glMatrixMode);
trampoline(mode);
}
HOOK_EXPORT void WINAPI qfx_glLoadMatrixd(const GLdouble *m)
{
auto trampoline = hooks::call(qfx_glLoadMatrixd);
trampoline(m);
if (RENDERER->GetIsInitialized() && MATRIXMODE == GL_PROJECTION)
{
RENDERER->OnProjection(!IS_3D_PROJECTION_MATRIX(m));
}
}
HOOK_EXPORT void WINAPI qfx_glLoadMatrixf(const GLfloat *m)
{
auto trampoline = hooks::call(qfx_glLoadMatrixf);
trampoline(m);
if (RENDERER->GetIsInitialized() && MATRIXMODE == GL_PROJECTION)
{
RENDERER->OnProjection(!IS_3D_PROJECTION_MATRIX(m));
}
}
HOOK_EXPORT void WINAPI qfx_glFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar)
{
auto trampoline = hooks::call(qfx_glFrustum);
trampoline(left, right, bottom, top, zNear, zFar);
if (RENDERER->GetIsInitialized() && MATRIXMODE == GL_PROJECTION)
{
RENDERER->OnProjection(false);
}
}
HOOK_EXPORT void WINAPI qfx_glOrtho( GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble zNear, GLdouble zFar )
{
auto trampoline = hooks::call(qfx_glOrtho);
trampoline(left, right, bottom, top, zNear, zFar);
if (RENDERER->GetIsInitialized() && MATRIXMODE == GL_PROJECTION)
{
RENDERER->OnProjection(true);
}
}
HOOK_EXPORT void WINAPI qfx_glBlendFunc(GLenum sfactor, GLenum dfactor)
{
if (RENDERER->GetIsInitialized())
{
RENDERER->OnSetBlendFunc(sfactor, dfactor);
}
else
{
auto trampoline = hooks::call(qfx_glBlendFunc);
trampoline(sfactor, dfactor);
}
}
HOOK_EXPORT void WINAPI qfx_glBindTexture(GLenum target, GLuint texture)
{
auto trampoline = hooks::call(qfx_glBindTexture);
trampoline(target, texture);
if (RENDERER->GetIsInitialized() && target == GL_TEXTURE_2D)
{
RENDERER->OnBindTex2D();
}
}
HOOK_EXPORT BOOL WINAPI qfx_wglMakeCurrent( HDC hdc, HGLRC hglrc )
{
auto trampoline = hooks::call(qfx_wglMakeCurrent);
QfxRuntime::Init();
if (!trampoline(hdc, hglrc))
return FALSE;
else if (QfxRuntime::GetIsInitialized() && RENDERER != nullptr)
RENDERER->OnMakeCurrent( hdc, hglrc );
return TRUE;
}
HOOK_EXPORT BOOL WINAPI qfx_wglDeleteContext( HGLRC hglrc )
{
if (RENDERER->GetIsInitialized())
RENDERER->OnDeleteContext(hglrc);
auto trampoline = hooks::call(qfx_wglDeleteContext);
return trampoline(hglrc);
}
HOOK_EXPORT BOOL WINAPI qfx_wglSwapBuffers(HDC hdc)
{
if (!RENDERER->GetIsInitialized())
{
auto reshadeSwap = hooks::call(qfx_wglSwapBuffers);
return reshadeSwap(hdc);
}
else
{
return RENDERER->OnSwapBuffers(hdc);
}
}
HOOK_EXPORT BOOL WINAPI qfxGL_wglSwapBuffers(HDC hdc)
{
if (!RENDERER->GetIsInitialized())
{
auto baseSwap = hooks::call(qfxGL_wglSwapBuffers);
return baseSwap(hdc);
}
else
{
return GL_FALSE;
}
}
|
// Copyright (c) 2011-2014 The Bitcoin Core developers
// Copyright (c) 2017 The BTBZ developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "data/script_invalid.json.h"
#include "data/script_valid.json.h"
#include "core_io.h"
#include "key.h"
#include "keystore.h"
#include "main.h"
#include "script/script.h"
#include "script/script_error.h"
#include "script/sign.h"
#include "util.h"
#if defined(HAVE_CONSENSUS_LIB)
#include "script/bitcoinconsensus.h"
#endif
#include <fstream>
#include <stdint.h>
#include <string>
#include <vector>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
#include <univalue.h>
using namespace std;
using namespace boost::algorithm;
// Uncomment if you want to output updated JSON tests.
// #define UPDATE_JSON_TESTS
static const unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC;
unsigned int ParseScriptFlags(string strFlags);
string FormatScriptFlags(unsigned int flags);
UniValue
read_json(const std::string& jsondata)
{
UniValue v;
if (!v.read(jsondata) || !v.isArray())
{
BOOST_ERROR("Parse error.");
return UniValue(UniValue::VARR);
}
return v.get_array();
}
BOOST_AUTO_TEST_SUITE(script_tests)
CMutableTransaction BuildCreditingTransaction(const CScript& scriptPubKey)
{
CMutableTransaction txCredit;
txCredit.nVersion = 1;
txCredit.nLockTime = 0;
txCredit.vin.resize(1);
txCredit.vout.resize(1);
txCredit.vin[0].prevout.SetNull();
txCredit.vin[0].scriptSig = CScript() << CScriptNum(0) << CScriptNum(0);
txCredit.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
txCredit.vout[0].scriptPubKey = scriptPubKey;
txCredit.vout[0].nValue = 0;
return txCredit;
}
CMutableTransaction BuildSpendingTransaction(const CScript& scriptSig, const CMutableTransaction& txCredit)
{
CMutableTransaction txSpend;
txSpend.nVersion = 1;
txSpend.nLockTime = 0;
txSpend.vin.resize(1);
txSpend.vout.resize(1);
txSpend.vin[0].prevout.hash = txCredit.GetHash();
txSpend.vin[0].prevout.n = 0;
txSpend.vin[0].scriptSig = scriptSig;
txSpend.vin[0].nSequence = std::numeric_limits<unsigned int>::max();
txSpend.vout[0].scriptPubKey = CScript();
txSpend.vout[0].nValue = 0;
return txSpend;
}
void DoTest(const CScript& scriptPubKey, const CScript& scriptSig, int flags, bool expect, const std::string& message)
{
ScriptError err;
CMutableTransaction tx = BuildSpendingTransaction(scriptSig, BuildCreditingTransaction(scriptPubKey));
CMutableTransaction tx2 = tx;
BOOST_CHECK_MESSAGE(VerifyScript(scriptSig, scriptPubKey, flags, MutableTransactionSignatureChecker(&tx, 0), &err) == expect, message);
BOOST_CHECK_MESSAGE(expect == (err == SCRIPT_ERR_OK), std::string(ScriptErrorString(err)) + ": " + message);
#if defined(HAVE_CONSENSUS_LIB)
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << tx2;
BOOST_CHECK_MESSAGE(bitcoinconsensus_verify_script(begin_ptr(scriptPubKey), scriptPubKey.size(), (const unsigned char*)&stream[0], stream.size(), 0, flags, NULL) == expect,message);
#endif
}
void static NegateSignatureS(std::vector<unsigned char>& vchSig) {
// Parse the signature.
std::vector<unsigned char> r, s;
r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
unsigned char hashtype = vchSig.back();
// Really ugly to implement mod-n negation here, but it would be feature creep to expose such functionality from libsecp256k1.
static const unsigned char order[33] = {
0x00,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE,
0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B,
0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41
};
while (s.size() < 33) {
s.insert(s.begin(), 0x00);
}
int carry = 0;
for (int p = 32; p >= 1; p--) {
int n = (int)order[p] - s[p] - carry;
s[p] = (n + 256) & 0xFF;
carry = (n < 0);
}
assert(carry == 0);
if (s.size() > 1 && s[0] == 0 && s[1] < 0x80) {
s.erase(s.begin());
}
// Reconstruct the signature.
vchSig.clear();
vchSig.push_back(0x30);
vchSig.push_back(4 + r.size() + s.size());
vchSig.push_back(0x02);
vchSig.push_back(r.size());
vchSig.insert(vchSig.end(), r.begin(), r.end());
vchSig.push_back(0x02);
vchSig.push_back(s.size());
vchSig.insert(vchSig.end(), s.begin(), s.end());
vchSig.push_back(hashtype);
}
namespace
{
const unsigned char vchKey0[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1};
const unsigned char vchKey1[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
const unsigned char vchKey2[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0};
struct KeyData
{
CKey key0, key0C, key1, key1C, key2, key2C;
CPubKey pubkey0, pubkey0C, pubkey0H;
CPubKey pubkey1, pubkey1C;
CPubKey pubkey2, pubkey2C;
KeyData()
{
key0.Set(vchKey0, vchKey0 + 32, false);
key0C.Set(vchKey0, vchKey0 + 32, true);
pubkey0 = key0.GetPubKey();
pubkey0H = key0.GetPubKey();
pubkey0C = key0C.GetPubKey();
*const_cast<unsigned char*>(&pubkey0H[0]) = 0x06 | (pubkey0H[64] & 1);
key1.Set(vchKey1, vchKey1 + 32, false);
key1C.Set(vchKey1, vchKey1 + 32, true);
pubkey1 = key1.GetPubKey();
pubkey1C = key1C.GetPubKey();
key2.Set(vchKey2, vchKey2 + 32, false);
key2C.Set(vchKey2, vchKey2 + 32, true);
pubkey2 = key2.GetPubKey();
pubkey2C = key2C.GetPubKey();
}
};
class TestBuilder
{
private:
CScript scriptPubKey;
CTransaction creditTx;
CMutableTransaction spendTx;
bool havePush;
std::vector<unsigned char> push;
std::string comment;
int flags;
void DoPush()
{
if (havePush) {
spendTx.vin[0].scriptSig << push;
havePush = false;
}
}
void DoPush(const std::vector<unsigned char>& data)
{
DoPush();
push = data;
havePush = true;
}
public:
TestBuilder(const CScript& redeemScript, const std::string& comment_, int flags_, bool P2SH = false) : scriptPubKey(redeemScript), havePush(false), comment(comment_), flags(flags_)
{
if (P2SH) {
creditTx = BuildCreditingTransaction(CScript() << OP_HASH160 << ToByteVector(CScriptID(redeemScript)) << OP_EQUAL);
} else {
creditTx = BuildCreditingTransaction(redeemScript);
}
spendTx = BuildSpendingTransaction(CScript(), creditTx);
}
TestBuilder& Add(const CScript& script)
{
DoPush();
spendTx.vin[0].scriptSig += script;
return *this;
}
TestBuilder& Num(int num)
{
DoPush();
spendTx.vin[0].scriptSig << num;
return *this;
}
TestBuilder& Push(const std::string& hex)
{
DoPush(ParseHex(hex));
return *this;
}
TestBuilder& PushSig(const CKey& key, int nHashType = SIGHASH_ALL, unsigned int lenR = 32, unsigned int lenS = 32)
{
uint256 hash = SignatureHash(scriptPubKey, spendTx, 0, nHashType);
std::vector<unsigned char> vchSig, r, s;
uint32_t iter = 0;
do {
key.Sign(hash, vchSig, iter++);
if ((lenS == 33) != (vchSig[5 + vchSig[3]] == 33)) {
NegateSignatureS(vchSig);
}
r = std::vector<unsigned char>(vchSig.begin() + 4, vchSig.begin() + 4 + vchSig[3]);
s = std::vector<unsigned char>(vchSig.begin() + 6 + vchSig[3], vchSig.begin() + 6 + vchSig[3] + vchSig[5 + vchSig[3]]);
} while (lenR != r.size() || lenS != s.size());
vchSig.push_back(static_cast<unsigned char>(nHashType));
DoPush(vchSig);
return *this;
}
TestBuilder& Push(const CPubKey& pubkey)
{
DoPush(std::vector<unsigned char>(pubkey.begin(), pubkey.end()));
return *this;
}
TestBuilder& PushRedeem()
{
DoPush(static_cast<std::vector<unsigned char> >(scriptPubKey));
return *this;
}
TestBuilder& EditPush(unsigned int pos, const std::string& hexin, const std::string& hexout)
{
assert(havePush);
std::vector<unsigned char> datain = ParseHex(hexin);
std::vector<unsigned char> dataout = ParseHex(hexout);
assert(pos + datain.size() <= push.size());
BOOST_CHECK_MESSAGE(std::vector<unsigned char>(push.begin() + pos, push.begin() + pos + datain.size()) == datain, comment);
push.erase(push.begin() + pos, push.begin() + pos + datain.size());
push.insert(push.begin() + pos, dataout.begin(), dataout.end());
return *this;
}
TestBuilder& DamagePush(unsigned int pos)
{
assert(havePush);
assert(pos < push.size());
push[pos] ^= 1;
return *this;
}
TestBuilder& Test(bool expect)
{
TestBuilder copy = *this; // Make a copy so we can rollback the push.
DoPush();
DoTest(creditTx.vout[0].scriptPubKey, spendTx.vin[0].scriptSig, flags, expect, comment);
*this = copy;
return *this;
}
UniValue GetJSON()
{
DoPush();
UniValue array(UniValue::VARR);
array.push_back(FormatScript(spendTx.vin[0].scriptSig));
array.push_back(FormatScript(creditTx.vout[0].scriptPubKey));
array.push_back(FormatScriptFlags(flags));
array.push_back(comment);
return array;
}
std::string GetComment()
{
return comment;
}
const CScript& GetScriptPubKey()
{
return creditTx.vout[0].scriptPubKey;
}
};
}
BOOST_AUTO_TEST_CASE(script_build)
{
const KeyData keys;
std::vector<TestBuilder> good;
std::vector<TestBuilder> bad;
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
"P2PK", 0
).PushSig(keys.key0));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0) << OP_CHECKSIG,
"P2PK, bad sig", 0
).PushSig(keys.key0).DamagePush(10));
good.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
"P2PKH", 0
).PushSig(keys.key1).Push(keys.pubkey1C));
bad.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey2C.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
"P2PKH, bad pubkey", 0
).PushSig(keys.key2).Push(keys.pubkey2C).DamagePush(5));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
"P2PK anyonecanpay", 0
).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
"P2PK anyonecanpay marked with normal hashtype", 0
).PushSig(keys.key1, SIGHASH_ALL | SIGHASH_ANYONECANPAY).EditPush(70, "81", "01"));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
"P2SH(P2PK)", SCRIPT_VERIFY_P2SH, true
).PushSig(keys.key0).PushRedeem());
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0C) << OP_CHECKSIG,
"P2SH(P2PK), bad redeemscript", SCRIPT_VERIFY_P2SH, true
).PushSig(keys.key0).PushRedeem().DamagePush(10));
good.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
"P2SH(P2PKH), bad sig but no VERIFY_P2SH", 0, true
).PushSig(keys.key0).DamagePush(10).PushRedeem());
bad.push_back(TestBuilder(CScript() << OP_DUP << OP_HASH160 << ToByteVector(keys.pubkey1.GetID()) << OP_EQUALVERIFY << OP_CHECKSIG,
"P2SH(P2PKH), bad sig", SCRIPT_VERIFY_P2SH, true
).PushSig(keys.key0).DamagePush(10).PushRedeem());
good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"3-of-3", 0
).Num(0).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"3-of-3, 2 sigs", 0
).Num(0).PushSig(keys.key0).PushSig(keys.key1).Num(0));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"P2SH(2-of-3)", SCRIPT_VERIFY_P2SH, true
).Num(0).PushSig(keys.key1).PushSig(keys.key2).PushRedeem());
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"P2SH(2-of-3), 1 sig", SCRIPT_VERIFY_P2SH, true
).Num(0).PushSig(keys.key1).Num(0).PushRedeem());
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too much R padding but no DERSIG", 0
).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too much R padding", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key1, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too much S padding but no DERSIG", 0
).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too much S padding", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key1, SIGHASH_ALL).EditPush(1, "44", "45").EditPush(37, "20", "2100"));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too little R padding but no DERSIG", 0
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"P2PK with too little R padding", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with bad sig with too much R padding but no DERSIG", 0
).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with bad sig with too much R padding", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000").DamagePush(10));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with too much R padding but no DERSIG", 0
).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with too much R padding", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key2, SIGHASH_ALL, 31, 32).EditPush(1, "43021F", "44022000"));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 1, without DERSIG", 0
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 1, with DERSIG", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 2, without DERSIG", 0
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 2, with DERSIG", SCRIPT_VERIFY_DERSIG
).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 3, without DERSIG", 0
).Num(0));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 3, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 4, without DERSIG", 0
).Num(0));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 4, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 5, without DERSIG", 0
).Num(1));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG,
"BIP66 example 5, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(1));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 6, without DERSIG", 0
).Num(1));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1C) << OP_CHECKSIG << OP_NOT,
"BIP66 example 6, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(1));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 7, without DERSIG", 0
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 7, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 8, without DERSIG", 0
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 8, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 9, without DERSIG", 0
).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 9, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 10, without DERSIG", 0
).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 10, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).Num(0).PushSig(keys.key2, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220"));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 11, without DERSIG", 0
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG,
"BIP66 example 11, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 12, without DERSIG", 0
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_2 << OP_CHECKMULTISIG << OP_NOT,
"BIP66 example 12, with DERSIG", SCRIPT_VERIFY_DERSIG
).Num(0).PushSig(keys.key1, SIGHASH_ALL, 33, 32).EditPush(1, "45022100", "440220").Num(0));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
"P2PK with high S but no LOW_S", 0
).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
"P2PK with high S", SCRIPT_VERIFY_LOW_S
).PushSig(keys.key2, SIGHASH_ALL, 32, 33));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
"P2PK with hybrid pubkey but no STRICTENC", 0
).PushSig(keys.key0, SIGHASH_ALL));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG,
"P2PK with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
).PushSig(keys.key0, SIGHASH_ALL));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with hybrid pubkey but no STRICTENC", 0
).PushSig(keys.key0, SIGHASH_ALL));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with hybrid pubkey", SCRIPT_VERIFY_STRICTENC
).PushSig(keys.key0, SIGHASH_ALL));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with invalid hybrid pubkey but no STRICTENC", 0
).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey0H) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with invalid hybrid pubkey", SCRIPT_VERIFY_STRICTENC
).PushSig(keys.key0, SIGHASH_ALL).DamagePush(10));
good.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
"1-of-2 with the second 1 hybrid pubkey and no STRICTENC", 0
).Num(0).PushSig(keys.key1, SIGHASH_ALL));
good.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey0H) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
"1-of-2 with the second 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
).Num(0).PushSig(keys.key1, SIGHASH_ALL));
bad.push_back(TestBuilder(CScript() << OP_1 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey0H) << OP_2 << OP_CHECKMULTISIG,
"1-of-2 with the first 1 hybrid pubkey", SCRIPT_VERIFY_STRICTENC
).Num(0).PushSig(keys.key1, SIGHASH_ALL));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
"P2PK with undefined hashtype but no STRICTENC", 0
).PushSig(keys.key1, 5));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG,
"P2PK with undefined hashtype", SCRIPT_VERIFY_STRICTENC
).PushSig(keys.key1, 5));
good.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with invalid sig and undefined hashtype but no STRICTENC", 0
).PushSig(keys.key1, 5).DamagePush(10));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey1) << OP_CHECKSIG << OP_NOT,
"P2PK NOT with invalid sig and undefined hashtype", SCRIPT_VERIFY_STRICTENC
).PushSig(keys.key1, 5).DamagePush(10));
good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"3-of-3 with nonzero dummy but no NULLDUMMY", 0
).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG,
"3-of-3 with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2));
good.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
"3-of-3 NOT with invalid sig and nonzero dummy but no NULLDUMMY", 0
).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
bad.push_back(TestBuilder(CScript() << OP_3 << ToByteVector(keys.pubkey0C) << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey2C) << OP_3 << OP_CHECKMULTISIG << OP_NOT,
"3-of-3 NOT with invalid sig with nonzero dummy", SCRIPT_VERIFY_NULLDUMMY
).Num(1).PushSig(keys.key0).PushSig(keys.key1).PushSig(keys.key2).DamagePush(10));
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
"2-of-2 with two identical keys and sigs pushed using OP_DUP but no SIGPUSHONLY", 0
).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP));
bad.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
"2-of-2 with two identical keys and sigs pushed using OP_DUP", SCRIPT_VERIFY_SIGPUSHONLY
).Num(0).PushSig(keys.key1).Add(CScript() << OP_DUP));
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
"P2SH(P2PK) with non-push scriptSig but no SIGPUSHONLY", 0
).PushSig(keys.key2).PushRedeem());
bad.push_back(TestBuilder(CScript() << ToByteVector(keys.pubkey2C) << OP_CHECKSIG,
"P2SH(P2PK) with non-push scriptSig", SCRIPT_VERIFY_SIGPUSHONLY
).PushSig(keys.key2).PushRedeem());
good.push_back(TestBuilder(CScript() << OP_2 << ToByteVector(keys.pubkey1C) << ToByteVector(keys.pubkey1C) << OP_2 << OP_CHECKMULTISIG,
"2-of-2 with two identical keys and sigs pushed", SCRIPT_VERIFY_SIGPUSHONLY
).Num(0).PushSig(keys.key1).PushSig(keys.key1));
std::set<std::string> tests_good;
std::set<std::string> tests_bad;
{
UniValue json_good = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid)));
UniValue json_bad = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid)));
for (unsigned int idx = 0; idx < json_good.size(); idx++) {
const UniValue& tv = json_good[idx];
tests_good.insert(tv.get_array().write());
}
for (unsigned int idx = 0; idx < json_bad.size(); idx++) {
const UniValue& tv = json_bad[idx];
tests_bad.insert(tv.get_array().write());
}
}
std::string strGood;
std::string strBad;
BOOST_FOREACH(TestBuilder& test, good) {
test.Test(true);
std::string str = test.GetJSON().write();
#ifndef UPDATE_JSON_TESTS
if (tests_good.count(str) == 0) {
BOOST_CHECK_MESSAGE(false, "Missing auto script_valid test: " + test.GetComment());
}
#endif
strGood += str + ",\n";
}
BOOST_FOREACH(TestBuilder& test, bad) {
test.Test(false);
std::string str = test.GetJSON().write();
#ifndef UPDATE_JSON_TESTS
if (tests_bad.count(str) == 0) {
BOOST_CHECK_MESSAGE(false, "Missing auto script_invalid test: " + test.GetComment());
}
#endif
strBad += str + ",\n";
}
#ifdef UPDATE_JSON_TESTS
FILE* valid = fopen("script_valid.json.gen", "w");
fputs(strGood.c_str(), valid);
fclose(valid);
FILE* invalid = fopen("script_invalid.json.gen", "w");
fputs(strBad.c_str(), invalid);
fclose(invalid);
#endif
}
BOOST_AUTO_TEST_CASE(script_valid)
{
// Read tests from test/data/script_valid.json
// Format is an array of arrays
// Inner arrays are [ "scriptSig", "scriptPubKey", "flags" ]
// ... where scriptSig and scriptPubKey are stringified
// scripts.
UniValue tests = read_json(std::string(json_tests::script_valid, json_tests::script_valid + sizeof(json_tests::script_valid)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
string strTest = test.write();
if (test.size() < 3) // Allow size > 3; extra stuff ignored (useful for comments)
{
if (test.size() != 1) {
BOOST_ERROR("Bad test: " << strTest);
}
continue;
}
string scriptSigString = test[0].get_str();
CScript scriptSig = ParseScript(scriptSigString);
string scriptPubKeyString = test[1].get_str();
CScript scriptPubKey = ParseScript(scriptPubKeyString);
unsigned int scriptflags = ParseScriptFlags(test[2].get_str());
DoTest(scriptPubKey, scriptSig, scriptflags, true, strTest);
}
}
BOOST_AUTO_TEST_CASE(script_invalid)
{
// Scripts that should evaluate as invalid
UniValue tests = read_json(std::string(json_tests::script_invalid, json_tests::script_invalid + sizeof(json_tests::script_invalid)));
for (unsigned int idx = 0; idx < tests.size(); idx++) {
UniValue test = tests[idx];
string strTest = test.write();
if (test.size() < 3) // Allow size > 3; extra stuff ignored (useful for comments)
{
if (test.size() != 1) {
BOOST_ERROR("Bad test: " << strTest);
}
continue;
}
string scriptSigString = test[0].get_str();
CScript scriptSig = ParseScript(scriptSigString);
string scriptPubKeyString = test[1].get_str();
CScript scriptPubKey = ParseScript(scriptPubKeyString);
unsigned int scriptflags = ParseScriptFlags(test[2].get_str());
DoTest(scriptPubKey, scriptSig, scriptflags, false, strTest);
}
}
BOOST_AUTO_TEST_CASE(script_PushData)
{
// Check that PUSHDATA1, PUSHDATA2, and PUSHDATA4 create the same value on
// the stack as the 1-75 opcodes do.
static const unsigned char direct[] = { 1, 0x5a };
static const unsigned char pushdata1[] = { OP_PUSHDATA1, 1, 0x5a };
static const unsigned char pushdata2[] = { OP_PUSHDATA2, 1, 0, 0x5a };
static const unsigned char pushdata4[] = { OP_PUSHDATA4, 1, 0, 0, 0, 0x5a };
ScriptError err;
vector<vector<unsigned char> > directStack;
BOOST_CHECK(EvalScript(directStack, CScript(&direct[0], &direct[sizeof(direct)]), true, BaseSignatureChecker(), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
vector<vector<unsigned char> > pushdata1Stack;
BOOST_CHECK(EvalScript(pushdata1Stack, CScript(&pushdata1[0], &pushdata1[sizeof(pushdata1)]), true, BaseSignatureChecker(), &err));
BOOST_CHECK(pushdata1Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
vector<vector<unsigned char> > pushdata2Stack;
BOOST_CHECK(EvalScript(pushdata2Stack, CScript(&pushdata2[0], &pushdata2[sizeof(pushdata2)]), true, BaseSignatureChecker(), &err));
BOOST_CHECK(pushdata2Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
vector<vector<unsigned char> > pushdata4Stack;
BOOST_CHECK(EvalScript(pushdata4Stack, CScript(&pushdata4[0], &pushdata4[sizeof(pushdata4)]), true, BaseSignatureChecker(), &err));
BOOST_CHECK(pushdata4Stack == directStack);
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
CScript
sign_multisig(CScript scriptPubKey, std::vector<CKey> keys, CTransaction transaction)
{
uint256 hash = SignatureHash(scriptPubKey, transaction, 0, SIGHASH_ALL);
CScript result;
//
// NOTE: CHECKMULTISIG has an unfortunate bug; it requires
// one extra item on the stack, before the signatures.
// Putting OP_0 on the stack is the workaround;
// fixing the bug would mean splitting the block chain (old
// clients would not accept new CHECKMULTISIG transactions,
// and vice-versa)
//
result << OP_0;
BOOST_FOREACH(const CKey &key, keys)
{
vector<unsigned char> vchSig;
BOOST_CHECK(key.Sign(hash, vchSig));
vchSig.push_back((unsigned char)SIGHASH_ALL);
result << vchSig;
}
return result;
}
CScript
sign_multisig(CScript scriptPubKey, const CKey &key, CTransaction transaction)
{
std::vector<CKey> keys;
keys.push_back(key);
return sign_multisig(scriptPubKey, keys, transaction);
}
BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG12)
{
ScriptError err;
CKey key1, key2, key3;
key1.MakeNewKey(true);
key2.MakeNewKey(false);
key3.MakeNewKey(true);
CScript scriptPubKey12;
scriptPubKey12 << OP_1 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << OP_2 << OP_CHECKMULTISIG;
CMutableTransaction txFrom12 = BuildCreditingTransaction(scriptPubKey12);
CMutableTransaction txTo12 = BuildSpendingTransaction(CScript(), txFrom12);
CScript goodsig1 = sign_multisig(scriptPubKey12, key1, txTo12);
BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
txTo12.vout[0].nValue = 2;
BOOST_CHECK(!VerifyScript(goodsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
CScript goodsig2 = sign_multisig(scriptPubKey12, key2, txTo12);
BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
CScript badsig1 = sign_multisig(scriptPubKey12, key3, txTo12);
BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey12, flags, MutableTransactionSignatureChecker(&txTo12, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
}
BOOST_AUTO_TEST_CASE(script_CHECKMULTISIG23)
{
ScriptError err;
CKey key1, key2, key3, key4;
key1.MakeNewKey(true);
key2.MakeNewKey(false);
key3.MakeNewKey(true);
key4.MakeNewKey(false);
CScript scriptPubKey23;
scriptPubKey23 << OP_2 << ToByteVector(key1.GetPubKey()) << ToByteVector(key2.GetPubKey()) << ToByteVector(key3.GetPubKey()) << OP_3 << OP_CHECKMULTISIG;
CMutableTransaction txFrom23 = BuildCreditingTransaction(scriptPubKey23);
CMutableTransaction txTo23 = BuildSpendingTransaction(CScript(), txFrom23);
std::vector<CKey> keys;
keys.push_back(key1); keys.push_back(key2);
CScript goodsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear();
keys.push_back(key1); keys.push_back(key3);
CScript goodsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear();
keys.push_back(key2); keys.push_back(key3);
CScript goodsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(VerifyScript(goodsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
keys.clear();
keys.push_back(key2); keys.push_back(key2); // Can't re-use sig
CScript badsig1 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig1, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear();
keys.push_back(key2); keys.push_back(key1); // sigs must be in correct order
CScript badsig2 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig2, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear();
keys.push_back(key3); keys.push_back(key2); // sigs must be in correct order
CScript badsig3 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig3, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear();
keys.push_back(key4); keys.push_back(key2); // sigs must match pubkeys
CScript badsig4 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig4, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear();
keys.push_back(key1); keys.push_back(key4); // sigs must match pubkeys
CScript badsig5 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig5, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_EVAL_FALSE, ScriptErrorString(err));
keys.clear(); // Must have signatures
CScript badsig6 = sign_multisig(scriptPubKey23, keys, txTo23);
BOOST_CHECK(!VerifyScript(badsig6, scriptPubKey23, flags, MutableTransactionSignatureChecker(&txTo23, 0), &err));
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_INVALID_STACK_OPERATION, ScriptErrorString(err));
}
BOOST_AUTO_TEST_CASE(script_combineSigs)
{
// Test the CombineSignatures function
CBasicKeyStore keystore;
vector<CKey> keys;
vector<CPubKey> pubkeys;
for (int i = 0; i < 3; i++)
{
CKey key;
key.MakeNewKey(i%2 == 1);
keys.push_back(key);
pubkeys.push_back(key.GetPubKey());
keystore.AddKey(key);
}
CMutableTransaction txFrom = BuildCreditingTransaction(GetScriptForDestination(keys[0].GetPubKey().GetID()));
CMutableTransaction txTo = BuildSpendingTransaction(CScript(), txFrom);
CScript& scriptPubKey = txFrom.vout[0].scriptPubKey;
CScript& scriptSig = txTo.vin[0].scriptSig;
CScript empty;
CScript combined = CombineSignatures(scriptPubKey, txTo, 0, empty, empty);
BOOST_CHECK(combined.empty());
// Single signature case:
SignSignature(keystore, txFrom, txTo, 0); // changes scriptSig
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
BOOST_CHECK(combined == scriptSig);
combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
BOOST_CHECK(combined == scriptSig);
CScript scriptSigCopy = scriptSig;
// Signing again will give a different, valid signature:
SignSignature(keystore, txFrom, txTo, 0);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);
// P2SH, single-signature case:
CScript pkSingle; pkSingle << ToByteVector(keys[0].GetPubKey()) << OP_CHECKSIG;
keystore.AddCScript(pkSingle);
scriptPubKey = GetScriptForDestination(CScriptID(pkSingle));
SignSignature(keystore, txFrom, txTo, 0);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
BOOST_CHECK(combined == scriptSig);
combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
BOOST_CHECK(combined == scriptSig);
scriptSigCopy = scriptSig;
SignSignature(keystore, txFrom, txTo, 0);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
BOOST_CHECK(combined == scriptSigCopy || combined == scriptSig);
// dummy scriptSigCopy with placeholder, should always choose non-placeholder:
scriptSigCopy = CScript() << OP_0 << static_cast<vector<unsigned char> >(pkSingle);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSigCopy, scriptSig);
BOOST_CHECK(combined == scriptSig);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, scriptSigCopy);
BOOST_CHECK(combined == scriptSig);
// Hardest case: Multisig 2-of-3
scriptPubKey = GetScriptForMultisig(2, pubkeys);
keystore.AddCScript(scriptPubKey);
SignSignature(keystore, txFrom, txTo, 0);
combined = CombineSignatures(scriptPubKey, txTo, 0, scriptSig, empty);
BOOST_CHECK(combined == scriptSig);
combined = CombineSignatures(scriptPubKey, txTo, 0, empty, scriptSig);
BOOST_CHECK(combined == scriptSig);
// A couple of partially-signed versions:
vector<unsigned char> sig1;
uint256 hash1 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_ALL);
BOOST_CHECK(keys[0].Sign(hash1, sig1));
sig1.push_back(SIGHASH_ALL);
vector<unsigned char> sig2;
uint256 hash2 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_NONE);
BOOST_CHECK(keys[1].Sign(hash2, sig2));
sig2.push_back(SIGHASH_NONE);
vector<unsigned char> sig3;
uint256 hash3 = SignatureHash(scriptPubKey, txTo, 0, SIGHASH_SINGLE);
BOOST_CHECK(keys[2].Sign(hash3, sig3));
sig3.push_back(SIGHASH_SINGLE);
// Not fussy about order (or even existence) of placeholders or signatures:
CScript partial1a = CScript() << OP_0 << sig1 << OP_0;
CScript partial1b = CScript() << OP_0 << OP_0 << sig1;
CScript partial2a = CScript() << OP_0 << sig2;
CScript partial2b = CScript() << sig2 << OP_0;
CScript partial3a = CScript() << sig3;
CScript partial3b = CScript() << OP_0 << OP_0 << sig3;
CScript partial3c = CScript() << OP_0 << sig3 << OP_0;
CScript complete12 = CScript() << OP_0 << sig1 << sig2;
CScript complete13 = CScript() << OP_0 << sig1 << sig3;
CScript complete23 = CScript() << OP_0 << sig2 << sig3;
combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial1b);
BOOST_CHECK(combined == partial1a);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial1a, partial2a);
BOOST_CHECK(combined == complete12);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial1a);
BOOST_CHECK(combined == complete12);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial1b, partial2b);
BOOST_CHECK(combined == complete12);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial1b);
BOOST_CHECK(combined == complete13);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial2a, partial3a);
BOOST_CHECK(combined == complete23);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial2b);
BOOST_CHECK(combined == complete23);
combined = CombineSignatures(scriptPubKey, txTo, 0, partial3b, partial3a);
BOOST_CHECK(combined == partial3c);
}
BOOST_AUTO_TEST_CASE(script_standard_push)
{
ScriptError err;
for (int i=0; i<67000; i++) {
CScript script;
script << i;
BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Number " << i << " is not pure push.");
BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Number " << i << " push is not minimal data.");
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
for (unsigned int i=0; i<=MAX_SCRIPT_ELEMENT_SIZE; i++) {
std::vector<unsigned char> data(i, '\111');
CScript script;
script << data;
BOOST_CHECK_MESSAGE(script.IsPushOnly(), "Length " << i << " is not pure push.");
BOOST_CHECK_MESSAGE(VerifyScript(script, CScript() << OP_1, SCRIPT_VERIFY_MINIMALDATA, BaseSignatureChecker(), &err), "Length " << i << " push is not minimal data.");
BOOST_CHECK_MESSAGE(err == SCRIPT_ERR_OK, ScriptErrorString(err));
}
}
BOOST_AUTO_TEST_CASE(script_IsPushOnly_on_invalid_scripts)
{
// IsPushOnly returns false when given a script containing only pushes that
// are invalid due to truncation. IsPushOnly() is consensus critical
// because P2SH evaluation uses it, although this specific behavior should
// not be consensus critical as the P2SH evaluation would fail first due to
// the invalid push. Still, it doesn't hurt to test it explicitly.
static const unsigned char direct[] = { 1 };
BOOST_CHECK(!CScript(direct, direct+sizeof(direct)).IsPushOnly());
}
BOOST_AUTO_TEST_SUITE_END()
|
#include "Internal.hpp"
using namespace AppCUI::OS;
using SpecialFolderList = std::vector<std::pair<std::string, std::filesystem::path>>;
void AddSpecialFolder(REFKNOWNFOLDERID specialFolerID, const char * name, SpecialFolderList& specialFolderList)
{
LPWSTR resultPath = nullptr;
HRESULT hr;
hr = SHGetKnownFolderPath(specialFolerID, KF_FLAG_CREATE, NULL, &resultPath);
if (SUCCEEDED(hr))
{
specialFolderList.push_back({ name, resultPath });
}
if (resultPath)
CoTaskMemFree(resultPath);
}
void AppCUI::OS::GetSpecialFolders(SpecialFolderList& specialFolderList, SpecialFoldersType type, bool clearVector)
{
if (clearVector)
specialFolderList.clear();
if ((type == SpecialFoldersType::All) || (type == SpecialFoldersType::Drives))
{
char drivePath[4] = "_:\\";
std::string name;
for (char drv = 'A'; drv <= 'Z'; drv++)
{
drivePath[0] = drv;
UINT type = GetDriveTypeA(drivePath);
name = drivePath;
switch (type)
{
case DRIVE_CDROM:
name += " (CD-ROM)";
break;
case DRIVE_FIXED:
name += " (Local)";
break;
case DRIVE_REMOVABLE:
name += " (Removable)";
break;
case DRIVE_RAMDISK:
name += " (RAM-Drive)";
break;
case DRIVE_REMOTE:
name += " (Remote)";
break;
default:
continue;
}
specialFolderList.push_back({ name, drivePath });
}
}
if ((type == SpecialFoldersType::All) || (type == SpecialFoldersType::SpecialLocations))
{
// special folers
AddSpecialFolder(FOLDERID_Desktop, "Desktop", specialFolderList);
AddSpecialFolder(FOLDERID_Documents, "Documents", specialFolderList);
AddSpecialFolder(FOLDERID_LocalDocuments, "Local Documents", specialFolderList);
AddSpecialFolder(FOLDERID_Downloads, "Downloads", specialFolderList);
AddSpecialFolder(FOLDERID_LocalDownloads, "Local Downloads", specialFolderList);
AddSpecialFolder(FOLDERID_Music, "Music", specialFolderList);
AddSpecialFolder(FOLDERID_LocalMusic, "Local Music", specialFolderList);
AddSpecialFolder(FOLDERID_Pictures, "Pictures", specialFolderList);
AddSpecialFolder(FOLDERID_LocalPictures, "Local Pictures", specialFolderList);
AddSpecialFolder(FOLDERID_Videos, "Videos", specialFolderList);
AddSpecialFolder(FOLDERID_LocalVideos, "Local Videos", specialFolderList);
}
}
std::filesystem::path AppCUI::OS::GetCurrentApplicationPath()
{
WCHAR path[1024];
DWORD nrChars = GetModuleFileNameW(NULL, path, (sizeof(path)/sizeof(WCHAR)) - 1);
if (nrChars == 0)
return std::filesystem::path(); // empty path
if (nrChars <= ((sizeof(path) / sizeof(WCHAR)) - 1))
{
path[nrChars] = 0; // add the last NULL char
return std::filesystem::path(path);
}
// path is larger than 1024 character
try
{
WCHAR* tempPath = new WCHAR[(size_t)nrChars + 2];
nrChars = GetModuleFileNameW(NULL, tempPath, nrChars + 1);
if (nrChars == 0)
{
delete[] tempPath;
return std::filesystem::path(); // empty path
}
tempPath[nrChars] = 0;
std::filesystem::path app_path(tempPath);
delete[] tempPath;
return app_path;
}
catch (...)
{
// exception -> return an empty path
return std::filesystem::path();
}
}
|
#pragma once
#include "API/Types.hpp"
#include "Common.hpp"
#include "Services/Hooks/Hooks.hpp"
#include "ViewPtr.hpp"
namespace Events {
class PVPEvents
{
public:
PVPEvents(NWNXLib::ViewPtr<NWNXLib::Services::HooksProxy> hooker);
private:
static int32_t HandlePlayerToServerPVPListOperationsHook(CNWSMessage*, CNWSPlayer*, uint8_t);
};
}
|
// Copyright 2019 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 "components/content_settings/browser/content_settings_manager_impl.h"
#include "base/memory/ptr_util.h"
#include "components/content_settings/browser/page_specific_content_settings.h"
#include "components/content_settings/core/browser/cookie_settings.h"
#include "components/page_load_metrics/browser/metrics_web_contents_observer.h"
#include "components/page_load_metrics/browser/page_load_metrics_observer.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_process_host.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
using content_settings::PageSpecificContentSettings;
namespace content_settings {
namespace {
void OnStorageAccessed(int process_id,
int frame_id,
const GURL& origin_url,
const GURL& top_origin_url,
bool blocked_by_policy,
page_load_metrics::StorageType storage_type) {
content::RenderFrameHost* frame =
content::RenderFrameHost::FromID(process_id, frame_id);
content::WebContents* web_contents =
content::WebContents::FromRenderFrameHost(frame);
if (!web_contents)
return;
page_load_metrics::MetricsWebContentsObserver* metrics_observer =
page_load_metrics::MetricsWebContentsObserver::FromWebContents(
web_contents);
if (metrics_observer) {
metrics_observer->OnStorageAccessed(origin_url, top_origin_url,
blocked_by_policy, storage_type);
}
}
void OnDomStorageAccessed(int process_id,
int frame_id,
const GURL& origin_url,
const GURL& top_origin_url,
bool local,
bool blocked_by_policy) {
PageSpecificContentSettings* settings =
PageSpecificContentSettings::GetForFrame(
content::RenderFrameHost::FromID(process_id, frame_id));
if (settings)
settings->OnDomStorageAccessed(origin_url, local, blocked_by_policy);
}
} // namespace
ContentSettingsManagerImpl::~ContentSettingsManagerImpl() = default;
// static
void ContentSettingsManagerImpl::Create(
content::RenderProcessHost* render_process_host,
mojo::PendingReceiver<content_settings::mojom::ContentSettingsManager>
receiver,
std::unique_ptr<Delegate> delegate) {
mojo::MakeSelfOwnedReceiver(base::WrapUnique(new ContentSettingsManagerImpl(
render_process_host, std::move(delegate))),
std::move(receiver));
}
void ContentSettingsManagerImpl::Clone(
mojo::PendingReceiver<content_settings::mojom::ContentSettingsManager>
receiver) {
mojo::MakeSelfOwnedReceiver(
base::WrapUnique(new ContentSettingsManagerImpl(*this)),
std::move(receiver));
}
void ContentSettingsManagerImpl::AllowStorageAccess(
int32_t render_frame_id,
StorageType storage_type,
const url::Origin& origin,
const GURL& site_for_cookies,
const url::Origin& top_frame_origin,
base::OnceCallback<void(bool)> callback) {
GURL url = origin.GetURL();
bool allowed = cookie_settings_->IsFullCookieAccessAllowed(
url, site_for_cookies, top_frame_origin);
if (delegate_->AllowStorageAccess(render_process_id_, render_frame_id,
storage_type, url, allowed, &callback)) {
DCHECK(!callback);
return;
}
switch (storage_type) {
case StorageType::DATABASE:
PageSpecificContentSettings::WebDatabaseAccessed(
render_process_id_, render_frame_id, url, !allowed);
break;
case StorageType::LOCAL_STORAGE:
OnDomStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), true, !allowed);
OnStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), !allowed,
page_load_metrics::StorageType::kLocalStorage);
break;
case StorageType::SESSION_STORAGE:
OnDomStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), false, !allowed);
OnStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), !allowed,
page_load_metrics::StorageType::kSessionStorage);
break;
case StorageType::FILE_SYSTEM:
PageSpecificContentSettings::FileSystemAccessed(
render_process_id_, render_frame_id, url, !allowed);
OnStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), !allowed,
page_load_metrics::StorageType::kFileSystem);
break;
case StorageType::INDEXED_DB:
PageSpecificContentSettings::IndexedDBAccessed(
render_process_id_, render_frame_id, url, !allowed);
OnStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), !allowed,
page_load_metrics::StorageType::kIndexedDb);
break;
case StorageType::CACHE:
PageSpecificContentSettings::CacheStorageAccessed(
render_process_id_, render_frame_id, url, !allowed);
OnStorageAccessed(render_process_id_, render_frame_id, url,
top_frame_origin.GetURL(), !allowed,
page_load_metrics::StorageType::kCacheStorage);
break;
case StorageType::WEB_LOCKS:
// State not persisted, no need to record anything.
break;
}
std::move(callback).Run(allowed);
}
void ContentSettingsManagerImpl::OnContentBlocked(int32_t render_frame_id,
ContentSettingsType type) {
PageSpecificContentSettings* settings =
PageSpecificContentSettings::GetForFrame(render_process_id_,
render_frame_id);
if (settings)
settings->OnContentBlocked(type);
}
ContentSettingsManagerImpl::ContentSettingsManagerImpl(
content::RenderProcessHost* render_process_host,
std::unique_ptr<Delegate> delegate)
: delegate_(std::move(delegate)),
render_process_id_(render_process_host->GetID()),
cookie_settings_(delegate_->GetCookieSettings(
render_process_host->GetBrowserContext())) {}
ContentSettingsManagerImpl::ContentSettingsManagerImpl(
const ContentSettingsManagerImpl& other)
: delegate_(other.delegate_->Clone()),
render_process_id_(other.render_process_id_),
cookie_settings_(other.cookie_settings_) {}
} // namespace content_settings
|
// ------------------------------------------------------------------------ //
// Copyright 2021 SPTK Working Group //
// //
// Licensed under the Apache License, Version 2.0 (the "License"); //
// you may not use this file except in compliance with the License. //
// You may obtain a copy of the License at //
// //
// http://www.apache.org/licenses/LICENSE-2.0 //
// //
// Unless required by applicable law or agreed to in writing, software //
// distributed under the License is distributed on an "AS IS" BASIS, //
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //
// See the License for the specific language governing permissions and //
// limitations under the License. //
// ------------------------------------------------------------------------ //
#include <fstream> // std::ifstream
#include <iomanip> // std::setw
#include <iostream> // std::cerr, std::cin, std::cout, std::endl, etc.
#include <sstream> // std::ostringstream
#include <vector> // std::vector
#include "Getopt/getoptwin.h"
#include "SPTK/conversion/mel_cepstrum_to_mlsa_digital_filter_coefficients.h"
#include "SPTK/utils/sptk_utils.h"
namespace {
const int kDefaultNumOrder(25);
const double kDefaultAlpha(0.35);
void PrintUsage(std::ostream* stream) {
// clang-format off
*stream << std::endl;
*stream << " mc2b - convert mel-cepstrum to MLSA digital filter coefficients" << std::endl; // NOLINT
*stream << std::endl;
*stream << " usage:" << std::endl;
*stream << " mc2b [ options ] [ infile ] > stdout" << std::endl;
*stream << " options:" << std::endl;
*stream << " -m m : order of mel-cepstrum ( int)[" << std::setw(5) << std::right << kDefaultNumOrder << "][ 0 <= m <= ]" << std::endl; // NOLINT
*stream << " -a a : all-pass constant (double)[" << std::setw(5) << std::right << kDefaultAlpha << "][ -1.0 < a < 1.0 ]" << std::endl; // NOLINT
*stream << " -h : print this message" << std::endl;
*stream << " infile:" << std::endl;
*stream << " mel-cepstrum (double)[stdin]" << std::endl; // NOLINT
*stream << " stdout:" << std::endl;
*stream << " MLSA filter coefficients (double)" << std::endl;
*stream << std::endl;
*stream << " SPTK: version " << sptk::kVersion << std::endl;
*stream << std::endl;
// clang-format on
}
} // namespace
/**
* @a mc2b [ @e option ] [ @e infile ]
*
* - @b -m @e int
* - order of coefficients @f$(0 \le M)@f$
* - @b -a @e double
* - all-pass constant @f$(|\alpha| < 1)@f$
* - @b infile @e str
* - double-type mel-cepstral coefficients
* - @b stdout
* - double-type MLSA digital filter coefficients
*
* The below example converts mel-cepstral coefficients into MLSA digital filter
* coefficients:
*
* @code{.sh}
* mc2b < data.mc > data.b
* @endcode
*
* The converted MLSA digital filter coefficients can be reverted by
*
* @code{.sh}
* b2mc < data.b > data.mc
* @endcode
*
* @param[in] argc Number of arguments.
* @param[in] argv Argument vector.
* @return 0 on success, 1 on failure.
*/
int main(int argc, char* argv[]) {
int num_order(kDefaultNumOrder);
double alpha(kDefaultAlpha);
for (;;) {
const int option_char(getopt_long(argc, argv, "m:a:h", NULL, NULL));
if (-1 == option_char) break;
switch (option_char) {
case 'm': {
if (!sptk::ConvertStringToInteger(optarg, &num_order) ||
num_order < 0) {
std::ostringstream error_message;
error_message << "The argument for the -m option must be a "
<< "non-negative integer";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
break;
}
case 'a': {
if (!sptk::ConvertStringToDouble(optarg, &alpha) ||
!sptk::IsValidAlpha(alpha)) {
std::ostringstream error_message;
error_message
<< "The argument for the -a option must be in (-1.0, 1.0)";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
break;
}
case 'h': {
PrintUsage(&std::cout);
return 0;
}
default: {
PrintUsage(&std::cerr);
return 1;
}
}
}
const int num_input_files(argc - optind);
if (1 < num_input_files) {
std::ostringstream error_message;
error_message << "Too many input files";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
const char* input_file(0 == num_input_files ? NULL : argv[optind]);
std::ifstream ifs;
ifs.open(input_file, std::ios::in | std::ios::binary);
if (ifs.fail() && NULL != input_file) {
std::ostringstream error_message;
error_message << "Cannot open file " << input_file;
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
std::istream& input_stream(ifs.fail() ? std::cin : ifs);
sptk::MelCepstrumToMlsaDigitalFilterCoefficients
mel_cepstrum_to_mlsa_digital_filter_coefficients(num_order, alpha);
if (!mel_cepstrum_to_mlsa_digital_filter_coefficients.IsValid()) {
std::ostringstream error_message;
error_message
<< "Failed to initialize MelCepstrumToMlsaDigitalFilterCoefficients";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
const int length(num_order + 1);
std::vector<double> mel_cepstrum(length);
std::vector<double> mlsa_digital_filter_coefficients(length);
while (sptk::ReadStream(false, 0, 0, length, &mel_cepstrum, &input_stream,
NULL)) {
if (!mel_cepstrum_to_mlsa_digital_filter_coefficients.Run(
mel_cepstrum, &mlsa_digital_filter_coefficients)) {
std::ostringstream error_message;
error_message << "Failed to convert mel-cepstrum to MLSA digital "
"filter coefficients";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
if (!sptk::WriteStream(0, length, mlsa_digital_filter_coefficients,
&std::cout, NULL)) {
std::ostringstream error_message;
error_message << "Failed to write MLSA digital filter coefficients";
sptk::PrintErrorMessage("mc2b", error_message);
return 1;
}
}
return 0;
}
|
#include "generics/aliveentity.hpp"
void AliveEntity::increaseHealth(float modifier){
this->health += modifier;
}
void AliveEntity::increaseSpeed(float modifier){
this->speed += modifier;
}
void AliveEntity::decreaseHealth(float modifier){
this->onCombo = true;
this->entityComboDelimeter.resetLastUpdate();
this->comboDamage += modifier;
this->damageOutput.setString(IntToString::IntToString((int) - comboDamage));
this->health -= modifier;
}
void AliveEntity::decreaseSpeed(float modifier){
this->speed -= modifier;
}
AliveEntity::AliveEntity(int x, int y, float health, float speed, sf::Texture const& texture,
int spriteX, int spriteY, int spriteW, int spriteH,
float entityGravity, int spriteInitX, int spriteEndX, int spriteInitY, int spriteEndY) :
SpritedEntity::SpritedEntity(texture, spriteX, spriteY, spriteW, spriteH),
AnimatedEntity::AnimatedEntity(spriteInitX, spriteEndX, spriteInitY, spriteEndY),
entityComboDelimeter(sf::seconds(2.5)) {
this->movement = sf::Vector2f(0.f, 0.f);
setSpritePosition(x, y);
this->entityGravity = entityGravity;
this->isJumping = true;
this->animationLeftLoop = 0;
this->animationRightLoop = 0;
this->maxHealth = health;
this->health = health;
this->originalSpeed = speed;
this->speed = speed;
this->quad = 0;
this->comboDamage = 0;
this->onCombo = false;
}
void AliveEntity::moveEntity(){
moveSprite(movement);
}
void AliveEntity::moveEntity(const DynamicGrid& dynaGrid){
moveSprite(movement);
updateQuad(dynaGrid.getQuad(getSpritePosition()));
}
sf::Vector2f AliveEntity::getMovement() const{
return this->movement;
}
void AliveEntity::setMovementX(float x){
this->movement.x = x;
}
void AliveEntity::setMovementY(float y){
this->movement.y = y;
}
void AliveEntity::applyGravity(){
if (this->movement.y < 6)
this->movement.y += entityGravity;
}
bool AliveEntity::getIsJumping() const{
return this->isJumping;
}
void AliveEntity::setIsJumping(bool jumping){
this->isJumping = jumping;
}
float AliveEntity::getGravity() const{
return this->entityGravity;
}
float AliveEntity::getHealth() const{
return this->health;
}
float AliveEntity::getMaxHealth() const{
return this->maxHealth;
}
void AliveEntity::updateQuad(int newQuad){
if(quad != newQuad){
quad = newQuad;
}
}
int AliveEntity::getQuad() const{
return this->quad;
}
void AliveEntity::cccomboBreak(){
this->onCombo = false;
this->comboDamage = 0;
}
bool AliveEntity::getOnCombo() const{
return this->onCombo;
}
GenericTimeHandler* AliveEntity::getEntityComboDelimeter(){
return &this->entityComboDelimeter;
}
void AliveEntity::setComboDelimeter(int seconds){
this->entityComboDelimeter = GenericTimeHandler(sf::seconds(seconds));
}
void AliveEntity::init(const sf::Font& font){
this->damageOutput = sf::Text(std::string("-0"), font);
this->damageOutput.setCharacterSize(20);
this->damageOutput.setColor(sf::Color::Red);
}
void AliveEntity::updateDamageText(){
this->damageOutput.setPosition(getSpritePosition().x + getSpriteLocalBounds().width/2 - this->damageOutput.getLocalBounds().width/2, getSpritePosition().y - 32);
}
sf::Text AliveEntity::getDamageOutput() const{
return this->damageOutput;
}
void AliveEntity::drawText(sf::RenderTarget& target){
target.draw(this->damageOutput);
}
bool AliveEntity::isFacingRight() const{
return this->facingRight;
}
void AliveEntity::setDoubleJump(bool doubleJump){
this->doubleJump = doubleJump;
}
|
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 Sensics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <osvr/Util/EigenCoreGeometry.h>
template <typename T>
inline void dumpKalmanDebugOuput(const char name[], const char expr[],
T const &value) {
std::cout << "\n(Kalman Debug Output) " << name << " [" << expr << "]:\n"
<< value << std::endl;
}
#define OSVR_KALMAN_DEBUG_OUTPUT(Name, Value) \
dumpKalmanDebugOuput(Name, #Value, Value)
// Internal Includes
#include "ContentsInvalid.h"
#include <osvr/Kalman/FlexibleKalmanFilter.h>
#include <osvr/Kalman/PoseConstantVelocity.h>
#include <osvr/Kalman/PoseDampedConstantVelocity.h>
#include <osvr/Kalman/AbsoluteOrientationMeasurement.h>
#include <osvr/Kalman/AbsolutePositionMeasurement.h>
// Library/third-party includes
#include "gtest/gtest.h"
// Standard includes
#include <iostream>
using ProcessModel = osvr::kalman::PoseConstantVelocityProcessModel;
using State = ProcessModel::State;
using AbsoluteOrientationMeasurement =
osvr::kalman::AbsoluteOrientationMeasurement<State>;
using AbsolutePositionMeasurement =
osvr::kalman::AbsolutePositionMeasurement<State>;
using Filter = osvr::kalman::FlexibleKalmanFilter<ProcessModel>;
class Stability : public ::testing::Test {
public:
template <typename Filter> void dumpInitialState(Filter const &filter) {
ASSERT_EQ(iteration, 0)
<< "Internal test logic error: should only call "
"dumpInitialState before iterations begin.";
dumpState(filter.state(), "Initial state");
}
template <typename State>
void dumpState(State const &state, const char msg[]) {
std::cout << "\n" << msg << " (iteration " << iteration << "):\n"
<< state << std::endl;
}
template <typename Filter, typename Measurement>
void filterAndCheck(Filter &filter, Measurement &meas, double dt = 0.1) {
filter.predict(dt);
dumpState(filter.state(), "After prediction");
ASSERT_FALSE(stateContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid floating-point value in the state "
"after prediction step of iteration "
<< iteration;
ASSERT_FALSE(covarianceContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid state covariance matrix (invalid "
"floating-point, or invariants violated) after prediction step "
"of iteration "
<< iteration;
ASSERT_FALSE(
covarianceContentsInvalid(meas.getCovariance(filter.state())))
<< "ERROR: Detected invalid contents (invalid floating-point, or "
"invariants violated) in measurement covariance "
"matrix, iteration "
<< iteration << "\n" << meas.getCovariance(filter.state());
filter.correct(meas);
dumpState(filter.state(), "After correction");
ASSERT_FALSE(stateContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid floating-point value in the state "
"after correction step of iteration "
<< iteration;
ASSERT_FALSE(covarianceContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid state covariance matrix (invalid "
"floating-point, or invariants violated) after correction step "
"of iteration "
<< iteration;
iteration++;
}
template <typename Filter, typename Measurement>
void filterAndCheckRepeatedly(Filter &filter, Measurement &meas,
double dt = 0.1,
std::size_t iterations = 100) {
for (iteration = 0; iteration < iterations; iteration++) {
filter.predict(dt);
dumpState(filter.state(), "After prediction");
ASSERT_FALSE(stateContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid floating-point value in the "
"state "
"after prediction step of iteration "
<< iteration;
ASSERT_FALSE(covarianceContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid state covariance matrix "
"(invalid "
"floating-point, or invariants violated) after prediction "
"step "
"of iteration "
<< iteration;
ASSERT_FALSE(
covarianceContentsInvalid(meas.getCovariance(filter.state())))
<< "ERROR: Detected invalid contents (invalid floating-point, "
"or "
"invariants violated) in measurement covariance "
"matrix, iteration "
<< iteration << "\n" << meas.getCovariance(filter.state());
filter.correct(meas);
dumpState(filter.state(), "After correction");
ASSERT_FALSE(stateContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid floating-point value in the "
"state "
"after correction step of iteration "
<< iteration;
ASSERT_FALSE(covarianceContentsInvalid(filter.state()))
<< "ERROR: Detected an invalid state covariance matrix "
"(invalid "
"floating-point, or invariants violated) after correction "
"step "
"of iteration "
<< iteration;
}
}
private:
std::size_t iteration = 0;
};
template <typename T> class VariedProcessModelStability : public Stability {};
typedef ::testing::Types<osvr::kalman::PoseConstantVelocityProcessModel,
osvr::kalman::PoseDampedConstantVelocityProcessModel>
ProcessModelTypes;
TYPED_TEST_CASE(VariedProcessModelStability, ProcessModelTypes);
TYPED_TEST(VariedProcessModelStability,
IdentityAbsoluteOrientationMeasurement) {
using Filter = osvr::kalman::FlexibleKalmanFilter<TypeParam>;
auto filter = Filter{};
auto meas = AbsoluteOrientationMeasurement{
Eigen::Quaterniond::Identity(),
Eigen::Vector3d(0.00001, 0.00001, 0.00001)};
this->dumpInitialState(filter);
this->filterAndCheckRepeatedly(filter, meas);
/// @todo check that it's roughly identity
}
TYPED_TEST(VariedProcessModelStability, IdentityAbsolutePositionMeasurement) {
using Filter = osvr::kalman::FlexibleKalmanFilter<TypeParam>;
auto filter = Filter{};
auto meas = AbsolutePositionMeasurement{
Eigen::Vector3d::Zero(), Eigen::Vector3d::Constant(0.000007)};
this->dumpInitialState(filter);
this->filterAndCheckRepeatedly(filter, meas);
/// @todo check that it's roughly identity
}
TYPED_TEST(VariedProcessModelStability, AbsolutePositionMeasurementXlate111) {
using Filter = osvr::kalman::FlexibleKalmanFilter<TypeParam>;
auto filter = Filter{};
auto meas = AbsolutePositionMeasurement{
Eigen::Vector3d::Constant(1), Eigen::Vector3d::Constant(0.000007)};
this->dumpInitialState(filter);
this->filterAndCheckRepeatedly(filter, meas);
/// @todo check that it's roughly identity orientation, position of 1, 1, 1
}
|
#include "log_manager.h"
#include <sstream>
namespace pbr::shared::apis::logging {
bool log_manager::add_endpoint(const std::shared_ptr<endpoint>& endpoint) noexcept {
if (!endpoint) {
return false;
}
std::scoped_lock<std::mutex> lock(this->_mutex);
this->_endpoints.push_back(endpoint);
return true;
}
const std::vector<std::shared_ptr<endpoint>>& log_manager::get_endpoints() const noexcept {
std::scoped_lock<std::mutex> lock(this->_mutex);
return this->_endpoints;
}
void log_manager::set_log_level(const log_levels level) noexcept {
std::scoped_lock<std::mutex> lock(this->_mutex);
this->_current_log_level = level;
}
log_levels log_manager::get_log_level() const noexcept {
std::scoped_lock<std::mutex> lock(this->_mutex);
return this->_current_log_level;
}
void log_manager::log_message(std::string_view message,
const log_levels level,
std::string_view prefix) noexcept {
if (level < this->_current_log_level) {
return;
}
// prefix: date time | level> message
std::stringstream ss;
if (!prefix.empty()) {
ss << prefix << ": ";
}
ss << this->_datetime_manager->get_date_time_as_utc_string()
<< " | "
<< to_string(level)
<< "> "
<< message;
auto formatted_message = ss.str();
std::scoped_lock<std::mutex> lock(this->_mutex);
for (const auto& e : this->_endpoints) {
e->log(formatted_message, level);
}
}
}
|
#include<cstdio>
#include <cstring>
#define BASE 1000
#define WIDTH 255
#define DBGOUT(a) ({\
printf("DEBUG:line[%d]:out: "#a"=",__LINE__);\
out(a);\
putchar('\n');\
})
typedef struct{
int buf[WIDTH],top=0;
}BGint;
BGint a[WIDTH][WIDTH];
BGint dp[WIDTH][WIDTH];
int m,n;
void read(void);
void solve(int);
void clear(void);
BGint* max(BGint*,BGint*);
BGint* add(BGint*,BGint*);
BGint* mov(BGint*,BGint*);
BGint* pow2(BGint*,int);
BGint* out(BGint*);
BGint* mul(BGint*,BGint*);
BGint* init(BGint*);
int main(){
BGint ans;
init(&ans);
read();
int i;
for(i=0;i<n;++i){
solve(i);
add(&ans,&dp[0][m-1]);
}
out(&ans);
putchar('\n');
return 0;
}
void clear(void){
int i,j;
for(i=0;i<=m;++i){
for(j=0;j<=m;++j) {
init(dp[i]+j);
}
}
}
void solve(int now){
int l,r;
clear();
for(l=m-1;l>=0;--l){
for(r=l;r<m;++r){
int time=l+m-r;
if(r){
BGint tmp1,tmp2,eax,ebx;
mov(&tmp1,dp[l+1]+r);
mov(&eax,a[now]+l);
pow2(&ebx,time);
mul(&eax,&ebx);
add(&tmp1,&eax);
mov(&tmp2,dp[l]+r-1);
mov(&eax,a[now]+r);
pow2(&ebx,time);
mul(&eax,&ebx);
add(&tmp2,&eax);
mov(dp[l]+r,max(&tmp1,&tmp2));
} else{
BGint tmp,eax,ebx;
mov(&tmp,dp[l+1]+r);
mov(&eax,a[now]+l);
pow2(&ebx,time);
mul(&eax,&ebx);
add(&tmp,&eax);
mov(dp[l]+r,&tmp);
}
}
}
}
void read(){
int i,j;
scanf("%d%d",&n,&m);
for(i=0;i<n;i++)
for(j=0;j<m;j++){
init(a[i]+j);
scanf("%d",a[i][j].buf);
if(a[i][j].buf[0]>=1000) {
a[i][j].buf[0]-=1000;
a[i][j].buf[1]=1;
a[i][j].top=2;
}else a[i][j].top=1;
}
}
BGint* pow2(BGint* dest,int time){
BGint base;
init(dest);
init(&base);
base.buf[0]=2;
dest->buf[0]=1;
while(time){
if(time & 1) mul(dest,&base);
mul(&base,&base);
time>>=1;
}
return dest;
}
BGint* max(BGint* a,BGint* b){
int p=a->top;
if(a->top > b->top) return a;
if(a->top < b->top) return b;
while(--p>=0){
if(a->buf[p] > b->buf[p]) return a;
if(a->buf[p] < b->buf[p]) return b;
}
return a;
}
BGint* mov(BGint* dest,BGint* src){
memcpy(dest->buf,src->buf,sizeof(int)*WIDTH);
dest->top=src->top;
return dest;
}
BGint* add(BGint* a,BGint* b){
int i,bit=(a->top > b->top) ? a->top : b->top;
for(i=0;i<bit;++i) {
a->buf[i]+=b->buf[i];
if(a->buf[i] >= BASE) ++a->buf[i+1];
a->buf[i]%=BASE;
}
a->top=1;
while(a->buf[a->top]) ++a->top;
return a;
}
BGint* mul(BGint* a,BGint* b){
int i,j;
BGint ans;
init(&ans);
for(i=0;i<a->top;++i)
for(j=0;j<b->top;++j){
ans.buf[i+j]+=(a->buf[i])*(b->buf[j]);
if(ans.buf[i+j]>=BASE) {
ans.buf[i+j+1]+=ans.buf[i+j]/BASE;
ans.buf[i+j]%=BASE;
}
}
while(ans.buf[ans.top]) ++ans.top;
mov(a,&ans);
return a;
}
BGint* out(BGint *a){
int i=a->top-1;
printf("%d",a->buf[i--]);
while(i>=0) printf("%03d",a->buf[i--]);
return a;
}
BGint* init(BGint* a){
a->top=1;
memset(a->buf,0,sizeof(int)*WIDTH);
return a;
}
|
// Copyright 2016 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fcntl.h>
#include <fuchsia/media/playback/cpp/fidl.h>
#include <fuchsia/sys/cpp/fidl.h>
#include <fuchsia/ui/views/cpp/fidl.h>
#include <lib/sys/cpp/testing/test_with_environment.h>
#include <queue>
#include "lib/fsl/io/fd.h"
#include "lib/media/cpp/timeline_function.h"
#include "lib/media/cpp/type_converters.h"
#include "lib/ui/scenic/cpp/view_token_pair.h"
#include "src/lib/fxl/logging.h"
#include "src/media/playback/mediaplayer/test/command_queue.h"
#include "src/media/playback/mediaplayer/test/fakes/fake_audio.h"
#include "src/media/playback/mediaplayer/test/fakes/fake_scenic.h"
#include "src/media/playback/mediaplayer/test/fakes/fake_wav_reader.h"
#include "src/media/playback/mediaplayer/test/sink_feeder.h"
namespace media_player {
namespace test {
static constexpr uint16_t kSamplesPerFrame = 2; // Stereo
static constexpr uint32_t kFramesPerSecond = 48000; // 48kHz
static constexpr size_t kSinkFeedSize = 65536;
static constexpr uint32_t kSinkFeedMaxPacketSize = 4096;
static constexpr uint32_t kSinkFeedMaxPacketCount = 10;
constexpr char kBearFilePath[] = "/pkg/data/media_test_data/bear.mp4";
// Base class for mediaplayer tests.
class MediaPlayerTests : public sys::testing::TestWithEnvironment {
protected:
void SetUp() override {
auto services = CreateServices();
// Add the service under test using its launch info.
fuchsia::sys::LaunchInfo launch_info{
"fuchsia-pkg://fuchsia.com/mediaplayer#meta/mediaplayer.cmx"};
zx_status_t status = services->AddServiceWithLaunchInfo(
std::move(launch_info), fuchsia::media::playback::Player::Name_);
EXPECT_EQ(ZX_OK, status);
services->AddService(fake_audio_.GetRequestHandler());
services->AddService(fake_scenic_.GetRequestHandler());
// Create the synthetic environment.
environment_ = CreateNewEnclosingEnvironment("mediaplayer_tests", std::move(services));
// Instantiate the player under test.
environment_->ConnectToService(player_.NewRequest());
commands_.Init(player_.get());
player_.set_error_handler([this](zx_status_t status) {
FXL_LOG(ERROR) << "Player connection closed, status " << status << ".";
player_connection_closed_ = true;
QuitLoop();
});
player_.events().OnStatusChanged = [this](fuchsia::media::playback::PlayerStatus status) {
commands_.NotifyStatusChanged(status);
};
}
void TearDown() override { EXPECT_FALSE(player_connection_closed_); }
// Queues commands to wait for end of stream and to call |QuitLoop|.
void QuitOnEndOfStream() {
commands_.WaitForEndOfStream();
commands_.Invoke([this]() { QuitLoop(); });
}
// Executes queued commands with the specified timeout.
void Execute(zx::duration timeout = zx::sec(60)) {
commands_.Execute();
EXPECT_FALSE(RunLoopWithTimeout(zx::duration(timeout)));
}
// Creates a view.
void CreateView() {
auto [view_token, view_holder_token] = scenic::ViewTokenPair::New();
player_->CreateView(std::move(view_token));
view_holder_token_ = std::move(view_holder_token);
}
fuchsia::media::playback::PlayerPtr player_;
bool player_connection_closed_ = false;
FakeWavReader fake_reader_;
FakeAudio fake_audio_;
FakeScenic fake_scenic_;
fuchsia::ui::views::ViewHolderToken view_holder_token_;
std::unique_ptr<sys::testing::EnclosingEnvironment> environment_;
bool sink_connection_closed_ = false;
SinkFeeder sink_feeder_;
CommandQueue commands_;
};
// Play a synthetic WAV file from beginning to end.
TEST_F(MediaPlayerTests, PlayWav) {
fake_audio_.renderer().ExpectPackets({{0, 4096, 0x20c39d1e31991800},
{1024, 4096, 0xeaf137125d313800},
{2048, 4096, 0x6162095671991800},
{3072, 4096, 0x36e551c7dd41f800},
{4096, 4096, 0x23dcbf6fb1991800},
{5120, 4096, 0xee0a5963dd313800},
{6144, 4096, 0x647b2ba7f1991800},
{7168, 4096, 0x39fe74195d41f800},
{8192, 4096, 0xb3de76b931991800},
{9216, 4096, 0x7e0c10ad5d313800},
{10240, 4096, 0xf47ce2f171991800},
{11264, 4096, 0xca002b62dd41f800},
{12288, 4096, 0xb6f7990ab1991800},
{13312, 4096, 0x812532fedd313800},
{14336, 4096, 0xf7960542f1991800},
{15360, 4052, 0x7308a9824acbd5ea}});
fuchsia::media::playback::SeekingReaderPtr fake_reader_ptr;
fidl::InterfaceRequest<fuchsia::media::playback::SeekingReader> reader_request =
fake_reader_ptr.NewRequest();
fake_reader_.Bind(std::move(reader_request));
fuchsia::media::playback::SourcePtr source;
player_->CreateReaderSource(std::move(fake_reader_ptr), source.NewRequest());
player_->SetSource(std::move(source));
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
}
// Play a synthetic WAV file from beginning to end, delaying the retirement of
// the last packet to simulate delayed end-of-stream recognition.
TEST_F(MediaPlayerTests, PlayWavDelayEos) {
fake_audio_.renderer().ExpectPackets({{0, 4096, 0x20c39d1e31991800},
{1024, 4096, 0xeaf137125d313800},
{2048, 4096, 0x6162095671991800},
{3072, 4096, 0x36e551c7dd41f800},
{4096, 4096, 0x23dcbf6fb1991800},
{5120, 4096, 0xee0a5963dd313800},
{6144, 4096, 0x647b2ba7f1991800},
{7168, 4096, 0x39fe74195d41f800},
{8192, 4096, 0xb3de76b931991800},
{9216, 4096, 0x7e0c10ad5d313800},
{10240, 4096, 0xf47ce2f171991800},
{11264, 4096, 0xca002b62dd41f800},
{12288, 4096, 0xb6f7990ab1991800},
{13312, 4096, 0x812532fedd313800},
{14336, 4096, 0xf7960542f1991800},
{15360, 4052, 0x7308a9824acbd5ea}});
fuchsia::media::playback::SeekingReaderPtr fake_reader_ptr;
fidl::InterfaceRequest<fuchsia::media::playback::SeekingReader> reader_request =
fake_reader_ptr.NewRequest();
fake_reader_.Bind(std::move(reader_request));
fuchsia::media::playback::SourcePtr source;
player_->CreateReaderSource(std::move(fake_reader_ptr), source.NewRequest());
player_->SetSource(std::move(source));
fake_audio_.renderer().DelayPacketRetirement(15360);
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
}
// Play a synthetic WAV file from beginning to end, retaining packets. This
// tests the ability of the player to handle the case in which the audio
// renderer is holding on to packets for too long.
TEST_F(MediaPlayerTests, PlayWavRetainPackets) {
fake_audio_.renderer().SetRetainPackets(true);
fuchsia::media::playback::SeekingReaderPtr fake_reader_ptr;
fidl::InterfaceRequest<fuchsia::media::playback::SeekingReader> reader_request =
fake_reader_ptr.NewRequest();
fake_reader_.Bind(std::move(reader_request));
// Need more than 1s of data.
fake_reader_.SetSize(256000);
fuchsia::media::playback::SourcePtr source;
player_->CreateReaderSource(std::move(fake_reader_ptr), source.NewRequest());
player_->SetSource(std::move(source));
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
}
// Play an LPCM elementary stream using |ElementarySource|
TEST_F(MediaPlayerTests, ElementarySource) {
fake_audio_.renderer().ExpectPackets({{0, 4096, 0xd2fbd957e3bf0000},
{1024, 4096, 0xda25db3fa3bf0000},
{2048, 4096, 0xe227e0f6e3bf0000},
{3072, 4096, 0xe951e2dea3bf0000},
{4096, 4096, 0x37ebf7d3e3bf0000},
{5120, 4096, 0x3f15f9bba3bf0000},
{6144, 4096, 0x4717ff72e3bf0000},
{7168, 4096, 0x4e42015aa3bf0000},
{8192, 4096, 0xeabc5347e3bf0000},
{9216, 4096, 0xf1e6552fa3bf0000},
{10240, 4096, 0xf9e85ae6e3bf0000},
{11264, 4096, 0x01125ccea3bf0000},
{12288, 4096, 0x4fac71c3e3bf0000},
{13312, 4096, 0x56d673aba3bf0000},
{14336, 4096, 0x5ed87962e3bf0000},
{15360, 4096, 0x66027b4aa3bf0000}});
fuchsia::media::playback::ElementarySourcePtr elementary_source;
player_->CreateElementarySource(0, false, false, nullptr, elementary_source.NewRequest());
fuchsia::media::AudioStreamType audio_stream_type;
audio_stream_type.sample_format = fuchsia::media::AudioSampleFormat::SIGNED_16;
audio_stream_type.channels = kSamplesPerFrame;
audio_stream_type.frames_per_second = kFramesPerSecond;
fuchsia::media::StreamType stream_type;
stream_type.medium_specific.set_audio(std::move(audio_stream_type));
stream_type.encoding = fuchsia::media::AUDIO_ENCODING_LPCM;
fuchsia::media::SimpleStreamSinkPtr sink;
elementary_source->AddStream(std::move(stream_type), kFramesPerSecond, 1, sink.NewRequest());
sink.set_error_handler([this](zx_status_t status) {
FXL_LOG(ERROR) << "SimpleStreamSink connection closed.";
sink_connection_closed_ = true;
QuitLoop();
});
// Here we're upcasting from a
// |fidl::InterfaceHandle<fuchsia::media::playback::ElementarySource>| to a
// |fidl::InterfaceHandle<fuchsia::media::playback::Source>| the only way we
// currently can. The compiler has no way of knowing whether this is
// legit.
// TODO(dalesat): Do this safely once FIDL-329 is fixed.
player_->SetSource(fidl::InterfaceHandle<fuchsia::media::playback::Source>(
elementary_source.Unbind().TakeChannel()));
sink_feeder_.Init(std::move(sink), kSinkFeedSize, kSamplesPerFrame * sizeof(int16_t),
kSinkFeedMaxPacketSize, kSinkFeedMaxPacketCount);
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
EXPECT_FALSE(sink_connection_closed_);
}
// Opens an SBC elementary stream using |ElementarySource|.
TEST_F(MediaPlayerTests, ElementarySourceWithSBC) {
fuchsia::media::playback::ElementarySourcePtr elementary_source;
player_->CreateElementarySource(1, false, false, nullptr, elementary_source.NewRequest());
fuchsia::media::AudioStreamType audio_stream_type;
audio_stream_type.sample_format = fuchsia::media::AudioSampleFormat::SIGNED_16;
audio_stream_type.channels = kSamplesPerFrame;
audio_stream_type.frames_per_second = kFramesPerSecond;
fuchsia::media::StreamType stream_type;
stream_type.medium_specific.set_audio(std::move(audio_stream_type));
stream_type.encoding = fuchsia::media::AUDIO_ENCODING_SBC;
fuchsia::media::SimpleStreamSinkPtr sink;
elementary_source->AddStream(std::move(stream_type), kFramesPerSecond, 1, sink.NewRequest());
sink.set_error_handler([this](zx_status_t status) {
FXL_LOG(ERROR) << "SimpleStreamSink connection closed.";
sink_connection_closed_ = true;
QuitLoop();
});
// Here we're upcasting from a
// |fidl::InterfaceHandle<fuchsia::media::playback::ElementarySource>| to a
// |fidl::InterfaceHandle<fuchsia::media::playback::Source>| the only way we
// currently can. The compiler has no way of knowing whether this is
// legit.
// TODO(FIDL-329): Do this safely once FIDL-329 is fixed.
player_->SetSource(fidl::InterfaceHandle<fuchsia::media::playback::Source>(
elementary_source.Unbind().TakeChannel()));
commands_.WaitForAudioConnected();
commands_.Invoke([this]() { QuitLoop(); });
Execute();
EXPECT_FALSE(sink_connection_closed_);
}
// Opens an AAC elementary stream using |ElementarySource|.
TEST_F(MediaPlayerTests, ElementarySourceWithAAC) {
fuchsia::media::playback::ElementarySourcePtr elementary_source;
player_->CreateElementarySource(1, false, false, nullptr, elementary_source.NewRequest());
fuchsia::media::AudioStreamType audio_stream_type;
audio_stream_type.sample_format = fuchsia::media::AudioSampleFormat::SIGNED_16;
audio_stream_type.channels = kSamplesPerFrame;
audio_stream_type.frames_per_second = kFramesPerSecond;
fuchsia::media::StreamType stream_type;
stream_type.medium_specific.set_audio(std::move(audio_stream_type));
stream_type.encoding = fuchsia::media::AUDIO_ENCODING_AAC;
fuchsia::media::SimpleStreamSinkPtr sink;
elementary_source->AddStream(std::move(stream_type), kFramesPerSecond, 1, sink.NewRequest());
sink.set_error_handler([this](zx_status_t status) {
FXL_LOG(ERROR) << "SimpleStreamSink connection closed.";
sink_connection_closed_ = true;
QuitLoop();
});
// Here we're upcasting from a
// |fidl::InterfaceHandle<fuchsia::media::playback::ElementarySource>| to a
// |fidl::InterfaceHandle<fuchsia::media::playback::Source>| the only way we
// currently can. The compiler has no way of knowing whether this is
// legit.
// TODO(FIDL-329): Do this safely once FIDL-329 is fixed.
player_->SetSource(fidl::InterfaceHandle<fuchsia::media::playback::Source>(
elementary_source.Unbind().TakeChannel()));
commands_.WaitForAudioConnected();
commands_.Invoke([this]() { QuitLoop(); });
Execute();
EXPECT_FALSE(sink_connection_closed_);
}
// Tries to open a bogus elementary stream using |ElementarySource|.
TEST_F(MediaPlayerTests, ElementarySourceWithBogus) {
fuchsia::media::playback::ElementarySourcePtr elementary_source;
player_->CreateElementarySource(1, false, false, nullptr, elementary_source.NewRequest());
fuchsia::media::AudioStreamType audio_stream_type;
audio_stream_type.sample_format = fuchsia::media::AudioSampleFormat::SIGNED_16;
audio_stream_type.channels = kSamplesPerFrame;
audio_stream_type.frames_per_second = kFramesPerSecond;
fuchsia::media::StreamType stream_type;
stream_type.medium_specific.set_audio(std::move(audio_stream_type));
stream_type.encoding = "bogus encoding";
fuchsia::media::SimpleStreamSinkPtr sink;
elementary_source->AddStream(std::move(stream_type), kFramesPerSecond, 1, sink.NewRequest());
sink.set_error_handler([this](zx_status_t status) {
FXL_LOG(ERROR) << "SimpleStreamSink connection closed.";
sink_connection_closed_ = true;
QuitLoop();
});
// Here we're upcasting from a
// |fidl::InterfaceHandle<fuchsia::media::playback::ElementarySource>| to a
// |fidl::InterfaceHandle<fuchsia::media::playback::Source>| the only way we
// currently can. The compiler has no way of knowing whether this is
// legit.
// TODO(FIDL-329): Do this safely once is fixed.
player_->SetSource(fidl::InterfaceHandle<fuchsia::media::playback::Source>(
elementary_source.Unbind().TakeChannel()));
commands_.WaitForProblem();
commands_.Invoke([this]() { QuitLoop(); });
Execute();
EXPECT_FALSE(sink_connection_closed_);
}
// Play a real A/V file from beginning to end.
TEST_F(MediaPlayerTests, PlayBear) {
// TODO(dalesat): Use ExpectPackets for audio.
// This doesn't currently work, because the decoder behaves differently on
// different targets.
fake_scenic_.session().SetExpectations(
1,
{
.width = 2,
.height = 2,
.stride = 2 * sizeof(uint32_t),
.pixel_format = fuchsia::images::PixelFormat::BGRA_8,
},
{
.width = 1280,
.height = 738,
.stride = 1280,
.pixel_format = fuchsia::images::PixelFormat::YV12,
},
720, {{0, 944640, 0x0864378c3655ba47}, {133729451, 944640, 0x2481a21b1e543c8e},
{167096118, 944640, 0xe4294049f22539bc}, {200462784, 944640, 0xde1058aba916ffad},
{233829451, 944640, 0xc3fc580b34dc0383}, {267196118, 944640, 0xff31322e5ccdebe0},
{300562784, 944640, 0x64d31206ece7417f}, {333929451, 944640, 0xf1c6bf7fe1be29be},
{367296118, 944640, 0x72f44e5249a05c15}, {400662784, 944640, 0x1ad7e92183fb3aa4},
{434029451, 944640, 0x24b78b95d8c8b73d}, {467396118, 944640, 0x25a798d9af5a1b7e},
{500762784, 944640, 0x3379288b1f4197a5}, {534129451, 944640, 0x15fb9c205590cbc9},
{567496118, 944640, 0xc04a1834aec8b399}, {600862784, 944640, 0x97eded0e3b6348d3},
{634229451, 944640, 0x09dba227982ba479}, {667596118, 944640, 0x4d2a1042babc479c},
{700962784, 944640, 0x379f96a35774dc2b}, {734329451, 944640, 0x2d95a4b5506bd4c3},
{767696118, 944640, 0xda99bf00cd971999}, {801062784, 944640, 0x20a21550eb717da2},
{834429451, 944640, 0x3733b96d2279460b}, {867796118, 944640, 0x8ea51ee0088cda67},
{901162784, 944640, 0x8d6af19e5d9629ae}, {934529451, 944640, 0xd9765bd28098f093},
{967896118, 944640, 0x9a747455b496c9d1}, {1001262784, 944640, 0xfc8e90e73cc086f6},
{1034629451, 944640, 0xc3dec92946fc0005}, {1067996118, 944640, 0x215b196e790214c4},
{1101362784, 944640, 0x30b114015d719041}, {1134729451, 944640, 0x5ed6e582ac4022a1},
{1168096118, 944640, 0xbccb6f8ba8601507}, {1201462784, 944640, 0x34eab6666dc6c717},
{1234829451, 944640, 0x5e33bfc44650245f}, {1268196118, 944640, 0x736397b78e0850ff},
{1301562784, 944640, 0x620d7190a9e49a31}, {1334929451, 944640, 0x436e952327e311ea},
{1368296118, 944640, 0xf6fa16fc170a85f3}, {1401662784, 944640, 0x9f457e1a66323ead},
{1435029451, 944640, 0xb1747e31ea5358db}, {1468396118, 944640, 0x4da84ec1c5cb45de},
{1501762784, 944640, 0x5454f9007dc4de01}, {1535129451, 944640, 0x8e9777accf38e4f0},
{1568496118, 944640, 0x16a2ebade809e497}, {1601862784, 944640, 0x36d323606ebca2f4},
{1635229451, 944640, 0x17eaf1e84353dec9}, {1668596118, 944640, 0xdb1b344498520386},
{1701962784, 944640, 0xec53764065860e7f}, {1735329451, 944640, 0x110a7dddd4c45a54},
{1768696118, 944640, 0x6df1c973722f01c7}, {1802062784, 944640, 0x2e18f1e1544e002a},
{1835429451, 944640, 0x0de7b784dd8b0494}, {1868796118, 944640, 0x6e254cd1652be6a9},
{1902162784, 944640, 0x6353cb7c270b06c2}, {1935529451, 944640, 0x8d62a2ddb0350ab9},
{1968896118, 944640, 0xaf0ee1376ded95cd}, {2002262784, 944640, 0xf617917814de4169},
{2035629451, 944640, 0xf686efcec861909f}, {2068996118, 944640, 0x539f93afe6863cca},
{2102362784, 944640, 0x12c5c5e4eb5b2649}, {2135729451, 944640, 0x984cf8179effd823},
{2169096118, 944640, 0xfcb0cc2eb449ed16}, {2202462784, 944640, 0xf070b3572db477cc},
{2235829451, 944640, 0x5dd53f712ce8e1a6}, {2269196118, 944640, 0x02e0600528534bef},
{2302562784, 944640, 0x53120fbaca19e13b}, {2335929451, 944640, 0xd66e3cb3e70897eb},
{2369296118, 944640, 0x9f4138aa8e84cbf4}, {2402662784, 944640, 0xf350694d6a12ec39},
{2436029451, 944640, 0x08c986a97ab8fbb3}, {2469396118, 944640, 0x229d2b908659b728},
{2502762784, 944640, 0xf54cbe4582a3f8e1}, {2536129451, 944640, 0x8c8985c6649a3e1c},
{2569496118, 944640, 0x711e04eccc5e4527}, {2602862784, 944640, 0x78e2979034921e70},
{2636229451, 944640, 0x51c3524f5bf83a62}, {2669596118, 944640, 0x12b6f7b7591e7044},
{2702962784, 944640, 0xca8d7ac09b973a4b}, {2736329451, 944640, 0x3e666b376fcaa466},
{2769696118, 944640, 0x8f3657c9648b6dbb}, {2803062784, 944640, 0x19a30916a3375f4e}});
CreateView();
commands_.SetFile(kBearFilePath);
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
EXPECT_TRUE(fake_scenic_.session().expected());
}
// Play a real A/V file from beginning to end, retaining audio packets. This
// tests the ability of the player to handle the case in which the audio
// renderer is holding on to packets for too long.
TEST_F(MediaPlayerTests, PlayBearRetainAudioPackets) {
CreateView();
fake_audio_.renderer().SetRetainPackets(true);
commands_.SetFile(kBearFilePath);
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
EXPECT_TRUE(fake_scenic_.session().expected());
}
// Regression test for US-544.
TEST_F(MediaPlayerTests, RegressionTestUS544) {
CreateView();
commands_.SetFile(kBearFilePath);
// Play for two seconds and pause.
commands_.Play();
commands_.WaitForPosition(zx::sec(2));
commands_.Pause();
// Wait a bit.
commands_.Sleep(zx::sec(2));
// Seek to the beginning and resume playing.
commands_.Seek(zx::sec(0));
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
EXPECT_TRUE(fake_scenic_.session().expected());
}
// Regression test for QA-539.
// Verifies that the player can play two files in a row.
TEST_F(MediaPlayerTests, RegressionTestQA539) {
CreateView();
commands_.SetFile(kBearFilePath);
// Play the file to the end.
commands_.Play();
commands_.WaitForEndOfStream();
// Reload the file.
commands_.SetFile(kBearFilePath);
commands_.Play();
QuitOnEndOfStream();
Execute();
EXPECT_TRUE(fake_audio_.renderer().expected());
EXPECT_TRUE(fake_scenic_.session().expected());
}
} // namespace test
} // namespace media_player
|
#pragma once
#ifndef OPENGM_EXTERNAL_QPBO_HXX
#define OPENGM_EXTERNAL_QPBO_HXX
#include "opengm/graphicalmodel/graphicalmodel.hxx"
#include "opengm/inference/inference.hxx"
#include "opengm/inference/visitors/visitors.hxx"
//#include "opengm/inference/alphabetaswap.hxx"
//#include "opengm/inference/alphaexpansion.hxx"
#include "QPBO.h"
namespace opengm {
namespace external {
/// \brief QPBO Algorithm
///
/// C. Rother, V. Kolmogorov, V. Lempitsky, and M. Szummer. "Optimizing binary MRFs via extended roof duality". CVPR 2007
///
/// \ingroup inference
/// \ingroup external_inference
template<class GM>
class QPBO : public Inference<GM, opengm::Minimizer> {
public:
typedef GM GraphicalModelType;
typedef opengm::Minimizer AccumulationType;
OPENGM_GM_TYPE_TYPEDEFS;
typedef visitors::VerboseVisitor<QPBO<GM> > VerboseVisitorType;
typedef visitors::TimingVisitor<QPBO<GM> > TimingVisitorType;
typedef visitors::EmptyVisitor<QPBO<GM> > EmptyVisitorType;
///TriBool
enum TriBool {
TB0, TB1, TBX
};
template<class _GM>
struct RebindGm{
typedef QPBO<_GM> type;
};
template<class _GM,class _ACC>
struct RebindGmAndAcc{
typedef QPBO<_GM> type;
};
///Parameter for opengm::external::QPBO
struct Parameter {
/// using probeing technique
bool useProbeing_;
/// forcing strong persistency
bool strongPersistency_;
/// using improving technique
bool useImproveing_;
/// initial configuration for improving
std::vector<size_t> label_;
/// \brief constructor
template<class P>
Parameter(const P & p)
:
strongPersistency_(p.strongPersistency_),
useImproveing_ (p.useImproveing_),
useProbeing_ (p.useProbeing_)
{
}
Parameter() {
strongPersistency_ = true;
useImproveing_ = false;
useProbeing_ = false;
}
};
// construction
QPBO(const GraphicalModelType& gm, const Parameter para = Parameter());
~QPBO();
// query
std::string name() const;
const GraphicalModelType& graphicalModel() const;
// inference
InferenceTermination infer();
template<class VisitorType>
InferenceTermination infer(VisitorType&);
InferenceTermination arg(std::vector<LabelType>&, const size_t& = 1) const;
InferenceTermination arg(std::vector<TriBool>&, const size_t& = 1) const;
virtual typename GM::ValueType bound() const;
virtual typename GM::ValueType value() const;
double partialOptimality(std::vector<bool>&) const;
private:
const GraphicalModelType& gm_;
Parameter parameter_;
kolmogorov::qpbo::QPBO<ValueType>* qpbo_;
ValueType constTerm_;
ValueType bound_;
int* label_;
int* defaultLabel_;
};
// public interface
/// \brief Construcor
/// \param gm graphical model
/// \param para belief propargation paramaeter
template<class GM>
QPBO<GM>
::QPBO(
const typename QPBO::GraphicalModelType& gm,
const Parameter para
)
: gm_(gm), bound_(-std::numeric_limits<ValueType>::infinity()) {
parameter_ = para;
label_ = new int[gm_.numberOfVariables()];
defaultLabel_ = new int[gm_.numberOfVariables()];
for(size_t i = 0; i < gm_.numberOfVariables(); ++i) {
label_[i] = -1;
defaultLabel_[i] = 0;
}
if(parameter_.label_.size() > 0) {
for(size_t i = 0; i < parameter_.label_.size(); ++i) {
defaultLabel_[i] = parameter_.label_[i];
}
}
size_t numVariables = gm_.numberOfVariables();
size_t numPairwiseFactors = 0;
constTerm_ = 0;
size_t vec0[] = {0};
size_t vec1[] = {1};
size_t vec00[] = {0, 0};
size_t vec01[] = {0, 1};
size_t vec10[] = {1, 0};
size_t vec11[] = {1, 1};
for(size_t j = 0; j < gm_.numberOfVariables(); ++j) {
if(gm_.numberOfLabels(j) != 2) {
throw RuntimeError("This implementation of QPBO supports only binary variables.");
}
}
for(size_t j = 0; j < gm_.numberOfFactors(); ++j) {
if(gm_[j].numberOfVariables() == 2) {
++numPairwiseFactors;
}
else if(gm_[j].numberOfVariables() > 2) {
throw RuntimeError("This implementation of QPBO supports only factors of order <= 2.");
}
}
qpbo_ = new kolmogorov::qpbo::QPBO<ValueType > (numVariables, numPairwiseFactors); // max number of nodes & edges
qpbo_->AddNode(numVariables); // add two nodes
for(size_t j = 0; j < gm_.numberOfFactors(); ++j) {
if(gm_[j].numberOfVariables() == 0) {
; //constTerm_+= gm_[j](0);
}
else if(gm_[j].numberOfVariables() == 1) {
qpbo_->AddUnaryTerm((int) (gm_[j].variableIndex(0)), gm_[j](vec0), gm_[j](vec1));
}
else if(gm_[j].numberOfVariables() == 2) {
qpbo_->AddPairwiseTerm((int) (gm_[j].variableIndex(0)), (int) (gm_[j].variableIndex(1)),
gm_[j](vec00), gm_[j](vec01), gm_[j](vec10), gm_[j](vec11));
}
}
qpbo_->MergeParallelEdges();
}
template<class GM>
QPBO<GM>
::~QPBO() {
delete label_;
delete defaultLabel_;
delete qpbo_;
}
template<class GM>
inline std::string
QPBO<GM>
::name() const {
return "QPBO";
}
template<class GM>
inline const typename QPBO<GM>::GraphicalModelType&
QPBO<GM>
::graphicalModel() const {
return gm_;
}
template<class GM>
inline InferenceTermination
QPBO<GM>
::infer() {
EmptyVisitorType v;
return infer(v);
}
template<class GM>
template<class VisitorType>
InferenceTermination
QPBO<GM>::infer(VisitorType& visitor)
{
visitor.begin(*this);
qpbo_->Solve();
if(!parameter_.strongPersistency_) {
qpbo_->ComputeWeakPersistencies();
}
bound_ = constTerm_ + 0.5 * qpbo_->ComputeTwiceLowerBound();
int countUnlabel = 0;
int *listUnlabel = new int[gm_.numberOfVariables()];
for(size_t i = 0; i < gm_.numberOfVariables(); ++i) {
label_[i] = qpbo_->GetLabel(i);
if(label_[i] < 0) {
listUnlabel[countUnlabel++] = i;
}
}
// Initialize mapping for probe
int *mapping = new int[gm_.numberOfVariables()];
for(int i = 0; i < static_cast<int>(gm_.numberOfVariables()); i++) {
mapping[i] = i * 2;
}
/*PROBEING*/
if(parameter_.useProbeing_ && countUnlabel > 0) {
typename kolmogorov::qpbo::QPBO<ValueType>::ProbeOptions options;
//options.C = 1000000000;
//options.dilation = 1;
options.weak_persistencies = 1;
//options.iters = (int)(10);//parameter_.numberOfProbeingIterations_);
int *new_mapping = new int[gm_.numberOfVariables()];
qpbo_->Probe(new_mapping, options);
qpbo_->MergeMappings(gm_.numberOfVariables(), mapping, new_mapping);
qpbo_->ComputeWeakPersistencies();
delete new_mapping;
// Read out entire labelling again (as weak persistencies may have changed)
countUnlabel = 0;
for(IndexType i = 0; i < gm_.numberOfVariables(); ++i) {
label_[i] = qpbo_->GetLabel(mapping[i] / 2);
if(label_[i] < 0)
listUnlabel[countUnlabel++] = i;
else
label_[i] = (label_[i] + mapping[i]) % 2;
}
}
if(parameter_.useImproveing_ && countUnlabel > 0) {
int *improve_order = new int[countUnlabel];
// Set the labels to the user-defined value
for(size_t i = 0; static_cast<int>(i) < countUnlabel; i++) {
improve_order[i] = mapping[listUnlabel[i]] / 2;
qpbo_->SetLabel(improve_order[i], defaultLabel_[improve_order[i]]);
}
// Randomize order
for(int i = 0; i < countUnlabel - 1; ++i) {
int j = i + (int) (((double) rand() / ((double) RAND_MAX + 1)) * (countUnlabel - i));
OPENGM_ASSERT(j < countUnlabel);
int k = improve_order[j];
improve_order[j] = improve_order[i];
improve_order[i] = k;
}
// Run QPBO-I
qpbo_->Improve(countUnlabel, improve_order);
delete improve_order;
// Read out the labels
for(int i = 0; i < countUnlabel; ++i) {
label_[listUnlabel[i]] = (qpbo_->GetLabel(mapping[listUnlabel[i]] / 2) + mapping[listUnlabel[i]]) % 2;
}
}
visitor.end(*this);
delete mapping;
delete listUnlabel;
return NORMAL;
}
template<class GM>
inline InferenceTermination
QPBO<GM>
::arg(std::vector<LabelType>& arg, const size_t& n) const {
if(n > 1) {
return UNKNOWN;
}
else {
arg.resize(gm_.numberOfVariables());
for(size_t i = 0; i < gm_.numberOfVariables(); ++i) {
if(label_[i] < 0) arg[i] = defaultLabel_[i];
else arg[i] = label_[i];
}
return NORMAL;
}
}
template<class GM>
inline InferenceTermination
QPBO<GM>
::arg(std::vector<TriBool>& arg, const size_t& n) const {
if(n > 1) {
return UNKNOWN;
}
else {
arg.resize(gm_.numberOfVariables(), TBX);
for(int i = 0; i < gm_.numberOfVariables(); ++i) {
if(label_[i] < 0) arg[i] = TBX;
if(label_[i] == 0) arg[i] = TB0;
else arg[i] = TB1;
}
return NORMAL;
}
}
template<class GM>
double QPBO<GM>::partialOptimality(std::vector<bool>& opt) const
{
double p=0;
opt.resize(gm_.numberOfVariables());
for(IndexType i = 0; i < gm_.numberOfVariables(); ++i) {
if(label_[i] < 0) {opt[i] = 0;}
else {opt[i] = 1; ++p;}
}
return p/gm_.numberOfVariables();
}
template<class GM>
inline typename GM::ValueType
QPBO<GM>
::bound() const {
return bound_;//constTerm_ + 0.5 * qpbo_->ComputeTwiceLowerBound();
}
template<class GM>
inline typename GM::ValueType
QPBO<GM>
::value() const {
std::vector<LabelType> c;
arg(c);
return gm_.evaluate(c);
//return constTerm_ + 0.5 * qpbo_->ComputeTwiceEnergy();
}
} // namespace external
} // namespace opengm
#endif // #ifndef OPENGM_EXTERNAL_QPBO_HXX
|
// Copyright 2019 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 <memory>
#include <vector>
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/shelf_model.h"
#include "ash/public/cpp/window_properties.h"
#include "ash/shell.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/platform_apps/app_browsertest_util.h"
#include "chrome/browser/ash/arc/arc_util.h"
#include "chrome/browser/ash/arc/session/arc_session_manager.h"
#include "chrome/browser/ash/borealis/borealis_service.h"
#include "chrome/browser/ash/borealis/borealis_window_manager.h"
#include "chrome/browser/ash/borealis/borealis_window_manager_mock.h"
#include "chrome/browser/ash/guest_os/guest_os_registry_service.h"
#include "chrome/browser/ash/guest_os/guest_os_registry_service_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller.h"
#include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_test_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/web_applications/test/web_app_browsertest_util.h"
#include "chrome/browser/web_applications/components/web_application_info.h"
#include "components/arc/arc_service_manager.h"
#include "components/arc/arc_util.h"
#include "components/arc/session/arc_bridge_service.h"
#include "components/arc/test/fake_app_instance.h"
#include "components/exo/shell_surface_util.h"
#include "components/services/app_service/public/cpp/instance.h"
#include "components/services/app_service/public/cpp/instance_registry.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
#include "extensions/browser/app_window/app_window.h"
#include "extensions/common/constants.h"
#include "extensions/common/extension.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/display/display.h"
#include "ui/views/widget/widget.h"
using extensions::AppWindow;
using extensions::Extension;
namespace mojo {
template <>
struct TypeConverter<arc::mojom::ArcPackageInfoPtr,
arc::mojom::ArcPackageInfo> {
static arc::mojom::ArcPackageInfoPtr Convert(
const arc::mojom::ArcPackageInfo& package_info) {
return package_info.Clone();
}
};
} // namespace mojo
namespace {
constexpr char kTestAppName[] = "Test ARC App";
constexpr char kTestAppName2[] = "Test ARC App 2";
constexpr char kTestAppPackage[] = "test.arc.app.package";
constexpr char kTestAppActivity[] = "test.arc.app.package.activity";
constexpr char kTestAppActivity2[] = "test.arc.gitapp.package.activity2";
ash::ShelfAction SelectItem(
const ash::ShelfID& id,
ui::EventType event_type = ui::ET_MOUSE_PRESSED,
int64_t display_id = display::kInvalidDisplayId,
ash::ShelfLaunchSource source = ash::LAUNCH_FROM_UNKNOWN) {
return SelectShelfItem(id, event_type, display_id, source);
}
std::string GetTestApp1Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity);
}
std::string GetTestApp2Id(const std::string& package_name) {
return ArcAppListPrefs::GetAppId(package_name, kTestAppActivity2);
}
std::vector<arc::mojom::AppInfoPtr> GetTestAppsList(
const std::string& package_name,
bool multi_app) {
std::vector<arc::mojom::AppInfoPtr> apps;
arc::mojom::AppInfoPtr app(arc::mojom::AppInfo::New());
app->name = kTestAppName;
app->package_name = package_name;
app->activity = kTestAppActivity;
app->sticky = false;
apps.push_back(std::move(app));
if (multi_app) {
app = arc::mojom::AppInfo::New();
app->name = kTestAppName2;
app->package_name = package_name;
app->activity = kTestAppActivity2;
app->sticky = false;
apps.push_back(std::move(app));
}
return apps;
}
std::string CreateIntentUriWithShelfGroupAndLogicalWindow(
const std::string& shelf_group_id,
const std::string& logical_window_id) {
return base::StringPrintf(
"#Intent;S.org.chromium.arc.logical_window_id=%s;"
"S.org.chromium.arc.shelf_group_id=%s;end",
logical_window_id.c_str(), shelf_group_id.c_str());
}
// Creates an exo app window and sets its shell application id. The returned
// Widget is owned by its NativeWidget (the underlying aura::Window).
views::Widget* CreateExoWindow(const std::string& window_app_id) {
views::Widget::InitParams params(views::Widget::InitParams::TYPE_WINDOW);
params.bounds = gfx::Rect(5, 5, 20, 20);
params.context = ash::Shell::GetPrimaryRootWindow();
views::Widget* widget = new views::Widget();
widget->Init(std::move(params));
// Set app id before showing the window to be recognized in
// AppServiceAppWindowLauncherController.
exo::SetShellApplicationId(widget->GetNativeWindow(), window_app_id);
widget->Show();
widget->Activate();
return widget;
}
} // namespace
class AppServiceAppWindowBrowserTest
: public extensions::PlatformAppBrowserTest {
protected:
AppServiceAppWindowBrowserTest() = default;
~AppServiceAppWindowBrowserTest() override = default;
void SetUp() override { extensions::PlatformAppBrowserTest::SetUp(); }
void SetUpOnMainThread() override {
controller_ = ChromeLauncherController::instance();
ASSERT_TRUE(controller_);
extensions::PlatformAppBrowserTest::SetUpOnMainThread();
app_service_proxy_ = apps::AppServiceProxyFactory::GetForProfile(profile());
ASSERT_TRUE(app_service_proxy_);
}
ash::ShelfModel* shelf_model() { return controller_->shelf_model(); }
// Returns the last item in the shelf.
const ash::ShelfItem& GetLastLauncherItem() {
return shelf_model()->items()[shelf_model()->item_count() - 1];
}
apps::InstanceState GetAppInstanceState(const std::string& app_id,
const aura::Window* window) {
auto instance_state = apps::InstanceState::kUnknown;
app_service_proxy_->InstanceRegistry().ForOneInstance(
window, [&app_id, &instance_state](const apps::InstanceUpdate& inner) {
if (inner.AppId() == app_id) {
instance_state = inner.State();
}
});
return instance_state;
}
ChromeLauncherController* controller_ = nullptr;
apps::AppServiceProxyChromeOs* app_service_proxy_ = nullptr;
};
// Test that we have the correct instance for Chrome apps.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBrowserTest, ExtensionAppsWindow) {
const extensions::Extension* app =
LoadAndLaunchPlatformApp("launch", "Launched");
extensions::AppWindow* window = CreateAppWindow(profile(), app);
ASSERT_TRUE(window);
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
EXPECT_EQ(1u, windows.size());
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app->id(), *windows.begin()));
const ash::ShelfItem& item = GetLastLauncherItem();
// Since it is already active, clicking it should minimize.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
GetAppInstanceState(app->id(), *windows.begin()));
// Click the item again to activate the app.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app->id(), *windows.begin()));
CloseAppWindow(window);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
EXPECT_EQ(0u, windows.size());
}
// Test that we have the correct instances with more than one window.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBrowserTest, MultipleWindows) {
const extensions::Extension* app =
LoadAndLaunchPlatformApp("launch", "Launched");
extensions::AppWindow* app_window1 = CreateAppWindow(profile(), app);
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
auto* window1 = *windows.begin();
// Add a second window; confirm the shelf item stays; check the app menu.
extensions::AppWindow* app_window2 = CreateAppWindow(profile(), app);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
EXPECT_EQ(2u, windows.size());
aura::Window* window2 = nullptr;
for (auto* window : windows) {
if (window != window1)
window2 = window;
}
// The window1 is inactive.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible,
GetAppInstanceState(app->id(), window1));
// The window2 is active.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app->id(), window2));
// Close the second window; confirm the shelf item stays; check the app menu.
CloseAppWindow(app_window2);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
EXPECT_EQ(1u, windows.size());
// The window1 is active again.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app->id(), window1));
// Close the first window; the shelf item should be removed.
CloseAppWindow(app_window1);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app->id());
EXPECT_EQ(0u, windows.size());
}
// Test that we have the correct instances with one HostedApp and one window.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBrowserTest,
HostedAppandExtensionApp) {
const extensions::Extension* extension1 = InstallHostedApp();
LaunchHostedApp(extension1);
std::string app_id1 = extension1->id();
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id1);
EXPECT_EQ(1u, windows.size());
auto* window1 = *windows.begin();
// The window1 is active.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible | apps::InstanceState::kActive,
GetAppInstanceState(app_id1, window1));
// Add an Extension app.
const extensions::Extension* extension2 =
LoadAndLaunchPlatformApp("launch", "Launched");
auto* app_window = CreateAppWindow(profile(), extension2);
std::string app_id2 = extension2->id();
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id2);
EXPECT_EQ(1u, windows.size());
auto* window2 = *windows.begin();
// The window1 is inactive.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible,
GetAppInstanceState(app_id1, window1));
// The window2 is active.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible | apps::InstanceState::kActive,
GetAppInstanceState(app_id2, window2));
// Close the Extension app's window..
CloseAppWindow(app_window);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id2);
EXPECT_EQ(0u, windows.size());
// The window1 is active.
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible | apps::InstanceState::kActive,
GetAppInstanceState(app_id1, window1));
// Close the HostedApp.
TabStripModel* tab_strip = browser()->tab_strip_model();
tab_strip->CloseWebContentsAt(tab_strip->active_index(),
TabStripModel::CLOSE_NONE);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id1);
EXPECT_EQ(0u, windows.size());
}
class AppServiceAppWindowLacrosBrowserTest
: public AppServiceAppWindowBrowserTest {
public:
AppServiceAppWindowLacrosBrowserTest() {
feature_list_.InitAndEnableFeature(chromeos::features::kLacrosSupport);
}
~AppServiceAppWindowLacrosBrowserTest() override = default;
private:
base::test::ScopedFeatureList feature_list_;
};
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowLacrosBrowserTest, LacrosWindow) {
// Create a fake Lacros window. The native window owns the widget.
views::Widget* widget = CreateExoWindow("org.chromium.lacros.12345");
using extension_misc::kLacrosAppId;
auto windows =
app_service_proxy_->InstanceRegistry().GetWindows(kLacrosAppId);
EXPECT_EQ(1u, windows.size());
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(kLacrosAppId, *windows.begin()));
// Find the Lacros shelf item.
int lacros_index = shelf_model()->ItemIndexByAppID(kLacrosAppId);
ASSERT_NE(-1, lacros_index);
const ash::ShelfItem& item = shelf_model()->items()[lacros_index];
// Since it is already active, clicking it should minimize.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
GetAppInstanceState(kLacrosAppId, *windows.begin()));
// Click the item again to activate the window.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(kLacrosAppId, *windows.begin()));
widget->CloseNow();
windows = app_service_proxy_->InstanceRegistry().GetWindows(kLacrosAppId);
EXPECT_EQ(0u, windows.size());
}
class AppServiceAppWindowBorealisBrowserTest
: public AppServiceAppWindowBrowserTest {
public:
~AppServiceAppWindowBorealisBrowserTest() override = default;
std::string MakeBorealisApp(const std::string& vm,
const std::string& container,
const std::string& name) {
vm_tools::apps::ApplicationList list;
list.set_vm_name(vm);
list.set_container_name(container);
list.set_vm_type(vm_tools::apps::ApplicationList_VmType_BOREALIS);
vm_tools::apps::App* app = list.add_apps();
app->set_desktop_file_id(name);
app->mutable_name()->add_values()->set_value(name);
app->set_no_display(false);
guest_os::GuestOsRegistryServiceFactory::GetForProfile(profile())
->UpdateApplicationList(list);
// We need to propagate the newly created app to the various registries
// before it can be used.
app_service_proxy_->FlushMojoCallsForTesting();
return guest_os::GuestOsRegistryService::GenerateAppId(name, vm, container);
}
};
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBorealisBrowserTest,
BorealisKnownApp) {
// Generate a fake app.
std::string app_id = MakeBorealisApp("vm", "container", "foo");
views::Widget* widget = CreateExoWindow("org.chromium.borealis.wmclass.foo");
EXPECT_EQ(1u,
app_service_proxy_->InstanceRegistry().GetWindows(app_id).size());
EXPECT_NE(-1, shelf_model()->ItemIndexByAppID(app_id));
widget->CloseNow();
EXPECT_TRUE(
app_service_proxy_->InstanceRegistry().GetWindows(app_id).empty());
}
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBorealisBrowserTest,
BorealisUnknownApp) {
views::Widget* widget = CreateExoWindow("org.chromium.borealis.wmclass.bar");
std::string app_id = "borealis_anon:org.chromium.borealis.wmclass.bar";
EXPECT_EQ(1u,
app_service_proxy_->InstanceRegistry().GetWindows(app_id).size());
ASSERT_NE(-1, shelf_model()->ItemIndexByAppID(app_id));
// Initially, anonymous apps haven't been published, as that is an
// asynchronous operation. This means their shelf item has no title.
EXPECT_TRUE(shelf_model()
->items()[shelf_model()->ItemIndexByAppID(app_id)]
.title.empty());
// Flushing calls here simulates the fraction-of-seconds delay between the
// window appearing and its app being published.
app_service_proxy_->FlushMojoCallsForTesting();
// Now that the app is published, it will have a name based on the app_id
EXPECT_EQ(
"wmclass.bar",
base::UTF16ToUTF8(shelf_model()
->items()[shelf_model()->ItemIndexByAppID(app_id)]
.title));
widget->CloseNow();
EXPECT_TRUE(
app_service_proxy_->InstanceRegistry().GetWindows(app_id).empty());
}
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowBorealisBrowserTest,
BorealisSession) {
std::string app_id = MakeBorealisApp("vm", "container", "foo");
testing::StrictMock<borealis::MockLifetimeObserver> observer;
base::ScopedObservation<
borealis::BorealisWindowManager,
borealis::BorealisWindowManager::AppWindowLifetimeObserver>
observation(&observer);
observation.Observe(
&borealis::BorealisService::GetForProfile(profile())->WindowManager());
testing::InSequence sequence;
EXPECT_CALL(observer, OnSessionStarted());
EXPECT_CALL(observer, OnAppStarted(app_id));
EXPECT_CALL(observer, OnWindowStarted(app_id, testing::_));
views::Widget* widget = CreateExoWindow("org.chromium.borealis.wmclass.foo");
EXPECT_CALL(observer, OnWindowFinished(app_id, widget->GetNativeWindow()));
EXPECT_CALL(observer, OnAppFinished(app_id));
EXPECT_CALL(observer, OnSessionFinished());
widget->CloseNow();
}
class AppServiceAppWindowWebAppBrowserTest
: public AppServiceAppWindowBrowserTest {
protected:
AppServiceAppWindowWebAppBrowserTest() = default;
~AppServiceAppWindowWebAppBrowserTest() override = default;
// AppServiceAppWindowBrowserTest:
void SetUpOnMainThread() override {
AppServiceAppWindowBrowserTest::SetUpOnMainThread();
https_server_.AddDefaultHandlers(GetChromeTestDataDir());
ASSERT_TRUE(https_server_.Start());
}
// |SetUpWebApp()| must be called after |SetUpOnMainThread()| to make sure
// the Network Service process has been setup properly.
std::string CreateWebApp() const {
auto web_app_info = std::make_unique<WebApplicationInfo>();
web_app_info->start_url = GetAppURL();
web_app_info->scope = GetAppURL().GetWithoutFilename();
std::string app_id =
web_app::InstallWebApp(browser()->profile(), std::move(web_app_info));
CreateWebAppWindow(app_id);
return app_id;
}
GURL GetAppURL() const {
return https_server_.GetURL("app.com", "/ssl/google.html");
}
void CreateWebAppWindow(const std::string& app_id) const {
content::TestNavigationObserver navigation_observer(GetAppURL());
navigation_observer.StartWatchingNewWebContents();
web_app::LaunchWebAppBrowser(browser()->profile(), app_id);
navigation_observer.WaitForNavigationFinished();
}
private:
// For mocking a secure site.
net::EmbeddedTestServer https_server_;
};
// Test that we have the correct instance for Web apps.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowWebAppBrowserTest, WebAppsWindow) {
std::string app_id = CreateWebApp();
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
EXPECT_EQ(1u, windows.size());
aura::Window* window = *windows.begin();
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window));
const ash::ShelfItem& item = GetLastLauncherItem();
// Since it is already active, clicking it should minimize.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
GetAppInstanceState(app_id, window));
// Click the item again to activate the app.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window));
controller_->Close(item.id);
// Make sure that the window is closed.
base::RunLoop().RunUntilIdle();
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
EXPECT_EQ(0u, windows.size());
}
// Tests that web app with multiple open windows can be activated from the app
// list.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowWebAppBrowserTest,
LaunchFromAppList) {
std::string app_id = CreateWebApp();
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
ASSERT_EQ(1u, windows.size());
aura::Window* window1 = *windows.begin();
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window1));
const ash::ShelfItem item = GetLastLauncherItem();
// Since it is already active, clicking it should minimize.
SelectItem(item.id);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
GetAppInstanceState(app_id, window1));
// Create another window.
CreateWebAppWindow(app_id);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
ASSERT_EQ(2u, windows.size());
aura::Window* window2 =
*windows.begin() == window1 ? *windows.rbegin() : *windows.begin();
ASSERT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window2));
// Bring the browser window to foreground.
browser()->window()->Show();
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window2));
// Launching the first app from the app list should activate it.
SelectItem(item.id, ui::ET_MOUSE_PRESSED, display::kInvalidDisplayId,
ash::LAUNCH_FROM_APP_LIST);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window1));
// Selecting an active app from the app list should not minimize it.
SelectItem(item.id, ui::ET_MOUSE_PRESSED, display::kInvalidDisplayId,
ash::LAUNCH_FROM_APP_LIST);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
GetAppInstanceState(app_id, window1));
}
class AppServiceAppWindowArcAppBrowserTest
: public AppServiceAppWindowBrowserTest {
protected:
// AppServiceAppWindowBrowserTest:
void SetUpCommandLine(base::CommandLine* command_line) override {
AppServiceAppWindowBrowserTest::SetUpCommandLine(command_line);
arc::SetArcAvailableCommandLineForTesting(command_line);
}
void SetUpInProcessBrowserTestFixture() override {
AppServiceAppWindowBrowserTest::SetUpInProcessBrowserTestFixture();
arc::ArcSessionManager::SetUiEnabledForTesting(false);
}
void SetUpOnMainThread() override {
AppServiceAppWindowBrowserTest::SetUpOnMainThread();
arc::SetArcPlayStoreEnabledForProfile(profile(), true);
// This ensures app_prefs()->GetApp() below never returns nullptr.
base::RunLoop run_loop;
app_prefs()->SetDefaultAppsReadyCallback(run_loop.QuitClosure());
run_loop.Run();
}
void InstallTestApps(const std::string& package_name, bool multi_app) {
app_host()->OnAppListRefreshed(GetTestAppsList(package_name, multi_app));
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info =
app_prefs()->GetApp(GetTestApp1Id(package_name));
ASSERT_TRUE(app_info);
EXPECT_TRUE(app_info->ready);
if (multi_app) {
std::unique_ptr<ArcAppListPrefs::AppInfo> app_info2 =
app_prefs()->GetApp(GetTestApp2Id(package_name));
ASSERT_TRUE(app_info2);
EXPECT_TRUE(app_info2->ready);
}
}
void SendPackageAdded(const std::string& package_name, bool package_synced) {
arc::mojom::ArcPackageInfo package_info;
package_info.package_name = package_name;
package_info.package_version = 1;
package_info.last_backup_android_id = 1;
package_info.last_backup_time = 1;
package_info.sync = package_synced;
package_info.system = false;
app_host()->OnPackageAdded(arc::mojom::ArcPackageInfo::From(package_info));
base::RunLoop().RunUntilIdle();
}
void StartInstance() {
app_instance_ = std::make_unique<arc::FakeAppInstance>(app_host());
arc_brige_service()->app()->SetInstance(app_instance_.get());
}
void StopInstance() {
if (app_instance_)
arc_brige_service()->app()->CloseInstance(app_instance_.get());
arc_session_manager()->Shutdown();
}
ArcAppListPrefs* app_prefs() { return ArcAppListPrefs::Get(profile()); }
// Returns as AppHost interface in order to access to private implementation
// of the interface.
arc::mojom::AppHost* app_host() { return app_prefs(); }
private:
arc::ArcSessionManager* arc_session_manager() {
return arc::ArcSessionManager::Get();
}
arc::ArcBridgeService* arc_brige_service() {
return arc::ArcServiceManager::Get()->arc_bridge_service();
}
std::unique_ptr<arc::FakeAppInstance> app_instance_;
};
// Test that we have the correct instance for ARC apps.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowArcAppBrowserTest, ArcAppsWindow) {
// Install app to remember existing apps.
StartInstance();
InstallTestApps(kTestAppPackage, true);
SendPackageAdded(kTestAppPackage, false);
// Create the window for app1.
views::Widget* arc_window1 = CreateExoWindow("org.chromium.arc.1");
const std::string app_id1 = GetTestApp1Id(kTestAppPackage);
// Simulate task creation so the app is marked as running/open.
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id1);
app_host()->OnTaskCreated(1, info->package_name, info->activity, info->name,
info->intent_uri, /*session_id=*/0);
EXPECT_TRUE(controller_->GetItem(ash::ShelfID(app_id1)));
// Check the window state in instance for app1
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id1);
EXPECT_EQ(1u, windows.size());
aura::Window* window1 = *windows.begin();
apps::InstanceState latest_state =
app_service_proxy_->InstanceRegistry().GetState(window1);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
latest_state);
app_host()->OnTaskSetActive(1);
latest_state = app_service_proxy_->InstanceRegistry().GetState(window1);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
latest_state);
controller_->PinAppWithID(app_id1);
// Create the task id for app2 first, then create the window.
const std::string app_id2 = GetTestApp2Id(kTestAppPackage);
info = app_prefs()->GetApp(app_id2);
app_host()->OnTaskCreated(2, info->package_name, info->activity, info->name,
info->intent_uri, /*session_id=*/0);
views::Widget* arc_window2 = CreateExoWindow("org.chromium.arc.2");
EXPECT_TRUE(controller_->GetItem(ash::ShelfID(app_id2)));
// Check the window state in instance for app2
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id2);
EXPECT_EQ(1u, windows.size());
aura::Window* window2 = *windows.begin();
latest_state = app_service_proxy_->InstanceRegistry().GetState(window2);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
latest_state);
// App1 is inactive.
latest_state = app_service_proxy_->InstanceRegistry().GetState(window1);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible,
latest_state);
// Select the app1
SelectItem(ash::ShelfID(app_id1));
latest_state = app_service_proxy_->InstanceRegistry().GetState(window1);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
latest_state);
latest_state = app_service_proxy_->InstanceRegistry().GetState(window2);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kVisible,
latest_state);
// Close the window for app1, and destroy the task.
arc_window1->CloseNow();
app_host()->OnTaskDestroyed(1);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id1);
EXPECT_EQ(0u, windows.size());
// App2 is activated.
latest_state = app_service_proxy_->InstanceRegistry().GetState(window2);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
latest_state);
// destroy the task for app2 and close the window.
app_host()->OnTaskDestroyed(2);
arc_window2->CloseNow();
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id2);
EXPECT_EQ(0u, windows.size());
StopInstance();
}
// Test what happens when the logical window ID is provided, and some window
// might be hidden in the shelf.
IN_PROC_BROWSER_TEST_F(AppServiceAppWindowArcAppBrowserTest, LogicalWindowId) {
// Install app to remember existing apps.
StartInstance();
InstallTestApps(kTestAppPackage, true);
SendPackageAdded(kTestAppPackage, false);
// Create the windows for the app.
views::Widget* arc_window1 = CreateExoWindow("org.chromium.arc.1");
views::Widget* arc_window2 = CreateExoWindow("org.chromium.arc.2");
// Simulate task creation so the app is marked as running/open.
const std::string app_id = GetTestApp1Id(kTestAppPackage);
std::unique_ptr<ArcAppListPrefs::AppInfo> info = app_prefs()->GetApp(app_id);
app_host()->OnTaskCreated(1, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroupAndLogicalWindow(
"shelf_group_1", "logical_window_1"),
/*session_id=*/0);
app_host()->OnTaskCreated(2, info->package_name, info->activity, info->name,
CreateIntentUriWithShelfGroupAndLogicalWindow(
"shelf_group_1", "logical_window_1"),
/*session_id=*/0);
// Both windows should show up in the instance registry.
auto windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
EXPECT_EQ(2u, windows.size());
// Of those two, one should be hidden.
auto is_hidden = [](aura::Window* w) {
return w->GetProperty(ash::kHideInShelfKey);
};
EXPECT_EQ(1, std::count_if(windows.begin(), windows.end(), is_hidden));
// The hidden window should be task_id 2.
aura::Window* window1 =
*(std::find_if_not(windows.begin(), windows.end(), is_hidden));
aura::Window* window2 =
*(std::find_if(windows.begin(), windows.end(), is_hidden));
apps::InstanceState latest_state =
app_service_proxy_->InstanceRegistry().GetState(window1);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
latest_state);
latest_state = app_service_proxy_->InstanceRegistry().GetState(window2);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning,
latest_state);
// If the user focuses window 2, it should become active, but still hidden in
// the shelf.
app_host()->OnTaskSetActive(2);
latest_state = app_service_proxy_->InstanceRegistry().GetState(window2);
EXPECT_EQ(apps::InstanceState::kStarted | apps::InstanceState::kRunning |
apps::InstanceState::kActive | apps::InstanceState::kVisible,
latest_state);
EXPECT_TRUE(window2->GetProperty(ash::kHideInShelfKey));
// Close first window. No window should be hidden anymore.
arc_window1->CloseNow();
app_host()->OnTaskDestroyed(1);
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
EXPECT_EQ(1u, windows.size());
EXPECT_EQ(0, std::count_if(windows.begin(), windows.end(), is_hidden));
// Close second window.
app_host()->OnTaskDestroyed(2);
arc_window2->CloseNow();
windows = app_service_proxy_->InstanceRegistry().GetWindows(app_id);
EXPECT_EQ(0u, windows.size());
}
|
//===-- BPFISelLowering.cpp - BPF DAG Lowering Implementation ------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the interfaces that BPF uses to lower LLVM code into a
// selection DAG.
//
//===----------------------------------------------------------------------===//
#include "BPFISelLowering.h"
#include "BPF.h"
#include "BPFSubtarget.h"
#include "BPFTargetMachine.h"
#include "llvm/CodeGen/CallingConvLower.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
#include "llvm/CodeGen/ValueTypes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "bpf-lower"
static cl::opt<bool> BPFExpandMemcpyInOrder("bpf-expand-memcpy-in-order",
cl::Hidden, cl::init(false),
cl::desc("Expand memcpy into load/store pairs in order"));
static void fail(const SDLoc &DL, SelectionDAG &DAG, const Twine &Msg) {
MachineFunction &MF = DAG.getMachineFunction();
DAG.getContext()->diagnose(
DiagnosticInfoUnsupported(MF.getFunction(), Msg, DL.getDebugLoc()));
}
static void fail(const SDLoc &DL, SelectionDAG &DAG, const char *Msg,
SDValue Val) {
MachineFunction &MF = DAG.getMachineFunction();
std::string Str;
raw_string_ostream OS(Str);
OS << Msg;
Val->print(OS);
OS.flush();
DAG.getContext()->diagnose(
DiagnosticInfoUnsupported(MF.getFunction(), Str, DL.getDebugLoc()));
}
BPFTargetLowering::BPFTargetLowering(const TargetMachine &TM,
const BPFSubtarget &STI)
: TargetLowering(TM) {
// Set up the register classes.
addRegisterClass(MVT::i64, &BPF::GPRRegClass);
if (STI.getHasAlu32())
addRegisterClass(MVT::i32, &BPF::GPR32RegClass);
// Compute derived properties from the register classes
computeRegisterProperties(STI.getRegisterInfo());
setStackPointerRegisterToSaveRestore(BPF::R11);
setOperationAction(ISD::BR_CC, MVT::i64, Custom);
setOperationAction(ISD::BR_JT, MVT::Other, Expand);
setOperationAction(ISD::BRIND, MVT::Other, Expand);
setOperationAction(ISD::BRCOND, MVT::Other, Expand);
setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
for (auto VT : { MVT::i32, MVT::i64 }) {
if (VT == MVT::i32 && !STI.getHasAlu32())
continue;
setOperationAction(ISD::SDIVREM, VT, Expand);
setOperationAction(ISD::UDIVREM, VT, Expand);
setOperationAction(ISD::SREM, VT, Expand);
setOperationAction(ISD::UREM, VT, Expand);
setOperationAction(ISD::MULHU, VT, Expand);
setOperationAction(ISD::MULHS, VT, Expand);
setOperationAction(ISD::UMUL_LOHI, VT, Expand);
setOperationAction(ISD::SMUL_LOHI, VT, Expand);
setOperationAction(ISD::ROTR, VT, Expand);
setOperationAction(ISD::ROTL, VT, Expand);
setOperationAction(ISD::SHL_PARTS, VT, Expand);
setOperationAction(ISD::SRL_PARTS, VT, Expand);
setOperationAction(ISD::SRA_PARTS, VT, Expand);
setOperationAction(ISD::CTPOP, VT, Expand);
setOperationAction(ISD::SETCC, VT, Expand);
setOperationAction(ISD::SELECT, VT, Expand);
setOperationAction(ISD::SELECT_CC, VT, Custom);
}
if (STI.getHasAlu32()) {
setOperationAction(ISD::BSWAP, MVT::i32, Promote);
setOperationAction(ISD::BR_CC, MVT::i32,
STI.getHasJmp32() ? Custom : Promote);
}
setOperationAction(ISD::CTTZ, MVT::i64, Custom);
setOperationAction(ISD::CTLZ, MVT::i64, Custom);
setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Custom);
setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Expand);
// Extended load operations for i1 types must be promoted
for (MVT VT : MVT::integer_valuetypes()) {
setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i8, Expand);
setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i16, Expand);
setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i32, Expand);
}
setBooleanContents(ZeroOrOneBooleanContent);
// Function alignments (log2)
setMinFunctionAlignment(3);
setPrefFunctionAlignment(3);
if (BPFExpandMemcpyInOrder) {
// LLVM generic code will try to expand memcpy into load/store pairs at this
// stage which is before quite a few IR optimization passes, therefore the
// loads and stores could potentially be moved apart from each other which
// will cause trouble to memcpy pattern matcher inside kernel eBPF JIT
// compilers.
//
// When -bpf-expand-memcpy-in-order specified, we want to defer the expand
// of memcpy to later stage in IR optimization pipeline so those load/store
// pairs won't be touched and could be kept in order. Hence, we set
// MaxStoresPerMem* to zero to disable the generic getMemcpyLoadsAndStores
// code path, and ask LLVM to use target expander EmitTargetCodeForMemcpy.
MaxStoresPerMemset = MaxStoresPerMemsetOptSize = 0;
MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = 0;
MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = 0;
} else {
// inline memcpy() for kernel to see explicit copy
unsigned CommonMaxStores =
STI.getSelectionDAGInfo()->getCommonMaxStoresPerMemFunc();
MaxStoresPerMemset = MaxStoresPerMemsetOptSize = CommonMaxStores;
MaxStoresPerMemcpy = MaxStoresPerMemcpyOptSize = CommonMaxStores;
MaxStoresPerMemmove = MaxStoresPerMemmoveOptSize = CommonMaxStores;
}
// CPU/Feature control
HasAlu32 = STI.getHasAlu32();
HasJmp32 = STI.getHasJmp32();
HasJmpExt = STI.getHasJmpExt();
}
bool BPFTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
return false;
}
std::pair<unsigned, const TargetRegisterClass *>
BPFTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
StringRef Constraint,
MVT VT) const {
if (Constraint.size() == 1)
// GCC Constraint Letters
switch (Constraint[0]) {
case 'r': // GENERAL_REGS
return std::make_pair(0U, &BPF::GPRRegClass);
default:
break;
}
return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
}
SDValue BPFTargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
switch (Op.getOpcode()) {
case ISD::BR_CC:
return LowerBR_CC(Op, DAG);
case ISD::GlobalAddress:
return LowerGlobalAddress(Op, DAG);
case ISD::SELECT_CC:
return LowerSELECT_CC(Op, DAG);
default:
llvm_unreachable("unimplemented operand");
}
}
// Calling Convention Implementation
#include "BPFGenCallingConv.inc"
SDValue BPFTargetLowering::LowerFormalArguments(
SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
switch (CallConv) {
default:
report_fatal_error("Unsupported calling convention");
case CallingConv::C:
case CallingConv::Fast:
break;
}
MachineFunction &MF = DAG.getMachineFunction();
MachineRegisterInfo &RegInfo = MF.getRegInfo();
// Assign locations to all of the incoming arguments.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
CCInfo.AnalyzeFormalArguments(Ins, getHasAlu32() ? CC_BPF32 : CC_BPF64);
for (auto &VA : ArgLocs) {
if (VA.isRegLoc()) {
// Arguments passed in registers
EVT RegVT = VA.getLocVT();
MVT::SimpleValueType SimpleTy = RegVT.getSimpleVT().SimpleTy;
switch (SimpleTy) {
default: {
errs() << "LowerFormalArguments Unhandled argument type: "
<< RegVT.getEVTString() << '\n';
llvm_unreachable(0);
}
case MVT::i32:
case MVT::i64:
unsigned VReg = RegInfo.createVirtualRegister(SimpleTy == MVT::i64 ?
&BPF::GPRRegClass :
&BPF::GPR32RegClass);
RegInfo.addLiveIn(VA.getLocReg(), VReg);
SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, VReg, RegVT);
// If this is an value that has been promoted to wider types, insert an
// assert[sz]ext to capture this, then truncate to the right size.
if (VA.getLocInfo() == CCValAssign::SExt)
ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
DAG.getValueType(VA.getValVT()));
else if (VA.getLocInfo() == CCValAssign::ZExt)
ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
DAG.getValueType(VA.getValVT()));
if (VA.getLocInfo() != CCValAssign::Full)
ArgValue = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), ArgValue);
InVals.push_back(ArgValue);
break;
}
} else {
fail(DL, DAG, "defined with too many args");
InVals.push_back(DAG.getConstant(0, DL, VA.getLocVT()));
}
}
if (IsVarArg || MF.getFunction().hasStructRetAttr()) {
fail(DL, DAG, "functions with VarArgs or StructRet are not supported");
}
return Chain;
}
const unsigned BPFTargetLowering::MaxArgs = 5;
SDValue BPFTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
SmallVectorImpl<SDValue> &InVals) const {
SelectionDAG &DAG = CLI.DAG;
auto &Outs = CLI.Outs;
auto &OutVals = CLI.OutVals;
auto &Ins = CLI.Ins;
SDValue Chain = CLI.Chain;
SDValue Callee = CLI.Callee;
bool &IsTailCall = CLI.IsTailCall;
CallingConv::ID CallConv = CLI.CallConv;
bool IsVarArg = CLI.IsVarArg;
MachineFunction &MF = DAG.getMachineFunction();
// BPF target does not support tail call optimization.
IsTailCall = false;
switch (CallConv) {
default:
report_fatal_error("Unsupported calling convention");
case CallingConv::Fast:
case CallingConv::C:
break;
}
// Analyze operands of the call, assigning locations to each operand.
SmallVector<CCValAssign, 16> ArgLocs;
CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
CCInfo.AnalyzeCallOperands(Outs, getHasAlu32() ? CC_BPF32 : CC_BPF64);
unsigned NumBytes = CCInfo.getNextStackOffset();
if (Outs.size() > MaxArgs)
fail(CLI.DL, DAG, "too many args to ", Callee);
for (auto &Arg : Outs) {
ISD::ArgFlagsTy Flags = Arg.Flags;
if (!Flags.isByVal())
continue;
fail(CLI.DL, DAG, "pass by value not supported ", Callee);
}
auto PtrVT = getPointerTy(MF.getDataLayout());
Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
SmallVector<std::pair<unsigned, SDValue>, MaxArgs> RegsToPass;
// Walk arg assignments
for (unsigned i = 0,
e = std::min(static_cast<unsigned>(ArgLocs.size()), MaxArgs);
i != e; ++i) {
CCValAssign &VA = ArgLocs[i];
SDValue Arg = OutVals[i];
// Promote the value if needed.
switch (VA.getLocInfo()) {
default:
llvm_unreachable("Unknown loc info");
case CCValAssign::Full:
break;
case CCValAssign::SExt:
Arg = DAG.getNode(ISD::SIGN_EXTEND, CLI.DL, VA.getLocVT(), Arg);
break;
case CCValAssign::ZExt:
Arg = DAG.getNode(ISD::ZERO_EXTEND, CLI.DL, VA.getLocVT(), Arg);
break;
case CCValAssign::AExt:
Arg = DAG.getNode(ISD::ANY_EXTEND, CLI.DL, VA.getLocVT(), Arg);
break;
}
// Push arguments into RegsToPass vector
if (VA.isRegLoc())
RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
else
llvm_unreachable("call arg pass bug");
}
SDValue InFlag;
// Build a sequence of copy-to-reg nodes chained together with token chain and
// flag operands which copy the outgoing args into registers. The InFlag in
// necessary since all emitted instructions must be stuck together.
for (auto &Reg : RegsToPass) {
Chain = DAG.getCopyToReg(Chain, CLI.DL, Reg.first, Reg.second, InFlag);
InFlag = Chain.getValue(1);
}
// If the callee is a GlobalAddress node (quite common, every direct call is)
// turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
// Likewise ExternalSymbol -> TargetExternalSymbol.
if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
Callee = DAG.getTargetGlobalAddress(G->getGlobal(), CLI.DL, PtrVT,
G->getOffset(), 0);
} else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee)) {
Callee = DAG.getTargetExternalSymbol(E->getSymbol(), PtrVT, 0);
fail(CLI.DL, DAG, Twine("A call to built-in function '"
+ StringRef(E->getSymbol())
+ "' is not supported."));
}
// Returns a chain & a flag for retval copy to use.
SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
SmallVector<SDValue, 8> Ops;
Ops.push_back(Chain);
Ops.push_back(Callee);
// Add argument registers to the end of the list so that they are
// known live into the call.
for (auto &Reg : RegsToPass)
Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
if (InFlag.getNode())
Ops.push_back(InFlag);
Chain = DAG.getNode(BPFISD::CALL, CLI.DL, NodeTys, Ops);
InFlag = Chain.getValue(1);
// Create the CALLSEQ_END node.
Chain = DAG.getCALLSEQ_END(
Chain, DAG.getConstant(NumBytes, CLI.DL, PtrVT, true),
DAG.getConstant(0, CLI.DL, PtrVT, true), InFlag, CLI.DL);
InFlag = Chain.getValue(1);
// Handle result values, copying them out of physregs into vregs that we
// return.
return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, CLI.DL, DAG,
InVals);
}
SDValue
BPFTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
bool IsVarArg,
const SmallVectorImpl<ISD::OutputArg> &Outs,
const SmallVectorImpl<SDValue> &OutVals,
const SDLoc &DL, SelectionDAG &DAG) const {
unsigned Opc = BPFISD::RET_FLAG;
// CCValAssign - represent the assignment of the return value to a location
SmallVector<CCValAssign, 16> RVLocs;
MachineFunction &MF = DAG.getMachineFunction();
// CCState - Info about the registers and stack slot.
CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
if (MF.getFunction().getReturnType()->isAggregateType()) {
fail(DL, DAG, "only integer returns supported");
return DAG.getNode(Opc, DL, MVT::Other, Chain);
}
// Analize return values.
CCInfo.AnalyzeReturn(Outs, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64);
SDValue Flag;
SmallVector<SDValue, 4> RetOps(1, Chain);
// Copy the result values into the output registers.
for (unsigned i = 0; i != RVLocs.size(); ++i) {
CCValAssign &VA = RVLocs[i];
assert(VA.isRegLoc() && "Can only return in registers!");
Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVals[i], Flag);
// Guarantee that all emitted copies are stuck together,
// avoiding something bad.
Flag = Chain.getValue(1);
RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
}
RetOps[0] = Chain; // Update chain.
// Add the flag if we have it.
if (Flag.getNode())
RetOps.push_back(Flag);
return DAG.getNode(Opc, DL, MVT::Other, RetOps);
}
SDValue BPFTargetLowering::LowerCallResult(
SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
MachineFunction &MF = DAG.getMachineFunction();
// Assign locations to each value returned by this call.
SmallVector<CCValAssign, 16> RVLocs;
CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
if (Ins.size() >= 2) {
fail(DL, DAG, "only small returns supported");
for (unsigned i = 0, e = Ins.size(); i != e; ++i)
InVals.push_back(DAG.getConstant(0, DL, Ins[i].VT));
return DAG.getCopyFromReg(Chain, DL, 1, Ins[0].VT, InFlag).getValue(1);
}
CCInfo.AnalyzeCallResult(Ins, getHasAlu32() ? RetCC_BPF32 : RetCC_BPF64);
// Copy all of the result registers out of their specified physreg.
for (auto &Val : RVLocs) {
Chain = DAG.getCopyFromReg(Chain, DL, Val.getLocReg(),
Val.getValVT(), InFlag).getValue(1);
InFlag = Chain.getValue(2);
InVals.push_back(Chain.getValue(0));
}
return Chain;
}
static void NegateCC(SDValue &LHS, SDValue &RHS, ISD::CondCode &CC) {
switch (CC) {
default:
break;
case ISD::SETULT:
case ISD::SETULE:
case ISD::SETLT:
case ISD::SETLE:
CC = ISD::getSetCCSwappedOperands(CC);
std::swap(LHS, RHS);
break;
}
}
SDValue BPFTargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
SDValue Chain = Op.getOperand(0);
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
SDValue LHS = Op.getOperand(2);
SDValue RHS = Op.getOperand(3);
SDValue Dest = Op.getOperand(4);
SDLoc DL(Op);
if (!getHasJmpExt())
NegateCC(LHS, RHS, CC);
return DAG.getNode(BPFISD::BR_CC, DL, Op.getValueType(), Chain, LHS, RHS,
DAG.getConstant(CC, DL, LHS.getValueType()), Dest);
}
SDValue BPFTargetLowering::LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const {
SDValue LHS = Op.getOperand(0);
SDValue RHS = Op.getOperand(1);
SDValue TrueV = Op.getOperand(2);
SDValue FalseV = Op.getOperand(3);
ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
SDLoc DL(Op);
if (!getHasJmpExt())
NegateCC(LHS, RHS, CC);
SDValue TargetCC = DAG.getConstant(CC, DL, LHS.getValueType());
SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
return DAG.getNode(BPFISD::SELECT_CC, DL, VTs, Ops);
}
const char *BPFTargetLowering::getTargetNodeName(unsigned Opcode) const {
switch ((BPFISD::NodeType)Opcode) {
case BPFISD::FIRST_NUMBER:
break;
case BPFISD::RET_FLAG:
return "BPFISD::RET_FLAG";
case BPFISD::CALL:
return "BPFISD::CALL";
case BPFISD::SELECT_CC:
return "BPFISD::SELECT_CC";
case BPFISD::BR_CC:
return "BPFISD::BR_CC";
case BPFISD::Wrapper:
return "BPFISD::Wrapper";
case BPFISD::MEMCPY:
return "BPFISD::MEMCPY";
}
return nullptr;
}
SDValue BPFTargetLowering::LowerGlobalAddress(SDValue Op,
SelectionDAG &DAG) const {
auto N = cast<GlobalAddressSDNode>(Op);
assert(N->getOffset() == 0 && "Invalid offset for global address");
SDLoc DL(Op);
const GlobalValue *GV = N->getGlobal();
SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i64);
return DAG.getNode(BPFISD::Wrapper, DL, MVT::i64, GA);
}
unsigned
BPFTargetLowering::EmitSubregExt(MachineInstr &MI, MachineBasicBlock *BB,
unsigned Reg, bool isSigned) const {
const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
const TargetRegisterClass *RC = getRegClassFor(MVT::i64);
int RShiftOp = isSigned ? BPF::SRA_ri : BPF::SRL_ri;
MachineFunction *F = BB->getParent();
DebugLoc DL = MI.getDebugLoc();
MachineRegisterInfo &RegInfo = F->getRegInfo();
unsigned PromotedReg0 = RegInfo.createVirtualRegister(RC);
unsigned PromotedReg1 = RegInfo.createVirtualRegister(RC);
unsigned PromotedReg2 = RegInfo.createVirtualRegister(RC);
BuildMI(BB, DL, TII.get(BPF::MOV_32_64), PromotedReg0).addReg(Reg);
BuildMI(BB, DL, TII.get(BPF::SLL_ri), PromotedReg1)
.addReg(PromotedReg0).addImm(32);
BuildMI(BB, DL, TII.get(RShiftOp), PromotedReg2)
.addReg(PromotedReg1).addImm(32);
return PromotedReg2;
}
MachineBasicBlock *
BPFTargetLowering::EmitInstrWithCustomInserterMemcpy(MachineInstr &MI,
MachineBasicBlock *BB)
const {
MachineFunction *MF = MI.getParent()->getParent();
MachineRegisterInfo &MRI = MF->getRegInfo();
MachineInstrBuilder MIB(*MF, MI);
unsigned ScratchReg;
// This function does custom insertion during lowering BPFISD::MEMCPY which
// only has two register operands from memcpy semantics, the copy source
// address and the copy destination address.
//
// Because we will expand BPFISD::MEMCPY into load/store pairs, we will need
// a third scratch register to serve as the destination register of load and
// source register of store.
//
// The scratch register here is with the Define | Dead | EarlyClobber flags.
// The EarlyClobber flag has the semantic property that the operand it is
// attached to is clobbered before the rest of the inputs are read. Hence it
// must be unique among the operands to the instruction. The Define flag is
// needed to coerce the machine verifier that an Undef value isn't a problem
// as we anyway is loading memory into it. The Dead flag is needed as the
// value in scratch isn't supposed to be used by any other instruction.
ScratchReg = MRI.createVirtualRegister(&BPF::GPRRegClass);
MIB.addReg(ScratchReg,
RegState::Define | RegState::Dead | RegState::EarlyClobber);
return BB;
}
MachineBasicBlock *
BPFTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
MachineBasicBlock *BB) const {
const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
DebugLoc DL = MI.getDebugLoc();
unsigned Opc = MI.getOpcode();
bool isSelectRROp = (Opc == BPF::Select ||
Opc == BPF::Select_64_32 ||
Opc == BPF::Select_32 ||
Opc == BPF::Select_32_64);
bool isMemcpyOp = Opc == BPF::MEMCPY;
#ifndef NDEBUG
bool isSelectRIOp = (Opc == BPF::Select_Ri ||
Opc == BPF::Select_Ri_64_32 ||
Opc == BPF::Select_Ri_32 ||
Opc == BPF::Select_Ri_32_64);
assert((isSelectRROp || isSelectRIOp || isMemcpyOp) &&
"Unexpected instr type to insert");
#endif
if (isMemcpyOp)
return EmitInstrWithCustomInserterMemcpy(MI, BB);
bool is32BitCmp = (Opc == BPF::Select_32 ||
Opc == BPF::Select_32_64 ||
Opc == BPF::Select_Ri_32 ||
Opc == BPF::Select_Ri_32_64);
// To "insert" a SELECT instruction, we actually have to insert the diamond
// control-flow pattern. The incoming instruction knows the destination vreg
// to set, the condition code register to branch on, the true/false values to
// select between, and a branch opcode to use.
const BasicBlock *LLVM_BB = BB->getBasicBlock();
MachineFunction::iterator I = ++BB->getIterator();
// ThisMBB:
// ...
// TrueVal = ...
// jmp_XX r1, r2 goto Copy1MBB
// fallthrough --> Copy0MBB
MachineBasicBlock *ThisMBB = BB;
MachineFunction *F = BB->getParent();
MachineBasicBlock *Copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
MachineBasicBlock *Copy1MBB = F->CreateMachineBasicBlock(LLVM_BB);
F->insert(I, Copy0MBB);
F->insert(I, Copy1MBB);
// Update machine-CFG edges by transferring all successors of the current
// block to the new block which will contain the Phi node for the select.
Copy1MBB->splice(Copy1MBB->begin(), BB,
std::next(MachineBasicBlock::iterator(MI)), BB->end());
Copy1MBB->transferSuccessorsAndUpdatePHIs(BB);
// Next, add the true and fallthrough blocks as its successors.
BB->addSuccessor(Copy0MBB);
BB->addSuccessor(Copy1MBB);
// Insert Branch if Flag
int CC = MI.getOperand(3).getImm();
int NewCC;
switch (CC) {
#define SET_NEWCC(X, Y) \
case ISD::X: \
if (is32BitCmp && HasJmp32) \
NewCC = isSelectRROp ? BPF::Y##_rr_32 : BPF::Y##_ri_32; \
else \
NewCC = isSelectRROp ? BPF::Y##_rr : BPF::Y##_ri; \
break
SET_NEWCC(SETGT, JSGT);
SET_NEWCC(SETUGT, JUGT);
SET_NEWCC(SETGE, JSGE);
SET_NEWCC(SETUGE, JUGE);
SET_NEWCC(SETEQ, JEQ);
SET_NEWCC(SETNE, JNE);
SET_NEWCC(SETLT, JSLT);
SET_NEWCC(SETULT, JULT);
SET_NEWCC(SETLE, JSLE);
SET_NEWCC(SETULE, JULE);
default:
report_fatal_error("unimplemented select CondCode " + Twine(CC));
}
unsigned LHS = MI.getOperand(1).getReg();
bool isSignedCmp = (CC == ISD::SETGT ||
CC == ISD::SETGE ||
CC == ISD::SETLT ||
CC == ISD::SETLE);
// eBPF at the moment only has 64-bit comparison. Any 32-bit comparison need
// to be promoted, however if the 32-bit comparison operands are destination
// registers then they are implicitly zero-extended already, there is no
// need of explicit zero-extend sequence for them.
//
// We simply do extension for all situations in this method, but we will
// try to remove those unnecessary in BPFMIPeephole pass.
if (is32BitCmp && !HasJmp32)
LHS = EmitSubregExt(MI, BB, LHS, isSignedCmp);
if (isSelectRROp) {
unsigned RHS = MI.getOperand(2).getReg();
if (is32BitCmp && !HasJmp32)
RHS = EmitSubregExt(MI, BB, RHS, isSignedCmp);
BuildMI(BB, DL, TII.get(NewCC)).addReg(LHS).addReg(RHS).addMBB(Copy1MBB);
} else {
int64_t imm32 = MI.getOperand(2).getImm();
// sanity check before we build J*_ri instruction.
assert (isInt<32>(imm32));
BuildMI(BB, DL, TII.get(NewCC))
.addReg(LHS).addImm(imm32).addMBB(Copy1MBB);
}
// Copy0MBB:
// %FalseValue = ...
// # fallthrough to Copy1MBB
BB = Copy0MBB;
// Update machine-CFG edges
BB->addSuccessor(Copy1MBB);
// Copy1MBB:
// %Result = phi [ %FalseValue, Copy0MBB ], [ %TrueValue, ThisMBB ]
// ...
BB = Copy1MBB;
BuildMI(*BB, BB->begin(), DL, TII.get(BPF::PHI), MI.getOperand(0).getReg())
.addReg(MI.getOperand(5).getReg())
.addMBB(Copy0MBB)
.addReg(MI.getOperand(4).getReg())
.addMBB(ThisMBB);
MI.eraseFromParent(); // The pseudo instruction is gone now.
return BB;
}
EVT BPFTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
EVT VT) const {
return getHasAlu32() ? MVT::i32 : MVT::i64;
}
MVT BPFTargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
EVT VT) const {
return (getHasAlu32() && VT == MVT::i32) ? MVT::i32 : MVT::i64;
}
|
/**
* Copyright (c) Glow Contributors. See CONTRIBUTORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "glow/LLVMIRCodeGen/AllocationsInfo.h"
#include "glow/Backend/BackendUtils.h"
#include "glow/Backend/CompiledFunction.h"
#include "glow/CodeGen/MemoryAllocator.h"
#include "glow/Graph/Graph.h"
#include "glow/Graph/Nodes.h"
#include "glow/Graph/PlaceholderBindings.h"
#include "glow/IR/IRUtils.h"
#include "glow/IR/Instrs.h"
#include "glow/Support/Debug.h"
#include "glow/Support/Memory.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "jit-allocations"
using namespace glow;
using llvm::cast;
using llvm::dyn_cast;
using llvm::isa;
void AllocationsInfo::allocateWeightVars(const IRFunction *F) {
// Compute the new offsets for all the weights, do not reuse their current
// addresses. Process all constant WeightVars first.
for (auto &v : F->findConstants()) {
assert(isa<WeightVar>(F->getWeightForNode(v)) && "Expected WeightVar");
auto *w = cast<WeightVar>(F->getWeightForNode(v));
if (allocatedAddress_.count(v)) {
allocatedAddress_[w] = allocatedAddress_[v];
continue;
}
auto numBytes = w->getSizeInBytes();
size_t addr = constantWeightVarsAllocator.allocate(numBytes, v);
allocatedAddress_[v] = addr;
allocatedAddress_[w] = addr;
}
// Placeholders should be allocated in a order of
// intput|inputOutput|output|neither.
auto contiguousPlaceholders =
getContiguousPlaceHolder(F->findPlaceholders(), *F);
// Compute the offsets and total memory requirements for Placeholders.
for (auto it = contiguousPlaceholders.begin();
it != contiguousPlaceholders.end(); it++) {
auto &v = it->addr;
// Get the WeightVar for each Placeholder to calculate offsets.
assert(isa<WeightVar>(F->getWeightForNode(v)) && "Expected WeightVar");
auto *w = cast<WeightVar>(F->getWeightForNode(v));
if (allocatedAddress_.count(w)) {
continue;
}
auto numBytes = w->getSizeInBytes();
size_t addr = mutableWeightVarsAllocator.allocate(numBytes, w);
allocatedAddress_[w] = addr;
}
// Remember that max required memory size for each kind of weights.
constantWeightVarsMemSize_ = constantWeightVarsAllocator.getMaxMemoryUsage();
mutableWeightVarsMemSize_ = mutableWeightVarsAllocator.getMaxMemoryUsage();
DEBUG_GLOW(for (auto &A
: allocatedAddress_) {
if (isa<AllocActivationInst>(A.first) || isa<TensorViewInst>(A.first))
continue;
assert(valueNumbers_.count(A.first) && "Unknown weight");
if (isa<Constant>(A.first))
continue;
auto *weight = dyn_cast<WeightVar>(A.first);
llvm::StringRef kind =
valueNumbers_[weight].first == ValueKind::ConstantWeight
? "constant weight"
: "mutable weight";
llvm::dbgs() << "Allocated " << kind << " " << weight->getName()
<< " size: " << weight->getSizeInBytes()
<< " address range: [" << allocatedAddress_[weight] << ", "
<< allocatedAddress_[weight] + weight->getSizeInBytes()
<< "]\n";
});
}
void AllocationsInfo::allocateActivations(const IRFunction *F) {
// Maps activations and views to some offset within the heap.
llvm::DenseMap<const Value *, uint64_t> activationAddr;
// Assign device-space addresses to the activations.
for (const auto &I : F->getInstrs()) {
if (auto *A = dyn_cast<AllocActivationInst>(&I)) {
auto numBytes = I.getSizeInBytes();
size_t addr = activationsAllocator.allocate(numBytes, A);
assert(!activationAddr.count(A) && "Allocation already made!");
activationAddr[A] = addr;
continue;
}
if (auto *D = dyn_cast<DeallocActivationInst>(&I)) {
auto *A = D->getAlloc();
assert(activationAddr.count(A) && "Invalid deallocation!");
activationsAllocator.deallocate(A);
continue;
}
}
activationsMemSize_ = activationsAllocator.getMaxMemoryUsage();
// Register specific addresses within the heap to activations.
for (auto &A : activationAddr) {
allocatedAddress_[A.first] = A.second;
}
DEBUG_GLOW(for (auto &A
: allocatedAddress_) {
if (!isa<AllocActivationInst>(A.first)) {
continue;
}
if (isa<Constant>(A.first))
continue;
auto *act = dyn_cast<AllocActivationInst>(A.first);
llvm::dbgs() << "Allocated activation " << act->getName()
<< " size: " << act->getSizeInBytes() << " address range: ["
<< allocatedAddress_[act] << ", "
<< allocatedAddress_[act] + act->getSizeInBytes() << "]\n";
});
}
void AllocationsInfo::allocateTensorViews(const IRFunction *F) {
for (const auto &I : F->getInstrs()) {
if (const auto *TVI = dyn_cast<TensorViewInst>(&I)) {
auto *viewOrigin = getOrigin(TVI);
assert(allocatedAddress_.count(viewOrigin) &&
"Did not find original WeightVar or AllocActivation for a "
"TensorView.");
size_t originAddr = allocatedAddress_[viewOrigin];
// Calculate the offset into the underlying alloc activation.
size_t offset = calculateTensorViewOffset(TVI);
// Calculate the correct address using this offset into the alloc
// activation and map from the original TVI to it.
assert(!allocatedAddress_.count(TVI) && "Allocation already made!");
allocatedAddress_[TVI] = originAddr + offset;
continue;
}
}
}
void AllocationsInfo::numberValues(const IRFunction *F) {
// Assign numbers to all weights.
for (auto &v : F->findConstants()) {
assert(isa<WeightVar>(F->getWeightForNode(v)));
auto *w = cast<WeightVar>(F->getWeightForNode(v));
if (valueNumbers_.count(v)) {
valueNumbers_[w] = valueNumbers_[v];
continue;
}
valueNumbers_[v] = std::make_pair(ValueKind::ConstantWeight, valueIdx_);
valueNumbers_[w] = std::make_pair(ValueKind::ConstantWeight, valueIdx_++);
}
// Assign numbers to all placeholders.
for (auto &v : F->findPlaceholders()) {
assert(isa<WeightVar>(F->getWeightForNode(v)));
auto *w = cast<WeightVar>(F->getWeightForNode(v));
if (valueNumbers_.count(w)) {
continue;
}
valueNumbers_[w] = std::make_pair(ValueKind::MutableWeight, valueIdx_++);
}
// Assign numbers to all activations and tensorviews.
for (const auto &I : F->getInstrs()) {
if (auto *A = dyn_cast<AllocActivationInst>(&I)) {
assert(!valueNumbers_.count(A) &&
"Activation should be defined only once");
valueNumbers_[A] = std::make_pair(ValueKind::Activation, valueIdx_++);
continue;
}
if (auto *A = dyn_cast<TensorViewInst>(&I)) {
auto *viewOrigin = getOrigin(A);
auto kind = ValueKind::Activation;
if (auto *w = dyn_cast<WeightVar>(viewOrigin)) {
kind = w->isConstant() ? ValueKind::ConstantWeight
: ValueKind::MutableWeight;
}
assert(!valueNumbers_.count(A) &&
"TensorView should be defined only once");
valueNumbers_[A] = std::make_pair(kind, valueIdx_++);
continue;
}
}
DEBUG_GLOW(for (auto &A
: valueNumbers_) {
if (isa<Constant>(A.first))
continue;
auto *v = static_cast<const Value *>(A.first);
llvm::dbgs() << "Value number for " << v->getName() << ": "
<< A.second.second << "\n";
});
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY!
#include "config.h"
#if ENABLE(WEB_AUDIO)
#include "V8AudioNode.h"
#include "bindings/core/v8/ExceptionState.h"
#include "bindings/core/v8/V8DOMConfiguration.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "bindings/core/v8/V8ObjectConstructor.h"
#include "bindings/modules/v8/V8AudioContext.h"
#include "bindings/modules/v8/V8AudioNode.h"
#include "bindings/modules/v8/V8AudioParam.h"
#include "core/dom/ContextFeatures.h"
#include "core/dom/Document.h"
#include "core/inspector/ConsoleMessage.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/TraceEvent.h"
#include "wtf/GetPtr.h"
#include "wtf/RefPtr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8AudioNode::wrapperTypeInfo = { gin::kEmbedderBlink, V8AudioNode::domTemplate, V8AudioNode::refObject, V8AudioNode::derefObject, V8AudioNode::trace, 0, 0, V8AudioNode::preparePrototypeObject, V8AudioNode::installConditionallyEnabledProperties, "AudioNode", &V8EventTarget::wrapperTypeInfo, WrapperTypeInfo::WrapperTypeObjectPrototype, WrapperTypeInfo::ObjectClassId, WrapperTypeInfo::InheritFromEventTarget, WrapperTypeInfo::Independent, WrapperTypeInfo::GarbageCollectedObject };
#if defined(COMPONENT_BUILD) && defined(WIN32) && COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in AudioNode.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// bindings/core/v8/ScriptWrappable.h.
const WrapperTypeInfo& AudioNode::s_wrapperTypeInfo = V8AudioNode::wrapperTypeInfo;
namespace AudioNodeV8Internal {
static void contextAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
RawPtr<AudioContext> cppValue(impl->context());
if (cppValue && DOMDataStore::setReturnValue(info.GetReturnValue(), cppValue.get()))
return;
v8::Local<v8::Value> v8Value(toV8(cppValue.get(), holder, info.GetIsolate()));
if (!v8Value.IsEmpty()) {
V8HiddenValue::setHiddenValue(info.GetIsolate(), holder, v8AtomicString(info.GetIsolate(), "context"), v8Value);
v8SetReturnValue(info, v8Value);
}
}
static void contextAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::contextAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void numberOfInputsAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
v8SetReturnValueUnsigned(info, impl->numberOfInputs());
}
static void numberOfInputsAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::numberOfInputsAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void numberOfOutputsAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
v8SetReturnValueUnsigned(info, impl->numberOfOutputs());
}
static void numberOfOutputsAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::numberOfOutputsAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelCountAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
v8SetReturnValueUnsigned(info, impl->channelCount());
}
static void channelCountAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::channelCountAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelCountAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "channelCount", "AudioNode", holder, info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(holder);
unsigned cppValue = toUInt32(info.GetIsolate(), v8Value, NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
impl->setChannelCount(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void channelCountAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
AudioNodeV8Internal::channelCountAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelCountModeAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
v8SetReturnValueString(info, impl->channelCountMode(), info.GetIsolate());
}
static void channelCountModeAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::channelCountModeAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelCountModeAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "channelCountMode", "AudioNode", holder, info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
static const char* validValues[] = {
"max",
"clamped-max",
"explicit",
};
if (!isValidEnum(cppValue, validValues, WTF_ARRAY_LENGTH(validValues), "ChannelCountMode", exceptionState)) {
currentExecutionContext(info.GetIsolate())->addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, exceptionState.message()));
return;
}
impl->setChannelCountMode(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void channelCountModeAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
AudioNodeV8Internal::channelCountModeAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelInterpretationAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
AudioNode* impl = V8AudioNode::toImpl(holder);
v8SetReturnValueString(info, impl->channelInterpretation(), info.GetIsolate());
}
static void channelInterpretationAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMGetter");
AudioNodeV8Internal::channelInterpretationAttributeGetter(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void channelInterpretationAttributeSetter(v8::Local<v8::Value> v8Value, const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Object> holder = info.Holder();
ExceptionState exceptionState(ExceptionState::SetterContext, "channelInterpretation", "AudioNode", holder, info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(holder);
V8StringResource<> cppValue = v8Value;
if (!cppValue.prepare())
return;
static const char* validValues[] = {
"speakers",
"discrete",
};
if (!isValidEnum(cppValue, validValues, WTF_ARRAY_LENGTH(validValues), "ChannelInterpretation", exceptionState)) {
currentExecutionContext(info.GetIsolate())->addConsoleMessage(ConsoleMessage::create(JSMessageSource, WarningMessageLevel, exceptionState.message()));
return;
}
impl->setChannelInterpretation(cppValue, exceptionState);
exceptionState.throwIfNeeded();
}
static void channelInterpretationAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
v8::Local<v8::Value> v8Value = info[0];
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMSetter");
AudioNodeV8Internal::channelInterpretationAttributeSetter(v8Value, info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void connect1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "connect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioNode* destination;
unsigned output;
unsigned input;
{
destination = V8AudioNode::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioNode'.");
exceptionState.throwIfNeeded();
return;
}
if (!info[1]->IsUndefined()) {
output = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
} else {
output = 0u;
}
if (!info[2]->IsUndefined()) {
input = toUInt32(info.GetIsolate(), info[2], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
} else {
input = 0u;
}
}
impl->connect(destination, output, input, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void connect2Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "connect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioParam* destination;
unsigned output;
{
destination = V8AudioParam::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioParam'.");
exceptionState.throwIfNeeded();
return;
}
if (!info[1]->IsUndefined()) {
output = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
} else {
output = 0u;
}
}
impl->connect(destination, output, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void connectMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "connect", "AudioNode", info.Holder(), info.GetIsolate());
switch (std::min(3, info.Length())) {
case 1:
if (V8AudioNode::hasInstance(info[0], info.GetIsolate())) {
connect1Method(info);
return;
}
if (V8AudioParam::hasInstance(info[0], info.GetIsolate())) {
connect2Method(info);
return;
}
break;
case 2:
if (V8AudioNode::hasInstance(info[0], info.GetIsolate())) {
connect1Method(info);
return;
}
if (V8AudioParam::hasInstance(info[0], info.GetIsolate())) {
connect2Method(info);
return;
}
break;
case 3:
if (true) {
connect1Method(info);
return;
}
break;
default:
break;
}
if (info.Length() < 1) {
exceptionState.throwTypeError(ExceptionMessages::notEnoughArguments(1, info.Length()));
exceptionState.throwIfNeeded();
return;
}
exceptionState.throwTypeError("No function was found that matched the signature provided.");
exceptionState.throwIfNeeded();
return;
}
static void connectMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
AudioNodeV8Internal::connectMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
static void disconnect1Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
impl->disconnect();
}
static void disconnect2Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
unsigned output;
{
output = toUInt32(info.GetIsolate(), info[0], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->disconnect(output, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnect3Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioNode* destination;
{
destination = V8AudioNode::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioNode'.");
exceptionState.throwIfNeeded();
return;
}
}
impl->disconnect(destination, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnect4Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioNode* destination;
unsigned output;
{
destination = V8AudioNode::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioNode'.");
exceptionState.throwIfNeeded();
return;
}
output = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->disconnect(destination, output, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnect5Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioNode* destination;
unsigned output;
unsigned input;
{
destination = V8AudioNode::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioNode'.");
exceptionState.throwIfNeeded();
return;
}
output = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
input = toUInt32(info.GetIsolate(), info[2], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->disconnect(destination, output, input, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnect6Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioParam* destination;
{
destination = V8AudioParam::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioParam'.");
exceptionState.throwIfNeeded();
return;
}
}
impl->disconnect(destination, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnect7Method(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
AudioNode* impl = V8AudioNode::toImpl(info.Holder());
AudioParam* destination;
unsigned output;
{
destination = V8AudioParam::toImplWithTypeCheck(info.GetIsolate(), info[0]);
if (!destination) {
exceptionState.throwTypeError("parameter 1 is not of type 'AudioParam'.");
exceptionState.throwIfNeeded();
return;
}
output = toUInt32(info.GetIsolate(), info[1], NormalConversion, exceptionState);
if (exceptionState.throwIfNeeded())
return;
}
impl->disconnect(destination, output, exceptionState);
if (exceptionState.hadException()) {
exceptionState.throwIfNeeded();
return;
}
}
static void disconnectMethod(const v8::FunctionCallbackInfo<v8::Value>& info)
{
ExceptionState exceptionState(ExceptionState::ExecutionContext, "disconnect", "AudioNode", info.Holder(), info.GetIsolate());
switch (std::min(3, info.Length())) {
case 0:
if (true) {
disconnect1Method(info);
return;
}
break;
case 1:
if (V8AudioNode::hasInstance(info[0], info.GetIsolate())) {
disconnect3Method(info);
return;
}
if (V8AudioParam::hasInstance(info[0], info.GetIsolate())) {
disconnect6Method(info);
return;
}
if (true) {
disconnect2Method(info);
return;
}
break;
case 2:
if (V8AudioNode::hasInstance(info[0], info.GetIsolate())) {
disconnect4Method(info);
return;
}
if (V8AudioParam::hasInstance(info[0], info.GetIsolate())) {
disconnect7Method(info);
return;
}
break;
case 3:
if (true) {
disconnect5Method(info);
return;
}
break;
default:
break;
}
exceptionState.throwTypeError("No function was found that matched the signature provided.");
exceptionState.throwIfNeeded();
return;
}
static void disconnectMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
TRACE_EVENT_SET_SAMPLING_STATE("blink", "DOMMethod");
AudioNodeV8Internal::disconnectMethod(info);
TRACE_EVENT_SET_SAMPLING_STATE("v8", "V8Execution");
}
} // namespace AudioNodeV8Internal
static const V8DOMConfiguration::AccessorConfiguration V8AudioNodeAccessors[] = {
{"context", AudioNodeV8Internal::contextAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"numberOfInputs", AudioNodeV8Internal::numberOfInputsAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"numberOfOutputs", AudioNodeV8Internal::numberOfOutputsAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"channelCount", AudioNodeV8Internal::channelCountAttributeGetterCallback, AudioNodeV8Internal::channelCountAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"channelCountMode", AudioNodeV8Internal::channelCountModeAttributeGetterCallback, AudioNodeV8Internal::channelCountModeAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
{"channelInterpretation", AudioNodeV8Internal::channelInterpretationAttributeGetterCallback, AudioNodeV8Internal::channelInterpretationAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), V8DOMConfiguration::ExposedToAllScripts, V8DOMConfiguration::OnPrototype, V8DOMConfiguration::CheckHolder},
};
static const V8DOMConfiguration::MethodConfiguration V8AudioNodeMethods[] = {
{"connect", AudioNodeV8Internal::connectMethodCallback, 0, 1, V8DOMConfiguration::ExposedToAllScripts},
{"disconnect", AudioNodeV8Internal::disconnectMethodCallback, 0, 0, V8DOMConfiguration::ExposedToAllScripts},
};
static void installV8AudioNodeTemplate(v8::Local<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate)
{
functionTemplate->ReadOnlyPrototype();
v8::Local<v8::Signature> defaultSignature;
defaultSignature = V8DOMConfiguration::installDOMClassTemplate(isolate, functionTemplate, "AudioNode", V8EventTarget::domTemplate(isolate), V8AudioNode::internalFieldCount,
0, 0,
V8AudioNodeAccessors, WTF_ARRAY_LENGTH(V8AudioNodeAccessors),
V8AudioNodeMethods, WTF_ARRAY_LENGTH(V8AudioNodeMethods));
v8::Local<v8::ObjectTemplate> instanceTemplate = functionTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = functionTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Custom toString template
functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate());
}
v8::Local<v8::FunctionTemplate> V8AudioNode::domTemplate(v8::Isolate* isolate)
{
return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8AudioNodeTemplate);
}
bool V8AudioNode::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8AudioNode::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate)
{
return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
AudioNode* V8AudioNode::toImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value)
{
return hasInstance(value, isolate) ? toImpl(v8::Local<v8::Object>::Cast(value)) : 0;
}
void V8AudioNode::refObject(ScriptWrappable* scriptWrappable)
{
}
void V8AudioNode::derefObject(ScriptWrappable* scriptWrappable)
{
}
} // namespace blink
#endif // ENABLE(WEB_AUDIO)
|
#include"Vector3.h"
Vector3::Vector3(){}
Vector3::Vector3(double x_,double y_,double z_){
x=x_;
y=y_;
z=z_;
}
Vector3 Vector3::operator*(double cons){
Vector3 ans;
ans.x=cons*x;
ans.y=cons*y;
ans.z=cons*z;
return ans;
}
|
// Copyright (c) 2019-2021 The BIGKEYCOIN Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <node/psbt.h>
#include <psbt.h>
#include <pubkey.h>
#include <script/script.h>
#include <streams.h>
#include <util/check.h>
#include <version.h>
#include <cstdint>
#include <optional>
#include <string>
#include <vector>
using node::AnalyzePSBT;
using node::PSBTAnalysis;
using node::PSBTInputAnalysis;
void initialize_psbt()
{
static const ECCVerifyHandle verify_handle;
}
FUZZ_TARGET_INIT(psbt, initialize_psbt)
{
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
PartiallySignedTransaction psbt_mut;
std::string error;
if (!DecodeRawPSBT(psbt_mut, fuzzed_data_provider.ConsumeRandomLengthString(), error)) {
return;
}
const PartiallySignedTransaction psbt = psbt_mut;
const PSBTAnalysis analysis = AnalyzePSBT(psbt);
(void)PSBTRoleName(analysis.next);
for (const PSBTInputAnalysis& input_analysis : analysis.inputs) {
(void)PSBTRoleName(input_analysis.next);
}
(void)psbt.IsNull();
std::optional<CMutableTransaction> tx = psbt.tx;
if (tx) {
const CMutableTransaction& mtx = *tx;
const PartiallySignedTransaction psbt_from_tx{mtx};
}
for (const PSBTInput& input : psbt.inputs) {
(void)PSBTInputSigned(input);
(void)input.IsNull();
}
(void)CountPSBTUnsignedInputs(psbt);
for (const PSBTOutput& output : psbt.outputs) {
(void)output.IsNull();
}
for (size_t i = 0; i < psbt.tx->vin.size(); ++i) {
CTxOut tx_out;
if (psbt.GetInputUTXO(tx_out, i)) {
(void)tx_out.IsNull();
(void)tx_out.ToString();
}
}
psbt_mut = psbt;
(void)FinalizePSBT(psbt_mut);
psbt_mut = psbt;
CMutableTransaction result;
if (FinalizeAndExtractPSBT(psbt_mut, result)) {
const PartiallySignedTransaction psbt_from_tx{result};
}
PartiallySignedTransaction psbt_merge;
if (!DecodeRawPSBT(psbt_merge, fuzzed_data_provider.ConsumeRandomLengthString(), error)) {
psbt_merge = psbt;
}
psbt_mut = psbt;
(void)psbt_mut.Merge(psbt_merge);
psbt_mut = psbt;
(void)CombinePSBTs(psbt_mut, {psbt_mut, psbt_merge});
psbt_mut = psbt;
for (unsigned int i = 0; i < psbt_merge.tx->vin.size(); ++i) {
(void)psbt_mut.AddInput(psbt_merge.tx->vin[i], psbt_merge.inputs[i]);
}
for (unsigned int i = 0; i < psbt_merge.tx->vout.size(); ++i) {
Assert(psbt_mut.AddOutput(psbt_merge.tx->vout[i], psbt_merge.outputs[i]));
}
psbt_mut.unknown.insert(psbt_merge.unknown.begin(), psbt_merge.unknown.end());
}
|
//
// Created by mati on 08.05.2020.
//
#include <unistd.h>
#include "Dron.h"
Dron::Dron(std::shared_ptr<drawNS::Draw3DAPI> ptrApi, const SWektor<double, ROZMIAR> &sr) : Prostopadloscian(ptrApi, sr)/*, Sruba(ptrApi, sr)*/{
Sruba TmpLewa(ptrApi, Prostopadloscian::Wierzcholki[0]);
Lewa = TmpLewa;
Sruba TmpPrawa(ptrApi, Prostopadloscian::Wierzcholki[1]);
Prawa = TmpPrawa;
SWektor<double,ROZMIAR> tmp;
tmp = Prostopadloscian::srodek - Prostopadloscian::Wierzcholki[0];
r_dron = tmp.dlugosc();
}
void Dron::Obroc(double kat) {
int klatki = 100;
double kat_klatke = kat/klatki;
for (int i = 0; i <klatki; i++) {
Prostopadloscian::Obroc(kat_klatke);
Lewa.Obroc(kat_klatke);
Prawa.Obroc(kat_klatke);
/* if (kat > 0)
Prawa.Wiruj();
else if(kat < 0)
Lewa.Wiruj();*/
}
}
void Dron::Rysuj() {
Prostopadloscian::Rysuj();
Lewa.Rysuj();
Prawa.Rysuj();
}
void Dron::Przesun(double odleglosc, double kat) {
int klatki = 10;
double odl_klatki = odleglosc / klatki;
double kat_klatki = kat / klatki;
for (int i = 0; i <klatki; i++) {
std::cout << "krok "<<i<<"\n";
Prostopadloscian::Przesun(odl_klatki, kat_klatki);
/* Lewa.Przesun(odl_klatki, kat_klatki);
Prawa.Przesun(odl_klatki, kat_klatki);*/
}
Lewa.Przesun(-odleglosc, kat);
Prawa.Przesun(-odleglosc, kat);
}
double Dron::get_r() const {
return r_dron;
}
const SWektor<double, ROZMIAR> Dron::get_srodek() const {
return Prostopadloscian::srodek;
}
|
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include "Logger.h"
Logger::Logger(void)
{
m_count = 0;
memset(m_dirname, 0, sizeof(m_dirname));
memset(m_logname, 0, sizeof(m_logname));
}
Logger::~Logger(void)
{
if(m_fp != NULL)
{
fclose(m_fp);
m_fp = NULL;
}
if(m_buf != NULL)
{
delete [] m_buf;
m_buf = NULL;
}
}
bool Logger::Init(const char* file_name, int log_buf_size /* = 8192 */, int split_lines /* = 5000000 */)
{
m_log_buf_size = log_buf_size;
m_split_lines = split_lines;
m_buf = new char[m_log_buf_size];
memset(m_buf, 0, sizeof(m_buf));
time_t t = time(NULL);
struct tm mytm;
localtime_s(&mytm, &t);
char * pfilename = (char *) file_name;
char * p = strrchr(pfilename, '\\');
char log_full_name[256] = {0};
if (p == NULL)
{
strncpy_s(m_logname, file_name, sizeof(m_logname));
_snprintf(log_full_name, 255, "%d_%02d_%02d_%s", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday, file_name);
}
else
{
strncpy_s(m_logname, p + 1, sizeof(m_logname));
strncpy_s(m_dirname, file_name, p - file_name + 1);
_snprintf(log_full_name, 255, "%s%d_%02d_%02d_%s", m_dirname, mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday, m_logname);
}
m_today = mytm.tm_mday;
m_fp = fopen(log_full_name, "a+");
if (m_fp == NULL)
{
return false;
}
return true;
}
void Logger::Write(int level, const char* format, ...)
{
struct timeval now = {0, 0};
Gettimeofday(&now, NULL);
time_t t = now.tv_sec;
struct tm mytm;
localtime_s(&mytm, &t);
char s[16] = {0};
switch (level)
{
case 0: strncpy(s, "[debug]", 15);
break;
case 1: strncpy(s, "[info]", 15);
break;
case 2: strncpy(s, "[warn]", 15);
break;
case 3: strncpy(s, "[error]", 15);
break;
default: strncpy(s, "[info]", 15);
break;
}
int n = _snprintf(m_buf, 48, "%s [%d-%02d-%02d %02d:%02d:%02d.%06d] ", s, mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec, now.tv_usec);
m_count++;
if(m_today != mytm.tm_mday || m_count % m_split_lines == 0)
{
char newfile[256] = {0};
fflush(m_fp);
fclose(m_fp);
m_fp = NULL;
char filetail[16] = {0};
_snprintf(filetail, 16, "%d_%02d_%02d_", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday);
if(m_today != mytm.tm_mday) {
_snprintf(newfile, 255, "%s%s%s", m_dirname, filetail, m_logname);
m_today = mytm.tm_mday;
m_count = 0;
} else {
_snprintf(newfile, 255, "%s%s%s.%d", m_dirname, filetail, m_logname, m_count / m_split_lines);
}
m_fp = fopen(newfile, "a+");
}
va_list valist;
va_start(valist, format);
int m = _vsnprintf(m_buf + n, m_log_buf_size - 1, format, valist);
m_buf[n + m + 1] = '\n';
fwrite(m_buf, strlen(m_buf), 1, m_fp);
va_end(valist);
}
void Logger::WriteError(const char* format, ...)
{
struct timeval now = {0, 0};
Gettimeofday(&now, NULL);
time_t t = now.tv_sec;
struct tm * sys_tm = localtime(&t);
struct tm mytm = *sys_tm;
int n = _snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06d [error] ", mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec, now.tv_usec);
m_count++;
if(m_today != mytm.tm_mday || m_count % m_split_lines == 0)
{
char newfile[256] = {0};
fflush(m_fp);
fclose(m_fp);
m_fp = NULL;
char filetail[16] = {0};
_snprintf(filetail, 16, "%d_%02d_%02d_", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday);
if(m_today != mytm.tm_mday)
{
_snprintf(newfile, 255, "%s%s%s", m_dirname, filetail, m_logname);
m_today = mytm.tm_mday;
m_count = 0;
}
else
{
_snprintf(newfile, 255, "%s%s%s.%d", m_dirname, filetail, m_logname, m_count / m_split_lines);
}
m_fp = fopen(newfile, "a+");
}
va_list valist;
va_start(valist, format);
int m = _vsnprintf(m_buf + n, m_log_buf_size - 1, format, valist);
m_buf[n + m + 1] = '\n';
fwrite(m_buf, strlen(m_buf), 1, m_fp);
va_end(valist);
}
void Logger::WriteInfo(const char* format, ...)
{
struct timeval now = {0, 0};
Gettimeofday(&now, NULL);
time_t t = now.tv_sec;
struct tm * sys_tm = localtime(&t);
struct tm mytm = *sys_tm;
int n = _snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06d [info] ", mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec, now.tv_usec);
m_count++;
if(m_today != mytm.tm_mday || m_count % m_split_lines == 0)
{
char newfile[256] = {0};
fflush(m_fp);
fclose(m_fp);
m_fp = NULL;
char filetail[16] = {0};
_snprintf(filetail, 16, "%d_%02d_%02d_", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday);
if(m_today != mytm.tm_mday)
{
_snprintf(newfile, 255, "%s%s%s", m_dirname, filetail, m_logname);
m_today = mytm.tm_mday;
m_count = 0;
}
else
{
_snprintf(newfile, 255, "%s%s%s.%d", m_dirname, filetail, m_logname, m_count / m_split_lines);
}
m_fp = fopen(newfile, "a+");
}
va_list valist;
va_start(valist, format);
int m = _vsnprintf(m_buf + n, m_log_buf_size - 1, format, valist);
m_buf[n + m + 1] = '\n';
fwrite(m_buf, strlen(m_buf), 1, m_fp);
va_end(valist);
}
void Logger::WriteDebug(const char* format, ...)
{
struct timeval now = {0, 0};
Gettimeofday(&now, NULL);
time_t t = now.tv_sec;
struct tm * sys_tm = localtime(&t);
struct tm mytm = *sys_tm;
int n = _snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06d [debug] ", mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec, now.tv_usec);
m_count++;
if(m_today != mytm.tm_mday || m_count % m_split_lines == 0)
{
char newfile[256] = {0};
fflush(m_fp);
fclose(m_fp);
m_fp = NULL;
char filetail[16] = {0};
_snprintf(filetail, 16, "%d_%02d_%02d_", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday);
if(m_today != mytm.tm_mday)
{
_snprintf(newfile, 255, "%s%s%s", m_dirname, filetail, m_logname);
m_today = mytm.tm_mday;
m_count = 0;
}
else
{
_snprintf(newfile, 255, "%s%s%s.%d", m_dirname, filetail, m_logname, m_count / m_split_lines);
}
m_fp = fopen(newfile, "a+");
}
va_list valist;
va_start(valist, format);
int m = _vsnprintf(m_buf + n, m_log_buf_size - 1, format, valist);
m_buf[n + m + 1] = '\n';
fwrite(m_buf, strlen(m_buf), 1, m_fp);
va_end(valist);
}
void Logger::WriteWarn(const char* format, ...)
{
struct timeval now = {0, 0};
Gettimeofday(&now, NULL);
time_t t = now.tv_sec;
struct tm * sys_tm = localtime(&t);
struct tm mytm = *sys_tm;
int n = _snprintf(m_buf, 48, "%d-%02d-%02d %02d:%02d:%02d.%06d [warn] ", mytm.tm_year+1900, mytm.tm_mon+1, mytm.tm_mday,
mytm.tm_hour, mytm.tm_min, mytm.tm_sec, now.tv_usec);
m_count++;
if(m_today != mytm.tm_mday || m_count % m_split_lines == 0)
{
char newfile[256] = {0};
fflush(m_fp);
fclose(m_fp);
m_fp = NULL;
char filetail[16] = {0};
_snprintf(filetail, 16, "%d_%02d_%02d_", mytm.tm_year + 1900, mytm.tm_mon + 1, mytm.tm_mday);
if(m_today != mytm.tm_mday)
{
_snprintf(newfile, 255, "%s%s%s", m_dirname, filetail, m_logname);
m_today = mytm.tm_mday;
m_count = 0;
}
else
{
_snprintf(newfile, 255, "%s%s%s.%d", m_dirname, filetail, m_logname, m_count / m_split_lines);
}
m_fp = fopen(newfile, "a+");
}
va_list valist;
va_start(valist, format);
int m = _vsnprintf(m_buf + n, m_log_buf_size - 1, format, valist);
m_buf[n + m + 1] = '\n';
fwrite(m_buf, strlen(m_buf), 1, m_fp);
va_end(valist);
}
void Logger::Flush()
{
fflush(m_fp);
}
int Logger::Gettimeofday(struct timeval *tv, void * tzp)
{
time_t clock;
struct tm tm;
SYSTEMTIME wtm;
GetLocalTime(&wtm);
tm.tm_year = wtm.wYear - 1900;
tm.tm_mon = wtm.wMonth - 1;
tm.tm_mday = wtm.wDay;
tm.tm_hour = wtm.wHour;
tm.tm_min = wtm.wMinute;
tm.tm_sec = wtm.wSecond;
tm.tm_isdst = -1;
clock = mktime(&tm);
tv->tv_sec = (long) clock;
tv->tv_usec = wtm.wMilliseconds * 1000;
return 0;
}
|
#include <iostream>
#include <map>
#include <string>
#include <ctype.h>
#include <locale>
#include <windows.h>
using namespace std;
string fromDos (string dosString)
{
char buf[1000000] ;
OemToCharA(dosString.c_str(), buf) ; // windows.h
return buf ;
}
int main()
{
setlocale (LC_ALL, "bulgarian") ;
std::string UserInput = "";
std::cout << "Please, input string >>";
std::getline(std::cin,UserInput);
UserInput = fromDos(UserInput) ;
std::cout << "You Enter:" << UserInput;
std::map<std::string,unsigned int> Counters;
Counters["upper"] = 0;
Counters["lower"] = 0;
Counters["other"] = 0;
unsigned int len = UserInput.length();
for(unsigned int i=0;i<len;i++)
{
if ( islower(UserInput[i]) )
{
Counters["lower"]++;
}
else if ( isupper(UserInput[i]) )
{
Counters["upper"]++;
}
else
{
Counters["other"]++;
}
}
std::cout << std::endl << "Uppers: " << Counters["upper"] << std::endl;
std::cout << std::endl << "Lowers: " << Counters["lower"] << std::endl;
std::cout << std::endl << "Other:" << Counters["other"] << std::endl;
return 0;
}
|
/* IZ3D_FILE: $Id: PostprocessedOutput.cpp 1540 2008-12-25 14:41:36Z kostik $
*
* Project : iZ3D Stereo Driver
* Copyright (C) iZ3D Inc. 2002 - 2010
*
* $Author: kostik $
* $Revision: 1540 $
* $Date: 2008-12-25 17:41:36 +0300 (Чт, 25 дек 2008) $
* $LastChangedBy: kostik $
* $URL: svn://svn.neurok.ru/dev/driver/trunk/S3DWrapper9/PostprocessedOutput.cpp $
*/
#include "StdAfx.h"
#include "PostprocessedOutput_dx9.h"
using namespace DX9Output;
PostprocessedOutput::PostprocessedOutput(DWORD mode, DWORD spanMode)
: OutputMethod(mode, spanMode)
, m_bMultiPassRendering(false)
{
m_Caps = ocOutputFromTexture;
}
PostprocessedOutput::~PostprocessedOutput(void)
{
}
HRESULT PostprocessedOutput::Initialize(IDirect3DDevice9* dev, bool MultiPass)
{
HRESULT res = S_OK;
Clear();
OutputMethod::Initialize(dev, MultiPass);
m_bMultiPassRendering = MultiPass;
if (m_bMultiPassRendering)
{
D3DCAPS9 caps;
m_pd3dDevice->GetDeviceCaps(&caps);
if (GetOutputChainsNumber() == 1)
m_bMultiPassRendering = false;
else if (!MultiPass && GetOutputChainsNumber() > caps.NumSimultaneousRTs)
m_bMultiPassRendering = true;
}
res = InitializeResources();
return res;
}
HRESULT PostprocessedOutput::InitializeSCData(CBaseSwapChain* pSwapChain)
{
HRESULT hResult = S_OK;
SIZE bb = pSwapChain->m_BackBufferSize;
pSwapChain->m_Vertex[0].x = 0 - .5f;
pSwapChain->m_Vertex[0].y = 0 - .5f;
pSwapChain->m_Vertex[0].z = 0;
pSwapChain->m_Vertex[0].rhw = 1;
pSwapChain->m_Vertex[0].tu = 0;
pSwapChain->m_Vertex[0].tv = 0;
pSwapChain->m_Vertex[1].x = bb.cx - .5f;
pSwapChain->m_Vertex[1].y = 0 - .5f;
pSwapChain->m_Vertex[1].z = 0;
pSwapChain->m_Vertex[1].rhw = 1;
pSwapChain->m_Vertex[1].tu = 1;
pSwapChain->m_Vertex[1].tv = 0;
pSwapChain->m_Vertex[2].x = bb.cx - .5f;
pSwapChain->m_Vertex[2].y = bb.cy - .5f;
pSwapChain->m_Vertex[2].z = 0;
pSwapChain->m_Vertex[2].rhw = 1;
pSwapChain->m_Vertex[2].tu = 1;
pSwapChain->m_Vertex[2].tv = 1;
pSwapChain->m_Vertex[3].x = 0 - .5f;
pSwapChain->m_Vertex[3].y = bb.cy - .5f;
pSwapChain->m_Vertex[3].z = 0;
pSwapChain->m_Vertex[3].rhw = 1;
pSwapChain->m_Vertex[3].tu = 0;
pSwapChain->m_Vertex[3].tv = 1;
hResult = InitializeSCResources(pSwapChain);
return hResult;
}
void PostprocessedOutput::Clear()
{
ClearResources();
m_pShaderMono.Release();
m_pShaderMonoAndGamma.Release();
m_pShader1stPass.Release();
m_pShader1stPassAndGamma.Release();
m_pShader2ndPass.Release();
m_pShader2ndPassAndGamma.Release();
m_pState.Release();
m_pStateWithGamma.Release();
OutputMethod::Clear();
}
HRESULT PostprocessedOutput::Output(CBaseSwapChain* pSwapChain)
{
HRESULT hResult = S_OK;
SetStatesBeforeDraw(pSwapChain);
IDirect3DSurface9* primary = pSwapChain->m_pPrimaryBackBuffer;
IDirect3DSurface9* secondary = pSwapChain->m_pSecondaryBackBuffer;
NSCALL(m_pd3dDevice->BeginScene());
if(SUCCEEDED(hResult))
{
DrawFirstPass(pSwapChain, primary, secondary);
//--- no MRT supported ---
if (m_bMultiPassRendering)
DrawSecondPass(pSwapChain, secondary);
NSCALL(m_pd3dDevice->EndScene());
}
return hResult;
}
HRESULT PostprocessedOutput::DrawFirstPass( CBaseSwapChain* pSwapChain, IDirect3DSurface9* primary, IDirect3DSurface9* secondary )
{
HRESULT hResult = S_OK;
NSCALL(m_pd3dDevice->SetRenderTarget(0, primary));
if (!m_bMultiPassRendering && GetOutputChainsNumber() > 1)
NSCALL(m_pd3dDevice->SetRenderTarget(1, secondary));
NSCALL(m_pd3dDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, pSwapChain->m_VertexSinglePass1Pass, sizeof(pSwapChain->m_VertexSinglePass1Pass[0])));
return hResult;
}
HRESULT PostprocessedOutput::DrawSecondPass( CBaseSwapChain* pSwapChain, IDirect3DSurface9* secondary )
{
HRESULT hResult = S_OK;
//DEBUG_TRACE2("Two pass rendering\n");
NSCALL(m_pd3dDevice->SetRenderTarget(0, secondary));
if(pSwapChain->m_CurrentRAMPisIdentity || !m_pShader2ndPassAndGamma)
m_pd3dDevice->SetPixelShader(m_pShader2ndPass);
else
m_pd3dDevice->SetPixelShader(m_pShader2ndPassAndGamma);
NSCALL(m_pd3dDevice->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, pSwapChain->m_VertexSinglePass2Pass, sizeof(pSwapChain->m_VertexSinglePass2Pass[0])));
return hResult;
}
HRESULT PostprocessedOutput::SetStatesBeforeDraw( CBaseSwapChain* pSwapChain )
{
HRESULT hResult = S_OK;
IDirect3DTexture9* left = pSwapChain->GetLeftBackBufferTex();
IDirect3DTexture9* right = pSwapChain->GetRightBackBufferTex();
IDirect3DTexture9* leftDepth = pSwapChain->GetLeftDepthStencilTex();
IDirect3DTexture9* rightDepth = pSwapChain->GetRightDepthStencilTex();
if(pSwapChain->m_CurrentRAMPisIdentity || m_pStateWithGamma == NULL)
m_pState->Apply();
else
m_pStateWithGamma->Apply();
if (left == right && m_pShaderMono && !m_bMultiPassRendering)
{
// Mono Mode
if(pSwapChain->m_CurrentRAMPisIdentity || m_pStateWithGamma == NULL) {
NSCALL(m_pd3dDevice->SetPixelShader(m_pShaderMono));
} else {
NSCALL(m_pd3dDevice->SetPixelShader(m_pShaderMonoAndGamma));
}
}
if (m_bProcessGammaRamp)
m_pd3dDevice->SetTexture(2, pSwapChain->m_GammaRAMPTexture);
SetStates(pSwapChain);
NSCALL(m_pd3dDevice->SetTexture(0, left));
NSCALL(m_pd3dDevice->SetTexture(1, right));
if (m_Caps & ocRequiredDepthMap)
{
NSCALL(m_pd3dDevice->SetTexture(3, leftDepth));
NSCALL(m_pd3dDevice->SetTexture(4, rightDepth));
}
ProcessSubMode();
return hResult;
}
|
#include<bits/stdc++.h>
using namespace std;
void solve(string word) {
int n = word.length();
if (n > 10) {
char begin = word.at(0);
char end = word.at(n-1);
cout << begin << n-2 << end << endl;
} else {
cout << word << endl;
}
}
int main() {
int t;
cin >> t;
for (int i = 0; i < t; i++) {
string word;
cin >> word;
solve(word);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.